@turnix-co/konva-editor 3.0.48 → 3.0.50
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.d.ts +31 -3
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
export{default as Konva}from'konva';import*as ve from'react';import ve__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,Palette,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,List,Plus,Export,CaretLeft,CaretDown,CaretUp,SidebarSimple,CaretRight,SpeakerHifiIcon,NotePencilIcon,PencilSimple,CopySimple,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,TextUnderline,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Copy,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 qd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import Uu from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {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 {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Ad=e=>{throw TypeError(e)};var Pd=(e,o,t)=>o.has(e)||Ad("Cannot "+t);var j=(e,o,t)=>(Pd(e,o,"read from private field"),t?t.call(e):o.get(e)),Re=(e,o,t)=>o.has(e)?Ad("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Ae=(e,o,t,a)=>(Pd(e,o,"write to private field"),o.set(e,t),t);var Ed=(e,o,t,a)=>({set _(r){Ae(e,o,r);},get _(){return j(e,o,a)}});var be=()=>useDispatch(),te=e=>useSelector(e),tt=be,He=te;var ti=20,oi=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}),ei=oi("Slide 1"),cp={slides:[ei],currentSlideId:ei.id,history:{[ei.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false,editingOverlayPosition:null},Dd=createSlice({name:"canvas",initialState:cp,reducers:{addSlide:e=>{if(e.slides.length>=ti)return;let o=oi(`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(u=>u.isActive).length<=1)return;let n=e.slides.findIndex(u=>u.id===t);if(n===-1)return;let i=e.slides[n];if(a?(i.isActive=false,i.updatedAt=Date.now()):(e.slides.splice(n,1),delete e.history[t]),e.currentSlideId===t){let u=e.slides.filter(s=>s.isActive);u.length>0&&(e.currentSlideId=u[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=ti)return;let t=e.slides.findIndex(n=>n.id===o.payload);if(t===-1)return;let a=e.slides[t],r={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),isActive:true,lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,r),e.currentSlideId=r.id,e.history[r.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},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[r]=e.slides.splice(t,1);e.slides.splice(a,0,r);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(r=>r.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload);if(a){let r={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(r),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,newTimestamp:n}=o.payload;switch(r){case "image":let i=t.images.find(g=>g.id===a);i&&(i.timestamp=n);break;case "video":let u=t.videos.find(g=>g.id===a);u&&(u.timestamp=n);break;case "shape":let s=t.shapes.find(g=>g.id===a);s&&(s.timestamp=n);break;case "text":let c=t.texts.find(g=>g.id===a);c&&(c.timestamp=n);break;case "flashcard":let m=t.flashcards.find(g=>g.id===a);m&&(m.timestamp=n);break;case "photoFrame":let d=t.photoFrames.find(g=>g.id===a);d&&(d.timestamp=n);break;case "mcq":let l=t.multipleChoices.find(g=>g.id===a);l&&(l.timestamp=n);break;case "trueFalse":let f=t.trueFalses.find(g=>g.id===a);f&&(f.timestamp=n);break;case "shortAnswer":let h=t.shortAnswers.find(g=>g.id===a);h&&(h.timestamp=n);break;case "longAnswer":let p=t.LongAnswer.find(g=>g.id===a);p&&(p.timestamp=n);break;case "fillInTheBlanks":let v=t.fillInTheBlanks.find(g=>g.id===a);v&&(v.timestamp=n);break;case "line":let y=t.lines.find(g=>g.id===a);y&&(y.timestamp=n);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);if(a){let r={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(r),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);if(a){let r={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(r),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(r),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let r=t.multipleChoices[t.multipleChoices.length-1];a.x=r.x+20,a.y=r.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(r=>r.id===o.payload);if(a){let r={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(r),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let r=t.trueFalses[t.trueFalses.length-1];a.x=r.x+20,a.y=r.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(r),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let r=t.shortAnswers[t.shortAnswers.length-1];a.x=r.x+20,a.y=r.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(r=>r.id===o.payload);if(a){let r={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(r),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let r=t.LongAnswer[t.LongAnswer.length-1];a.x=r.x+20,a.y=r.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload);if(a){let r={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(r),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let r=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=r.x+20,a.y=r.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(r=>r.id===o.payload);if(a){let r={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(r),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.images.splice(n,1);t.images.push(i);}}else if(r==="video"){let n=t.videos.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.videos.splice(n,1);t.videos.push(i);}}else if(r==="shape"){let n=t.shapes.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.shapes.splice(n,1);t.shapes.push(i);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.flashcards.splice(n,1);t.flashcards.push(i);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.photoFrames.splice(n,1);t.photoFrames.push(i);}}else if(r==="text"){let n=t.texts.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.texts.splice(n,1);t.texts.push(i);}}else if(r==="trueFalse"){let n=t.trueFalses.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.trueFalses.splice(n,1);t.trueFalses.push(i);}}else if(r==="shortAnswer"){let n=t.shortAnswers.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.shortAnswers.splice(n,1);t.shortAnswers.push(i);}}else if(r==="fillInTheBlanks"){let n=t.fillInTheBlanks.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.fillInTheBlanks.splice(n,1);t.fillInTheBlanks.push(i);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.images.splice(n,1);t.images.unshift(i);}}else if(r==="video"){let n=t.videos.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.videos.splice(n,1);t.videos.unshift(i);}}else if(r==="shape"){let n=t.shapes.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.shapes.splice(n,1);t.shapes.unshift(i);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.flashcards.splice(n,1);t.flashcards.unshift(i);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.photoFrames.splice(n,1);t.photoFrames.unshift(i);}}else if(r==="text"){let n=t.texts.findIndex(i=>i.id===a);if(n!==-1){let[i]=t.texts.splice(n,1);t.texts.unshift(i);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload,i=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);i&&(i.locked=!i.locked,"draggable"in i&&(i.draggable=!i.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,link:n}=o.payload,u=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="mcq"?t.multipleChoices:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(s=>s.id===a);u&&(u.link=n,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,altText:n}=o.payload,u=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(s=>s.id===a);u&&(u.altText=n,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,audioData:n}=o.payload,u=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(s=>s.id===a);u&&(u.audioData=n,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},editingOverlayPosition:(e,o)=>{e.editingOverlayPosition=o.payload;},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(r=>r.id===o.payload);if(a){let r={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(r),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a){let r={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(r),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let r=a.images.map((n,i)=>i).filter(n=>n!==a.currentIndex);if(r.length>0){let n=r[Math.floor(Math.random()*r.length)];a.navigationHistory.push(n),a.currentIndex=n;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);if(a){let r={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(r),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let r=o.past.pop();e.slides[t]=r;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let r=o.future.shift();e.slides[t]=r;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let r=JSON.parse(JSON.stringify(t));a.past.push(r),a.future=[],a.past.length>20&&a.past.shift();}catch(r){console.warn("Failed to save to history - data too large:",r),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;}}}),{addSlide:tr,deleteSlide:ar,duplicateSlide:or,setCurrentSlide:rr,setViewerMode:fp,updateSlideThumbnail:ri,setBackgroundColor:nr,reorderSlides:mp,loadSlides:go,addLine:ni,removeLine:pn,addImage:si,updateImage:xo,deleteImage:hn,duplicateImage:gn,addVideo:xn,updateVideo:bn,deleteVideo:vn,duplicateVideo:yn,toggleVideoPlaying:Wa,addShape:ii,updateShape:bo,duplicateShape:wn,deleteShape:Sn,addText:li,editingOverlayPosition:Rd,updateText:Ft,deleteText:Ln,duplicateText:In,addFlashcard:di,updateFlashcard:vo,deleteFlashcard:Cn,duplicateFlashcard:kn,editFlashcard:sr,nextFlashcard:ui,previousFlashcard:ci,addPhotoFrame:fi,updatePhotoFrame:Ka,deletePhotoFrame:Tn,duplicatePhotoFrame:Mn,toggleImageDrawingMode:mi,addImageAnnotation:pi,updateImageAnnotation:pp,clearImageAnnotations:hp,togglePhotoFrameDrawingMode:hi,addPhotoFrameAnnotation:gi,updatePhotoFrameAnnotation:gp,clearPhotoFrameAnnotations:xp,addMultipleChoice:xi,updateMultipleChoice:xa,editMultipleChoice:bp,deleteMultipleChoice:An,duplicateMultipleChoice:Pn,addTrueFalse:bi,updateTrueFalse:ba,deleteTrueFalse:En,duplicateTrueFalse:Dn,addShortAnswer:vi,updateShortAnswer:ir,deleteShortAnswer:Rn,duplicateShortAnswer:Fn,addLongAnswer:yi,updateLongAnswer:lr,deleteLongAnswer:Bn,duplicateLongAnswer:On,addFillInTheBlanks:wi,updateFillInTheBlanks:dr,deleteFillInTheBlanks:Nn,duplicateFillInTheBlanks:Hn,setShowMcqForm:va,setShowFlashcardForm:Ga,setActivityType:Si,setEditingActivity:ur,bringToFront:Li,sendToBack:Ii,toggleLock:Ci,setLink:qn,setAltText:Vn,setAudioData:Un,updateLastLine:vp,finalizeDrawing:ki,setLines:yp,updateLinePosition:wp,updateLineTransform:zn,deleteLineById:Wn,duplicateLine:Ti,updateElementOrder:cr,clearCanvas:Mi,undo:Kn,redo:Gn,saveToHistory:de,toggleSketchMode:Sp,setSketchMode:yt,setEditingTextId:fr,setPresentationTitle:Ai,setPresentationDescription:Pi,loadPresentationMetadata:Ei,setMetadataLoaded:jn}=Dd.actions;var Fd=e=>e.canvas.slides,ya=e=>e.canvas.currentSlideId,ge=createSelector([Fd,ya],(e,o)=>e.find(t=>t.id===o)),wa=createSelector([Fd],e=>e.filter(o=>o.isActive!==false)),Di=e=>e.canvas.slides,mr=createSelector([wa],e=>e.length<ti),Lp=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},pr=e=>e.canvas.presentationMetadata,Ri=e=>e.canvas.metadataLoaded,_n=e=>e.canvas.viewerMode,Fi=Dd.reducer;var Od=e=>{let o=be(),t=useRef(null),a=useRef(false),r=te(f=>f.toolbar.selectedTool),n=te(f=>f.toolbar.penColor),i=te(f=>f.toolbar.strokeWidth),u=te(f=>f.canvas.isSketchMode),s=te(f=>f.canvas.slides.find(p=>p.id===f.canvas.currentSlideId)?.lines||[]),c=useCallback(f=>{t.current=f;},[]),m=useCallback(f=>{r==="pen"&&t.current&&(o(de()),t.current.startDrawing(f),a.current=true);},[r,o]),d=useCallback(f=>{!t.current||!a.current||t.current.draw(f);},[]),l=useCallback(()=>{if(!t.current||!a.current)return;let f=t.current.stopDrawing();a.current=false,f&&f.points.length>=4&&o(ni(f)),o(ki()),e?.();},[o,e]);return {lines:s,tool:r,color:n,strokeWidth:i,isSketchMode:u,setCanvasRef:c,startDrawing:m,draw:d,stopDrawing:l}};var Vd=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:r,isSketchMode:n,style:i,xOffset:u=0,yOffset:s=0},c)=>{let m=useRef(null),d=useRef(false),l=useRef([]),f=useRef([]),h=useRef(null),p=useRef(t),v=useRef(a),y=useRef(r),g=useRef(n),x=useRef(u),w=useRef(s);useEffect(()=>{p.current=t,v.current=a,y.current=r,g.current=n,x.current=u,w.current=s;},[t,a,r,n,u,s]);let I=useCallback(()=>{let S=m.current;if(!S)return;let b=S.getContext("2d");b&&b.clearRect(0,0,S.width,S.height);},[]),k=useCallback(()=>{let S=m.current,b=f.current;if(!S||b.length<1)return;let C=S.getContext("2d");if(!C)return;if(C.clearRect(0,0,S.width,S.height),p.current==="eraser"?(C.globalCompositeOperation="destination-out",C.fillStyle="rgba(0,0,0,1)"):(C.globalCompositeOperation="source-over",C.fillStyle=v.current),b.length===1){C.beginPath(),C.arc(b[0].x,b[0].y,y.current/2,0,Math.PI*2),C.fill();return}let P=qd(b,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:R=>R,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(P.length<2)){C.beginPath(),C.moveTo(P[0][0],P[0][1]);for(let R=1;R<P.length;R++)C.lineTo(P[R][0],P[R][1]);C.closePath(),C.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:S=>{d.current=true;let b={x:S.x-x.current,y:S.y-w.current};l.current=[{x:S.x,y:S.y}],f.current=[b],h.current=S,k();},draw:S=>{if(!d.current||!h.current)return;let b=S.x-h.current.x,C=S.y-h.current.y;if(Math.sqrt(b*b+C*C)<2)return;let P={x:S.x-x.current,y:S.y-w.current};l.current.push({x:S.x,y:S.y}),f.current.push(P),h.current=S,k();},stopDrawing:()=>{if(!d.current)return null;if(d.current=false,l.current.length<2)return l.current=[],f.current=[],h.current=null,I(),null;let b=qd(l.current,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:M=>M,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(M=>[M[0],M[1]]),C={tool:p.current,points:b,color:v.current,strokeWidth:y.current,isSketch:true};return l.current=[],f.current=[],h.current=null,I(),C},clear:()=>{I(),l.current=[],f.current=[],h.current=null,d.current=false;},isDrawing:()=>d.current,getCanvasElement:()=>m.current}),[I,k]),useEffect(()=>{let S=m.current;S&&(S.width=e,S.height=o);},[e,o]),jsx("canvas",{ref:m,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...i}})});Vd.displayName="DirectDrawingCanvas";var Ud=Vd;var Wd=e=>{let o=be(),a=te(ge)?.images||[],r=useRef(new Map),n=useRef(new Map),i=useRef(new Set);useEffect(()=>{let m=new Set(a.map(d=>d.id));i.current.forEach(d=>{if(!m.has(d)){let l=n.current.get(d);l&&(l.src="",n.current.delete(d)),r.current.delete(d);}}),i.current=m;},[a]),useEffect(()=>()=>{n.current.forEach(m=>{m.src="";}),n.current.clear(),r.current.clear();},[]);let u=useCallback(m=>{if(n.current.has(m.id))return n.current.get(m.id);let d=new window.Image;return (m.src.startsWith("http://")||m.src.startsWith("https://"))&&(d.crossOrigin="anonymous"),d.src=m.src,n.current.set(m.id,d),d},[]),s=useCallback((m,d)=>{let l=m.target,f=l.id();a.find(p=>p.id===f)&&(o(xo({id:f,x:l.x(),y:l.y(),width:l.width(),height:l.height(),rotation:l.rotation()})),d?.());},[a,o]),c=useCallback((m,d)=>{let l=d.target,f=r.current.get(m);if(!f){console.error("\u274C Image node not found for id:",m);return}let h=l.scaleX(),p=l.scaleY(),v=l.rotation(),y=f.width(),g=f.height(),x=Math.max(5,y*h),w=Math.max(5,g*p);l.scaleX(1),l.scaleY(1),f.width(x),f.height(w),o(xo({id:m,width:x,height:w,x:l.x(),y:l.y(),rotation:v})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:u,imageRefs:r,handleDragEnd:s,handleImageTransformEnd:c}};var Kd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),n=useCallback((u,s)=>{let c=s.target,m=c.scaleX(),d=c.scaleY(),l=c.rotation(),f=Math.max(5,c.width()*m),h=Math.max(5,c.height()*d);c.scaleX(1),c.scaleY(1),c.width(f),c.height(h),o(xa({id:u,width:f,height:h,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:n,mcqRefs:a,handleDragEnd:(u,s)=>{o(xa({id:s,x:u.target.x(),y:u.target.y()})),e?.();}}};var Gd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),n=useCallback((u,s)=>{let c=s.target,m=c.scaleX(),d=c.scaleY(),l=c.rotation(),f=Math.max(5,c.width()*m),h=Math.max(5,c.height()*d);c.scaleX(1),c.scaleY(1),c.width(f),c.height(h),o(ba({id:u,width:f,height:h,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:n,handleTrueFalseDragEnd:(u,s)=>{o(ba({id:s,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var jd=e=>{let o=be(),a=te(ge)?.videos||[],r=useRef(new Map),n=useCallback(s=>{o(Wa(s));},[o]),i=useCallback((s,c)=>{let m=c.target;o(bn({id:s,x:m.x(),y:m.y()})),e?.();},[o,e]),u=useCallback((s,c)=>{let m=c.target,d=m.scaleX(),l=m.scaleY(),f=m.rotation(),h=Math.max(5,m.width()*d),p=Math.max(5,m.height()*l);m.scaleX(1),m.scaleY(1),m.width(h),m.height(p),o(bn({id:s,width:h,height:p,x:m.x(),y:m.y(),rotation:f})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:r,handleVideoClick:n,handleVideoDragEnd:i,handleVideoTransformEnd:u}};var $d=e=>{let o=be(),a=te(ge)?.shapes||[],r=useRef(new Map),n=useRef(new Map),[i,u]=useState(false),s=useCallback((m,d)=>{let l=d.target;o(bo({id:m,x:l.x(),y:l.y()})),e?.();},[o,e]),c=useCallback((m,d)=>{let l=d.target,f=a.find(x=>x.id===m);if(!f)return;let h=l.scaleX(),p=l.scaleY(),v=f.type?.toLowerCase();v==="arrow"||v==="line"||(l.scaleX(1),l.scaleY(1));let g={id:m,x:l.x(),y:l.y(),width:Math.max(5,l.width()*h),height:Math.max(5,l.height()*p),rotation:l.rotation()};switch(v){case "circle":g.radius=l.width()*h/2;break;case "star":g.innerRadius=l.width()*h/4,g.outerRadius=l.width()*h/2;break;case "triangle":g.radius=l.width()*h/2;break;case "ellipse":g.radiusX=l.width()*h/2,g.radiusY=l.height()*p/2;break;case "polygon":g.radius=l.width()*h/2;break;case "ring":let x=h;g.innerRadius=f.innerRadius&&f.innerRadius*x,g.outerRadius=f.outerRadius&&f.outerRadius*x;break;case "wedge":g.radius=f.radius&&f.radius*h;break;case "arc":g.innerRadius=f.innerRadius&&f.innerRadius*h,g.outerRadius=f.outerRadius&&f.outerRadius*h;break;case "arrow":case "line":{g.scaleX=h,g.scaleY=p,delete g.width,delete g.height;break}}o(bo(g)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:r,isDragging:i,loadedShapesRef:n,handleShapeDragEnd:s,handleShapeResizeEnd:c}};var Zd=(e,o)=>{let t=tt(),r=te(ge)?.texts||[],n=useRef(new Map),[i,u]=useState(null),[s,c]=useState("");return {texts:r,textRefs:n,handleDragEnd:(v,y)=>{let g=v.target;t(de()),t(Ft({id:y,x:g.x(),y:g.y()})),e();},handleTransformEnd:v=>{let y=n.current.get(v);if(!y)return;let g=y.scaleX(),x=y.scaleY(),w=r.find(k=>k.id===v);if(!w)return;let I=(g+x)/2;y.scaleX(1),y.scaleY(1),t(de()),t(Ft({id:v,x:y.x(),y:y.y(),width:Math.max(5,(w.width||100)*g),height:Math.max(5,(w.height||50)*x),fontSize:Math.round(Math.max(8,w.fontSize*I)),rotation:y.rotation()})),e();},handleDoubleClick:v=>{let y=r.find(g=>g.id===v);y&&!y.locked&&(u(v),c(y.text));},startEditing:v=>{let y=r.find(g=>g.id===v);y&&!y.locked&&(u(v),c(y.text));},editingTextId:i,editingValue:s,handleEditingChange:v=>{c(v);},finishEditing:()=>{if(i){let v=n.current.get(i),y=r.find(x=>x.id===i);t(de());let g={id:i,text:s};if(y&&(y.fontWeight!==void 0&&(g.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(g.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(g.textDecoration=y.textDecoration)),o?.current&&s.trim()){let x=o.current,w=x.offsetWidth,I=x.offsetHeight,k=1;if(v){let U=v.getStage();U&&(k=U.scaleX());}let S=14,b=(w-S)/k,C=(I-S)/k,M=s.split(`
|
|
3
|
-
`).length,R=r.find(U=>U.id===i)?.fontSize||24,B=M*R*1.2+10;g.width=Math.max(200,b),g.height=Math.max(50,C,B);}else if(v&&s.trim()){let x=v.text(),w=v.width();v.text(s),v.width(void 0);let I=v.width(),k=v.height();v.text(x),v.width(w),g.width=Math.max(200,I+20),g.height=Math.max(50,k+20);}t(Ft(g)),u(null),c(""),t(fr(null)),e();}}}};var Jd=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],r=useRef(new Map),n=useCallback((i,u)=>{let s=i.target;o(ir({id:u,x:s.x(),y:s.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:n}};var Qd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((n,i)=>{let u=n.target;o(lr({id:i,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var tu=e=>{let o=be(),a=te(ge)?.flashcards||[],r=useRef(new Map),n=useRef(new Map),i=useCallback((d,l)=>{if(n.current.has(l))return n.current.get(l);let f=new window.Image;return (d.startsWith("http://")||d.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=d,n.current.set(l,f),f},[]),u=useCallback((d,l)=>{let f=d.target,h=f.id();a.find(v=>v.id===h)&&(o(vo({id:h,x:f.x(),y:f.y()})),l?.());},[a,o]),s=useCallback((d,l)=>{let f=l.target,h=f.scaleX(),p=f.scaleY(),v=f.rotation(),y=Math.max(50,f.width()*h),g=Math.max(50,f.height()*p);f.scaleX(1),f.scaleY(1),f.width(y),f.height(g),o(vo({id:d,width:y,height:g,x:f.x(),y:f.y(),rotation:v})),f.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(d=>{o(ui(d)),e?.();},[o,e]),m=useCallback(d=>{o(ci(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:i,flashcardRefs:r,handleDragEnd:u,handleFlashcardTransformEnd:s,handleNext:c,handlePrevious:m}};var ru=e=>{let o=be(),a=te(ge)?.photoFrames||[],r=useRef(new Map),[n,i]=useState(new Map),u=useCallback((f,h)=>{console.log("handleDragEnd"),o(Ka({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),s=useCallback((f,h)=>{let p=h.target,v=p.scaleX(),y=p.scaleY(),g=p.rotation(),x=a.find(k=>k.id===f);if(!x)return;let w=Math.max(100,x.width*v),I=Math.max(100,x.height*y);p.scaleX(1),p.scaleY(1),o(Ka({id:f,width:w,height:I,x:p.x(),y:p.y(),rotation:g})),p.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return i(p=>{let v=new Map(p);return v.set(f,h),v}),o(Ka({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),m=useCallback(f=>{let h=n.get(f);h&&(h.getTracks().forEach(p=>p.stop()),i(p=>{let v=new Map(p);return v.delete(f),v}),o(Ka({id:f,isCapturing:false})),e?.());},[n,o,e]),d=useCallback((f,h)=>{let p=document.createElement("canvas");p.width=h.videoWidth,p.height=h.videoHeight;let v=p.getContext("2d");if(v){v.drawImage(h,0,0,p.width,p.height);let y=p.toDataURL("image/jpeg",.8);return o(Ka({id:f,capturedImageUrl:y,isCapturing:false})),m(f),e?.(),y}return null},[o,m,e]),l=useRef(n);return useEffect(()=>{l.current=n;},[n]),useEffect(()=>()=>{l.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:u,handlePhotoFrameTransformEnd:s,startCamera:c,stopCamera:m,capturePhoto:d,cameraStreams:n}};var nu=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((n,i)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...i,width:Math.max(o.minWidth,Math.min(i.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(i.height,o.maxHeight))}:i,[o]),a=useCallback((n,i,u,s,c,m,d,l=[])=>{if(e.current){if(n&&!l.find(p=>p.id===n)?.isPlaying){let p=i.get(n)||u.get(n)||s.get(n)||c.get(n)||m.get(n)||(d?d.get(n):null);if(p){e.current.boundBoxFunc(t),e.current.nodes([p]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var Zp=(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])},du=(e,o)=>{let t=tt(),a=He(_n),r=useRef(e);useEffect(()=>{r.current=e;},[e]);let n=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(ri({id:r.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),i=Zp(n,500);return {generateThumbnail:n,debouncedGenerateThumbnail:i}};var Qp=e=>e.flatMap(o=>[o[0],o[1]]),$n=(e,o)=>{let t=qd(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 Qp(t)};var uu=e=>{let o=be(),t=useRef(false),a=useRef(false),r=useRef([]),[n,i]=useState(null),u=te(x=>x.toolbar.selectedTool),s=te(x=>x.toolbar.penColor),c=te(x=>x.toolbar.strokeWidth),m=te(x=>x.canvas.isSketchMode),d=te(x=>x.canvas.slides.find(I=>I.id===x.canvas.currentSlideId)?.images.find(I=>I.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(x=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,r.current=[{x:x.x,y:x.y}];let w=x.x/h,I=x.y/p;i({tool:u,points:[w,I],color:s,strokeWidth:c/h,isSketch:m});},[u,s,c,m,h,p]),y=useCallback(x=>{if(!t.current||!n)return;a.current=true;let w=r.current[r.current.length-1];if(Math.sqrt(Math.pow(x.x-w.x,2)+Math.pow(x.y-w.y,2))<2)return;r.current.push({x:x.x,y:x.y});let k;if(m)k=$n(r.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,C)=>C%2===0?b/h:b/p);else {let S=x.x/h,b=x.y/p;k=[...n.points,S,b];}i(S=>S?{...S,points:k}:null);},[m,c,n,h,p]),g=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(pi({imageId:e,line:n})),i(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:l,activeLine:n,isDrawingMode:f,startDrawing:v,draw:y,stopDrawing:g,tool:u}};function qe({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),r=useRef(null);return {createHandlers:useCallback((i,u)=>({onTouchStart:s=>{let c=s.evt.touches[0];r.current={x:c.clientX,y:c.clientY},a.current=setTimeout(()=>{e(i,u)(s.evt);},o);},onTouchMove:s=>{if(!r.current)return;let c=s.evt.touches[0],m=Math.abs(c.clientX-r.current.x),d=Math.abs(c.clientY-r.current.y);(m>t||d>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),r.current=null;}}),[e,o,t])}}var hu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:i,onLongPress:u})=>{let{annotations:s,activeLine:c,stopDrawing:l,tool:f}=uu(e.id),{createHandlers:h}=qe({onLongPress:u});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=>{{n(e.id);return}},y=x=>{return;},g=x=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="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();else {let w=t.current.get(e.id);w?._contextMenuCleanup&&w._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:x=>r(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:x=>{x.evt.preventDefault();let w=x.evt;i(w,e.id,"image");},...f!=="pen"&&f!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onMouseMove:y,onMouseUp:g,...h(e.id,"image")}:{}}),s?.map((x,w)=>{let I=x.points.map((S,b)=>b%2===0?S*e.width+e.x:S*e.height+e.y),k=x.strokeWidth*e.width;return jsx(Line,{points:I,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:k,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},w)}),c&&jsx(Line,{points:c.points.map((x,w)=>w%2===0?x*e.width+e.x:x*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});hu.displayName="ImageWithDrawing";var Ui=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:i,onLongPress:u})=>jsx(Fragment,{children:e.map(s=>{let c=o(s);return c?jsx(hu,{img:s,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:i,onLongPress:u},s.id):null})}));Ui.displayName="ImageLayer";var uh=({src:e,x:o,id:t,y:a,width:r,height:n,isSelected:i,rotation:u=0,onTransformEnd:s,onDragEnd:c})=>{let m=be(),d=useRef(null),l=f=>{m(Wa(f));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:n,rotation:u,onDragEnd:c,onTransformEnd:s,children:[jsx(Rect,{width:r,height:n,fill:"black",stroke:i?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${n}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>l(t),onSeeking:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},gu=uh;var bh=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,nodeRef:i})=>{let[u,s]=useState(null),c=useSelector(p=>p.toolbar.selectedTool),m=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let p=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(p.crossOrigin="anonymous"),p.src=e.thumbnailDataUrl,p.onload=()=>{s(p);};}},[e.thumbnailDataUrl]),!u)return null;let d=e.width/2,l=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,80));return jsxs(Group,{draggable:!m,listening:!m,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...m?{}:{onDragEnd:a,onTransformEnd:r},ref:p=>{if(i(p),p){let v=p.getStage()?.container();if(v){let y=g=>{let x=p.getStage()?.getPointerPosition();if(x){let w={x:e.x,y:e.y,width:e.width,height:e.height};x.x>=w.x&&x.x<=w.x+w.width&&x.y>=w.y&&x.y<=w.y+w.height&&n(g);}};v.addEventListener("contextmenu",y),p._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",y);};}}},children:[jsx(Image$1,{image:u,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:d,y:l,radius:h,fill:"white",listening:!m,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...m?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:l,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!m,...m?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:l,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!m,...m?{}:{onClick:t,onTap:t}})]})},bu=bh;var Ki=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:n,onContextMenu:i})=>jsx(Fragment,{children:e.map(u=>jsxs(ve__default.Fragment,{children:[jsx(bu,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>a(u.id),onDragEnd:s=>r(u.id,s),onTransformEnd:s=>n(u.id,s),onContextMenu:s=>i(s,u.id,"video"),nodeRef:s=>{s?t.current.set(u.id,s):t.current.delete(u.id);}}),u.isPlaying&&!u.isRecorded&&jsx(gu,{id:u.id,src:u.objectUrl,x:u.x,y:u.y,width:u.width,height:u.height,isSelected:false,rotation:u.rotation,onTransformEnd:s=>n(u.id,s),onDragEnd:s=>r(u.id,s)})]},u.id))}));Ki.displayName="VideoLayer";var Gi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:n,onContextMenu:i,onLongPress:u})=>{let s=useSelector(d=>d.toolbar.selectedTool),c=s==="pen"||s==="eraser",{createHandlers:m}=qe({onLongPress:u});return jsx(Fragment,{children:e.map((d,l)=>{let f=d.id||l,h={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!c,listening:!c,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},radius:d.radius||d.width/2,width:d.width,height:d.width},f);case "star":return jsx(Star,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},sides:3,radius:d.radius||d.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},sides:d.sides||6,radius:d.radius||d.width/2},f);case "ellipse":return jsx(Ellipse,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},f);case "ring":return jsx(Ring,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "wedge":return jsx(Wedge,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},radius:d.radius||d.width/2,angle:d.angle||60},f);case "arrow":return jsx(Arrow,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(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:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(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:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(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:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},f)}})})});Gi.displayName="ShapeLayer";var wu=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:n,onDoubleClick:i,editingTextId:u,onLongPress:s})=>{let c=useSelector(l=>l.toolbar.selectedTool),m=c==="pen"||c==="eraser",{createHandlers:d}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(l=>{let f=l.id===u,h=l.fontWeight==="bold",p=h?Math.max(1,l.fontSize/25):0;return jsx(Text,{id:l.id,ref:v=>{v?o.current.set(l.id,v):o.current.delete(l.id);},text:l.text,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:!l.locked&&!f&&!m,listening:!m,fontSize:l.fontSize,fontFamily:l.fontFamily,fontStyle:l.fontStyle,fontWeight:l.fontWeight,textDecoration:l.textDecoration,fill:l.fill,stroke:h?l.fill:void 0,strokeWidth:p,align:l.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...m?{}:{onClick:()=>r(l.id),onTap:()=>r(l.id),onDblClick:()=>i(l.id),onDblTap:()=>i(l.id),onDragEnd:v=>t(v,l.id),onTransformEnd:()=>a(l.id),onContextMenu:v=>{v.evt.preventDefault();let y=v.evt;n(y,l.id,"text");},...d(l.id,"text")}},l.id)})})};var Wh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onNext:i,onPrevious:u,nodeRef:s,touchHandlers:c,currentTool:m})=>{let[d,l]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let g=new window.Image,x=e.images[e.currentIndex];(x.startsWith("http://")||x.startsWith("https://"))&&(g.crossOrigin="anonymous"),g.src=x,g.onload=()=>{l(g);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let f=8,h=2,p=Math.min(e.width,e.height)*.08,v=Math.max(16,Math.min(p,32)),y=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:r,...c,ref:g=>{if(s(g),g){let x=g.getStage()?.container();if(x){let w=I=>{let k=g.getStage()?.getPointerPosition();if(k){let S={x:e.x,y:e.y,width:e.width,height:e.height};k.x>=S.x&&k.x<=S.x+S.width&&k.y>=S.y&&k.y<=S.y+S.height&&n(I);}};x.addEventListener("contextmenu",w),g._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",w);};}}},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:h,listening:false}),jsx(Image$1,{x:h+4,y:h+4,image:d,width:e.width-(h+4)*2,height:e.height-(h+4)*2,cornerRadius:f-h,onClick:t,onTap:t}),jsx(Rect,{x:h,y:e.height-50,width:e.width-h*2,height:50,cornerRadius:[0,0,f-h,f-h],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:y+v,y:e.height/2,onClick:g=>{g.cancelBubble=true,u();},onTap:g=>{g.cancelBubble=true,u();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-y-v,y:e.height/2,onClick:g=>{g.cancelBubble=true,i();},onTap:g=>{g.cancelBubble=true,i();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Iu=Wh;var Xi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onNext:i,onPrevious:u,onContextMenu:s,onLongPress:c})=>{let{createHandlers:m}=qe({onLongPress:c});return jsx(Fragment,{children:e.map(d=>jsx(Iu,{flashcard:d,isSelected:t===d.id,onClick:()=>n(d.id),onDragEnd:a,onTransformEnd:l=>r(d.id,l),onContextMenu:l=>s(l,d.id,"flashcard"),onNext:()=>i(d.id),onPrevious:()=>u(d.id),touchHandlers:m(d.id,"flashcard"),nodeRef:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);}},d.id))})});Xi.displayName="FlashcardLayer";var ku=e=>{let o=be(),t=useRef(false),a=useRef(false),r=useRef([]),[n,i]=useState(null);te(x=>x.toolbar.selectedTool);let s=te(x=>x.toolbar.penColor),c=te(x=>x.toolbar.strokeWidth),m=te(x=>x.canvas.isSketchMode),d=te(x=>x.canvas.slides.find(I=>I.id===x.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(x=>{if(!f)return;t.current=true,a.current=false,r.current=[{x:x.x,y:x.y}];let w=x.x/h,I=x.y/p;i({tool:"pen",points:[w,I],color:s,strokeWidth:c/h,isSketch:m});},[f,s,c,m,h,p]),y=useCallback(x=>{if(!t.current||!n)return;a.current=true;let w=r.current[r.current.length-1];if(Math.sqrt(Math.pow(x.x-w.x,2)+Math.pow(x.y-w.y,2))<2)return;r.current.push({x:x.x,y:x.y});let k;if(m)k=$n(r.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,C)=>C%2===0?b/h:b/p);else {let S=x.x/h,b=x.y/p;k=[...n.points,S,b];}i(S=>S?{...S,points:k}:null);},[m,c,n,h,p]),g=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(gi({frameId:e,line:n})),i(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:l,activeLine:n,isDrawingMode:f,startDrawing:v,draw:y,stopDrawing:g}};var Zh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onStartCamera:i,onCapture:u,cameraStream:s,nodeRef:c,touchHandlers:m})=>{let[d,l]=useState(null),[f,h]=useState(null),p=useRef(null),v=useRef(null),y=useRef(null),g=useRef(null),x=useRef(0),w=33,I=useSelector(q=>q.toolbar.selectedTool),k=I==="pen"||I==="eraser",{annotations:S,activeLine:b,isDrawingMode:C,startDrawing:M,draw:P,stopDrawing:R}=ku(e.id);useEffect(()=>{if(!C)return;let q=()=>{R();},_=()=>{R();};return window.addEventListener("mouseup",q),window.addEventListener("touchend",_),()=>{window.removeEventListener("mouseup",q),window.removeEventListener("touchend",_);}},[R,C]),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=()=>{l(q);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&s){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=s;let Z=()=>{_.width=q.videoWidth||640,_.height=q.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",_.width,_.height);let Y=oe=>{if(oe-x.current<w){y.current=requestAnimationFrame(Y);return}x.current=oe;let J=_.getContext("2d");if(J&&q.readyState===q.HAVE_ENOUGH_DATA){J.drawImage(q,0,0,_.width,_.height);let ce=_.toDataURL("image/jpeg",.6),Se=new window.Image;Se.onload=()=>{h(Se);},Se.src=ce;}y.current=requestAnimationFrame(Y);};y.current=requestAnimationFrame(Y);};return q.onloadedmetadata=Z,q.readyState>=q.HAVE_METADATA&&Z(),q.play().catch(Y=>console.error("Error playing video:",Y)),()=>{y.current&&(cancelAnimationFrame(y.current),y.current=null);}}return ()=>{h(null),g.current&&(g.current.src="");}},[e.isCapturing,s]);let z=()=>{p.current&&e.isCapturing&&u(p.current);},B=q=>{if(e.capturedImageUrl){if(!C){t();return}let _=q.currentTarget,Z=_.getAbsoluteTransform().copy(),oe=_.getStage()?.getPointerPosition();if(oe){Z.invert();let J=Z.point(oe);M(J);}q.cancelBubble=true;}else t();},U=q=>{if(!C||!e.capturedImageUrl)return;let _=q.currentTarget,Z=_.getAbsoluteTransform().copy(),oe=_.getStage()?.getPointerPosition();if(oe){Z.invert();let J=Z.point(oe);P(J);}},N=()=>{!C||!e.capturedImageUrl||R();},V=e.isCapturing?f:d,F=Math.min(e.width,e.height)*.12,W=Math.max(25,Math.min(F,50)),G=e.width/2,se=e.height/2;return jsxs(Group,{id:e.id,draggable:!C&&!k,listening:true,x:e.x,y:e.y,...m,...k?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:q=>{if(c(q),q){let _=q.getStage()?.container();if(_){let Z=Y=>{let oe=q.getStage()?.getPointerPosition();if(oe){let J={x:e.x,y:e.y,width:e.width,height:e.height};oe.x>=J.x&&oe.x<=J.x+J.width&&oe.y>=J.y&&oe.y<=J.y+J.height&&n(Y);}};_.addEventListener("contextmenu",Z),q._contextMenuCleanup=()=>{_.removeEventListener("contextmenu",Z);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:V?"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}}),V&&jsx(Image$1,{image:V,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:B,onTap:B,onMouseDown:B,onTouchStart:B,onMouseMove:U,onTouchMove:U,onMouseUp:N,onTouchEnd:N,...k?{}:{onDragEnd:a,onTransformEnd:r}}),S?.map((q,_)=>{let Z=q.points.map((oe,J)=>J%2===0?oe*e.width:oe*e.height),Y=q.strokeWidth*e.width;return jsx(Line,{points:Z,stroke:q.tool==="eraser"?"white":q.color,strokeWidth:Y,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},_)}),b&&jsx(Line,{points:b.points.map((q,_)=>_%2===0?q*e.width:q*e.height),stroke:b.tool==="eraser"?"white":b.color,strokeWidth:b.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},"active"),!V&&!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:se-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:G-W+6,y:se-60,width:W*1.6,height:W*1.6,radius:W,fill:"white",cornerRadius:8,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?z():i();},onTap:q=>{q.cancelBubble=true,e.isCapturing?z():i();}}),jsx(Html,{groupProps:{x:G-12,y:se-40,width:W*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?z():i();}})})]}),jsx(Text,{x:0,y:se,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:se+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:G-24,y:se+104,width:W*1.6,height:W*1.6,radius:W,fill:"#096B76",cornerRadius:W,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?z():i();},onTap:q=>{q.cancelBubble=true,e.isCapturing?z():i();}}),jsx(Html,{groupProps:{x:G-8,y:se+120,width:W*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?z():i();}})})]}),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:G-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:q=>{q.stopPropagation(),z();},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})})})})]})]})},Pu=Zh;var el=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onStartCamera:i,onCapture:u,cameraStreams:s,onContextMenu:c,onLongPress:m})=>{let{createHandlers:d}=qe({onLongPress:m});return jsx(Fragment,{children:e.map(l=>jsx(Pu,{photoFrame:l,isSelected:t===l.id,onClick:()=>n(l.id),onDragEnd:f=>a(f,l.id),onTransformEnd:f=>r(l.id,f),onContextMenu:f=>c(f,l.id,"photoFrame"),onStartCamera:()=>i(l.id),onCapture:f=>u(l.id,f),cameraStream:s.get(l.id),touchHandlers:d(l.id,"photoFrame"),nodeRef:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);}},l.id))})});el.displayName="PhotoFrameLayer";var Fu=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:n="",isDrawingMode:i,menuRef:u})=>{useEffect(()=>{let d=f=>{u?.current&&!u.current.contains(f.target)&&a();},l=f=>{f.key==="Escape"&&a();};return document.addEventListener("mousedown",d),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",l);}},[a]);let s=useMemo(()=>[{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:"draw",label:i?"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"}),hideForTypes:["line","video"]},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{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(r)||l.hideForTypes&&l.hideForTypes.includes(r))),[r,i]),c=(d,l)=>{d==="order"||d==="lock"?t(d,l):(t(d),a());},m=jsx("div",{ref:u,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:s.map((d,l)=>jsxs("button",{onClick:f=>c(d.action,f),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${d.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[d.icon,jsx("span",{className:`font-medium ${d.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:d.label})]}),d.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},l))})});return createPortal(m,document.body)};var Bu=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let n=i=>{r.current&&!r.current.contains(i.target)&&a();};return document.addEventListener("mousedown",n),()=>{document.removeEventListener("mousedown",n);}},[a]),jsx("div",{ref:r,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((n,i)=>jsx("button",{onClick:()=>{n.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:n.label})},i))})})};var Nu=createContext(null),tl=()=>useContext(Nu);function xg({children:e,className:o="",style:t}){let a=useRef(null),[r,n]=useState(null);return useEffect(()=>{a.current&&n(a.current);},[]),jsx(Nu.Provider,{value:r,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function Ve(){let e=tl();return typeof document>"u"?null:e||document.body}var Hu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:n})=>{let[i,u]=useState(a),s=useRef(null),c=Ve();useEffect(()=>{s.current?.focus();},[]);let m=()=>{r(i),n();},d=f=>{f.key==="Enter"?m():f.key==="Escape"&&n();};return c?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:n,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:s,type:"text",value:i,onChange:f=>u(f.target.value),onKeyDown:d,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:n,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick: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"})]})]})}),c):null};var ts=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),n=useRef(null),i=Ve();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let u=d=>{d.preventDefault(),o(a);},s=(d,l,f)=>{f/=100;let h=l*Math.min(f,1-f)/100,p=v=>{let y=(v+d/30)%12,g=f-h*Math.max(Math.min(y-3,9-y,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!i)return null;let m=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:n,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:d=>d.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:u,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:d=>r(d.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:d=>r(d.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:d=>{let l=parseInt(d.target.value),f=s(l,100,50);r(f);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(d=>jsx("button",{type:"button",onClick:()=>r(d),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===d.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:d},title:d},d))})]})]}),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,i)};var Og=({imageSrc:e,onCrop:o})=>{let[t]=Uu(e),a=useRef(null),r=useRef(null),n=useRef(null),i=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),u=useMemo(()=>{let l=i.width*.5,f=i.height*.5,h=(i.width-l)/2,p=(i.height-f)/2;return {x:h,y:p,width:l,height:f}},[i]),[s,c]=useState(u);useEffect(()=>{c(u);},[u]),useEffect(()=>{n.current&&r.current&&(n.current.nodes([r.current]),n.current.getLayer()?.batchDraw());},[s]),useEffect(()=>{o(s.x,s.y,s.width,s.height);},[s,o]);let m=()=>{let l=r.current;if(!l)return;let f=l.scaleX(),h=l.scaleY();l.scaleX(1),l.scaleY(1),c({x:l.x(),y:l.y(),width:Math.max(20,l.width()*f),height:Math.max(20,l.height()*h)});},d=()=>{let l=r.current;l&&c({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:i.width,height:i.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:i.width,height:i.height}),jsx(Rect,{x:0,y:0,width:i.width,height:i.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:s.x,y:s.y,width:s.width,height:s.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:s.x,y:s.y,width:s.width,height:s.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:m,dragBoundFunc:l=>{let f=Math.max(0,Math.min(l.x,i.width-s.width)),h=Math.max(0,Math.min(l.y,i.height-s.height));return {x:f,y:h}}}),jsx(Transformer,{ref:n,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(l,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>i.width||f.y+f.height>i.height?l:f})]})})},zu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,n]=useState({x:0,y:0,width:0,height:0}),[i]=Uu(e),u=Ve();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let s=(d,l,f,h)=>{n({x:d,y:l,width:f,height:h});},c=()=>{if(!i)return;let f=Math.min(600/i.width,400/i.height),h=r.x/f,p=r.y/f,v=r.width/f,y=r.height/f,g=document.createElement("canvas");g.width=v,g.height=y;let x=g.getContext("2d");if(!x)return;x.drawImage(i,h,p,v,y,0,0,v,y);let w=g.toDataURL("image/png");o(w);};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.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:d=>d.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(Og,{imageSrc:e,onCrop:s})}),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:c,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"]})]})]})}),u):null};var Sr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let r=Ve(),[n,i]=useState(false),[u,s]=useState(null),[c,m]=useState(0),[d,l]=useState(true),f=useRef(null),h=useRef([]),p=useRef(null),v=useRef(null),y=useRef(null),g=useRef(null),x=useRef(null),w=useRef(null);useEffect(()=>()=>{y.current&&cancelAnimationFrame(y.current),p.current&&clearInterval(p.current),v.current&&v.current.getTracks().forEach(M=>M.stop());},[]);let I=async()=>{try{let M,P=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let N=o.current.getLayers();console.log("Konva layers:",N.length),N.forEach((Z,Y)=>{let oe=Z.getChildren();console.log(`Layer ${Y} children count:`,oe.length);});let V=document.createElement("canvas");V.width=o.current.width(),V.height=o.current.height();let F=V.getContext("2d",{willReadFrequently:!1});if(!F){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",V.width,"x",V.height),x.current=V;let W=()=>{if(F.clearRect(0,0,V.width,V.height),N.forEach(Z=>{let Y=Z.getCanvas()._canvas;Y&&F.drawImage(Y,0,0);}),a?.current){let Z=a.current;F.drawImage(Z,0,0);}};w.current=W,o.current.draw(),W(),await new Promise(Z=>setTimeout(Z,100)),console.log("Creating captureStream..."),M=V.captureStream(30),console.log("Canvas stream created, tracks:",M.getTracks().length);let se=M.getVideoTracks()[0];se&&console.log("Video track:",se.label,"state:",se.readyState);let q=0,_=()=>{W(),o?.current&&(o.current.getLayers().forEach(Y=>{Y.batchDraw();}),q++,q%60===0&&console.log("Drawing frame:",q)),y.current=requestAnimationFrame(_);};_();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{P=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(N){console.warn("Microphone access denied:",N);}let R=[...M.getVideoTracks()];P&&R.push(...P.getAudioTracks());let z=new MediaStream(R);v.current=z;let B="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?B="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?B="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?B="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(B="video/webm;codecs=vp8"),console.log("Using mimeType:",B);let U=new MediaRecorder(z,{mimeType:B,videoBitsPerSecond:25e5});f.current=U,h.current=[],U.ondataavailable=N=>{console.log("Data available, size:",N.data.size),N.data.size>0&&h.current.push(N.data);},U.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let N=new Blob(h.current,{type:B});console.log("Final blob size:",N.size),o?.current&&w.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(F=>{F.batchDraw();}),w.current(),g.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",g.current.length)),z.getTracks().forEach(V=>V.stop()),p.current&&clearInterval(p.current),y.current&&(cancelAnimationFrame(y.current),y.current=null),s(N);},U.onerror=N=>{console.error("MediaRecorder error:",N);},console.log("Starting recording..."),U.start(1e3),i(!0),m(0),p.current=setInterval(()=>{m(N=>N+1);},1e3);}catch(M){console.error("Error starting screen recording:",M),alert("Failed to start recording. Please ensure you granted permission.");}},k=()=>{f.current&&n&&(console.log("Stopping recording, state:",f.current.state),f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),i(false));},S=()=>{if(u){let M=URL.createObjectURL(u),P=document.createElement("a");P.href=M,P.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(M);}},b=M=>{let P=Math.floor(M/60),R=M%60;return `${P.toString().padStart(2,"0")}:${R.toString().padStart(2,"0")}`};if(!r)return null;if(n){let M=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:b(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:k,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(M,r)}let C=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:[!u&&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(!d),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${d?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:d?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:I,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"]})]})]}),u&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(u),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",b(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&g.current&&(t(u,g.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:S,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{s(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(C,r)};var ju=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let n=Ve(),[i,u]=useState(false),[s,c]=useState(null),[m,d]=useState(false),[l,f]=useState(0),h=useRef(null),p=useRef([]),v=useRef(null),y=useRef(null);useEffect(()=>{o&&!s&&fetch(o).then(M=>M.blob()).then(M=>c(M)).catch(M=>console.error("Error loading audio:",M));},[o,s]);let g=async()=>{try{let M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),P=new MediaRecorder(M);h.current=P,p.current=[],P.ondataavailable=R=>{R.data.size>0&&p.current.push(R.data);},P.onstop=()=>{let R=new Blob(p.current,{type:"audio/webm"});c(R),M.getTracks().forEach(z=>z.stop()),v.current&&clearInterval(v.current);},P.start(),u(!0),f(0),v.current=setInterval(()=>{f(R=>R+1);},1e3);}catch(M){console.error("Error starting audio recording:",M),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{h.current&&i&&(h.current.stop(),u(false));},w=()=>{if(s){let M=URL.createObjectURL(s),P=new Audio(M);y.current=P,P.onended=()=>{d(false),URL.revokeObjectURL(M);},P.play(),d(true);}},I=()=>{y.current&&(y.current.pause(),y.current.currentTime=0,d(false));},k=async()=>{if(s){let M=new FileReader;M.onloadend=()=>{let P=M.result;t(P),r();},M.readAsDataURL(s);}},S=()=>{c(null),a();},b=M=>{let P=Math.floor(M/60),R=M%60;return `${P.toString().padStart(2,"0")}:${R.toString().padStart(2,"0")}`};if(!n)return null;if(i){let M=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:b(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:x,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]})});return createPortal(M,n)}let C=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:[!s&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:g,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"]})}),s&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:m?I:w,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:S,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:k,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:r,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})});return createPortal(C,n)};var Ot=({audioData:e,x:o,y:t,width:a,scale:r=1,offsetX:n=0,offsetY:i=0,containerTop:u=90,containerRight:s=320})=>{let[c,m]=useState(false),d=useRef(null),l=p=>{if(p.stopPropagation(),c&&d.current)d.current.pause(),d.current.currentTime=0,m(false);else {let v=new Audio(e);d.current=v,v.onended=()=>{m(false);},v.onerror=()=>{console.error("Error playing audio"),m(false);},v.play(),m(true);}},f=(o+a)*r+n-15,h=t*r+i+u-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${c?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${f}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var $u=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=be(),r=te(ge),n=Ve(),i=useMemo(()=>{if(!r)return [];let y=[];return r.images?.forEach(g=>{y.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),r.videos?.forEach(g=>{y.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),r.shapes?.forEach(g=>{y.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),r.texts?.forEach(g=>{y.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),r.flashcards?.forEach(g=>{y.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),r.photoFrames?.forEach(g=>{y.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),r.multipleChoices?.forEach(g=>{y.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),r.trueFalses?.forEach(g=>{y.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),r.shortAnswers?.forEach(g=>{y.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),r.LongAnswer?.forEach(g=>{y.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),r.fillInTheBlanks?.forEach(g=>{y.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),r.lines?.forEach(g=>{g.id&&y.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),y.sort((g,x)=>x.timestamp-g.timestamp)},[r]),[u,s]=useState(i),[c,m]=useState(false);useEffect(()=>{c||s(i);},[i]);let d=y=>{let g="h-5 w-5";switch(y){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})}},h=y=>{m(true),s(y);},p=()=>{m(false);let y=Date.now();u.forEach((g,x)=>{let w=y-x;a(cr({id:g.id,type:g.type,newTimestamp:w}));});};if(!n)return null;let v=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-50 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-50 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:u.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:u,onReorder:h,className:"space-y-1",children:u.map(y=>{let g=y.id===e;return jsxs(Reorder.Item,{value:y,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(y.id,y.type),className:`font-medium ${g?"text-[#096B76]":"text-[#00000099]"}`,children:y.name})}),jsx("div",{className:`${g?"text-[#096B76]":"text-[#00000099]"}`,children:d(y.type)})]},y.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:[u.length," Layers"]})]})]})]});return createPortal(v,n)};var is=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o*1.2;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;n.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},Yu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n,touchHandlers:i})=>{let u=useSelector(P=>P.toolbar.selectedTool),s=u==="pen"||u==="eraser",[c,m]=useState(new Set),[d,l]=useState(false),[f,h]=useState(null),p=useRef(null);useEffect(()=>{let P=p.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id]);let v=new Set(e.data.responseOptions.correctIndex),y=v.size>1,g=P=>{d||m(y?R=>{let z=new Set(R);return z.has(P)?z.delete(P):z.add(P),z}:new Set([P]));},x=()=>{c.size>0&&l(true);},w=()=>{l(false),m(new Set);},I=c.size===v.size&&Array.from(c).every(P=>v.has(P)),k=Array.from(c).filter(P=>v.has(P)),S=y&&k.length>0&&!I,b=()=>I?"\u2713 Correct! Great job! \u{1F389}":S?`\u26A0 Partially correct (${k.length}/${v.size})`:"\u2717 Try again!",C=()=>I?{bg:"#dcfce7",text:"#166534"}:S?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},M=useMemo(()=>{let F=e.data.feedbackMode==="practice"?48:0,W=12,G=e.width-48,se=G-80,q=Math.max(60,is(e.data.question,20,G,"bold")+20),_=`Select ${v.size} answers (${c.size}/${v.size} selected)`,Z=y&&!d&&e.data.feedbackMode==="practice"?is(_,14,G)+10:0,Y=d&&e.data.feedbackMode==="practice"?Math.max(60,is(b(),16,G-40)+30):0,oe=e.data.responseOptions.options.map(Te=>{let Ie=is(Te,16,se);return Math.max(55,Ie+20)}),J=q+Z+Y,ce=oe.reduce((Te,Ie)=>Te+Ie+8,-8),Se=J+ce+W+F+24;return {padding:24,questionHeight:q,instructionHeight:Z,feedbackHeight:Y,optionsStartY:J,optionHeights:oe,totalHeight:Se,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:F,buttonTopMargin:W,availableWidth:G,optionTextWidth:se}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,d,c.size,v.size,y,b]);return jsxs(Group,{ref:p,name:"mcq-element",draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:M.totalHeight,...i,...s?{}:{onDragEnd:r,onClick:P=>t&&t(e.id),onTap:P=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:M.totalHeight,width:e.width,onTransformEnd:P=>o(e.id,P),onContextMenu:P=>{P.cancelBubble=true,n(P.evt,e.id,"mcq");}}),jsx(Text,{x:M.padding+8,y:M.padding,text:e.data.question,fontSize:M.questionFontSize,fontStyle:"bold",fill:"#111827",width:M.availableWidth,height:M.questionHeight-M.padding,wrap:"word",ellipsis:true,listening:false}),M.instructionHeight>0&&jsx(Text,{x:M.padding,y:M.questionHeight,text:`Select ${v.size} answers (${c.size}/${v.size} selected)`,fontSize:M.instructionFontSize,fill:"#6b7280",width:M.availableWidth,wrap:"word",listening:false}),d&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:M.padding+24,y:M.questionHeight+M.instructionHeight+10,width:M.availableWidth-40,height:M.feedbackHeight-20,fill:C().bg,cornerRadius:8}),jsx(Text,{x:M.padding+24,y:M.questionHeight+M.instructionHeight+10,width:M.availableWidth-40,height:M.feedbackHeight-20,text:b(),fontSize:M.feedbackFontSize,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((P,R)=>{let z=v.has(R),B=c.has(R),U=M.optionsStartY;for(let G=0;G<R;G++)U+=M.optionHeights[G]+M.optionGap;let N=M.optionHeights[R],V="#e5e7eb",F="#ffffff",W="#111827";return d&&z?(V="#22c55e",F="#dcfce7",W="#1B9D2C"):d&&B&&!z?(V="#ef4444",F="#fee2e2",W="#ef4444"):B&&(V="#096B76",F="#ECFFF8",W="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:M.padding+12,y:U+(N-20)/2,width:20,height:20,fill:B?"#096B76":"white",stroke:B?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:y?4:10,onClick:G=>{G.cancelBubble=true,g(R);},onTap:G=>{G.cancelBubble=true,g(R);}}),B&&jsx(Text,{x:M.padding+12,y:U+(N-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:M.padding+44,y:U,width:M.availableWidth-60,height:N,fill:F,stroke:V,strokeWidth:2,cornerRadius:8,onClick:G=>{G.cancelBubble=true,g(R);},onTap:G=>{G.cancelBubble=true,g(R);}}),jsx(Text,{x:M.padding+60,y:U+10,width:M.optionTextWidth,height:N-20,text:P,fontSize:M.optionFontSize,fill:W,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},R)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:M.optionsStartY+M.optionHeights.reduce((P,R)=>P+R+M.optionGap,-M.optionGap)+M.buttonTopMargin,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,h("check");},onMouseUp:P=>{P.cancelBubble=true,h(null),x();},onMouseLeave:P=>{P.cancelBubble=true,h(null);},onTouchStart:P=>{P.cancelBubble=true,h("check");},onTouchEnd:P=>{P.cancelBubble=true,h(null),x();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:M.padding+14,width:(M.availableWidth-24)/(d?2:1),height:M.buttonHeight,fill:c.size===0||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:M.padding+14,width:(M.availableWidth-24)/(d?2:1),height:M.buttonHeight,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-M.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),w();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),w();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:M.padding,width:(M.availableWidth-8)/2,height:M.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:M.padding,width:(M.availableWidth-8)/2,height:M.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Yu.displayName="MultipleChoice";var Zu=Yu;var kx=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;n.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},nl=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:r,touchHandlers:n})=>{let i=useDispatch(),u=useSelector(V=>V.toolbar.selectedTool),s=u==="pen"||u==="eraser",[c,m]=useState(false),[d,l]=useState(new Set),[f,h]=useState(false),[p,v]=useState(false),[y,g]=useState(0),x=new Set(e.data.responseOptions.correctIndex),w=Array.from(d).filter(V=>x.has(V)),I=d.size===x.size&&Array.from(d).every(V=>x.has(V)),k=w.length>0&&!I,S=()=>I?"\u2713 Correct! Great job!":k?`\u26A0 Partially correct (${w.length}/${x.size})`:"\u2717 Try again!",b=useMemo(()=>{let W=window.innerWidth*.4,G=20,se=18,q=28,_=40,Z=50,Y=20,oe=60,J=W-40,ce=Math.max(60,kx(e.data.question,G,J,"bold")+20),Se=340+Y,Te=100+ce+20,Ie=W-Y*2,De=Math.max(150,window.innerHeight*.3),At=e.data.feedbackMode==="practice",Pt=ce+50+De+(f?oe+18:0)+(At?_+(f?Z:0)+20:0),fo=Pt+100;return {screenX:340,screenY:100,screenWidth:W,screenHeight:fo,dropZoneX:Se,dropZoneY:Te,dropZoneWidth:Ie,dropZoneHeight:De,questionFontSize:G,questionHeight:ce,feedbackFontSize:se,feedbackHeight:oe,dropHereFontSize:q,buttonHeight:_,buttonGap:Z,padding:Y,contentWidth:J,totalContentHeight:Pt,isPracticeMode:At}},[e.data.question,e.data.feedbackMode,f,d.size]),C=useRef(null);useEffect(()=>{let V=C.current;if(V)return r.current.set(e.id,V),()=>{r.current.delete(e.id);}},[e.id]);let M=V=>{i(xa({id:e.id,x:V.target.x(),y:V.target.y()}));},P=V=>{let F=V.target,W=F.x(),G=F.y(),se=window.innerWidth*.2,_=W+se>b.dropZoneX&&W<b.dropZoneX+b.dropZoneWidth&&G+50>b.dropZoneY&&G<b.dropZoneY+b.dropZoneHeight;m(_);},R=(V,F)=>{let W=F.target,G=W.x(),se=W.y(),q=window.innerWidth*.2,Z=G+q>b.dropZoneX&&G<b.dropZoneX+b.dropZoneWidth&&se+50>b.dropZoneY&&se<b.dropZoneY+b.dropZoneHeight;l(Z?Y=>new Set(Y).add(V):Y=>{let oe=new Set(Y);return oe.delete(V),oe}),m(false);},z=()=>{h(true);},B=()=>{h(false),l(new Set),g(V=>V+1);},U=()=>I?{bg:"#dcfce7",text:"#166534"}:k?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},N=()=>f?I?"#4CAF50":k?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:C,name:"mcq-element",width:b.screenWidth,height:b.screenHeight,draggable:!s,listening:!s,...n,...s?{}:{onClick:V=>a&&a(e.id),onTap:V=>a&&a(e.id),onContextMenu:V=>{V.evt.preventDefault(),o(V.evt,e.id,"mcq");}},children:[jsxs(Group,{x:b.screenX,y:b.screenY,rotation:e.rotation,onDragEnd:M,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:b.totalContentHeight,width:b.screenWidth,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:b.padding,y:b.padding,width:b.contentWidth,height:b.questionHeight-b.padding,text:e.data.question,fontSize:b.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:b.padding,y:b.questionHeight+20,width:b.dropZoneWidth,height:b.dropZoneHeight,fill:"#EBF6F7",stroke:N(),strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:b.padding+3,y:b.questionHeight+20+b.dropZoneHeight+18,width:b.dropZoneWidth-5,height:b.feedbackHeight,fill:U().bg,cornerRadius:8}),jsx(Text,{x:b.padding,y:b.questionHeight+20+b.dropZoneHeight+20,width:b.dropZoneWidth,height:b.feedbackHeight,text:S(),fontSize:b.feedbackFontSize,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),d.size===0&&!f&&jsx(Text,{x:b.padding,y:b.questionHeight+20,width:b.dropZoneWidth,height:b.dropZoneHeight,text:x.size>1?`Drop ${x.size} Correct Answers Here`:"Drop Here",fontSize:b.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),b.isPracticeMode?jsxs(Group,{x:b.padding,y:b.questionHeight+20+b.dropZoneHeight+(f?b.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:()=>{v(true),z();},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),z();},onTouchEnd:()=>v(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:b.buttonHeight,width:b.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:b.dropZoneWidth,height:b.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:b.buttonGap,onMouseDown:B,onTouchStart:B,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:b.buttonHeight,width:b.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:b.dropZoneWidth,height:b.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((V,F)=>{let W=F%2,G=Math.floor(F/2),se=window.innerWidth*.2,q=50,_=10,Z=d.has(F),Y=x.has(F),oe=f&&Z,J="transparent";return oe?J=Y?"#4CAF50":"#ef4444":Z&&(J="#4CAF50"),jsxs(Group,{x:340+W*(se+_),y:b.screenY+b.totalContentHeight+G*(q+_)+20,draggable:!f,onDragMove:P,onDragEnd:ce=>R(F,ce),opacity:f&&!Z?.5:1,children:[jsx(Rect,{width:se-20,height:q,fill:"white",stroke:J,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:se-20,height:q,text:V,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${F}-${y}`)})]})};nl.displayName="MultipleChoiceDragAndDrop";var Ju=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n,onLongPress:i})=>{let{createHandlers:u}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(Zu,{multipleChoice:s,handleMcqTransform:o,mcqRefs:a,handleDragEnd:c=>r(c,s.id),onContextMenu:n,touchHandlers:u(s.id,"mcq")},s.id):jsx(nl,{multipleChoice:s,handleMcqTransform:o,mcqRefs:a,onContextMenu:n,touchHandlers:u(s.id,"mcq")},s.id))})};var Qu=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o*1.2;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;n.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},ec=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i})=>{let u=useSelector(b=>b.toolbar.selectedTool),s=u==="pen"||u==="eraser",[c,m]=useState(null),[d,l]=useState(false),[f,h]=useState(null),p=useRef(null);useEffect(()=>{let b=p.current;if(b)return a.current.set(e.id,b),()=>{a.current.delete(e.id);}},[e.id]);let v=()=>{c!==null&&l(true);},y=()=>{l(false),m(null);},g=e.data.responseOptions.correctAnswer,x=c===g,w=b=>{d||m(b);},I=()=>x?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",k=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},S=useMemo(()=>{let B=e.data.feedbackMode==="practice"?48:0,U=12,N=e.width-48,V=Math.max(60,Qu(e.data.question,20,N,"bold")+20),F=d&&e.data.feedbackMode==="practice"?Math.max(60,Qu(I(),16,N-40)+30):0,W=V+F,G=164,se=W+G+U+B+24;return {padding:24,questionHeight:V,feedbackHeight:F,optionsStartY:W,optionsHeight:G,totalHeight:se,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:B,buttonTopMargin:U,availableWidth:N}},[e.width,e.data.question,e.data.feedbackMode,d,I]);return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:S.totalHeight,...i,...s?{}:{onDragEnd:b=>n(b,e.id),onClick:b=>t&&t(e.id),onTap:b=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:S.totalHeight,width:e.width,onTransformEnd:b=>o(e.id,b),onContextMenu:b=>{b.cancelBubble=true,r(b.evt,e.id,"trueFalse");}}),jsx(Text,{x:S.padding+8,y:S.padding,text:e.data.question,fontSize:S.questionFontSize,fontStyle:"bold",fill:"#111827",width:S.availableWidth,height:S.questionHeight-S.padding,wrap:"word",ellipsis:true,listening:false}),d&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:S.padding+24,y:S.questionHeight+10,width:S.availableWidth-40,height:S.feedbackHeight-20,fill:k().bg,cornerRadius:8}),jsx(Text,{x:S.padding+24,y:S.questionHeight+10,width:S.availableWidth-40,height:S.feedbackHeight-20,text:I(),fontSize:S.feedbackFontSize,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((b,C)=>{let M=g===b.value,P=c===b.value,R=(e.width-S.padding*3)/2,z=S.padding+C*(R+S.padding),B=S.optionsStartY,U=b.value===true,N=U?"#10b981":"#ef4444",V="#ffffff",F="#ffffff",W="#e5e7eb";return d&&(M?(F=U?"#f0fdf4":"#fef2f2",W=U?"#86efac":"#fecaca"):P&&!M&&(F="#fee2e2",W="#ef4444")),P&&!d&&(W="#096B76",F="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:z,y:B,width:R,height:S.optionHeight+50,fill:F,stroke:W,strokeWidth:2,cornerRadius:12,onClick:G=>{G.cancelBubble=true,w(b.value);},onTap:G=>{G.cancelBubble=true,w(b.value);}}),jsx(Circle,{x:z+R/2,y:B+40,radius:28,fill:N,listening:false}),U?jsx(Text,{x:z+R/2-14,y:B+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:V,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:z+R/2-14,y:B+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:V,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:z,y:B+85,width:R,height:30,text:b.label,fontSize:S.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},b.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:S.optionsStartY+2*(S.optionHeight+S.optionGap)+S.buttonTopMargin,children:[jsxs(Group,{onMouseDown:b=>{b.cancelBubble=true,h("check");},onMouseUp:b=>{b.cancelBubble=true,h(null),v();},onMouseLeave:b=>{b.cancelBubble=true,h(null);},onTouchStart:b=>{b.cancelBubble=true,h("check");},onTouchEnd:b=>{b.cancelBubble=true,h(null),v();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:S.padding+14,width:(S.availableWidth-24)/(d?2:1),height:S.buttonHeight,fill:c===null||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:b=>b.cancelBubble=true,onTap:b=>b.cancelBubble=true}),jsx(Text,{x:S.padding+14,width:(S.availableWidth-24)/(d?2:1),height:S.buttonHeight,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-S.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),y();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),y();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:S.padding,width:(S.availableWidth-8)/2,height:S.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:b=>b.cancelBubble=true,onTap:b=>b.cancelBubble=true}),jsx(Text,{x:S.padding,width:(S.availableWidth-8)/2,height:S.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});ec.displayName="TrueFalse";var tc=ec;var qx="#FFFFFF",ll=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t,touchHandlers:a})=>{let r=useDispatch(),n=useSelector(Y=>Y.toolbar.selectedTool),i=n==="pen"||n==="eraser",[u,s]=useState(false),[c,m]=useState(null),[d,l]=useState(false),[f,h]=useState(false),[p,v]=useState(0),[y,g]=useState(false),x=340,w=100,I=window.innerWidth*.4,k=window.innerHeight*.5,S=I-40,b=k-300,C=20,M=60,P=S,R=b,z=I*.2-40,B=50,U=useRef(null),N=Y=>{r(ba({id:e.id,x:Y.target.x(),y:Y.target.y()}));},V=Y=>{let oe=Y.target,J=oe.x(),ce=oe.y(),Se=Math.max(0,Math.min(J+z,C+P)-Math.max(J,C)),Te=Math.max(0,Math.min(ce+B,M+R)-Math.max(ce,M)),Ie=Se*Te,De=z*B;s(Ie/De>=.5);},F=(Y,oe)=>{let J=oe.target,ce=J.x(),Se=J.y(),Te=Math.max(0,Math.min(ce+z,C+P)-Math.max(ce,C)),Ie=Math.max(0,Math.min(Se+B,M+R)-Math.max(Se,M)),De=Te*Ie,At=z*B;if(De/At>=.5)m(Y);else return;s(false);},W=()=>{l(true);},G=()=>{l(false),m(null),v(Y=>Y+1);},se=e.data.responseOptions.correctAnswer,q=c===se,_=()=>q?"\u2713 Correct! Great job!":"\u2717 Try again!",Z=()=>q?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:U,name:"trueFalse-element",width:I,height:k,draggable:!i,listening:!i,...a,...i?{}:{onContextMenu:Y=>{Y.evt.preventDefault(),o(Y.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:w,rotation:e.rotation,onDragEnd:N,children:[jsx(Rect,{fill:"white",stroke:u?"#4CAF50":"#e5e7eb",strokeWidth:u?4:2,cornerRadius:12,height:d?k:e.data.feedbackMode==="practice"?k-50:k-100,width:I,shadowColor:u?"#4CAF50":"transparent",shadowBlur:u?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:I-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:S,height:b,fill:"transparent",stroke:u?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:S,height:60,fill:Z().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:S,height:60,text:_(),fontSize:18,fontStyle:"bold",fill:Z().text,align:"center",verticalAlign:"middle"})]}),c===null&&!d&&jsx(Text,{x:20,y:60,width:S,height:b-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:k-100,children:[jsxs(Group,{onMouseDown:()=>{c!==null&&(h(true),W());},onMouseUp:()=>h(false),onMouseLeave:()=>h(false),onTouchStart:()=>{c!==null&&(h(true),W());},onTouchEnd:()=>h(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:c===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{y:50,onMouseDown:G,onTouchStart:G,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((Y,oe)=>{let J=window.innerWidth*.2,ce=50,Se=10,Te=c===Y.value,Ie=se===Y.value,De=d&&Te,At="transparent";return De?At=Ie?"#4CAF50":"#ef4444":Te&&(At="#4CAF50"),jsxs(Group,{x:16+oe*(J+Se),y:w+k-300,draggable:!d,onDragMove:V,onDragEnd:Pt=>F(Y.value,Pt),opacity:d&&!Te?.5:1,children:[jsx(Rect,{width:J-40,height:ce,fill:"#075560",stroke:At,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:J-40,height:ce,text:Y.label,fontSize:18,fontStyle:"bold",fill:qx,align:"center",verticalAlign:"middle",listening:false})]},`${Y.value}-${p}`)})]})})};ll.displayName="TrueFalseDragAndDrop";var ac=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:n,onLongPress:i})=>{let{createHandlers:u}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(tc,{trueFalse:s,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:u(s.id,"trueFalse")},s.id):jsx(ll,{trueFalse:s,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:n,touchHandlers:u(s.id,"trueFalse")},s.id))})};var Ca=new WeakMap,Do=new WeakMap,Mr={current:[]},ul=false,Tr=0,kr=new Set,ls=new Map;function oc(e){let o=Array.from(e).sort((t,a)=>t instanceof Gt&&t.options.deps.includes(a)?1:a instanceof Gt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(Mr.current.includes(t))continue;Mr.current.push(t),t.recompute();let a=Do.get(t);if(a)for(let r of a){let n=Ca.get(r);n&&oc(n);}}}function zx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Wx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function ds(e){if(Tr>0&&!ls.has(e)&&ls.set(e,e.prevState),kr.add(e),!(Tr>0)&&!ul)try{for(ul=!0;kr.size>0;){let o=Array.from(kr);kr.clear();for(let t of o){let a=ls.get(t)??t.prevState;t.prevState=a,zx(t);}for(let t of o){let a=Ca.get(t);a&&(Mr.current.push(t),oc(a));}for(let t of o){let a=Ca.get(t);if(a)for(let r of a)Wx(r);}}}finally{ul=false,Mr.current=[],ls.clear();}}function Lt(e){Tr++;try{e();}finally{if(Tr--,Tr===0){let o=kr.values().next().value;o&&ds(o);}}}function rc(e){return typeof e=="function"}var Qt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,n;this.listeners.add(a);let i=(n=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:n.call(r,a,this);return ()=>{this.listeners.delete(a),i?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,r;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):rc(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),ds(this);}};var Gt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),r=new Array(t);for(let n=0;n<t;n++){let i=this.options.deps[n];a[n]=i.prevState,r[n]=i.state;}return this.lastSeenDepValues=r,{prevDepVals:a,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let n of this.options.deps)n instanceof e&&n.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let n=0;n<r.length;n++)if(r[n]!==a[n]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,r;this.listeners.add(t);let n=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),n?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof Qt){let a=Ca.get(t);a||(a=new Set,Ca.set(t,a)),a.add(this);let r=Do.get(this);r||(r=new Set,Do.set(this,r)),r.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof Qt){let a=Ca.get(t);a&&a.delete(this);let r=Do.get(this);r&&r.delete(t);}}};function Kx(e){return typeof e=="function"}function cl(e,...o){return Kx(e)?e(...o):e}function nc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ka,ht,it,Ar,Ta,$a,ra,Ro,Pr,us,Er,Fo,Ya=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Re(this,ka,true);Re(this,ht);Re(this,it);Re(this,Ar);Re(this,Ta);Re(this,$a);Re(this,ra);Re(this,Ro);Re(this,Pr,0);Re(this,us,5);Re(this,Er,()=>{this.debugLog("Connected to event bus"),Ae(this,$a,true),this.debugLog("Emitting queued events",j(this,Ta)),j(this,Ta).forEach(o=>this.emitEventToBus(o)),Ae(this,Ta,[]),this.stopConnectLoop(),j(this,it).call(this).removeEventListener("tanstack-connect-success",j(this,Er));});Re(this,Fo,()=>{if(j(this,it).call(this).addEventListener("tanstack-connect-success",j(this,Er)),j(this,Pr)<j(this,us)){Ed(this,Pr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}j(this,it).call(this).removeEventListener("tanstack-connect",j(this,Fo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Ae(this,ht,o),Ae(this,ka,a),Ae(this,it,this.getGlobalTarget),Ae(this,Ar,t),this.debugLog(" Initializing event subscription for plugin",j(this,ht)),Ae(this,Ta,[]),Ae(this,$a,false),Ae(this,ra,null),Ae(this,Ro,r);}startConnectLoop(){j(this,ra)!==null||j(this,$a)||(this.debugLog(`Starting connect loop (every ${j(this,Ro)}ms)`),Ae(this,ra,setInterval(j(this,Fo),j(this,Ro))));}stopConnectLoop(){j(this,ra)!==null&&(clearInterval(j(this,ra)),Ae(this,ra,null),this.debugLog("Stopped connect loop"));}debugLog(...o){j(this,Ar)&&console.log(`\u{1F334} [tanstack-devtools:${j(this,ht)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return j(this,ht)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});j(this,it).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{j(this,it).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!j(this,ka)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!j(this,$a)){this.debugLog("Bus not available, will be pushed as soon as connected"),j(this,Ta).push({type:`${j(this,ht)}:${o}`,payload:t,pluginId:j(this,ht)}),typeof CustomEvent<"u"&&(j(this,Fo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${j(this,ht)}:${o}`,payload:t,pluginId:j(this,ht)})}on(o,t){let a=`${j(this,ht)}:${o}`;if(!j(this,ka))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=n=>{this.debugLog("Received event from bus",n.detail),t(n.detail);};return j(this,it).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{j(this,it).call(this).removeEventListener(a,r);}}onAll(o){if(!j(this,ka))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return j(this,it).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,it).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!j(this,ka))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;j(this,ht)&&r.pluginId!==j(this,ht)||o(r);};return j(this,it).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,it).call(this).removeEventListener("tanstack-devtools-global",t)}};ka=new WeakMap,ht=new WeakMap,it=new WeakMap,Ar=new WeakMap,Ta=new WeakMap,$a=new WeakMap,ra=new WeakMap,Ro=new WeakMap,Pr=new WeakMap,us=new WeakMap,Er=new WeakMap,Fo=new WeakMap;var fl=class extends Ya{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},sc=(e,o)=>{ml.emit(e,o);},ml=new fl;function ic(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Gx={enabled:true,leading:true,trailing:true,wait:0},Ma,It,Za,Ja,Qa,Bo,cs=class{constructor(o,t){Re(this,Ma);Re(this,It);Re(this,Za);Re(this,Ja);Re(this,Qa);Re(this,Bo);this.fn=o,this.store=new Qt(ic()),this.setOptions=a=>{this.options={...this.options,...a},j(this,Za).call(this)||this.cancel();},Ae(this,It,a=>{this.store.setState(r=>{let n={...r,...a},{isPending:i}=n;return {...n,status:j(this,Za).call(this)?i?"pending":"idle":"disabled"}}),sc("Throttler",this);}),Ae(this,Za,()=>!!cl(this.options.enabled,this)),Ae(this,Ja,()=>cl(this.options.wait,this)),this.maybeExecute=(...a)=>{j(this,It).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),n=r-this.store.state.lastExecutionTime,i=j(this,Ja).call(this);if(this.options.leading&&n>=i)j(this,Qa).call(this,...a);else if(j(this,It).call(this,{lastArgs:a}),!j(this,Ma)&&this.options.trailing){let u=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,s=i-u;j(this,It).call(this,{isPending:true}),Ae(this,Ma,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&j(this,Qa).call(this,...c);},s));}},Ae(this,Qa,(...a)=>{if(!j(this,Za).call(this))return;this.fn(...a);let r=Date.now(),n=r+j(this,Ja).call(this);j(this,Bo).call(this),j(this,It).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:n,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||j(this,It).call(this,{nextExecutionTime:void 0});},j(this,Ja).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&j(this,Qa).call(this,...this.store.state.lastArgs);},Ae(this,Bo,()=>{j(this,Ma)&&(clearTimeout(j(this,Ma)),Ae(this,Ma,void 0));}),this.cancel=()=>{j(this,Bo).call(this),j(this,It).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{j(this,It).call(this,ic());},this.key=nc(t.key),this.options={...Gx,...t},j(this,It).call(this,this.options.initialState??{}),ml.on("d-Throttler",a=>{a.payload.key===this.key&&(j(this,It).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Ma=new WeakMap,It=new WeakMap,Za=new WeakMap,Ja=new WeakMap,Qa=new WeakMap,Bo=new WeakMap;function pl(e,o){return new cs(e,o).maybeExecute}function Aa(e,o){return typeof e=="function"?e(o):e}function Pa(e,o){return hs(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function Oo(e,o,t){let a=hs(o);function r(n){if(!a.length)return Aa(t,n);let i=a.shift();if(typeof i=="string"||typeof i=="number"&&!Array.isArray(n))return typeof n=="object"?(n===null&&(n={}),{...n,[i]:r(n[i])}):{[i]:r()};if(Array.isArray(n)&&typeof i=="number"){let u=n.slice(0,i);return [...u.length?u:new Array(i),r(n[i]),...n.slice(i+1)]}return [...new Array(i),r()]}return r(e)}function gl(e,o){let t=hs(o);function a(r){if(!r)return;if(t.length===1){let i=t[0];if(Array.isArray(r)&&typeof i=="number")return r.filter((c,m)=>m!==i);let{[i]:u,...s}=r;return s}let n=t.shift();if(typeof n=="string"&&typeof r=="object")return {...r,[n]:a(r[n])};if(typeof n=="number"&&Array.isArray(r)){if(n>=r.length)return r;let i=r.slice(0,n);return [...i.length?i:new Array(n),a(r[n]),...r.slice(n+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var jx=/^(\d+)$/gm,_x=/\.(\d+)(?=\.)/gm,Xx=/^(\d+)\./gm,$x=/\.(\d+$)/gm,Yx=/\.{2,}/gm,hl="__int__",fs=`${hl}$1`;function hs(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(jx,fs).replace(_x,`.${fs}.`).replace(Xx,`${fs}.`).replace($x,`.${fs}`).replace(Yx,".").split(".").map(o=>{if(o.startsWith(hl)){let t=o.substring(hl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function xl(e){return !(Array.isArray(e)&&e.length===0)}function No(e,o){let t=a=>a.validators.filter(Boolean).map(r=>({cause:r.cause,validate:r.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Ho(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:n}=o.validators||{},i=t??0,u=s=>s.validators.filter(Boolean).map(c=>{let m=c?.cause||e,d=i;switch(m){case "change":d=r??i;break;case "blur":d=a??i;break;case "dynamic":d=n??i;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:m,validate:c.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var Dr=e=>!!e&&typeof e=="object"&&"fields"in e;function Ea(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[r,n]of e)if(!o.has(r)||!Object.is(n,o.get(r)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let r of e)if(!o.has(r))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let r of t)if(!a.includes(r)||!Ea(e[r],o[r]))return false;return true}var gs=({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},xs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Ze(e,o){return e==null?o:{...e,...o}}var eo=256,ps=[],ms;for(;eo--;)ps[eo]=(eo+256).toString(16).substring(1);function bl(){let e=0,o,t="";if(!ms||eo+16>256){for(ms=new Array(256),e=256;e--;)ms[e]=256*Math.random()|0;e=0,eo=0;}for(;e<16;e++)o=ms[eo+e],e===6?t+=ps[o&15|64]:e===8?t+=ps[o&63|128]:t+=ps[o],e&1&&e>1&&e<11&&(t+="-");return eo++,t}var Da=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},n={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},i=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,r,n,i],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,i],form:e.form});case "change":return e.runValidation({validators:[a,i],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Zx(e,o){let t=new Map;for(let a of e){let r=a.path??[],n=o,i="";for(let u=0;u<r.length;u++){let s=r[u];if(s===void 0)continue;let c=typeof s=="object"?s.key:s,m=Number(c);Array.isArray(n)&&!Number.isNaN(m)?i+=`[${m}]`:i+=(u>0?".":"")+String(c),typeof n=="object"&&n!==null?n=n[c]:n=void 0;}t.set(i,(t.get(i)??[]).concat(a));}return Object.fromEntries(t)}var lc=(e,o)=>{let t=Zx(e,o);return {form:t,fields:t}},Ra={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:lc(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:lc(a.issues,e)}},bs=e=>!!e&&"~standard"in e;var qo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function Rr(e){function o(d,l,f,h){let p=a(d,l,f,h);({insert:()=>u(p,d,l),remove:()=>s(p),swap:()=>h!==void 0&&m(p,d,l,h),move:()=>h!==void 0&&c(p,d,l,h)})[f]();}function t(d,l){return `${d}[${l}]`}function a(d,l,f,h){let p=[t(d,l)];if(f==="swap")p.push(t(d,h));else if(f==="move"){let[v,y]=[Math.min(l,h),Math.max(l,h)];for(let g=v;g<=y;g++)p.push(t(d,g));}else {let v=e.getFieldValue(d),y=Array.isArray(v)?v.length:0;for(let g=l+1;g<y;g++)p.push(t(d,g));}return Object.keys(e.fieldInfo).filter(v=>p.some(y=>v.startsWith(y)))}function r(d,l){return d.replace(/\[(\d+)\]/,(f,h)=>{let p=parseInt(h,10);return `[${l==="up"?p+1:Math.max(0,p-1)}]`})}function n(d,l){(l==="up"?d:[...d].reverse()).forEach(h=>{let p=r(h.toString(),l),v=e.getFieldMeta(p);v?e.setFieldMeta(h,v):e.setFieldMeta(h,i());});}let i=()=>qo,u=(d,l,f)=>{n(d,"down"),d.forEach(h=>{h.toString().startsWith(t(l,f))&&e.setFieldMeta(h,i());});},s=d=>{n(d,"up");},c=(d,l,f,h)=>{let p=new Map(Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,f))).map(v=>[v,e.getFieldMeta(v)]));n(d,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,h))).forEach(v=>{let y=v.replace(t(l,h),t(l,f)),g=p.get(y);g&&e.setFieldMeta(v,g);});},m=(d,l,f,h)=>{d.forEach(p=>{if(!p.toString().startsWith(t(l,f)))return;let v=p.toString().replace(t(l,f),t(l,h)),[y,g]=[e.getFieldMeta(p),e.getFieldMeta(v)];y&&e.setFieldMeta(v,y),g&&e.setFieldMeta(p,g);});};return {handleArrayFieldMetaShift:o}}var vl=class extends Ya{constructor(){super({pluginId:"form-devtools"});}},Ct=new vl;function yl(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var Br=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),n=()=>{a(),r(),Ct.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:i}=this.options.validators||{};return Ct.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),i&&this.validateSync("mount"),n},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let n=!!a.transform?.deps?.some((s,c)=>s!==this.prevTransformArray[c]),i=a.defaultValues&&!Ea(a.defaultValues,r.defaultValues)&&!this.state.isTouched,u=!Ea(a.defaultState,r.defaultState)&&!this.state.isTouched;!i&&!u&&!n||(Lt(()=>{this.baseStore.setState(()=>yl(Object.assign({},this.state,u?a.defaultState:{},i?{values:a.defaultValues}:{},n?{_force_re_eval:!this.state._force_re_eval}:{})));}),Ct.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:n}=this.state,i=this.resetFieldMeta(n);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>yl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:i}));},this.validateAllFields=async a=>{let r=[];return Lt(()=>{Object.values(this.fieldInfo).forEach(i=>{if(!i.instance)return;let u=i.instance;r.push(Promise.resolve().then(()=>u.validate(a,{skipFormValidation:!0}))),i.instance.state.meta.isTouched||i.instance.setMeta(s=>({...s,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,n)=>{let i=this.getFieldValue(a),u=Array.isArray(i)?Math.max(i.length-1,0):null,s=[`${a}[${r}]`];for(let l=r+1;l<=(u??0);l++)s.push(`${a}[${l}]`);let c=Object.keys(this.fieldInfo).filter(l=>s.some(f=>l.startsWith(f))),m=[];return Lt(()=>{c.forEach(l=>{m.push(Promise.resolve().then(()=>this.validateField(l,n)));});}),(await Promise.all(m)).flat()},this.validateField=(a,r)=>{let n=this.fieldInfo[a]?.instance;return n?(n.state.meta.isTouched||n.setMeta(i=>({...i,isTouched:true})),n.validate(r)):[]},this.validateSync=a=>{let r=No(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Da}),n=false,i={};return Lt(()=>{for(let c of r){if(!c.validate)continue;let m=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:l}=vs(m),f=Fr(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let p=this.getFieldMeta(h);if(!p)continue;let{errorMap:v,errorSourceMap:y}=p,g=l?.[h],{newErrorValue:x,newSource:w}=gs({newFormValidatorError:g,isPreviousErrorFromFormValidator:y?.[f]==="form",previousErrorValue:v?.[f]});w==="form"&&(i[h]={...i[h],[f]:g}),v?.[f]!==x&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[f]:x},errorSourceMap:{...I.errorSourceMap,[f]:w}}));}this.state.errorMap?.[f]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:d}})),(d||l)&&(n=!0);}let u=Fr("submit");this.state.errorMap?.[u]&&a!=="submit"&&!n&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let s=Fr("server");this.state.errorMap?.[s]&&a!=="server"&&!n&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[s]:void 0}}));}),{hasErrored:n,fieldsErrorMap:i}},this.validateAsync=async a=>{let r=Ho(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Da});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let n=[],i;for(let c of r){if(!c.validate)continue;let m=Fr(c.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[m]={lastAbortController:l},n.push(new Promise(async f=>{let h;try{h=await new Promise((g,x)=>{setTimeout(async()=>{if(l.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(w){x(w);}},c.debounceMs);});}catch(g){h=g;}let{formError:p,fieldErrors:v}=vs(h);v&&(i=i?{...i,...v}:v);let y=Fr(c.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let x=this.getFieldMeta(g);if(!x)continue;let{errorMap:w,errorSourceMap:I}=x,k=i?.[g],{newErrorValue:S,newSource:b}=gs({newFormValidatorError:k,isPreviousErrorFromFormValidator:I?.[y]==="form",previousErrorValue:w?.[y]});w?.[y]!==S&&this.setFieldMeta(g,C=>({...C,errorMap:{...C.errorMap,[y]:S},errorSourceMap:{...C.errorSourceMap,[y]:b}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[y]:p}})),f(i?{fieldErrors:i,errorMapKey:y}:void 0);}));}let u=[],s={};if(n.length){u=await Promise.all(n);for(let c of u)if(c?.fieldErrors){let{errorMapKey:m}=c;for(let[d,l]of Object.entries(c.fieldErrors)){let h={...s[d]||{},[m]:l};s[d]=h;}}}return this.baseStore.setState(c=>({...c,isFormValidating:false})),s},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:n}=this.validateSync(a);return r&&!this.options.asyncAlways?n:this.validateAsync(a)},this.getFieldValue=a=>Pa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var r;return (r=this.fieldInfo)[a]||(r[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,r)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:Aa(r,n.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,n)=>{let i=n;return r[i]=qo,r},{}),this.setFieldValue=(a,r,n)=>{let i=n?.dontUpdateMeta??false,u=n?.dontRunListeners??false,s=n?.dontValidate??false;Lt(()=>{i||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:Oo(c.values,a,r)}));}),u||this.getFieldInfo(a).instance?.triggerOnChangeListener(),s||this.validateField(a,"change");},this.deleteField=a=>{let n=[...Object.keys(this.fieldInfo).filter(i=>{let u=a.toString();return i!==u&&i.startsWith(u)}),a];this.baseStore.setState(i=>{let u={...i};return n.forEach(s=>{u.values=gl(u.values,s),delete this.fieldInfo[s],delete u.fieldMetaBase[s];}),u});},this.pushFieldValue=(a,r,n)=>{this.setFieldValue(a,i=>[...Array.isArray(i)?i:[],r],n);},this.insertFieldValue=async(a,r,n,i)=>{this.setFieldValue(a,s=>[...s.slice(0,r),n,...s.slice(r)],Ze(i,{dontValidate:true}));let u=i?.dontValidate??false;u||await this.validateField(a,"change"),Rr(this).handleArrayFieldMetaShift(a,r,"insert"),u||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,n,i)=>{this.setFieldValue(a,s=>s.map((c,m)=>m===r?n:c),Ze(i,{dontValidate:true})),(i?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,n)=>{let i=this.getFieldValue(a),u=Array.isArray(i)?Math.max(i.length-1,0):null;if(this.setFieldValue(a,c=>c.filter((m,d)=>d!==r),Ze(n,{dontValidate:true})),Rr(this).handleArrayFieldMetaShift(a,r,"remove"),u!==null){let c=`${a}[${u}]`;this.deleteField(c);}(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,n,i)=>{this.setFieldValue(a,s=>{let c=s[r],m=s[n];return Oo(Oo(s,`${r}`,m),`${n}`,c)},Ze(i,{dontValidate:true})),Rr(this).handleArrayFieldMetaShift(a,r,"swap",n),(i?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.moveFieldValues=(a,r,n,i)=>{this.setFieldValue(a,s=>{let c=[...s];return c.splice(n,0,c.splice(r,1)[0]),c},Ze(i,{dontValidate:true})),Rr(this).handleArrayFieldMetaShift(a,r,"move",n),(i?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.clearFieldValues=(a,r)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,[],Ze(r,{dontValidate:true})),i!==null)for(let s=0;s<=i;s++){let c=`${a}[${s}]`;this.deleteField(c);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:qo},values:this.options.defaultValues?Oo(r.values,a,Pa(this.options.defaultValues,a)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[r,n])=>(Object.keys(n).length&&n.errors.length&&(a[r]={errors:n.errors,errorMap:n.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Ra.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ra.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??bl(),this._devtoolsSubmissionOverride=false,this.baseStore=new Qt(yl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Gt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let i=n,u=a?.[0],s=r[0],c=0,m={};for(let d of Object.keys(s.fieldMetaBase)){let l=s.fieldMetaBase[d],f=u?.fieldMetaBase[d],h=i?.[d],p=Pa(s.values,d),v=h?.errors;if(!f||l.errorMap!==f.errorMap){v=Object.values(l.errorMap??{}).filter(I=>I!==void 0);let w=this.getFieldInfo(d)?.instance;w&&!w.options.disableErrorFlat&&(v=v?.flat(1));}let y=!xl(v??[]),g=!l.isDirty,x=Ea(p,Pa(this.options.defaultValues,d))||Ea(p,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===y&&h.isDefaultValue===x&&h.errors===v&&l===f){m[d]=h,c++;continue}m[d]={...l,errors:v,isPristine:g,isValid:y,isDefaultValue:x};}return Object.keys(s.fieldMetaBase).length&&i&&c===Object.keys(s.fieldMetaBase).length?i:m}}),this.store=new Gt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let i=n,u=a?.[0],s=r[0],c=r[1],m=Object.values(c).filter(Boolean),d=m.some(B=>B.isValidating),l=m.every(B=>B.isValid),f=m.some(B=>B.isTouched),h=m.some(B=>B.isBlurred),p=m.every(B=>B.isDefaultValue),v=f&&s.errorMap?.onMount,y=m.some(B=>B.isDirty),g=!y,x=!!(s.errorMap?.onMount||m.some(B=>B?.errorMap?.onMount)),w=!!d,I=i?.errors??[];(!u||s.errorMap!==u.errorMap)&&(I=Object.values(s.errorMap).reduce((B,U)=>U===void 0?B:U&&Dr(U)?(B.push(U.form),B):(B.push(U),B),[]));let k=I.length===0,S=l&&k,b=this.options.canSubmitWhenInvalid??false,C=s.submissionAttempts===0&&!f&&!x||!w&&!s.isSubmitting&&S||b,M=s.errorMap;if(v&&(I=I.filter(B=>B!==s.errorMap.onMount),M=Object.assign(M,{onMount:void 0})),i&&u&&i.errorMap===M&&i.fieldMeta===this.fieldMetaDerived.state&&i.errors===I&&i.isFieldsValidating===d&&i.isFieldsValid===l&&i.isFormValid===k&&i.isValid===S&&i.canSubmit===C&&i.isTouched===f&&i.isBlurred===h&&i.isPristine===g&&i.isDefaultValue===p&&i.isDirty===y&&Ea(u,s))return i;let P={...s,errorMap:M,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:l,isFormValid:k,isValid:S,canSubmit:C,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:p,isDirty:y},R=this.options.transform?.deps??[];if(R.length!==this.prevTransformArray.length||R.some((B,U)=>B!==this.prevTransformArray[U])){let B=Object.assign({},this,{state:P});this.options.transform?.fn(B),P=B.state,this.prevTransformArray=R;}return P}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=pl(a=>Ct.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),Ct.on("request-form-state",a=>{a.payload.id===this._formId&&Ct.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Ct.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),Ct.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 bs(o.validate)?Ra[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(r=>({...r,isSubmitted:false,submissionAttempts:r.submissionAttempts+1,isSubmitSuccessful:false})),Lt(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(n=>({...n,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(r=>({...r,isSubmitting:true}));let a=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Ct.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(r=>r.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Ct.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}Lt(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance?.options.listeners?.onSubmit?.({value:r.instance.state.value,fieldApi:r.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),Lt(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),Ct.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(n=>({...n,isSubmitSuccessful:false})),Ct.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){Lt(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(Dr(a)){let{formError:n,fieldErrors:i}=vs(a);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,c=>({...c,errorMap:{...c.errorMap,[r]:i?.[u]},errorSourceMap:{...c.errorSourceMap,[r]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[r]:n}}));}else this.baseStore.setState(n=>({...n,errorMap:{...n.errorMap,[r]:a}}));});});}};function vs(e){if(e){if(Dr(e)){let o=vs(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function Fr(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 Or=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let n=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});n&&this.setMeta(i=>({...i,errorMap:{...i?.errorMap,onMount:n},errorSourceMap:{...i?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let r=Pa(t.form.options.defaultValues,t.name),n=t.defaultValue??r;a?this.setValue(i=>i||n,{dontUpdateMeta:true}):n!==void 0&&this.setValue(n,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Ze(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Ze(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,Ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,Ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Ze(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,Ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,Ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Ze(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),r=[];for(let n of a){if(!n.instance)continue;let{onChangeListenTo:i,onBlurListenTo:u}=n.instance.options.validators||{};t==="change"&&i?.includes(this.name)&&r.push(n.instance),t==="blur"&&u?.includes(this.name)&&r.push(n.instance);}return r},this.validateSync=(t,a)=>{let r=No(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Da}),i=this.getLinkedFields(t).reduce((c,m)=>{let d=No(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Da});return d.forEach(l=>{l.field=m;}),c.concat(d)},[]),u=false;Lt(()=>{let c=(m,d)=>{let l=ys(d.cause),f=d.validate?dc(m.runValidator({validate:d.validate,value:{value:m.store.state.value,validationSource:"field",fieldApi:m},type:"validate"})):void 0,h=a[l],{newErrorValue:p,newSource:v}=xs({formLevelError:h,fieldLevelError:f});m.state.meta.errorMap?.[l]!==p&&m.setMeta(y=>({...y,errorMap:{...y.errorMap,[l]:p},errorSourceMap:{...y.errorSourceMap,[l]:v}})),p&&(u=!0);};for(let m of r)c(this,m);for(let m of i)m.validate&&c(m.field,m);});let s=ys("submit");return this.state.meta.errorMap?.[s]&&t!=="submit"&&!u&&this.setMeta(c=>({...c,errorMap:{...c.errorMap,[s]:void 0},errorSourceMap:{...c.errorSourceMap,[s]:void 0}})),{hasErrored:u}},this.validateAsync=async(t,a)=>{let r=Ho(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Da}),n=await a,i=this.getLinkedFields(t),u=i.reduce((l,f)=>{let h=Ho(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Da});return h.forEach(p=>{p.field=f;}),l.concat(h)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of i)l.setMeta(f=>({...f,isValidating:true}));let s=[],c=[],m=(l,f,h)=>{let p=ys(f.cause);l.getInfo().validationMetaMap[p]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:y},h.push(new Promise(async g=>{let x;try{x=await new Promise((b,C)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(y.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:f.validate,value:{value:l.store.state.value,fieldApi:l,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(M){C(M);}},f.debounceMs);});}catch(b){x=b;}if(y.signal.aborted)return g(void 0);let w=dc(x),I=n[this.name]?.[p],{newErrorValue:k,newSource:S}=xs({formLevelError:I,fieldLevelError:w});l.setMeta(b=>({...b,errorMap:{...b?.errorMap,[p]:k},errorSourceMap:{...b.errorSourceMap,[p]:S}})),g(k);}));};for(let l of r)l.validate&&m(this,l,s);for(let l of u)l.validate&&m(l.field,l,c);let d=[];(s.length||c.length)&&(d=await Promise.all(s),await Promise.all(c)),this.setMeta(l=>({...l,isValidating:false}));for(let l of i)l.setMeta(f=>({...f,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:n}=this.validateSync(t,r[this.name]??{});if(n&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[ys(t)]?.lastAbortController.abort(),this.state.meta.errors;let i=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,i)},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=>Ra.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ra.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Gt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...qo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return bs(o.validate)?Ra[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 dc(e){if(e)return e}function ys(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 ws(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Qx)}function Qx(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,r]of e)if(!o.has(a)||!Object.is(r,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=uc(e);if(t.length!==uc(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 uc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Vo=typeof window<"u"?useLayoutEffect:useEffect;function sb(e){let[o]=useState(()=>{let a=new Or({...e,form:e.form,name:e.name});return a.Field=wl,a});return Vo(o.mount,[o]),Vo(()=>{o.update(e);}),ws(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var wl=(({children:e,...o})=>{let t=sb(o),a=useMemo(()=>Aa(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function db({form:e,selector:o,children:t}){let a=ws(e.store,o);return Aa(t,a)}function Sl(e){let o=useId(),[t]=useState(()=>{let a=new Br({...e,formId:o}),r=a;return r.Field=function(i){return jsx(wl,{...i,form:a})},r.Subscribe=function(i){return jsx(db,{form:a,selector:i.selector,children:i.children})},r});return Vo(t.mount,[]),Vo(()=>{t.update(e);}),t}function Ll({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 vb=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),r=Ve(),n=!!e,i=e?.data.questionType||t?.activityType||"multiple-choice",[u,s]=useState(i),c=Sl({defaultValues:{questionType:i,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 f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:300,rotation:n?e.rotation:0};o(n?ba(f):bi(f));}else if(l.questionType==="multiple-choice"){let f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:575,height:n?e.height:400,rotation:n?e.rotation:0};o(n?xa(f):xi(f));}else if(l.questionType==="short-answer"){let f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:400,rotation:n?e.rotation:0};o(n?ir(f):vi(f));}else if(l.questionType==="fill-in-the-blank"){let f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:400,rotation:n?e.rotation:0};o(n?dr(f):wi(f));}else if(l.questionType==="long-answer"){let f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:400,rotation:n?e.rotation:0};o(n?lr(f):yi(f));}o(va(false));}}),m=()=>{o(va(false));};if(!r)return null;let d=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(),c.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:n?"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(c.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:f=>{l.handleChange(f.target.value),s(f.target.value);},disabled:n,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 ${n?"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"})})})]}),n&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(Ll,{field:l})]})}),u&&!["short-answer","fill-in-the-blank","long-answer"].includes(u)&&jsx(c.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:f=>l.handleChange(f.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(Ll,{field:l})]})})]}),jsx(c.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 ${u==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:u==="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:u==="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"})]})]}),u==="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(Ll,{field:l})]})}),jsx(c.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:f=>l.handleChange(f.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(", ")})]})}),u==="true-false"&&jsx(c.Field,{name:"responseOptions.correctAnswer",children:l=>{let f=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 ${f===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"}),f===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 ${f===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"}),f===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"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value:l})=>{if(l.options.filter(h=>!h.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 f=(y,g)=>{let x=[...l.state.value.options];x[y]=g,l.handleChange({...l.state.value,options:x});},h=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},p=y=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let g=l.state.value.options.filter((w,I)=>I!==y),x=l.state.value.correctIndex?.filter(w=>w!==y).map(w=>w>y?w-1:w);l.handleChange({...l.state.value,options:g,correctIndex:x});},v=y=>{let g=l.state.value.correctIndex||[];if(g.includes(y))l.handleChange({...l.state.value,correctIndex:g.filter(w=>w!==y)});else {if(g.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...g,y]});}};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((y,g)=>{let x=!y.trim(),w=l.state.value.correctIndex?.includes(g),I=l.state.meta.isTouched&&x;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:()=>v(g),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${w?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:w&&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 ${I?"border-red-500 bg-red-50":w?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${g+1}`,value:y,onChange:k=>f(g,k.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:()=>p(g),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"})})]},g)})}),jsx("button",{type:"button",onClick:h,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"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.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:f=>{l.handleChange(f.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(", ")})]})}),u==="long-answer"&&jsx(c.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:f=>{l.handleChange(f.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(c.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,f])=>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:f?"Saving...":n?"Update Question":"Save Question"})})]})})});return createPortal(d,r)},mc=vb;var xc=({text:e,position:o})=>{let t=be(),a=c=>{t(de()),t(Ft({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+c))}));},r=c=>{t(de()),t(Ft({id:e.id,fill:c}));},n=()=>{t(de()),t(Ft({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},i=()=>{t(de()),t(Ft({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},u=()=>{t(de()),t(Ft({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},s=c=>{t(de()),t(Ft({id:e.id,fontFamily:c}));};return jsxs("div",{className:"absolute 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:100,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:c=>c.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:c=>s(c.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:n,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:i,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:u,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:c=>r(c.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 vc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:n,textareaRef:i})=>{let u=useRef(null),s=useMemo(()=>({fontSize:`${e.fontSize*n}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,n]),c=useCallback(m=>{m.style.height="auto",m.style.height=`${m.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(m).font,d.style.fontSize=m.style.fontSize,d.style.fontFamily=m.style.fontFamily,d.style.fontWeight=m.style.fontWeight,d.style.fontStyle=m.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let l=m.value.split(`
|
|
4
|
-
`),f=0;document.body.appendChild(d);for(let p of l){d.textContent=p||" ";let v=d.offsetWidth;v>f&&(f=v);}document.body.removeChild(d);let h=10;m.style.width=`${Math.max(200,f+h+20)}px`;},[]);return useEffect(()=>{let m=u.current;m&&(m.style.fontSize=`${e.fontSize*n}px`,m.style.fontFamily=e.fontFamily,m.style.fontStyle=e.fontStyle,m.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",m.style.textDecoration=e.textDecoration,m.style.color=e.fill,c(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,n,c]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(u.current=m,i.current=m,m){m.focus();let d=m.value.length;m.setSelectionRange(d,d),c(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:s},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var yc=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;n.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},wc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i})=>{let u=useSelector(S=>S.toolbar.selectedTool),s=u==="pen"||u==="eraser",c=useRef(null),[m,d]=useState(""),[l,f]=useState(false),[h,p]=useState(null);useEffect(()=>{let S=c.current;if(S)return a.current.set(e.id,S),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",y=l&&m.trim().toLowerCase()===v,g=()=>{f(false),d("");},x=()=>y?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",w=()=>y?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},I=e.data.feedbackMode==="practice",k=useMemo(()=>{let R=I?48:0,z=12,B=30,U=e.width-48,N=Math.max(60,yc(e.data.question,18,U,"bold")+20),V=l?Math.max(40,yc(x(),12,U/2)+20):0,F=l?54:20,W=N+V+B+50+12+z+R+24;return {padding:24,questionHeight:N,questionFontSize:18,feedbackHeight:V,feedbackFontSize:12,inputY:F,inputHeight:50,inputMargin:12,buttonHeight:R,buttonTopMargin:z,placeholderHeight:B,contentWidth:U,totalHeight:W}},[e.width,e.data.question,l,y,I,x]);return jsxs(Group,{ref:c,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:k.totalHeight,name:"sa-element",...i,...s?{}:{onDragEnd:n,onClick:()=>o&&o(e.id),onTap:()=>o&&o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:k.totalHeight,onTransformEnd:S=>t(e.id,S),onContextMenu:S=>{S.cancelBubble=true,r(S.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:k.padding+8,y:k.padding,fontSize:k.questionFontSize,fontStyle:"bold",fill:"#111827",width:k.contentWidth,height:k.questionHeight-k.padding,wrap:"word",listening:false}),jsx(Rect,{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight-k.inputY,width:k.contentWidth+4,height:k.inputHeight+6,fill:"#ffffff",stroke:y?"#22c55e":l?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight-k.inputY},divProps:{style:{width:`${k.contentWidth-4}px`,height:`${k.inputHeight}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:m,onChange:S=>d(S.target.value),disabled:l,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:l?"none":"auto"}})}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:k.padding,y:k.questionHeight+80,width:e.width/2+24,height:k.feedbackHeight,fill:w().bg,cornerRadius:8}),jsx(Text,{x:36,y:k.questionHeight+80,width:k.contentWidth,height:k.feedbackHeight,text:x(),fontSize:k.feedbackFontSize,fontStyle:"bold",fill:w().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:k.questionHeight+k.feedbackHeight+k.placeholderHeight+k.inputHeight+k.inputMargin+k.buttonTopMargin,children:[jsxs(Group,{onMouseDown:S=>{S.cancelBubble=true,p("check");},onMouseUp:S=>{S.cancelBubble=true,p(null),m.length>0&&f(true);},onMouseLeave:S=>{S.cancelBubble=true,p(null);},onTouchStart:S=>{S.cancelBubble=true,p("check");},onTouchEnd:S=>{S.cancelBubble=true,p(null),m.length>0&&f(true);},scaleX:h==="check"?.95:1,scaleY:h==="check"?.95:1,children:[jsx(Rect,{x:k.padding+14,width:(k.contentWidth-24)/(l?2:1),height:k.buttonHeight,fill:m.length===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:S=>S.cancelBubble=true,onTap:S=>S.cancelBubble=true}),jsx(Text,{x:k.padding+14,width:(k.contentWidth-24)/(l?2:1),height:k.buttonHeight,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-k.padding*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),g();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:k.padding,width:(k.contentWidth-8)/2,height:k.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:S=>S.cancelBubble=true,onTap:S=>S.cancelBubble=true}),jsx(Text,{x:k.padding,width:(k.contentWidth-8)/2,height:k.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});wc.displayName="ShortAnswer";var Sc=wc;var Ic=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,onLongPress:i})=>{let{createHandlers:u}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>jsx(Sc,{shortAnswer:s,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id),touchHandlers:u(s.id,"shortAnswer")},s.id))})};var Cc=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],r=useRef(new Map),n=useCallback((i,u)=>{let s=i.target;o(dr({id:u,x:s.x(),y:s.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:n}};var kl=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;n.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},kc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:n,touchHandlers:i})=>{let u=useSelector(S=>S.toolbar.selectedTool),s=u==="pen"||u==="eraser",c=useRef(null),[m,d]=useState(""),[l,f]=useState(false),[h,p]=useState(null);useEffect(()=>{let S=c.current;if(S)return n.current.set(e.id,S),()=>{n.current.delete(e.id);}},[e.id,n]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",y=l&&m.trim().toLowerCase()===v,g=()=>{f(false),d("");},x=()=>{m.length>0&&f(true);},w=e.data.feedbackMode==="practice",I=useMemo(()=>{let B=e.width-48,U=(B-15)/2,N=24,V=N,F=Math.max(60,kl(e.data.question.replace("_____","________"),24,B,"bold")+20);N+=F;let W=N,G=Math.max(35,kl("Enter your answer in the blank.",16,B)+10);N+=G;let se=N;N+=67;let q=N,_=l?Math.max(32,kl(y?"Right Answer, Great Job!":"Wrong Answer",14,B-40)+16):0;l&&(N+=_+16);let Z=N;return w&&(N+=64),N+=24,{padding:24,questionY:V,questionHeight:F,questionFontSize:24,helperTextY:W,helperTextHeight:G,helperTextFontSize:16,inputY:se,inputHeight:51,feedbackY:q,feedbackHeight:_,feedbackFontSize:14,buttonsY:Z,buttonHeight:64,buttonGap:15,buttonWidth:U,contentWidth:B,totalHeight:N}},[e.width,e.data.question,l,y,w]),k=()=>l?y?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:c,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...i,...s?{}:{onDragEnd:S=>a(S,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:I.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:S=>t(e.id,S),onContextMenu:S=>{S.cancelBubble=true,r?.(S.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:I.padding,y:I.questionY,fontSize:I.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:I.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:I.padding,y:I.helperTextY,fontSize:I.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:I.contentWidth,height:I.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:I.padding,y:I.inputY,width:I.contentWidth,height:I.inputHeight,fill:"#ffffff",stroke:k(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:I.padding,y:I.inputY},divProps:{style:{width:`${I.contentWidth}px`,height:`${I.inputHeight}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:m,onChange:S=>d(S.target.value),disabled:l,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"}})}),l&&jsxs(Group,{y:I.feedbackY,children:[jsx(Rect,{x:I.padding,width:y?206:140,height:I.feedbackHeight,fill:y?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:y?"\u2713":"\u2717",x:I.padding+10,y:0,width:16,height:I.feedbackHeight,fontSize:I.feedbackFontSize,fill:y?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:y?"Right Answer, Great Job!":"Wrong Answer",x:I.padding+30,y:0,height:I.feedbackHeight,fontSize:I.feedbackFontSize,fontStyle:"600",fill:y?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),w&&jsxs(Group,{y:I.buttonsY,children:[jsxs(Group,{x:I.padding,onMouseDown:S=>{S.cancelBubble=true,p("reset");},onMouseUp:S=>{S.cancelBubble=true,p(null),g();},onMouseLeave:S=>{S.cancelBubble=true,p(null);},onTouchStart:S=>{S.cancelBubble=true,p("reset");},onTouchEnd:S=>{S.cancelBubble=true,p(null),g();},scaleX:h==="reset"?.98:1,scaleY:h==="reset"?.98:1,children:[jsx(Rect,{width:I.buttonWidth,height:I.buttonHeight,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:I.buttonWidth,height:I.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:I.padding+I.buttonWidth+I.buttonGap,onMouseDown:S=>{S.cancelBubble=true,p("submit");},onMouseUp:S=>{S.cancelBubble=true,p(null),x();},onMouseLeave:S=>{S.cancelBubble=true,p(null);},onTouchStart:S=>{S.cancelBubble=true,p("submit");},onTouchEnd:S=>{S.cancelBubble=true,p(null),x();},scaleX:h==="submit"?.98:1,scaleY:h==="submit"?.98:1,children:[jsx(Rect,{width:I.buttonWidth,height:I.buttonHeight,fill:m.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:I.buttonWidth,height:I.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});kc.displayName="FillInTheBlanks";var Tc=kc;var Ac=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,onLongPress:n,fibRefs:i})=>{let{createHandlers:u}=qe({onLongPress:n});return jsx(Fragment,{children:e.map(s=>jsx(Tc,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:i,touchHandlers:u(s.id,"fillInTheBlanks")},s.id))})};var Al=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;n.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},El=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,touchHandlers:n,handleDragEnd:i})=>{let u=useSelector(k=>k.toolbar.selectedTool),s=u==="pen"||u==="eraser",c=useRef(null),[m,d]=useState(""),[l,f]=useState(false),[h,p]=useState(null);useEffect(()=>{let k=c.current;if(k)return a.current.set(e.id,k),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",y=l&&m.trim().toLowerCase()===v,g=()=>{f(false),d("");},x=()=>y?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",w=()=>y?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},I=useMemo(()=>{let B=e.width-48,U=Math.max(60,Al(e.data.question,20,B,"bold")+20),N=l?Math.max(60,Al(x(),14,B)+30):0,F=Math.max(30,Al("Answer (Extended response):",14,B)+10),W=U+N+F+120+12+12+48+24;return {padding:24,questionHeight:U,questionFontSize:20,feedbackHeight:N,feedbackFontSize:14,placeholderHeight:F,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:B,totalHeight:W}},[e.width,e.data.question,l,y,x]);return jsxs(Group,{ref:c,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:I.totalHeight,...n,name:"la-element",...s?{}:{onDragEnd:i,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:k=>{let S=c.current?.getStage()?.getPointerPosition();if(!S||!r)return;let b={x:e.x,y:e.y,width:e.width,height:I.totalHeight};S.x>=b.x&&S.x<=b.x+b.width&&S.y>=b.y&&S.y<=b.y+b.height&&r(k.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:I.totalHeight,onTransformEnd:k=>t(e.id,k)}),jsx(Text,{text:e.data.question,x:I.padding+8,y:I.padding,fontSize:I.questionFontSize,fontStyle:"bold",fill:"#111827",width:I.contentWidth,height:I.questionHeight-I.padding,wrap:"word",listening:false}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:I.padding,y:I.questionHeight,width:I.contentWidth,height:I.feedbackHeight,fill:w().bg,cornerRadius:8}),jsx(Text,{x:I.padding,y:I.questionHeight,width:I.contentWidth,height:I.feedbackHeight,text:x(),fontSize:I.feedbackFontSize,fontStyle:"bold",fill:w().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:I.padding,y:I.questionHeight+I.feedbackHeight+I.textareaMargin,fontSize:I.placeholderFontSize,fill:"#6b7280",width:I.contentWidth,wrap:"word",listening:false}),jsx(Rect,{x:I.padding,y:I.questionHeight+I.feedbackHeight+I.placeholderHeight,width:I.contentWidth,height:I.textareaHeight,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:I.padding,y:I.questionHeight+I.feedbackHeight+I.placeholderHeight},divProps:{style:{width:`${I.contentWidth}px`,height:`${I.textareaHeight}px`,pointerEvents:l?"none":"auto"}},children:jsx("textarea",{value:m,onChange:k=>d(k.target.value),disabled:l,placeholder:`Type your extended answer here...\r
|
|
2
|
+
export{default as Konva}from'konva';import*as ve from'react';import ve__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,Palette,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,List,Plus,Export,CaretLeft,CaretDown,CaretUp,SidebarSimple,CaretRight,SpeakerHifiIcon,NotePencilIcon,PencilSimple,CopySimple,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,TextUnderline,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Copy,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 Kd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import ju from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {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 {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Fd=e=>{throw TypeError(e)};var Bd=(e,o,t)=>o.has(e)||Fd("Cannot "+t);var G=(e,o,t)=>(Bd(e,o,"read from private field"),t?t.call(e):o.get(e)),Be=(e,o,t)=>o.has(e)?Fd("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Me=(e,o,t,a)=>(Bd(e,o,"write to private field"),o.set(e,t),t);var Od=(e,o,t,a)=>({set _(n){Me(e,o,n);},get _(){return G(e,o,a)}});var be=()=>useDispatch(),ee=e=>useSelector(e),_e=be,Re=ee;var ni=20,ii=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}),ri=ii("Slide 1"),gp={slides:[ri],currentSlideId:ri.id,history:{[ri.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false,editingOverlayPosition:null},Nd=createSlice({name:"canvas",initialState:gp,reducers:{addSlide:e=>{if(e.slides.length>=ni)return;let o=ii(`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(u=>u.isActive).length<=1)return;let r=e.slides.findIndex(u=>u.id===t);if(r===-1)return;let i=e.slides[r];if(a?(i.isActive=false,i.updatedAt=Date.now()):(e.slides.splice(r,1),delete e.history[t]),e.currentSlideId===t){let u=e.slides.filter(s=>s.isActive);u.length>0&&(e.currentSlideId=u[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=ni)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],n={...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,n),e.currentSlideId=n.id,e.history[n.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[n]=e.slides.splice(t,1);e.slides.splice(a,0,n);},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(n=>n.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(n=>n.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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,newTimestamp:r}=o.payload;switch(n){case "image":let i=t.images.find(g=>g.id===a);i&&(i.timestamp=r);break;case "video":let u=t.videos.find(g=>g.id===a);u&&(u.timestamp=r);break;case "shape":let s=t.shapes.find(g=>g.id===a);s&&(s.timestamp=r);break;case "text":let c=t.texts.find(g=>g.id===a);c&&(c.timestamp=r);break;case "flashcard":let m=t.flashcards.find(g=>g.id===a);m&&(m.timestamp=r);break;case "photoFrame":let d=t.photoFrames.find(g=>g.id===a);d&&(d.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(g=>g.id===a);l&&(l.timestamp=r);break;case "trueFalse":let f=t.trueFalses.find(g=>g.id===a);f&&(f.timestamp=r);break;case "shortAnswer":let h=t.shortAnswers.find(g=>g.id===a);h&&(h.timestamp=r);break;case "longAnswer":let p=t.LongAnswer.find(g=>g.id===a);p&&(p.timestamp=r);break;case "fillInTheBlanks":let y=t.fillInTheBlanks.find(g=>g.id===a);y&&(y.timestamp=r);break;case "line":let v=t.lines.find(g=>g.id===a);v&&(v.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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),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(n=>n.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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),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 n=t.multipleChoices[t.multipleChoices.length-1];a.x=n.x+20,a.y=n.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(n=>n.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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),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 n=t.trueFalses[t.trueFalses.length-1];a.x=n.x+20,a.y=n.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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),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 n=t.shortAnswers[t.shortAnswers.length-1];a.x=n.x+20,a.y=n.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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),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 n=t.LongAnswer[t.LongAnswer.length-1];a.x=n.x+20,a.y=n.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(n=>n.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(n=>n.id===o.payload);if(a){let n={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(n),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 n=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=n.x+20,a.y=n.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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),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:n}=o.payload;if(n==="image"){let r=t.images.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.images.splice(r,1);t.images.push(i);}}else if(n==="video"){let r=t.videos.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.videos.splice(r,1);t.videos.push(i);}}else if(n==="shape"){let r=t.shapes.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.shapes.splice(r,1);t.shapes.push(i);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.flashcards.splice(r,1);t.flashcards.push(i);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.photoFrames.splice(r,1);t.photoFrames.push(i);}}else if(n==="text"){let r=t.texts.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.texts.splice(r,1);t.texts.push(i);}}else if(n==="trueFalse"){let r=t.trueFalses.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.trueFalses.splice(r,1);t.trueFalses.push(i);}}else if(n==="shortAnswer"){let r=t.shortAnswers.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.shortAnswers.splice(r,1);t.shortAnswers.push(i);}}else if(n==="fillInTheBlanks"){let r=t.fillInTheBlanks.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.fillInTheBlanks.splice(r,1);t.fillInTheBlanks.push(i);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.images.splice(r,1);t.images.unshift(i);}}else if(n==="video"){let r=t.videos.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.videos.splice(r,1);t.videos.unshift(i);}}else if(n==="shape"){let r=t.shapes.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.shapes.splice(r,1);t.shapes.unshift(i);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.flashcards.splice(r,1);t.flashcards.unshift(i);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.photoFrames.splice(r,1);t.photoFrames.unshift(i);}}else if(n==="text"){let r=t.texts.findIndex(i=>i.id===a);if(r!==-1){let[i]=t.texts.splice(r,1);t.texts.unshift(i);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload,i=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);i&&(i.locked=!i.locked,"draggable"in i&&(i.draggable=!i.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,link:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="mcq"?t.multipleChoices:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(s=>s.id===a);u&&(u.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:n,altText:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(s=>s.id===a);u&&(u.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:n,audioData:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(s=>s.id===a);u&&(u.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();}},editingOverlayPosition:(e,o)=>{e.editingOverlayPosition=o.payload;},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),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(n=>n.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 n=a.images.map((r,i)=>i).filter(r=>r!==a.currentIndex);if(n.length>0){let r=n[Math.floor(Math.random()*n.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(n=>n.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(n=>n.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(n=>n.id===o.payload);if(a){let n={...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(n),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.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(n=>n.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(n=>n.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(n=>n.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(n=>n.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(n=>n.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(n=>n.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(n=>n.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 n=o.past.pop();e.slides[t]=n;}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 n=o.future.shift();e.slides[t]=n;}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 n=JSON.parse(JSON.stringify(t));a.past.push(n),a.future=[],a.past.length>20&&a.past.shift();}catch(n){console.warn("Failed to save to history - data too large:",n),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:lr,deleteSlide:dr,duplicateSlide:ur,setCurrentSlide:cr,setViewerMode:xp,updateSlideThumbnail:li,setBackgroundColor:fr,reorderSlides:bp,loadSlides:vo,addLine:di,removeLine:yn,addImage:ui,updateImage:yo,deleteImage:wn,duplicateImage:Sn,addVideo:wo,updateVideo:Ln,deleteVideo:In,duplicateVideo:Cn,toggleVideoPlaying:Ga,addShape:ci,updateShape:So,duplicateShape:kn,deleteShape:Tn,addText:fi,editingOverlayPosition:Hd,updateText:Rt,deleteText:Mn,duplicateText:An,addFlashcard:mi,updateFlashcard:Lo,deleteFlashcard:Pn,duplicateFlashcard:En,editFlashcard:mr,nextFlashcard:pi,previousFlashcard:hi,addPhotoFrame:gi,updatePhotoFrame:ja,deletePhotoFrame:Rn,duplicatePhotoFrame:Dn,toggleImageDrawingMode:xi,addImageAnnotation:bi,updateImageAnnotation:vp,clearImageAnnotations:yp,togglePhotoFrameDrawingMode:vi,addPhotoFrameAnnotation:yi,updatePhotoFrameAnnotation:wp,clearPhotoFrameAnnotations:Sp,addMultipleChoice:wi,updateMultipleChoice:ga,editMultipleChoice:Lp,deleteMultipleChoice:Fn,duplicateMultipleChoice:Bn,addTrueFalse:Si,updateTrueFalse:xa,deleteTrueFalse:On,duplicateTrueFalse:Nn,addShortAnswer:Li,updateShortAnswer:pr,deleteShortAnswer:Hn,duplicateShortAnswer:qn,addLongAnswer:Ii,updateLongAnswer:hr,deleteLongAnswer:Vn,duplicateLongAnswer:Un,addFillInTheBlanks:Ci,updateFillInTheBlanks:gr,deleteFillInTheBlanks:Wn,duplicateFillInTheBlanks:zn,setShowMcqForm:ba,setShowFlashcardForm:_a,setActivityType:ki,setEditingActivity:xr,bringToFront:Ti,sendToBack:Mi,toggleLock:Ai,setLink:Kn,setAltText:Gn,setAudioData:jn,updateLastLine:Ip,finalizeDrawing:Pi,setLines:Cp,updateLinePosition:kp,updateLineTransform:_n,deleteLineById:Xn,duplicateLine:Ei,updateElementOrder:br,clearCanvas:vr,undo:Io,redo:Co,saveToHistory:de,toggleSketchMode:Tp,setSketchMode:yt,setEditingTextId:yr,setPresentationTitle:Ri,setPresentationDescription:Di,loadPresentationMetadata:Fi,setMetadataLoaded:$n}=Nd.actions;var qd=e=>e.canvas.slides,va=e=>e.canvas.currentSlideId,ge=createSelector([qd,va],(e,o)=>e.find(t=>t.id===o)),ya=createSelector([qd],e=>e.filter(o=>o.isActive!==false)),Bi=e=>e.canvas.slides,wr=createSelector([ya],e=>e.length<ni),Mp=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},Sr=e=>e.canvas.presentationMetadata,Oi=e=>e.canvas.metadataLoaded,Yn=e=>e.canvas.viewerMode,Ni=Nd.reducer;var Ud=e=>{let o=be(),t=useRef(null),a=useRef(false),n=ee(f=>f.toolbar.selectedTool),r=ee(f=>f.toolbar.penColor),i=ee(f=>f.toolbar.strokeWidth),u=ee(f=>f.canvas.isSketchMode),s=ee(f=>f.canvas.slides.find(p=>p.id===f.canvas.currentSlideId)?.lines||[]),c=useCallback(f=>{t.current=f;},[]),m=useCallback(f=>{n==="pen"&&t.current&&(o(de()),t.current.startDrawing(f),a.current=true);},[n,o]),d=useCallback(f=>{!t.current||!a.current||t.current.draw(f);},[]),l=useCallback(()=>{if(!t.current||!a.current)return;let f=t.current.stopDrawing();a.current=false,f&&f.points.length>=4&&o(di(f)),o(Pi()),e?.();},[o,e]);return {lines:s,tool:n,color:r,strokeWidth:i,isSketchMode:u,setCanvasRef:c,startDrawing:m,draw:d,stopDrawing:l}};var Gd=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:n,isSketchMode:r,style:i,xOffset:u=0,yOffset:s=0},c)=>{let m=useRef(null),d=useRef(false),l=useRef([]),f=useRef([]),h=useRef(null),p=useRef(t),y=useRef(a),v=useRef(n),g=useRef(r),x=useRef(u),L=useRef(s);useEffect(()=>{p.current=t,y.current=a,v.current=n,g.current=r,x.current=u,L.current=s;},[t,a,n,r,u,s]);let S=useCallback(()=>{let w=m.current;if(!w)return;let b=w.getContext("2d");b&&b.clearRect(0,0,w.width,w.height);},[]),C=useCallback(()=>{let w=m.current,b=f.current;if(!w||b.length<1)return;let k=w.getContext("2d");if(!k)return;if(k.clearRect(0,0,w.width,w.height),p.current==="eraser"?(k.globalCompositeOperation="destination-out",k.fillStyle="rgba(0,0,0,1)"):(k.globalCompositeOperation="source-over",k.fillStyle=y.current),b.length===1){k.beginPath(),k.arc(b[0].x,b[0].y,v.current/2,0,Math.PI*2),k.fill();return}let P=Kd(b,{size:v.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:D=>D,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(P.length<2)){k.beginPath(),k.moveTo(P[0][0],P[0][1]);for(let D=1;D<P.length;D++)k.lineTo(P[D][0],P[D][1]);k.closePath(),k.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:w=>{d.current=true;let b={x:w.x-x.current,y:w.y-L.current};l.current=[{x:w.x,y:w.y}],f.current=[b],h.current=w,C();},draw:w=>{if(!d.current||!h.current)return;let b=w.x-h.current.x,k=w.y-h.current.y;if(Math.sqrt(b*b+k*k)<2)return;let P={x:w.x-x.current,y:w.y-L.current};l.current.push({x:w.x,y:w.y}),f.current.push(P),h.current=w,C();},stopDrawing:()=>{if(!d.current)return null;if(d.current=false,l.current.length<2)return l.current=[],f.current=[],h.current=null,S(),null;let b=Kd(l.current,{size:v.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:M=>M,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(M=>[M[0],M[1]]),k={tool:p.current,points:b,color:y.current,strokeWidth:v.current,isSketch:true};return l.current=[],f.current=[],h.current=null,S(),k},clear:()=>{S(),l.current=[],f.current=[],h.current=null,d.current=false;},isDrawing:()=>d.current,getCanvasElement:()=>m.current}),[S,C]),useEffect(()=>{let w=m.current;w&&(w.width=e,w.height=o);},[e,o]),jsx("canvas",{ref:m,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...i}})});Gd.displayName="DirectDrawingCanvas";var jd=Gd;var Xd=e=>{let o=be(),a=ee(ge)?.images||[],n=useRef(new Map),r=useRef(new Map),i=useRef(new Set);useEffect(()=>{let m=new Set(a.map(d=>d.id));i.current.forEach(d=>{if(!m.has(d)){let l=r.current.get(d);l&&(l.src="",r.current.delete(d)),n.current.delete(d);}}),i.current=m;},[a]),useEffect(()=>()=>{r.current.forEach(m=>{m.src="";}),r.current.clear(),n.current.clear();},[]);let u=useCallback(m=>{if(r.current.has(m.id))return r.current.get(m.id);let d=new window.Image;return (m.src.startsWith("http://")||m.src.startsWith("https://"))&&(d.crossOrigin="anonymous"),d.src=m.src,r.current.set(m.id,d),d},[]),s=useCallback((m,d)=>{let l=m.target,f=l.id();a.find(p=>p.id===f)&&(o(yo({id:f,x:l.x(),y:l.y(),width:l.width(),height:l.height(),rotation:l.rotation()})),d?.());},[a,o]),c=useCallback((m,d)=>{let l=d.target,f=n.current.get(m);if(!f){console.error("\u274C Image node not found for id:",m);return}let h=l.scaleX(),p=l.scaleY(),y=l.rotation(),v=f.width(),g=f.height(),x=Math.max(5,v*h),L=Math.max(5,g*p);l.scaleX(1),l.scaleY(1),f.width(x),f.height(L),o(yo({id:m,width:x,height:L,x:l.x(),y:l.y(),rotation:y})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:u,imageRefs:n,handleDragEnd:s,handleImageTransformEnd:c}};var $d=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),n=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((u,s)=>{let c=s.target,m=c.scaleX(),d=c.scaleY(),l=c.rotation(),f=Math.max(5,c.width()*m),h=Math.max(5,c.height()*d);c.scaleX(1),c.scaleY(1),c.width(f),c.height(h),o(ga({id:u,width:f,height:h,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:n,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(u,s)=>{o(ga({id:s,x:u.target.x(),y:u.target.y()})),e?.();}}};var Yd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),n=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((u,s)=>{let c=s.target,m=c.scaleX(),d=c.scaleY(),l=c.rotation(),f=Math.max(5,c.width()*m),h=Math.max(5,c.height()*d);c.scaleX(1),c.scaleY(1),c.width(f),c.height(h),o(xa({id:u,width:f,height:h,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:n,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(u,s)=>{o(xa({id:s,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var Zd=e=>{let o=be(),a=ee(ge)?.videos||[],n=useRef(new Map),r=useCallback(s=>{o(Ga(s));},[o]),i=useCallback((s,c)=>{let m=c.target;o(Ln({id:s,x:m.x(),y:m.y()})),e?.();},[o,e]),u=useCallback((s,c)=>{let m=c.target,d=m.scaleX(),l=m.scaleY(),f=m.rotation(),h=Math.max(5,m.width()*d),p=Math.max(5,m.height()*l);m.scaleX(1),m.scaleY(1),m.width(h),m.height(p),o(Ln({id:s,width:h,height:p,x:m.x(),y:m.y(),rotation:f})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:n,handleVideoClick:r,handleVideoDragEnd:i,handleVideoTransformEnd:u}};var eu=e=>{let o=be(),a=ee(ge)?.shapes||[],n=useRef(new Map),r=useRef(new Map),[i,u]=useState(false),s=useCallback((m,d)=>{let l=d.target;o(So({id:m,x:l.x(),y:l.y()})),e?.();},[o,e]),c=useCallback((m,d)=>{let l=d.target,f=a.find(x=>x.id===m);if(!f)return;let h=l.scaleX(),p=l.scaleY(),y=f.type?.toLowerCase();y==="arrow"||y==="line"||(l.scaleX(1),l.scaleY(1));let g={id:m,x:l.x(),y:l.y(),width:Math.max(5,l.width()*h),height:Math.max(5,l.height()*p),rotation:l.rotation()};switch(y){case "circle":g.radius=l.width()*h/2;break;case "star":g.innerRadius=l.width()*h/4,g.outerRadius=l.width()*h/2;break;case "triangle":g.radius=l.width()*h/2;break;case "ellipse":g.radiusX=l.width()*h/2,g.radiusY=l.height()*p/2;break;case "polygon":g.radius=l.width()*h/2;break;case "ring":let x=h;g.innerRadius=f.innerRadius&&f.innerRadius*x,g.outerRadius=f.outerRadius&&f.outerRadius*x;break;case "wedge":g.radius=f.radius&&f.radius*h;break;case "arc":g.innerRadius=f.innerRadius&&f.innerRadius*h,g.outerRadius=f.outerRadius&&f.outerRadius*h;break;case "arrow":case "line":{g.scaleX=h,g.scaleY=p,delete g.width,delete g.height;break}}o(So(g)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:n,isDragging:i,loadedShapesRef:r,handleShapeDragEnd:s,handleShapeResizeEnd:c}};var au=(e,o)=>{let t=_e(),n=ee(ge)?.texts||[],r=useRef(new Map),[i,u]=useState(null),[s,c]=useState("");return {texts:n,textRefs:r,handleDragEnd:(y,v)=>{let g=y.target;t(de()),t(Rt({id:v,x:g.x(),y:g.y()})),e();},handleTransformEnd:y=>{let v=r.current.get(y);if(!v)return;let g=v.scaleX(),x=v.scaleY(),L=n.find(C=>C.id===y);if(!L)return;let S=(g+x)/2;v.scaleX(1),v.scaleY(1),t(de()),t(Rt({id:y,x:v.x(),y:v.y(),width:Math.max(5,(L.width||100)*g),height:Math.max(5,(L.height||50)*x),fontSize:Math.round(Math.max(8,L.fontSize*S)),rotation:v.rotation()})),e();},handleDoubleClick:y=>{let v=n.find(g=>g.id===y);v&&!v.locked&&(u(y),c(v.text));},startEditing:y=>{let v=n.find(g=>g.id===y);v&&!v.locked&&(u(y),c(v.text));},editingTextId:i,editingValue:s,handleEditingChange:y=>{c(y);},finishEditing:()=>{if(i){let y=r.current.get(i),v=n.find(x=>x.id===i);t(de());let g={id:i,text:s};if(v&&(v.fontWeight!==void 0&&(g.fontWeight=v.fontWeight),v.fontStyle!==void 0&&(g.fontStyle=v.fontStyle),v.textDecoration!==void 0&&(g.textDecoration=v.textDecoration)),o?.current&&s.trim()){let x=o.current,L=x.offsetWidth,S=x.offsetHeight,C=1;if(y){let U=y.getStage();U&&(C=U.scaleX());}let w=14,b=(L-w)/C,k=(S-w)/C,M=s.split(`
|
|
3
|
+
`).length,D=n.find(U=>U.id===i)?.fontSize||24,B=M*D*1.2+10;g.width=Math.max(200,b),g.height=Math.max(50,k,B);}else if(y&&s.trim()){let x=y.text(),L=y.width();y.text(s),y.width(void 0);let S=y.width(),C=y.height();y.text(x),y.width(L),g.width=Math.max(200,S+20),g.height=Math.max(50,C+20);}t(Rt(g)),u(null),c(""),t(yr(null)),e();}}}};var ou=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],n=useRef(new Map),r=useCallback((i,u)=>{let s=i.target;o(pr({id:u,x:s.x(),y:s.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:n,handleShortAnswerDragEnd:r}};var ru=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),n=useCallback((r,i)=>{let u=r.target;o(hr({id:i,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:n}};var su=e=>{let o=be(),a=ee(ge)?.flashcards||[],n=useRef(new Map),r=useRef(new Map),i=useCallback((d,l)=>{if(r.current.has(l))return r.current.get(l);let f=new window.Image;return (d.startsWith("http://")||d.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=d,r.current.set(l,f),f},[]),u=useCallback((d,l)=>{let f=d.target,h=f.id();a.find(y=>y.id===h)&&(o(Lo({id:h,x:f.x(),y:f.y()})),l?.());},[a,o]),s=useCallback((d,l)=>{let f=l.target,h=f.scaleX(),p=f.scaleY(),y=f.rotation(),v=Math.max(50,f.width()*h),g=Math.max(50,f.height()*p);f.scaleX(1),f.scaleY(1),f.width(v),f.height(g),o(Lo({id:d,width:v,height:g,x:f.x(),y:f.y(),rotation:y})),f.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(d=>{o(pi(d)),e?.();},[o,e]),m=useCallback(d=>{o(hi(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:i,flashcardRefs:n,handleDragEnd:u,handleFlashcardTransformEnd:s,handleNext:c,handlePrevious:m}};var du=e=>{let o=be(),a=ee(ge)?.photoFrames||[],n=useRef(new Map),[r,i]=useState(new Map),u=useCallback((f,h)=>{console.log("handleDragEnd"),o(ja({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),s=useCallback((f,h)=>{let p=h.target,y=p.scaleX(),v=p.scaleY(),g=p.rotation(),x=a.find(C=>C.id===f);if(!x)return;let L=Math.max(100,x.width*y),S=Math.max(100,x.height*v);p.scaleX(1),p.scaleY(1),o(ja({id:f,width:L,height:S,x:p.x(),y:p.y(),rotation:g})),p.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return i(p=>{let y=new Map(p);return y.set(f,h),y}),o(ja({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),m=useCallback(f=>{let h=r.get(f);h&&(h.getTracks().forEach(p=>p.stop()),i(p=>{let y=new Map(p);return y.delete(f),y}),o(ja({id:f,isCapturing:false})),e?.());},[r,o,e]),d=useCallback((f,h)=>{let p=document.createElement("canvas");p.width=h.videoWidth,p.height=h.videoHeight;let y=p.getContext("2d");if(y){y.drawImage(h,0,0,p.width,p.height);let v=p.toDataURL("image/jpeg",.8);return o(ja({id:f,capturedImageUrl:v,isCapturing:false})),m(f),e?.(),v}return null},[o,m,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:n,handleDragEnd:u,handlePhotoFrameTransformEnd:s,startCamera:c,stopCamera:m,capturePhoto:d,cameraStreams:r}};var uu=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,i)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...i,width:Math.max(o.minWidth,Math.min(i.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(i.height,o.maxHeight))}:i,[o]),a=useCallback((r,i,u,s,c,m,d,l=[])=>{if(e.current){if(r&&!l.find(p=>p.id===r)?.isPlaying){let p=i.get(r)||u.get(r)||s.get(r)||c.get(r)||m.get(r)||(d?d.get(r):null);if(p){e.current.boundBoxFunc(t),e.current.nodes([p]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),n=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:n,boundBoxFunc:t}};var ah=(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])},pu=(e,o)=>{let t=_e(),a=Re(Yn),n=useRef(e);useEffect(()=>{n.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(li({id:n.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),i=ah(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:i}};var rh=e=>e.flatMap(o=>[o[0],o[1]]),Jn=(e,o)=>{let t=Kd(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 rh(t)};var hu=e=>{let o=be(),t=useRef(false),a=useRef(false),n=useRef([]),[r,i]=useState(null),u=ee(x=>x.toolbar.selectedTool),s=ee(x=>x.toolbar.penColor),c=ee(x=>x.toolbar.strokeWidth),m=ee(x=>x.canvas.isSketchMode),d=ee(x=>x.canvas.slides.find(S=>S.id===x.canvas.currentSlideId)?.images.find(S=>S.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,y=useCallback(x=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,n.current=[{x:x.x,y:x.y}];let L=x.x/h,S=x.y/p;i({tool:u,points:[L,S],color:s,strokeWidth:c/h,isSketch:m});},[u,s,c,m,h,p]),v=useCallback(x=>{if(!t.current||!r)return;a.current=true;let L=n.current[n.current.length-1];if(Math.sqrt(Math.pow(x.x-L.x,2)+Math.pow(x.y-L.y,2))<2)return;n.current.push({x:x.x,y:x.y});let C;if(m)C=Jn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,k)=>k%2===0?b/h:b/p);else {let w=x.x/h,b=x.y/p;C=[...r.points,w,b];}i(w=>w?{...w,points:C}:null);},[m,c,r,h,p]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(bi({imageId:e,line:r})),i(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:f,startDrawing:y,draw:v,stopDrawing:g,tool:u}};function qe({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),n=useRef(null);return {createHandlers:useCallback((i,u)=>({onTouchStart:s=>{let c=s.evt.touches[0];n.current={x:c.clientX,y:c.clientY},a.current=setTimeout(()=>{e(i,u)(s.evt);},o);},onTouchMove:s=>{if(!n.current)return;let c=s.evt.touches[0],m=Math.abs(c.clientX-n.current.x),d=Math.abs(c.clientY-n.current.y);(m>t||d>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),n.current=null;}}),[e,o,t])}}var yu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:i,onLongPress:u})=>{let{annotations:s,activeLine:c,stopDrawing:l,tool:f}=hu(e.id),{createHandlers:h}=qe({onLongPress:u});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 y=x=>{{r(e.id);return}},v=x=>{return;},g=x=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="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();else {let L=t.current.get(e.id);L?._contextMenuCleanup&&L._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:x=>n(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:x=>{x.evt.preventDefault();let L=x.evt;i(L,e.id,"image");},...f!=="pen"&&f!=="eraser"?{onClick:y,onTap:y,onMouseDown:y,onMouseMove:v,onMouseUp:g,...h(e.id,"image")}:{}}),s?.map((x,L)=>{let S=x.points.map((w,b)=>b%2===0?w*e.width+e.x:w*e.height+e.y),C=x.strokeWidth*e.width;return jsx(Line,{points:S,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},L)}),c&&jsx(Line,{points:c.points.map((x,L)=>L%2===0?x*e.width+e.x:x*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});yu.displayName="ImageWithDrawing";var Ki=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:i,onLongPress:u})=>jsx(Fragment,{children:e.map(s=>{let c=o(s);return c?jsx(yu,{img:s,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:i,onLongPress:u},s.id):null})}));Ki.displayName="ImageLayer";var hh=({src:e,x:o,id:t,y:a,width:n,height:r,isSelected:i,rotation:u=0,onTransformEnd:s,onDragEnd:c})=>{let m=be(),d=useRef(null),l=f=>{m(Ga(f));};return jsxs(Group,{draggable:true,x:o,y:a,width:n,height:r,rotation:u,onDragEnd:c,onTransformEnd:s,children:[jsx(Rect,{width:n,height:r,fill:"black",stroke:i?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${n}px`,height:`${r}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>l(t),onSeeking:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},wu=hh;var Lh=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,nodeRef:i})=>{let[u,s]=useState(null),c=useSelector(p=>p.toolbar.selectedTool),m=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let p=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(p.crossOrigin="anonymous"),p.src=e.thumbnailDataUrl,p.onload=()=>{s(p);};}},[e.thumbnailDataUrl]),!u)return null;let d=e.width/2,l=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,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:n},ref:p=>{if(i(p),p){let y=p.getStage()?.container();if(y){let v=g=>{let x=p.getStage()?.getPointerPosition();if(x){let L={x:e.x,y:e.y,width:e.width,height:e.height};x.x>=L.x&&x.x<=L.x+L.width&&x.y>=L.y&&x.y<=L.y+L.height&&r(g);}};y.addEventListener("contextmenu",v),p._contextMenuCleanup=()=>{y.removeEventListener("contextmenu",v);};}}},children:[jsx(Image$1,{image:u,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:d,y:l,radius:h,fill:"white",listening:!m,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...m?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:l,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!m,...m?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:l,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!m,...m?{}:{onClick:t,onTap:t}})]})},Lu=Lh;var _i=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:n,onTransformEnd:r,onContextMenu:i})=>jsx(Fragment,{children:e.map(u=>jsxs(ve__default.Fragment,{children:[jsx(Lu,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>a(u.id),onDragEnd:s=>n(u.id,s),onTransformEnd:s=>r(u.id,s),onContextMenu:s=>i(s,u.id,"video"),nodeRef:s=>{s?t.current.set(u.id,s):t.current.delete(u.id);}}),u.isPlaying&&!u.isRecorded&&jsx(wu,{id:u.id,src:u.objectUrl,x:u.x,y:u.y,width:u.width,height:u.height,isSelected:false,rotation:u.rotation,onTransformEnd:s=>r(u.id,s),onDragEnd:s=>n(u.id,s)})]},u.id))}));_i.displayName="VideoLayer";var Xi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:n,handleShapeDragStart:r,onContextMenu:i,onLongPress:u})=>{let s=useSelector(d=>d.toolbar.selectedTool),c=s==="pen"||s==="eraser",{createHandlers:m}=qe({onLongPress:u});return jsx(Fragment,{children:e.map((d,l)=>{let f=d.id||l,h={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!c,listening:!c,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},radius:d.radius||d.width/2,width:d.width,height:d.width},f);case "star":return jsx(Star,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},sides:3,radius:d.radius||d.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},sides:d.sides||6,radius:d.radius||d.width/2},f);case "ellipse":return jsx(Ellipse,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},f);case "ring":return jsx(Ring,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "wedge":return jsx(Wedge,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},radius:d.radius||d.width/2,angle:d.angle||60},f);case "arrow":return jsx(Arrow,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(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:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(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:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(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:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),i(p.evt,d.id,"shape");},...m(d.id,"shape")},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},f)}})})});Xi.displayName="ShapeLayer";var ku=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:n,onContextMenu:r,onDoubleClick:i,editingTextId:u,onLongPress:s})=>{let c=useSelector(l=>l.toolbar.selectedTool),m=c==="pen"||c==="eraser",{createHandlers:d}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(l=>{let f=l.id===u,h=l.fontWeight==="bold",p=h?Math.max(1,l.fontSize/25):0;return jsx(Text,{id:l.id,ref:y=>{y?o.current.set(l.id,y):o.current.delete(l.id);},text:l.text,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:!l.locked&&!f&&!m,listening:!m,fontSize:l.fontSize,fontFamily:l.fontFamily,fontStyle:l.fontStyle,fontWeight:l.fontWeight,textDecoration:l.textDecoration,fill:l.fill,stroke:h?l.fill:void 0,strokeWidth:p,align:l.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...m?{}:{onClick:()=>n(l.id),onTap:()=>n(l.id),onDblClick:()=>i(l.id),onDblTap:()=>i(l.id),onDragEnd:y=>t(y,l.id),onTransformEnd:()=>a(l.id),onContextMenu:y=>{y.evt.preventDefault();let v=y.evt;r(v,l.id,"text");},...d(l.id,"text")}},l.id)})})};var Xh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onNext:i,onPrevious:u,nodeRef:s,touchHandlers:c,currentTool:m})=>{let[d,l]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let g=new window.Image,x=e.images[e.currentIndex];(x.startsWith("http://")||x.startsWith("https://"))&&(g.crossOrigin="anonymous"),g.src=x,g.onload=()=>{l(g);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let f=8,h=2,p=Math.min(e.width,e.height)*.08,y=Math.max(16,Math.min(p,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:n,...c,ref:g=>{if(s(g),g){let x=g.getStage()?.container();if(x){let L=S=>{let C=g.getStage()?.getPointerPosition();if(C){let w={x:e.x,y:e.y,width:e.width,height:e.height};C.x>=w.x&&C.x<=w.x+w.width&&C.y>=w.y&&C.y<=w.y+w.height&&r(S);}};x.addEventListener("contextmenu",L),g._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",L);};}}},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:h,listening:false}),jsx(Image$1,{x:h+4,y:h+4,image:d,width:e.width-(h+4)*2,height:e.height-(h+4)*2,cornerRadius:f-h,onClick:t,onTap:t}),jsx(Rect,{x:h,y:e.height-50,width:e.width-h*2,height:50,cornerRadius:[0,0,f-h,f-h],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+y,y:e.height/2,onClick:g=>{g.cancelBubble=true,u();},onTap:g=>{g.cancelBubble=true,u();},children:[jsx(Circle,{radius:y,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-y,y:e.height/2,onClick:g=>{g.cancelBubble=true,i();},onTap:g=>{g.cancelBubble=true,i();},children:[jsx(Circle,{radius:y,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"})]})},Au=Xh;var Zi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onNext:i,onPrevious:u,onContextMenu:s,onLongPress:c})=>{let{createHandlers:m}=qe({onLongPress:c});return jsx(Fragment,{children:e.map(d=>jsx(Au,{flashcard:d,isSelected:t===d.id,onClick:()=>r(d.id),onDragEnd:a,onTransformEnd:l=>n(d.id,l),onContextMenu:l=>s(l,d.id,"flashcard"),onNext:()=>i(d.id),onPrevious:()=>u(d.id),touchHandlers:m(d.id,"flashcard"),nodeRef:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);}},d.id))})});Zi.displayName="FlashcardLayer";var Eu=e=>{let o=be(),t=useRef(false),a=useRef(false),n=useRef([]),[r,i]=useState(null);ee(x=>x.toolbar.selectedTool);let s=ee(x=>x.toolbar.penColor),c=ee(x=>x.toolbar.strokeWidth),m=ee(x=>x.canvas.isSketchMode),d=ee(x=>x.canvas.slides.find(S=>S.id===x.canvas.currentSlideId)?.photoFrames.find(S=>S.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,y=useCallback(x=>{if(!f)return;t.current=true,a.current=false,n.current=[{x:x.x,y:x.y}];let L=x.x/h,S=x.y/p;i({tool:"pen",points:[L,S],color:s,strokeWidth:c/h,isSketch:m});},[f,s,c,m,h,p]),v=useCallback(x=>{if(!t.current||!r)return;a.current=true;let L=n.current[n.current.length-1];if(Math.sqrt(Math.pow(x.x-L.x,2)+Math.pow(x.y-L.y,2))<2)return;n.current.push({x:x.x,y:x.y});let C;if(m)C=Jn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,k)=>k%2===0?b/h:b/p);else {let w=x.x/h,b=x.y/p;C=[...r.points,w,b];}i(w=>w?{...w,points:C}:null);},[m,c,r,h,p]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(yi({frameId:e,line:r})),i(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:f,startDrawing:y,draw:v,stopDrawing:g}};var ag=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onStartCamera:i,onCapture:u,cameraStream:s,nodeRef:c,touchHandlers:m})=>{let[d,l]=useState(null),[f,h]=useState(null),p=useRef(null),y=useRef(null),v=useRef(null),g=useRef(null),x=useRef(0),L=33,S=useSelector(V=>V.toolbar.selectedTool),C=S==="pen"||S==="eraser",{annotations:w,activeLine:b,isDrawingMode:k,startDrawing:M,draw:P,stopDrawing:D}=Eu(e.id);useEffect(()=>{if(!k)return;let V=()=>{D();},j=()=>{D();};return window.addEventListener("mouseup",V),window.addEventListener("touchend",j),()=>{window.removeEventListener("mouseup",V),window.removeEventListener("touchend",j);}},[D,k]),useEffect(()=>{if(e.capturedImageUrl){let V=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(V.crossOrigin="anonymous"),V.src=e.capturedImageUrl,V.onload=()=>{l(V);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&s){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),y.current||(y.current=document.createElement("canvas"));let V=p.current,j=y.current;V.srcObject=s;let Z=()=>{j.width=V.videoWidth||640,j.height=V.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",j.width,j.height);let Y=ne=>{if(ne-x.current<L){v.current=requestAnimationFrame(Y);return}x.current=ne;let J=j.getContext("2d");if(J&&V.readyState===V.HAVE_ENOUGH_DATA){J.drawImage(V,0,0,j.width,j.height);let ce=j.toDataURL("image/jpeg",.6),we=new window.Image;we.onload=()=>{h(we);},we.src=ce;}v.current=requestAnimationFrame(Y);};v.current=requestAnimationFrame(Y);};return V.onloadedmetadata=Z,V.readyState>=V.HAVE_METADATA&&Z(),V.play().catch(Y=>console.error("Error playing video:",Y)),()=>{v.current&&(cancelAnimationFrame(v.current),v.current=null);}}return ()=>{h(null),g.current&&(g.current.src="");}},[e.isCapturing,s]);let W=()=>{p.current&&e.isCapturing&&u(p.current);},B=V=>{if(e.capturedImageUrl){if(!k){t();return}let j=V.currentTarget,Z=j.getAbsoluteTransform().copy(),ne=j.getStage()?.getPointerPosition();if(ne){Z.invert();let J=Z.point(ne);M(J);}V.cancelBubble=true;}else t();},U=V=>{if(!k||!e.capturedImageUrl)return;let j=V.currentTarget,Z=j.getAbsoluteTransform().copy(),ne=j.getStage()?.getPointerPosition();if(ne){Z.invert();let J=Z.point(ne);P(J);}},N=()=>{!k||!e.capturedImageUrl||D();},q=e.isCapturing?f:d,F=Math.min(e.width,e.height)*.12,z=Math.max(25,Math.min(F,50)),_=e.width/2,oe=e.height/2;return jsxs(Group,{id:e.id,draggable:!k&&!C,listening:true,x:e.x,y:e.y,...m,...C?{}:{onDragEnd:a,onTransformEnd:n},rotation:e.rotation,width:e.width,height:e.height,ref:V=>{if(c(V),V){let j=V.getStage()?.container();if(j){let Z=Y=>{let ne=V.getStage()?.getPointerPosition();if(ne){let J={x:e.x,y:e.y,width:e.width,height:e.height};ne.x>=J.x&&ne.x<=J.x+J.width&&ne.y>=J.y&&ne.y<=J.y+J.height&&r(Y);}};j.addEventListener("contextmenu",Z),V._contextMenuCleanup=()=>{j.removeEventListener("contextmenu",Z);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:q?"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}}),q&&jsx(Image$1,{image:q,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:B,onTap:B,onMouseDown:B,onTouchStart:B,onMouseMove:U,onTouchMove:U,onMouseUp:N,onTouchEnd:N,...C?{}:{onDragEnd:a,onTransformEnd:n}}),w?.map((V,j)=>{let Z=V.points.map((ne,J)=>J%2===0?ne*e.width:ne*e.height),Y=V.strokeWidth*e.width;return jsx(Line,{points:Z,stroke:V.tool==="eraser"?"white":V.color,strokeWidth:Y,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:V.tool==="eraser"?"destination-out":"source-over",fill:V.isSketch?V.color:void 0,closed:V.isSketch,listening:false},j)}),b&&jsx(Line,{points:b.points.map((V,j)=>j%2===0?V*e.width:V*e.height),stroke:b.tool==="eraser"?"white":b.color,strokeWidth:b.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},"active"),!q&&!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:oe-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:_-z+6,y:oe-60,width:z*1.6,height:z*1.6,radius:z,fill:"white",cornerRadius:8,listening:true,onClick:V=>{V.cancelBubble=true,e.isCapturing?W():i();},onTap:V=>{V.cancelBubble=true,e.isCapturing?W():i();}}),jsx(Html,{groupProps:{x:_-12,y:oe-40,width:z*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:V=>{V.stopPropagation(),e.isCapturing?W():i();}})})]}),jsx(Text,{x:0,y:oe,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:oe+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:_-24,y:oe+104,width:z*1.6,height:z*1.6,radius:z,fill:"#096B76",cornerRadius:z,listening:true,onClick:V=>{V.cancelBubble=true,e.isCapturing?W():i();},onTap:V=>{V.cancelBubble=true,e.isCapturing?W():i();}}),jsx(Html,{groupProps:{x:_-8,y:oe+120,width:z*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:V=>{V.stopPropagation(),e.isCapturing?W():i();}})})]}),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:_-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:V=>{V.stopPropagation(),W();},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})})})})]})]})},Bu=ag;var ol=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onStartCamera:i,onCapture:u,cameraStreams:s,onContextMenu:c,onLongPress:m})=>{let{createHandlers:d}=qe({onLongPress:m});return jsx(Fragment,{children:e.map(l=>jsx(Bu,{photoFrame:l,isSelected:t===l.id,onClick:()=>r(l.id),onDragEnd:f=>a(f,l.id),onTransformEnd:f=>n(l.id,f),onContextMenu:f=>c(f,l.id,"photoFrame"),onStartCamera:()=>i(l.id),onCapture:f=>u(l.id,f),cameraStream:s.get(l.id),touchHandlers:d(l.id,"photoFrame"),nodeRef:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);}},l.id))})});ol.displayName="PhotoFrameLayer";var qu=({x:e,y:o,onAction:t,onClose:a,type:n,elementId:r="",isDrawingMode:i,menuRef:u})=>{useEffect(()=>{let d=f=>{u?.current&&!u.current.contains(f.target)&&a();},l=f=>{f.key==="Escape"&&a();};return document.addEventListener("mousedown",d),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",l);}},[a]);let s=useMemo(()=>[{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:"draw",label:i?"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"}),hideForTypes:["line","video"]},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{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(n)||l.hideForTypes&&l.hideForTypes.includes(n))),[n,i]),c=(d,l)=>{d==="order"||d==="lock"?t(d,l):(t(d),a());},m=jsx("div",{ref:u,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:s.map((d,l)=>jsxs("button",{onClick:f=>c(d.action,f),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${d.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[d.icon,jsx("span",{className:`font-medium ${d.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:d.label})]}),d.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},l))})});return createPortal(m,document.body)};var Vu=({x:e,y:o,items:t,onClose:a})=>{let n=useRef(null);return useEffect(()=>{let r=i=>{n.current&&!n.current.contains(i.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:n,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,i)=>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})},i))})})};var Wu=createContext(null),rl=()=>useContext(Wu);function Sg({children:e,className:o="",style:t}){let a=useRef(null),[n,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Wu.Provider,{value:n,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function Ve(){let e=rl();return typeof document>"u"?null:e||document.body}var zu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:n,onClose:r})=>{let[i,u]=useState(a),s=useRef(null),c=Ve();useEffect(()=>{s.current?.focus();},[]);let m=()=>{n(i),r();},d=f=>{f.key==="Enter"?m():f.key==="Escape"&&r();};return c?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:s,type:"text",value:i,onChange:f=>u(f.target.value),onKeyDown:d,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"})]})]})}),c):null};var rs=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,n]=useState(e),r=useRef(null),i=Ve();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let u=d=>{d.preventDefault(),o(a);},s=(d,l,f)=>{f/=100;let h=l*Math.min(f,1-f)/100,p=y=>{let v=(y+d/30)%12,g=f-h*Math.max(Math.min(v-3,9-v,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!i)return null;let m=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.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:d=>d.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:u,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:d=>n(d.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:d=>n(d.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:d=>{let l=parseInt(d.target.value),f=s(l,100,50);n(f);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(d=>jsx("button",{type:"button",onClick:()=>n(d),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===d.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:d},title:d},d))})]})]}),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,i)};var Ug=({imageSrc:e,onCrop:o})=>{let[t]=ju(e),a=useRef(null),n=useRef(null),r=useRef(null),i=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),u=useMemo(()=>{let l=i.width*.5,f=i.height*.5,h=(i.width-l)/2,p=(i.height-f)/2;return {x:h,y:p,width:l,height:f}},[i]),[s,c]=useState(u);useEffect(()=>{c(u);},[u]),useEffect(()=>{r.current&&n.current&&(r.current.nodes([n.current]),r.current.getLayer()?.batchDraw());},[s]),useEffect(()=>{o(s.x,s.y,s.width,s.height);},[s,o]);let m=()=>{let l=n.current;if(!l)return;let f=l.scaleX(),h=l.scaleY();l.scaleX(1),l.scaleY(1),c({x:l.x(),y:l.y(),width:Math.max(20,l.width()*f),height:Math.max(20,l.height()*h)});},d=()=>{let l=n.current;l&&c({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:i.width,height:i.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:i.width,height:i.height}),jsx(Rect,{x:0,y:0,width:i.width,height:i.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:s.x,y:s.y,width:s.width,height:s.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:n,x:s.x,y:s.y,width:s.width,height:s.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:m,dragBoundFunc:l=>{let f=Math.max(0,Math.min(l.x,i.width-s.width)),h=Math.max(0,Math.min(l.y,i.height-s.height));return {x:f,y:h}}}),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,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>i.width||f.y+f.height>i.height?l:f})]})})},_u=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[n,r]=useState({x:0,y:0,width:0,height:0}),[i]=ju(e),u=Ve();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let s=(d,l,f,h)=>{r({x:d,y:l,width:f,height:h});},c=()=>{if(!i)return;let f=Math.min(600/i.width,400/i.height),h=n.x/f,p=n.y/f,y=n.width/f,v=n.height/f,g=document.createElement("canvas");g.width=y,g.height=v;let x=g.getContext("2d");if(!x)return;x.drawImage(i,h,p,y,v,0,0,y,v);let L=g.toDataURL("image/png");o(L);};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.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:d=>d.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(Ug,{imageSrc:e,onCrop:s})}),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:c,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"]})]})]})}),u):null};var Xa=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let n=Ve(),[r,i]=useState(false),[u,s]=useState(null),[c,m]=useState(0),[d,l]=useState(true),f=useRef(null),h=useRef([]),p=useRef(null),y=useRef(null),v=useRef(null),g=useRef(null),x=useRef(null),L=useRef(null);useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current),p.current&&clearInterval(p.current),y.current&&y.current.getTracks().forEach(M=>M.stop());},[]);let S=async()=>{try{let M,P=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let N=o.current.getLayers();console.log("Konva layers:",N.length),N.forEach((Z,Y)=>{let ne=Z.getChildren();console.log(`Layer ${Y} children count:`,ne.length);});let q=document.createElement("canvas");q.width=o.current.width(),q.height=o.current.height();let F=q.getContext("2d",{willReadFrequently:!1});if(!F){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",q.width,"x",q.height),x.current=q;let z=()=>{if(F.clearRect(0,0,q.width,q.height),N.forEach(Z=>{let Y=Z.getCanvas()._canvas;Y&&F.drawImage(Y,0,0);}),a?.current){let Z=a.current;F.drawImage(Z,0,0);}};L.current=z,o.current.draw(),z(),await new Promise(Z=>setTimeout(Z,100)),console.log("Creating captureStream..."),M=q.captureStream(30),console.log("Canvas stream created, tracks:",M.getTracks().length);let oe=M.getVideoTracks()[0];oe&&console.log("Video track:",oe.label,"state:",oe.readyState);let V=0,j=()=>{z(),o?.current&&(o.current.getLayers().forEach(Y=>{Y.batchDraw();}),V++,V%60===0&&console.log("Drawing frame:",V)),v.current=requestAnimationFrame(j);};j();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{P=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(N){console.warn("Microphone access denied:",N);}let D=[...M.getVideoTracks()];P&&D.push(...P.getAudioTracks());let W=new MediaStream(D);y.current=W;let B="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?B="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?B="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?B="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(B="video/webm;codecs=vp8"),console.log("Using mimeType:",B);let U=new MediaRecorder(W,{mimeType:B,videoBitsPerSecond:25e5});f.current=U,h.current=[],U.ondataavailable=N=>{console.log("Data available, size:",N.data.size),N.data.size>0&&h.current.push(N.data);},U.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let N=new Blob(h.current,{type:B});console.log("Final blob size:",N.size),o?.current&&L.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(F=>{F.batchDraw();}),L.current(),g.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",g.current.length)),W.getTracks().forEach(q=>q.stop()),p.current&&clearInterval(p.current),v.current&&(cancelAnimationFrame(v.current),v.current=null),s(N);},U.onerror=N=>{console.error("MediaRecorder error:",N);},console.log("Starting recording..."),U.start(1e3),i(!0),m(0),p.current=setInterval(()=>{m(N=>N+1);},1e3);}catch(M){console.error("Error starting screen recording:",M),alert("Failed to start recording. Please ensure you granted permission.");}},C=()=>{f.current&&r&&(console.log("Stopping recording, state:",f.current.state),f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),i(false));},w=()=>{if(u){let M=URL.createObjectURL(u),P=document.createElement("a");P.href=M,P.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(M);}},b=M=>{let P=Math.floor(M/60),D=M%60;return `${P.toString().padStart(2,"0")}:${D.toString().padStart(2,"0")}`};if(!n)return null;if(r){let M=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:b(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:C,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(M,n)}let k=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:[!u&&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(!d),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${d?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:d?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:S,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"]})]})]}),u&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(u),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",b(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&g.current&&(t(u,g.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:w,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:()=>{s(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(k,n)};var Zu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:n})=>{let r=Ve(),[i,u]=useState(false),[s,c]=useState(null),[m,d]=useState(false),[l,f]=useState(0),h=useRef(null),p=useRef([]),y=useRef(null),v=useRef(null);useEffect(()=>{o&&!s&&fetch(o).then(M=>M.blob()).then(M=>c(M)).catch(M=>console.error("Error loading audio:",M));},[o,s]);let g=async()=>{try{let M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),P=new MediaRecorder(M);h.current=P,p.current=[],P.ondataavailable=D=>{D.data.size>0&&p.current.push(D.data);},P.onstop=()=>{let D=new Blob(p.current,{type:"audio/webm"});c(D),M.getTracks().forEach(W=>W.stop()),y.current&&clearInterval(y.current);},P.start(),u(!0),f(0),y.current=setInterval(()=>{f(D=>D+1);},1e3);}catch(M){console.error("Error starting audio recording:",M),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{h.current&&i&&(h.current.stop(),u(false));},L=()=>{if(s){let M=URL.createObjectURL(s),P=new Audio(M);v.current=P,P.onended=()=>{d(false),URL.revokeObjectURL(M);},P.play(),d(true);}},S=()=>{v.current&&(v.current.pause(),v.current.currentTime=0,d(false));},C=async()=>{if(s){let M=new FileReader;M.onloadend=()=>{let P=M.result;t(P),n();},M.readAsDataURL(s);}},w=()=>{c(null),a();},b=M=>{let P=Math.floor(M/60),D=M%60;return `${P.toString().padStart(2,"0")}:${D.toString().padStart(2,"0")}`};if(!r)return null;if(i){let M=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:b(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:x,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]})});return createPortal(M,r)}let k=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:[!s&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:g,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"]})}),s&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:m?S:L,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),m?"Playing...":"Play Audio"]}),jsx("button",{onClick:w,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:C,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:n,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(k,r)};var Ft=({audioData:e,x:o,y:t,width:a,scale:n=1,offsetX:r=0,offsetY:i=0,containerTop:u=90,containerRight:s=320})=>{let[c,m]=useState(false),d=useRef(null),l=p=>{if(p.stopPropagation(),c&&d.current)d.current.pause(),d.current.currentTime=0,m(false);else {let y=new Audio(e);d.current=y,y.onended=()=>{m(false);},y.onerror=()=>{console.error("Error playing audio"),m(false);},y.play(),m(true);}},f=(o+a)*n+r-15,h=t*n+i+u-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${c?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${f}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var ec=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=be(),n=ee(ge),r=Ve(),i=useMemo(()=>{if(!n)return [];let v=[];return n.images?.forEach(g=>{v.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),n.videos?.forEach(g=>{v.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),n.shapes?.forEach(g=>{v.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),n.texts?.forEach(g=>{v.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),n.flashcards?.forEach(g=>{v.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),n.photoFrames?.forEach(g=>{v.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),n.multipleChoices?.forEach(g=>{v.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),n.trueFalses?.forEach(g=>{v.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),n.shortAnswers?.forEach(g=>{v.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),n.LongAnswer?.forEach(g=>{v.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),n.fillInTheBlanks?.forEach(g=>{v.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),n.lines?.forEach(g=>{g.id&&v.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),v.sort((g,x)=>x.timestamp-g.timestamp)},[n]),[u,s]=useState(i),[c,m]=useState(false);useEffect(()=>{c||s(i);},[i]);let d=v=>{let g="h-5 w-5";switch(v){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})}},h=v=>{m(true),s(v);},p=()=>{m(false);let v=Date.now();u.forEach((g,x)=>{let L=v-x;a(br({id:g.id,type:g.type,newTimestamp:L}));});};if(!r)return null;let y=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-50 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-50 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:u.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:u,onReorder:h,className:"space-y-1",children:u.map(v=>{let g=v.id===e;return jsxs(Reorder.Item,{value:v,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(v.id,v.type),className:`font-medium ${g?"text-[#096B76]":"text-[#00000099]"}`,children:v.name})}),jsx("div",{className:`${g?"text-[#096B76]":"text-[#00000099]"}`,children:d(v.type)})]},v.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:[u.length," Layers"]})]})]})]});return createPortal(y,r)};var us=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;r.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},tc=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,touchHandlers:i})=>{let u=useSelector(P=>P.toolbar.selectedTool),s=u==="pen"||u==="eraser",[c,m]=useState(new Set),[d,l]=useState(false),[f,h]=useState(null),p=useRef(null);useEffect(()=>{let P=p.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id]);let y=new Set(e.data.responseOptions.correctIndex),v=y.size>1,g=P=>{d||m(v?D=>{let W=new Set(D);return W.has(P)?W.delete(P):W.add(P),W}:new Set([P]));},x=()=>{c.size>0&&l(true);},L=()=>{l(false),m(new Set);},S=c.size===y.size&&Array.from(c).every(P=>y.has(P)),C=Array.from(c).filter(P=>y.has(P)),w=v&&C.length>0&&!S,b=()=>S?"\u2713 Correct! Great job! \u{1F389}":w?`\u26A0 Partially correct (${C.length}/${y.size})`:"\u2717 Try again!",k=()=>S?{bg:"#dcfce7",text:"#166534"}:w?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},M=useMemo(()=>{let F=e.data.feedbackMode==="practice"?48:0,z=12,_=e.width-48,oe=_-80,V=Math.max(60,us(e.data.question,20,_,"bold")+20),j=`Select ${y.size} answers (${c.size}/${y.size} selected)`,Z=v&&!d&&e.data.feedbackMode==="practice"?us(j,14,_)+10:0,Y=d&&e.data.feedbackMode==="practice"?Math.max(60,us(b(),16,_-40)+30):0,ne=e.data.responseOptions.options.map(Pe=>{let Ee=us(Pe,16,oe);return Math.max(55,Ee+20)}),J=V+Z+Y,ce=ne.reduce((Pe,Ee)=>Pe+Ee+8,-8),we=J+ce+z+F+24;return {padding:24,questionHeight:V,instructionHeight:Z,feedbackHeight:Y,optionsStartY:J,optionHeights:ne,totalHeight:we,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:F,buttonTopMargin:z,availableWidth:_,optionTextWidth:oe}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,d,c.size,y.size,v,b]);return jsxs(Group,{ref:p,name:"mcq-element",draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:M.totalHeight,...i,...s?{}:{onDragEnd:n,onClick:P=>t&&t(e.id),onTap:P=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:M.totalHeight,width:e.width,onTransformEnd:P=>o(e.id,P),onContextMenu:P=>{P.cancelBubble=true,r(P.evt,e.id,"mcq");}}),jsx(Text,{x:M.padding+8,y:M.padding,text:e.data.question,fontSize:M.questionFontSize,fontStyle:"bold",fill:"#111827",width:M.availableWidth,height:M.questionHeight-M.padding,wrap:"word",ellipsis:true,listening:false}),M.instructionHeight>0&&jsx(Text,{x:M.padding,y:M.questionHeight,text:`Select ${y.size} answers (${c.size}/${y.size} selected)`,fontSize:M.instructionFontSize,fill:"#6b7280",width:M.availableWidth,wrap:"word",listening:false}),d&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:M.padding+24,y:M.questionHeight+M.instructionHeight+10,width:M.availableWidth-40,height:M.feedbackHeight-20,fill:k().bg,cornerRadius:8}),jsx(Text,{x:M.padding+24,y:M.questionHeight+M.instructionHeight+10,width:M.availableWidth-40,height:M.feedbackHeight-20,text:b(),fontSize:M.feedbackFontSize,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((P,D)=>{let W=y.has(D),B=c.has(D),U=M.optionsStartY;for(let _=0;_<D;_++)U+=M.optionHeights[_]+M.optionGap;let N=M.optionHeights[D],q="#e5e7eb",F="#ffffff",z="#111827";return d&&W?(q="#22c55e",F="#dcfce7",z="#1B9D2C"):d&&B&&!W?(q="#ef4444",F="#fee2e2",z="#ef4444"):B&&(q="#096B76",F="#ECFFF8",z="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:M.padding+12,y:U+(N-20)/2,width:20,height:20,fill:B?"#096B76":"white",stroke:B?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:v?4:10,onClick:_=>{_.cancelBubble=true,g(D);},onTap:_=>{_.cancelBubble=true,g(D);}}),B&&jsx(Text,{x:M.padding+12,y:U+(N-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:M.padding+44,y:U,width:M.availableWidth-60,height:N,fill:F,stroke:q,strokeWidth:2,cornerRadius:8,onClick:_=>{_.cancelBubble=true,g(D);},onTap:_=>{_.cancelBubble=true,g(D);}}),jsx(Text,{x:M.padding+60,y:U+10,width:M.optionTextWidth,height:N-20,text:P,fontSize:M.optionFontSize,fill:z,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},D)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:M.optionsStartY+M.optionHeights.reduce((P,D)=>P+D+M.optionGap,-M.optionGap)+M.buttonTopMargin,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,h("check");},onMouseUp:P=>{P.cancelBubble=true,h(null),x();},onMouseLeave:P=>{P.cancelBubble=true,h(null);},onTouchStart:P=>{P.cancelBubble=true,h("check");},onTouchEnd:P=>{P.cancelBubble=true,h(null),x();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:M.padding+14,width:(M.availableWidth-24)/(d?2:1),height:M.buttonHeight,fill:c.size===0||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:M.padding+14,width:(M.availableWidth-24)/(d?2:1),height:M.buttonHeight,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-M.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),L();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),L();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:M.padding,width:(M.availableWidth-8)/2,height:M.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:M.padding,width:(M.availableWidth-8)/2,height:M.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});tc.displayName="MultipleChoice";var ac=tc;var Ex=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;r.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},ll=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:n,touchHandlers:r})=>{let i=useDispatch(),u=useSelector(q=>q.toolbar.selectedTool),s=u==="pen"||u==="eraser",[c,m]=useState(false),[d,l]=useState(new Set),[f,h]=useState(false),[p,y]=useState(false),[v,g]=useState(0),x=new Set(e.data.responseOptions.correctIndex),L=Array.from(d).filter(q=>x.has(q)),S=d.size===x.size&&Array.from(d).every(q=>x.has(q)),C=L.length>0&&!S,w=()=>S?"\u2713 Correct! Great job!":C?`\u26A0 Partially correct (${L.length}/${x.size})`:"\u2717 Try again!",b=useMemo(()=>{let z=window.innerWidth*.4,_=20,oe=18,V=28,j=40,Z=50,Y=20,ne=60,J=z-40,ce=Math.max(60,Ex(e.data.question,_,J,"bold")+20),we=340+Y,Pe=100+ce+20,Ee=z-Y*2,Fe=Math.max(150,window.innerHeight*.3),nt=e.data.feedbackMode==="practice",At=ce+50+Fe+(f?ne+18:0)+(nt?j+(f?Z:0)+20:0),po=At+100;return {screenX:340,screenY:100,screenWidth:z,screenHeight:po,dropZoneX:we,dropZoneY:Pe,dropZoneWidth:Ee,dropZoneHeight:Fe,questionFontSize:_,questionHeight:ce,feedbackFontSize:oe,feedbackHeight:ne,dropHereFontSize:V,buttonHeight:j,buttonGap:Z,padding:Y,contentWidth:J,totalContentHeight:At,isPracticeMode:nt}},[e.data.question,e.data.feedbackMode,f,d.size]),k=useRef(null);useEffect(()=>{let q=k.current;if(q)return n.current.set(e.id,q),()=>{n.current.delete(e.id);}},[e.id]);let M=q=>{i(ga({id:e.id,x:q.target.x(),y:q.target.y()}));},P=q=>{let F=q.target,z=F.x(),_=F.y(),oe=window.innerWidth*.2,j=z+oe>b.dropZoneX&&z<b.dropZoneX+b.dropZoneWidth&&_+50>b.dropZoneY&&_<b.dropZoneY+b.dropZoneHeight;m(j);},D=(q,F)=>{let z=F.target,_=z.x(),oe=z.y(),V=window.innerWidth*.2,Z=_+V>b.dropZoneX&&_<b.dropZoneX+b.dropZoneWidth&&oe+50>b.dropZoneY&&oe<b.dropZoneY+b.dropZoneHeight;l(Z?Y=>new Set(Y).add(q):Y=>{let ne=new Set(Y);return ne.delete(q),ne}),m(false);},W=()=>{h(true);},B=()=>{h(false),l(new Set),g(q=>q+1);},U=()=>S?{bg:"#dcfce7",text:"#166534"}:C?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},N=()=>f?S?"#4CAF50":C?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:k,name:"mcq-element",width:b.screenWidth,height:b.screenHeight,draggable:!s,listening:!s,...r,...s?{}:{onClick:q=>a&&a(e.id),onTap:q=>a&&a(e.id),onContextMenu:q=>{q.evt.preventDefault(),o(q.evt,e.id,"mcq");}},children:[jsxs(Group,{x:b.screenX,y:b.screenY,rotation:e.rotation,onDragEnd:M,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:b.totalContentHeight,width:b.screenWidth,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:b.padding,y:b.padding,width:b.contentWidth,height:b.questionHeight-b.padding,text:e.data.question,fontSize:b.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:b.padding,y:b.questionHeight+20,width:b.dropZoneWidth,height:b.dropZoneHeight,fill:"#EBF6F7",stroke:N(),strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:b.padding+3,y:b.questionHeight+20+b.dropZoneHeight+18,width:b.dropZoneWidth-5,height:b.feedbackHeight,fill:U().bg,cornerRadius:8}),jsx(Text,{x:b.padding,y:b.questionHeight+20+b.dropZoneHeight+20,width:b.dropZoneWidth,height:b.feedbackHeight,text:w(),fontSize:b.feedbackFontSize,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),d.size===0&&!f&&jsx(Text,{x:b.padding,y:b.questionHeight+20,width:b.dropZoneWidth,height:b.dropZoneHeight,text:x.size>1?`Drop ${x.size} Correct Answers Here`:"Drop Here",fontSize:b.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),b.isPracticeMode?jsxs(Group,{x:b.padding,y:b.questionHeight+20+b.dropZoneHeight+(f?b.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:()=>{y(true),W();},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{y(true),W();},onTouchEnd:()=>y(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:b.buttonHeight,width:b.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:b.dropZoneWidth,height:b.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:b.buttonGap,onMouseDown:B,onTouchStart:B,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:b.buttonHeight,width:b.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:b.dropZoneWidth,height:b.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((q,F)=>{let z=F%2,_=Math.floor(F/2),oe=window.innerWidth*.2,V=50,j=10,Z=d.has(F),Y=x.has(F),ne=f&&Z,J="transparent";return ne?J=Y?"#4CAF50":"#ef4444":Z&&(J="#4CAF50"),jsxs(Group,{x:340+z*(oe+j),y:b.screenY+b.totalContentHeight+_*(V+j)+20,draggable:!f,onDragMove:P,onDragEnd:ce=>D(F,ce),opacity:f&&!Z?.5:1,children:[jsx(Rect,{width:oe-20,height:V,fill:"white",stroke:J,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:oe-20,height:V,text:q,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${F}-${v}`)})]})};ll.displayName="MultipleChoiceDragAndDrop";var oc=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:i})=>{let{createHandlers:u}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(ac,{multipleChoice:s,handleMcqTransform:o,mcqRefs:a,handleDragEnd:c=>n(c,s.id),onContextMenu:r,touchHandlers:u(s.id,"mcq")},s.id):jsx(ll,{multipleChoice:s,handleMcqTransform:o,mcqRefs:a,onContextMenu:r,touchHandlers:u(s.id,"mcq")},s.id))})};var rc=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;r.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},nc=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:i})=>{let u=useSelector(b=>b.toolbar.selectedTool),s=u==="pen"||u==="eraser",[c,m]=useState(null),[d,l]=useState(false),[f,h]=useState(null),p=useRef(null);useEffect(()=>{let b=p.current;if(b)return a.current.set(e.id,b),()=>{a.current.delete(e.id);}},[e.id]);let y=()=>{c!==null&&l(true);},v=()=>{l(false),m(null);},g=e.data.responseOptions.correctAnswer,x=c===g,L=b=>{d||m(b);},S=()=>x?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},w=useMemo(()=>{let B=e.data.feedbackMode==="practice"?48:0,U=12,N=e.width-48,q=Math.max(60,rc(e.data.question,20,N,"bold")+20),F=d&&e.data.feedbackMode==="practice"?Math.max(60,rc(S(),16,N-40)+30):0,z=q+F,_=164,oe=z+_+U+B+24;return {padding:24,questionHeight:q,feedbackHeight:F,optionsStartY:z,optionsHeight:_,totalHeight:oe,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:B,buttonTopMargin:U,availableWidth:N}},[e.width,e.data.question,e.data.feedbackMode,d,S]);return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:w.totalHeight,...i,...s?{}:{onDragEnd:b=>r(b,e.id),onClick:b=>t&&t(e.id),onTap:b=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:w.totalHeight,width:e.width,onTransformEnd:b=>o(e.id,b),onContextMenu:b=>{b.cancelBubble=true,n(b.evt,e.id,"trueFalse");}}),jsx(Text,{x:w.padding+8,y:w.padding,text:e.data.question,fontSize:w.questionFontSize,fontStyle:"bold",fill:"#111827",width:w.availableWidth,height:w.questionHeight-w.padding,wrap:"word",ellipsis:true,listening:false}),d&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:w.padding+24,y:w.questionHeight+10,width:w.availableWidth-40,height:w.feedbackHeight-20,fill:C().bg,cornerRadius:8}),jsx(Text,{x:w.padding+24,y:w.questionHeight+10,width:w.availableWidth-40,height:w.feedbackHeight-20,text:S(),fontSize:w.feedbackFontSize,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((b,k)=>{let M=g===b.value,P=c===b.value,D=(e.width-w.padding*3)/2,W=w.padding+k*(D+w.padding),B=w.optionsStartY,U=b.value===true,N=U?"#10b981":"#ef4444",q="#ffffff",F="#ffffff",z="#e5e7eb";return d&&(M?(F=U?"#f0fdf4":"#fef2f2",z=U?"#86efac":"#fecaca"):P&&!M&&(F="#fee2e2",z="#ef4444")),P&&!d&&(z="#096B76",F="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:W,y:B,width:D,height:w.optionHeight+50,fill:F,stroke:z,strokeWidth:2,cornerRadius:12,onClick:_=>{_.cancelBubble=true,L(b.value);},onTap:_=>{_.cancelBubble=true,L(b.value);}}),jsx(Circle,{x:W+D/2,y:B+40,radius:28,fill:N,listening:false}),U?jsx(Text,{x:W+D/2-14,y:B+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:q,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:W+D/2-14,y:B+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:q,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:W,y:B+85,width:D,height:30,text:b.label,fontSize:w.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},b.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:w.optionsStartY+2*(w.optionHeight+w.optionGap)+w.buttonTopMargin,children:[jsxs(Group,{onMouseDown:b=>{b.cancelBubble=true,h("check");},onMouseUp:b=>{b.cancelBubble=true,h(null),y();},onMouseLeave:b=>{b.cancelBubble=true,h(null);},onTouchStart:b=>{b.cancelBubble=true,h("check");},onTouchEnd:b=>{b.cancelBubble=true,h(null),y();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:w.padding+14,width:(w.availableWidth-24)/(d?2:1),height:w.buttonHeight,fill:c===null||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:b=>b.cancelBubble=true,onTap:b=>b.cancelBubble=true}),jsx(Text,{x:w.padding+14,width:(w.availableWidth-24)/(d?2:1),height:w.buttonHeight,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-w.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),v();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),v();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:w.padding,width:(w.availableWidth-8)/2,height:w.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:b=>b.cancelBubble=true,onTap:b=>b.cancelBubble=true}),jsx(Text,{x:w.padding,width:(w.availableWidth-8)/2,height:w.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});nc.displayName="TrueFalse";var sc=nc;var Kx="#FFFFFF",cl=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t,touchHandlers:a})=>{let n=useDispatch(),r=useSelector(Y=>Y.toolbar.selectedTool),i=r==="pen"||r==="eraser",[u,s]=useState(false),[c,m]=useState(null),[d,l]=useState(false),[f,h]=useState(false),[p,y]=useState(0),[v,g]=useState(false),x=340,L=100,S=window.innerWidth*.4,C=window.innerHeight*.5,w=S-40,b=C-300,k=20,M=60,P=w,D=b,W=S*.2-40,B=50,U=useRef(null),N=Y=>{n(xa({id:e.id,x:Y.target.x(),y:Y.target.y()}));},q=Y=>{let ne=Y.target,J=ne.x(),ce=ne.y(),we=Math.max(0,Math.min(J+W,k+P)-Math.max(J,k)),Pe=Math.max(0,Math.min(ce+B,M+D)-Math.max(ce,M)),Ee=we*Pe,Fe=W*B;s(Ee/Fe>=.5);},F=(Y,ne)=>{let J=ne.target,ce=J.x(),we=J.y(),Pe=Math.max(0,Math.min(ce+W,k+P)-Math.max(ce,k)),Ee=Math.max(0,Math.min(we+B,M+D)-Math.max(we,M)),Fe=Pe*Ee,nt=W*B;if(Fe/nt>=.5)m(Y);else return;s(false);},z=()=>{l(true);},_=()=>{l(false),m(null),y(Y=>Y+1);},oe=e.data.responseOptions.correctAnswer,V=c===oe,j=()=>V?"\u2713 Correct! Great job!":"\u2717 Try again!",Z=()=>V?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:U,name:"trueFalse-element",width:S,height:C,draggable:!i,listening:!i,...a,...i?{}:{onContextMenu:Y=>{Y.evt.preventDefault(),o(Y.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:L,rotation:e.rotation,onDragEnd:N,children:[jsx(Rect,{fill:"white",stroke:u?"#4CAF50":"#e5e7eb",strokeWidth:u?4:2,cornerRadius:12,height:d?C:e.data.feedbackMode==="practice"?C-50:C-100,width:S,shadowColor:u?"#4CAF50":"transparent",shadowBlur:u?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:S-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:w,height:b,fill:"transparent",stroke:u?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:w,height:60,fill:Z().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:w,height:60,text:j(),fontSize:18,fontStyle:"bold",fill:Z().text,align:"center",verticalAlign:"middle"})]}),c===null&&!d&&jsx(Text,{x:20,y:60,width:w,height:b-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:()=>{c!==null&&(h(true),z());},onMouseUp:()=>h(false),onMouseLeave:()=>h(false),onTouchStart:()=>{c!==null&&(h(true),z());},onTouchEnd:()=>h(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:c===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:w}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:w,height:40,align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{y:50,onMouseDown:_,onTouchStart:_,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:w}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:w,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((Y,ne)=>{let J=window.innerWidth*.2,ce=50,we=10,Pe=c===Y.value,Ee=oe===Y.value,Fe=d&&Pe,nt="transparent";return Fe?nt=Ee?"#4CAF50":"#ef4444":Pe&&(nt="#4CAF50"),jsxs(Group,{x:16+ne*(J+we),y:L+C-300,draggable:!d,onDragMove:q,onDragEnd:At=>F(Y.value,At),opacity:d&&!Pe?.5:1,children:[jsx(Rect,{width:J-40,height:ce,fill:"#075560",stroke:nt,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:J-40,height:ce,text:Y.label,fontSize:18,fontStyle:"bold",fill:Kx,align:"center",verticalAlign:"middle",listening:false})]},`${Y.value}-${p}`)})]})})};cl.displayName="TrueFalseDragAndDrop";var ic=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:i})=>{let{createHandlers:u}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(sc,{trueFalse:s,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:u(s.id,"trueFalse")},s.id):jsx(cl,{trueFalse:s,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:r,touchHandlers:u(s.id,"trueFalse")},s.id))})};var Ia=new WeakMap,Ho=new WeakMap,Br={current:[]},ml=false,Fr=0,Dr=new Set,cs=new Map;function lc(e){let o=Array.from(e).sort((t,a)=>t instanceof zt&&t.options.deps.includes(a)?1:a instanceof zt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(Br.current.includes(t))continue;Br.current.push(t),t.recompute();let a=Ho.get(t);if(a)for(let n of a){let r=Ia.get(n);r&&lc(r);}}}function _x(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Xx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function fs(e){if(Fr>0&&!cs.has(e)&&cs.set(e,e.prevState),Dr.add(e),!(Fr>0)&&!ml)try{for(ml=!0;Dr.size>0;){let o=Array.from(Dr);Dr.clear();for(let t of o){let a=cs.get(t)??t.prevState;t.prevState=a,_x(t);}for(let t of o){let a=Ia.get(t);a&&(Br.current.push(t),lc(a));}for(let t of o){let a=Ia.get(t);if(a)for(let n of a)Xx(n);}}}finally{ml=false,Br.current=[],cs.clear();}}function Lt(e){Fr++;try{e();}finally{if(Fr--,Fr===0){let o=Dr.values().next().value;o&&fs(o);}}}function dc(e){return typeof e=="function"}var Zt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var n,r;this.listeners.add(a);let i=(r=(n=this.options)==null?void 0:n.onSubscribe)==null?void 0:r.call(n,a,this);return ()=>{this.listeners.delete(a),i?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,n;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):dc(o)?this.state=o(this.prevState):this.state=o,(n=(a=this.options)==null?void 0:a.onUpdate)==null||n.call(a),fs(this);}};var zt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),n=new Array(t);for(let r=0;r<t;r++){let i=this.options.deps[r];a[r]=i.prevState,n[r]=i.state;}return this.lastSeenDepValues=n,{prevDepVals:a,currDepVals:n,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let n=this.getDepVals();this.state=this.options.fn(n),(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:n}=this.getDepVals();for(let r=0;r<n.length;r++)if(n[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,n;this.listeners.add(t);let r=(n=(a=this.options).onSubscribe)==null?void 0:n.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 Zt){let a=Ia.get(t);a||(a=new Set,Ia.set(t,a)),a.add(this);let n=Ho.get(this);n||(n=new Set,Ho.set(this,n)),n.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 Zt){let a=Ia.get(t);a&&a.delete(this);let n=Ho.get(this);n&&n.delete(t);}}};function $x(e){return typeof e=="function"}function pl(e,...o){return $x(e)?e(...o):e}function uc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Ca,ht,dt,Or,ka,Ja,oa,qo,Nr,ms,Hr,Vo,Qa=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:n=1e3}){Be(this,Ca,true);Be(this,ht);Be(this,dt);Be(this,Or);Be(this,ka);Be(this,Ja);Be(this,oa);Be(this,qo);Be(this,Nr,0);Be(this,ms,5);Be(this,Hr,()=>{this.debugLog("Connected to event bus"),Me(this,Ja,true),this.debugLog("Emitting queued events",G(this,ka)),G(this,ka).forEach(o=>this.emitEventToBus(o)),Me(this,ka,[]),this.stopConnectLoop(),G(this,dt).call(this).removeEventListener("tanstack-connect-success",G(this,Hr));});Be(this,Vo,()=>{if(G(this,dt).call(this).addEventListener("tanstack-connect-success",G(this,Hr)),G(this,Nr)<G(this,ms)){Od(this,Nr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}G(this,dt).call(this).removeEventListener("tanstack-connect",G(this,Vo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Me(this,ht,o),Me(this,Ca,a),Me(this,dt,this.getGlobalTarget),Me(this,Or,t),this.debugLog(" Initializing event subscription for plugin",G(this,ht)),Me(this,ka,[]),Me(this,Ja,false),Me(this,oa,null),Me(this,qo,n);}startConnectLoop(){G(this,oa)!==null||G(this,Ja)||(this.debugLog(`Starting connect loop (every ${G(this,qo)}ms)`),Me(this,oa,setInterval(G(this,Vo),G(this,qo))));}stopConnectLoop(){G(this,oa)!==null&&(clearInterval(G(this,oa)),Me(this,oa,null),this.debugLog("Stopped connect loop"));}debugLog(...o){G(this,Or)&&console.log(`\u{1F334} [tanstack-devtools:${G(this,ht)}-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 G(this,ht)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});G(this,dt).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{G(this,dt).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(!G(this,Ca)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!G(this,Ja)){this.debugLog("Bus not available, will be pushed as soon as connected"),G(this,ka).push({type:`${G(this,ht)}:${o}`,payload:t,pluginId:G(this,ht)}),typeof CustomEvent<"u"&&(G(this,Vo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${G(this,ht)}:${o}`,payload:t,pluginId:G(this,ht)})}on(o,t){let a=`${G(this,ht)}:${o}`;if(!G(this,Ca))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let n=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return G(this,dt).call(this).addEventListener(a,n),this.debugLog("Registered event to bus",a),()=>{G(this,dt).call(this).removeEventListener(a,n);}}onAll(o){if(!G(this,Ca))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;o(n);};return G(this,dt).call(this).addEventListener("tanstack-devtools-global",t),()=>G(this,dt).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!G(this,Ca))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;G(this,ht)&&n.pluginId!==G(this,ht)||o(n);};return G(this,dt).call(this).addEventListener("tanstack-devtools-global",t),()=>G(this,dt).call(this).removeEventListener("tanstack-devtools-global",t)}};Ca=new WeakMap,ht=new WeakMap,dt=new WeakMap,Or=new WeakMap,ka=new WeakMap,Ja=new WeakMap,oa=new WeakMap,qo=new WeakMap,Nr=new WeakMap,ms=new WeakMap,Hr=new WeakMap,Vo=new WeakMap;var hl=class extends Qa{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},cc=(e,o)=>{gl.emit(e,o);},gl=new hl;function fc(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Yx={enabled:true,leading:true,trailing:true,wait:0},Ta,It,eo,to,ao,Uo,ps=class{constructor(o,t){Be(this,Ta);Be(this,It);Be(this,eo);Be(this,to);Be(this,ao);Be(this,Uo);this.fn=o,this.store=new Zt(fc()),this.setOptions=a=>{this.options={...this.options,...a},G(this,eo).call(this)||this.cancel();},Me(this,It,a=>{this.store.setState(n=>{let r={...n,...a},{isPending:i}=r;return {...r,status:G(this,eo).call(this)?i?"pending":"idle":"disabled"}}),cc("Throttler",this);}),Me(this,eo,()=>!!pl(this.options.enabled,this)),Me(this,to,()=>pl(this.options.wait,this)),this.maybeExecute=(...a)=>{G(this,It).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let n=Date.now(),r=n-this.store.state.lastExecutionTime,i=G(this,to).call(this);if(this.options.leading&&r>=i)G(this,ao).call(this,...a);else if(G(this,It).call(this,{lastArgs:a}),!G(this,Ta)&&this.options.trailing){let u=this.store.state.lastExecutionTime?n-this.store.state.lastExecutionTime:0,s=i-u;G(this,It).call(this,{isPending:true}),Me(this,Ta,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&G(this,ao).call(this,...c);},s));}},Me(this,ao,(...a)=>{if(!G(this,eo).call(this))return;this.fn(...a);let n=Date.now(),r=n+G(this,to).call(this);G(this,Uo).call(this),G(this,It).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:n,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||G(this,It).call(this,{nextExecutionTime:void 0});},G(this,to).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&G(this,ao).call(this,...this.store.state.lastArgs);},Me(this,Uo,()=>{G(this,Ta)&&(clearTimeout(G(this,Ta)),Me(this,Ta,void 0));}),this.cancel=()=>{G(this,Uo).call(this),G(this,It).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{G(this,It).call(this,fc());},this.key=uc(t.key),this.options={...Yx,...t},G(this,It).call(this,this.options.initialState??{}),gl.on("d-Throttler",a=>{a.payload.key===this.key&&(G(this,It).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Ta=new WeakMap,It=new WeakMap,eo=new WeakMap,to=new WeakMap,ao=new WeakMap,Uo=new WeakMap;function xl(e,o){return new ps(e,o).maybeExecute}function Ma(e,o){return typeof e=="function"?e(o):e}function Aa(e,o){return bs(o).reduce((a,n)=>{if(a===null)return null;if(typeof a<"u")return a[n]},e)}function Wo(e,o,t){let a=bs(o);function n(r){if(!a.length)return Ma(t,r);let i=a.shift();if(typeof i=="string"||typeof i=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[i]:n(r[i])}):{[i]:n()};if(Array.isArray(r)&&typeof i=="number"){let u=r.slice(0,i);return [...u.length?u:new Array(i),n(r[i]),...r.slice(i+1)]}return [...new Array(i),n()]}return n(e)}function vl(e,o){let t=bs(o);function a(n){if(!n)return;if(t.length===1){let i=t[0];if(Array.isArray(n)&&typeof i=="number")return n.filter((c,m)=>m!==i);let{[i]:u,...s}=n;return s}let r=t.shift();if(typeof r=="string"&&typeof n=="object")return {...n,[r]:a(n[r])};if(typeof r=="number"&&Array.isArray(n)){if(r>=n.length)return n;let i=n.slice(0,r);return [...i.length?i:new Array(r),a(n[r]),...n.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var Zx=/^(\d+)$/gm,Jx=/\.(\d+)(?=\.)/gm,Qx=/^(\d+)\./gm,eb=/\.(\d+$)/gm,tb=/\.{2,}/gm,bl="__int__",hs=`${bl}$1`;function bs(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(Zx,hs).replace(Jx,`.${hs}.`).replace(Qx,`${hs}.`).replace(eb,`.${hs}`).replace(tb,".").split(".").map(o=>{if(o.startsWith(bl)){let t=o.substring(bl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function yl(e){return !(Array.isArray(e)&&e.length===0)}function zo(e,o){let t=a=>a.validators.filter(Boolean).map(n=>({cause:n.cause,validate:n.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Ko(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:n,onDynamicAsyncDebounceMs:r}=o.validators||{},i=t??0,u=s=>s.validators.filter(Boolean).map(c=>{let m=c?.cause||e,d=i;switch(m){case "change":d=n??i;break;case "blur":d=a??i;break;case "dynamic":d=r??i;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:m,validate:c.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var qr=e=>!!e&&typeof e=="object"&&"fields"in e;function Pa(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[n,r]of e)if(!o.has(n)||!Object.is(r,o.get(n)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let n of e)if(!o.has(n))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let n of t)if(!a.includes(n)||!Pa(e[n],o[n]))return false;return true}var vs=({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},ys=({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 oo=256,xs=[],gs;for(;oo--;)xs[oo]=(oo+256).toString(16).substring(1);function wl(){let e=0,o,t="";if(!gs||oo+16>256){for(gs=new Array(256),e=256;e--;)gs[e]=256*Math.random()|0;e=0,oo=0;}for(;e<16;e++)o=gs[oo+e],e===6?t+=xs[o&15|64]:e===8?t+=xs[o&63|128]:t+=xs[o],e&1&&e>1&&e<11&&(t+="-");return oo++,t}var Ea=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"},n={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},i=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,n,r,i],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[n,i],form:e.form});case "change":return e.runValidation({validators:[a,i],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function ab(e,o){let t=new Map;for(let a of e){let n=a.path??[],r=o,i="";for(let u=0;u<n.length;u++){let s=n[u];if(s===void 0)continue;let c=typeof s=="object"?s.key:s,m=Number(c);Array.isArray(r)&&!Number.isNaN(m)?i+=`[${m}]`:i+=(u>0?".":"")+String(c),typeof r=="object"&&r!==null?r=r[c]:r=void 0;}t.set(i,(t.get(i)??[]).concat(a));}return Object.fromEntries(t)}var mc=(e,o)=>{let t=ab(e,o);return {form:t,fields:t}},Ra={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:mc(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:mc(a.issues,e)}},ws=e=>!!e&&"~standard"in e;var Go={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function Vr(e){function o(d,l,f,h){let p=a(d,l,f,h);({insert:()=>u(p,d,l),remove:()=>s(p),swap:()=>h!==void 0&&m(p,d,l,h),move:()=>h!==void 0&&c(p,d,l,h)})[f]();}function t(d,l){return `${d}[${l}]`}function a(d,l,f,h){let p=[t(d,l)];if(f==="swap")p.push(t(d,h));else if(f==="move"){let[y,v]=[Math.min(l,h),Math.max(l,h)];for(let g=y;g<=v;g++)p.push(t(d,g));}else {let y=e.getFieldValue(d),v=Array.isArray(y)?y.length:0;for(let g=l+1;g<v;g++)p.push(t(d,g));}return Object.keys(e.fieldInfo).filter(y=>p.some(v=>y.startsWith(v)))}function n(d,l){return d.replace(/\[(\d+)\]/,(f,h)=>{let p=parseInt(h,10);return `[${l==="up"?p+1:Math.max(0,p-1)}]`})}function r(d,l){(l==="up"?d:[...d].reverse()).forEach(h=>{let p=n(h.toString(),l),y=e.getFieldMeta(p);y?e.setFieldMeta(h,y):e.setFieldMeta(h,i());});}let i=()=>Go,u=(d,l,f)=>{r(d,"down"),d.forEach(h=>{h.toString().startsWith(t(l,f))&&e.setFieldMeta(h,i());});},s=d=>{r(d,"up");},c=(d,l,f,h)=>{let p=new Map(Object.keys(e.fieldInfo).filter(y=>y.startsWith(t(l,f))).map(y=>[y,e.getFieldMeta(y)]));r(d,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(y=>y.startsWith(t(l,h))).forEach(y=>{let v=y.replace(t(l,h),t(l,f)),g=p.get(v);g&&e.setFieldMeta(y,g);});},m=(d,l,f,h)=>{d.forEach(p=>{if(!p.toString().startsWith(t(l,f)))return;let y=p.toString().replace(t(l,f),t(l,h)),[v,g]=[e.getFieldMeta(p),e.getFieldMeta(y)];v&&e.setFieldMeta(y,v),g&&e.setFieldMeta(p,g);});};return {handleArrayFieldMetaShift:o}}var Sl=class extends Qa{constructor(){super({pluginId:"form-devtools"});}},Ct=new Sl;function Ll(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 Wr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),n=this.store.mount(),r=()=>{a(),n(),Ct.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:i}=this.options.validators||{};return Ct.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),i&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let n=this.options;this.options=a;let r=!!a.transform?.deps?.some((s,c)=>s!==this.prevTransformArray[c]),i=a.defaultValues&&!Pa(a.defaultValues,n.defaultValues)&&!this.state.isTouched,u=!Pa(a.defaultState,n.defaultState)&&!this.state.isTouched;!i&&!u&&!r||(Lt(()=>{this.baseStore.setState(()=>Ll(Object.assign({},this.state,u?a.defaultState:{},i?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),Ct.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,n)=>{let{fieldMeta:r}=this.state,i=this.resetFieldMeta(r);a&&!n?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Ll({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:i}));},this.validateAllFields=async a=>{let n=[];return Lt(()=>{Object.values(this.fieldInfo).forEach(i=>{if(!i.instance)return;let u=i.instance;n.push(Promise.resolve().then(()=>u.validate(a,{skipFormValidation:!0}))),i.instance.state.meta.isTouched||i.instance.setMeta(s=>({...s,isTouched:!0}));});}),(await Promise.all(n)).flat()},this.validateArrayFieldsStartingFrom=async(a,n,r)=>{let i=this.getFieldValue(a),u=Array.isArray(i)?Math.max(i.length-1,0):null,s=[`${a}[${n}]`];for(let l=n+1;l<=(u??0);l++)s.push(`${a}[${l}]`);let c=Object.keys(this.fieldInfo).filter(l=>s.some(f=>l.startsWith(f))),m=[];return Lt(()=>{c.forEach(l=>{m.push(Promise.resolve().then(()=>this.validateField(l,r)));});}),(await Promise.all(m)).flat()},this.validateField=(a,n)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(i=>({...i,isTouched:true})),r.validate(n)):[]},this.validateSync=a=>{let n=zo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ea}),r=false,i={};return Lt(()=>{for(let c of n){if(!c.validate)continue;let m=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:l}=Ss(m),f=Ur(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let p=this.getFieldMeta(h);if(!p)continue;let{errorMap:y,errorSourceMap:v}=p,g=l?.[h],{newErrorValue:x,newSource:L}=vs({newFormValidatorError:g,isPreviousErrorFromFormValidator:v?.[f]==="form",previousErrorValue:y?.[f]});L==="form"&&(i[h]={...i[h],[f]:g}),y?.[f]!==x&&this.setFieldMeta(h,S=>({...S,errorMap:{...S.errorMap,[f]:x},errorSourceMap:{...S.errorSourceMap,[f]:L}}));}this.state.errorMap?.[f]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:d}})),(d||l)&&(r=!0);}let u=Ur("submit");this.state.errorMap?.[u]&&a!=="submit"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let s=Ur("server");this.state.errorMap?.[s]&&a!=="server"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[s]:void 0}}));}),{hasErrored:r,fieldsErrorMap:i}},this.validateAsync=async a=>{let n=Ko(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ea});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let r=[],i;for(let c of n){if(!c.validate)continue;let m=Ur(c.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[m]={lastAbortController:l},r.push(new Promise(async f=>{let h;try{h=await new Promise((g,x)=>{setTimeout(async()=>{if(l.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(L){x(L);}},c.debounceMs);});}catch(g){h=g;}let{formError:p,fieldErrors:y}=Ss(h);y&&(i=i?{...i,...y}:y);let v=Ur(c.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let x=this.getFieldMeta(g);if(!x)continue;let{errorMap:L,errorSourceMap:S}=x,C=i?.[g],{newErrorValue:w,newSource:b}=vs({newFormValidatorError:C,isPreviousErrorFromFormValidator:S?.[v]==="form",previousErrorValue:L?.[v]});L?.[v]!==w&&this.setFieldMeta(g,k=>({...k,errorMap:{...k.errorMap,[v]:w},errorSourceMap:{...k.errorSourceMap,[v]:b}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[v]:p}})),f(i?{fieldErrors:i,errorMapKey:v}:void 0);}));}let u=[],s={};if(r.length){u=await Promise.all(r);for(let c of u)if(c?.fieldErrors){let{errorMapKey:m}=c;for(let[d,l]of Object.entries(c.fieldErrors)){let h={...s[d]||{},[m]:l};s[d]=h;}}}return this.baseStore.setState(c=>({...c,isFormValidating:false})),s},this.validate=a=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(a);return n&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Aa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var n;return (n=this.fieldInfo)[a]||(n[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,n)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Ma(n,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((n,r)=>{let i=r;return n[i]=Go,n},{}),this.setFieldValue=(a,n,r)=>{let i=r?.dontUpdateMeta??false,u=r?.dontRunListeners??false,s=r?.dontValidate??false;Lt(()=>{i||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:Wo(c.values,a,n)}));}),u||this.getFieldInfo(a).instance?.triggerOnChangeListener(),s||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(i=>{let u=a.toString();return i!==u&&i.startsWith(u)}),a];this.baseStore.setState(i=>{let u={...i};return r.forEach(s=>{u.values=vl(u.values,s),delete this.fieldInfo[s],delete u.fieldMetaBase[s];}),u});},this.pushFieldValue=(a,n,r)=>{this.setFieldValue(a,i=>[...Array.isArray(i)?i:[],n],r);},this.insertFieldValue=async(a,n,r,i)=>{this.setFieldValue(a,s=>[...s.slice(0,n),r,...s.slice(n)],Je(i,{dontValidate:true}));let u=i?.dontValidate??false;u||await this.validateField(a,"change"),Vr(this).handleArrayFieldMetaShift(a,n,"insert"),u||await this.validateArrayFieldsStartingFrom(a,n,"change");},this.replaceFieldValue=async(a,n,r,i)=>{this.setFieldValue(a,s=>s.map((c,m)=>m===n?r:c),Je(i,{dontValidate:true})),(i?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.removeFieldValue=async(a,n,r)=>{let i=this.getFieldValue(a),u=Array.isArray(i)?Math.max(i.length-1,0):null;if(this.setFieldValue(a,c=>c.filter((m,d)=>d!==n),Je(r,{dontValidate:true})),Vr(this).handleArrayFieldMetaShift(a,n,"remove"),u!==null){let c=`${a}[${u}]`;this.deleteField(c);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.swapFieldValues=(a,n,r,i)=>{this.setFieldValue(a,s=>{let c=s[n],m=s[r];return Wo(Wo(s,`${n}`,m),`${r}`,c)},Je(i,{dontValidate:true})),Vr(this).handleArrayFieldMetaShift(a,n,"swap",r),(i?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,n,r,i)=>{this.setFieldValue(a,s=>{let c=[...s];return c.splice(r,0,c.splice(n,1)[0]),c},Je(i,{dontValidate:true})),Vr(this).handleArrayFieldMetaShift(a,n,"move",r),(i?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,n)=>{let r=this.getFieldValue(a),i=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],Je(n,{dontValidate:true})),i!==null)for(let s=0;s<=i;s++){let c=`${a}[${s}]`;this.deleteField(c);}(n?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:Go},values:this.options.defaultValues?Wo(n.values,a,Aa(this.options.defaultValues,a)):n.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[n,r])=>(Object.keys(r).length&&r.errors.length&&(a[n]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Ra.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ra.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??wl(),this._devtoolsSubmissionOverride=false,this.baseStore=new Zt(Ll({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new zt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let i=r,u=a?.[0],s=n[0],c=0,m={};for(let d of Object.keys(s.fieldMetaBase)){let l=s.fieldMetaBase[d],f=u?.fieldMetaBase[d],h=i?.[d],p=Aa(s.values,d),y=h?.errors;if(!f||l.errorMap!==f.errorMap){y=Object.values(l.errorMap??{}).filter(S=>S!==void 0);let L=this.getFieldInfo(d)?.instance;L&&!L.options.disableErrorFlat&&(y=y?.flat(1));}let v=!yl(y??[]),g=!l.isDirty,x=Pa(p,Aa(this.options.defaultValues,d))||Pa(p,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===v&&h.isDefaultValue===x&&h.errors===y&&l===f){m[d]=h,c++;continue}m[d]={...l,errors:y,isPristine:g,isValid:v,isDefaultValue:x};}return Object.keys(s.fieldMetaBase).length&&i&&c===Object.keys(s.fieldMetaBase).length?i:m}}),this.store=new zt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let i=r,u=a?.[0],s=n[0],c=n[1],m=Object.values(c).filter(Boolean),d=m.some(B=>B.isValidating),l=m.every(B=>B.isValid),f=m.some(B=>B.isTouched),h=m.some(B=>B.isBlurred),p=m.every(B=>B.isDefaultValue),y=f&&s.errorMap?.onMount,v=m.some(B=>B.isDirty),g=!v,x=!!(s.errorMap?.onMount||m.some(B=>B?.errorMap?.onMount)),L=!!d,S=i?.errors??[];(!u||s.errorMap!==u.errorMap)&&(S=Object.values(s.errorMap).reduce((B,U)=>U===void 0?B:U&&qr(U)?(B.push(U.form),B):(B.push(U),B),[]));let C=S.length===0,w=l&&C,b=this.options.canSubmitWhenInvalid??false,k=s.submissionAttempts===0&&!f&&!x||!L&&!s.isSubmitting&&w||b,M=s.errorMap;if(y&&(S=S.filter(B=>B!==s.errorMap.onMount),M=Object.assign(M,{onMount:void 0})),i&&u&&i.errorMap===M&&i.fieldMeta===this.fieldMetaDerived.state&&i.errors===S&&i.isFieldsValidating===d&&i.isFieldsValid===l&&i.isFormValid===C&&i.isValid===w&&i.canSubmit===k&&i.isTouched===f&&i.isBlurred===h&&i.isPristine===g&&i.isDefaultValue===p&&i.isDirty===v&&Pa(u,s))return i;let P={...s,errorMap:M,fieldMeta:this.fieldMetaDerived.state,errors:S,isFieldsValidating:d,isFieldsValid:l,isFormValid:C,isValid:w,canSubmit:k,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:p,isDirty:v},D=this.options.transform?.deps??[];if(D.length!==this.prevTransformArray.length||D.some((B,U)=>B!==this.prevTransformArray[U])){let B=Object.assign({},this,{state:P});this.options.transform?.fn(B),P=B.state,this.prevTransformArray=D;}return P}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=xl(a=>Ct.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),Ct.on("request-form-state",a=>{a.payload.id===this._formId&&Ct.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Ct.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),Ct.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 ws(o.validate)?Ra[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(n=>({...n,isSubmitted:false,submissionAttempts:n.submissionAttempts+1,isSubmitSuccessful:false})),Lt(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance&&(n.instance.state.meta.isTouched||n.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(n=>({...n,isSubmitting:true}));let a=()=>{this.baseStore.setState(n=>({...n,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Ct.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(n=>n.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Ct.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}Lt(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance?.options.listeners?.onSubmit?.({value:n.instance.state.value,fieldApi:n.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),Lt(()=>{this.baseStore.setState(n=>({...n,isSubmitted:!0,isSubmitSuccessful:!0})),Ct.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(n){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),Ct.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:n}),a(),n}}setErrorMap(o){Lt(()=>{Object.entries(o).forEach(([t,a])=>{let n=t;if(qr(a)){let{formError:r,fieldErrors:i}=Ss(a);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,c=>({...c,errorMap:{...c.errorMap,[n]:i?.[u]},errorSourceMap:{...c.errorSourceMap,[n]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[n]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[n]:a}}));});});}};function Ss(e){if(e){if(qr(e)){let o=Ss(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function Ur(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 zr=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:n}=this.options.validators||{};if(n){let r=this.runValidator({validate:n,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(i=>({...i,errorMap:{...i?.errorMap,onMount:r},errorSourceMap:{...i?.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 n=Aa(t.form.options.defaultValues,t.name),r=t.defaultValue??n;a?this.setValue(i=>i||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,n)=>{this.form.insertFieldValue(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,n)=>{this.form.replaceFieldValue(this.name,t,a,Je(n,{dontRunListeners:true})),n?.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,n)=>{this.form.swapFieldValues(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,n)=>{this.form.moveFieldValues(this.name,t,a,Je(n,{dontRunListeners:true})),n?.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),n=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:i,onBlurListenTo:u}=r.instance.options.validators||{};t==="change"&&i?.includes(this.name)&&n.push(r.instance),t==="blur"&&u?.includes(this.name)&&n.push(r.instance);}return n},this.validateSync=(t,a)=>{let n=zo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ea}),i=this.getLinkedFields(t).reduce((c,m)=>{let d=zo(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Ea});return d.forEach(l=>{l.field=m;}),c.concat(d)},[]),u=false;Lt(()=>{let c=(m,d)=>{let l=Ls(d.cause),f=d.validate?pc(m.runValidator({validate:d.validate,value:{value:m.store.state.value,validationSource:"field",fieldApi:m},type:"validate"})):void 0,h=a[l],{newErrorValue:p,newSource:y}=ys({formLevelError:h,fieldLevelError:f});m.state.meta.errorMap?.[l]!==p&&m.setMeta(v=>({...v,errorMap:{...v.errorMap,[l]:p},errorSourceMap:{...v.errorSourceMap,[l]:y}})),p&&(u=!0);};for(let m of n)c(this,m);for(let m of i)m.validate&&c(m.field,m);});let s=Ls("submit");return this.state.meta.errorMap?.[s]&&t!=="submit"&&!u&&this.setMeta(c=>({...c,errorMap:{...c.errorMap,[s]:void 0},errorSourceMap:{...c.errorSourceMap,[s]:void 0}})),{hasErrored:u}},this.validateAsync=async(t,a)=>{let n=Ko(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ea}),r=await a,i=this.getLinkedFields(t),u=i.reduce((l,f)=>{let h=Ko(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Ea});return h.forEach(p=>{p.field=f;}),l.concat(h)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of i)l.setMeta(f=>({...f,isValidating:true}));let s=[],c=[],m=(l,f,h)=>{let p=Ls(f.cause);l.getInfo().validationMetaMap[p]?.lastAbortController.abort();let v=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:v},h.push(new Promise(async g=>{let x;try{x=await new Promise((b,k)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(v.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:f.validate,value:{value:l.store.state.value,fieldApi:l,signal:v.signal,validationSource:"field"},type:"validateAsync"}));}catch(M){k(M);}},f.debounceMs);});}catch(b){x=b;}if(v.signal.aborted)return g(void 0);let L=pc(x),S=r[this.name]?.[p],{newErrorValue:C,newSource:w}=ys({formLevelError:S,fieldLevelError:L});l.setMeta(b=>({...b,errorMap:{...b?.errorMap,[p]:C},errorSourceMap:{...b.errorSourceMap,[p]:w}})),g(C);}));};for(let l of n)l.validate&&m(this,l,s);for(let l of u)l.validate&&m(l.field,l,c);let d=[];(s.length||c.length)&&(d=await Promise.all(s),await Promise.all(c)),this.setMeta(l=>({...l,isValidating:false}));for(let l of i)l.setMeta(f=>({...f,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:n}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,n[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Ls(t)]?.lastAbortController.abort(),this.state.meta.errors;let i=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,i)},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=>Ra.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ra.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new zt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Go,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return ws(o.validate)?Ra[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 pc(e){if(e)return e}function Ls(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 Is(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,rb)}function rb(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,n]of e)if(!o.has(a)||!Object.is(n,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=hc(e);if(t.length!==hc(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 hc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var jo=typeof window<"u"?useLayoutEffect:useEffect;function cb(e){let[o]=useState(()=>{let a=new zr({...e,form:e.form,name:e.name});return a.Field=Il,a});return jo(o.mount,[o]),jo(()=>{o.update(e);}),Is(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Il=(({children:e,...o})=>{let t=cb(o),a=useMemo(()=>Ma(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function pb({form:e,selector:o,children:t}){let a=Is(e.store,o);return Ma(t,a)}function Cl(e){let o=useId(),[t]=useState(()=>{let a=new Wr({...e,formId:o}),n=a;return n.Field=function(i){return jsx(Il,{...i,form:a})},n.Subscribe=function(i){return jsx(pb,{form:a,selector:i.selector,children:i.children})},n});return jo(t.mount,[]),jo(()=>{t.update(e);}),t}function kl({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 Ib=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),n=Ve(),r=!!e,i=e?.data.questionType||t?.activityType||"multiple-choice",[u,s]=useState(i),c=Cl({defaultValues:{questionType:i,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 f={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?xa(f):Si(f));}else if(l.questionType==="multiple-choice"){let f={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?ga(f):wi(f));}else if(l.questionType==="short-answer"){let f={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?pr(f):Li(f));}else if(l.questionType==="fill-in-the-blank"){let f={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?gr(f):Ci(f));}else if(l.questionType==="long-answer"){let f={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?hr(f):Ii(f));}o(ba(false));}}),m=()=>{o(ba(false));};if(!n)return null;let d=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(),c.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(c.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:f=>{l.handleChange(f.target.value),s(f.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(kl,{field:l})]})}),u&&!["short-answer","fill-in-the-blank","long-answer"].includes(u)&&jsx(c.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:f=>l.handleChange(f.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(kl,{field:l})]})})]}),jsx(c.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 ${u==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:u==="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:u==="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"})]})]}),u==="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(kl,{field:l})]})}),jsx(c.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:f=>l.handleChange(f.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(", ")})]})}),u==="true-false"&&jsx(c.Field,{name:"responseOptions.correctAnswer",children:l=>{let f=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 ${f===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"}),f===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 ${f===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"}),f===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"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value:l})=>{if(l.options.filter(h=>!h.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 f=(v,g)=>{let x=[...l.state.value.options];x[v]=g,l.handleChange({...l.state.value,options:x});},h=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},p=v=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let g=l.state.value.options.filter((L,S)=>S!==v),x=l.state.value.correctIndex?.filter(L=>L!==v).map(L=>L>v?L-1:L);l.handleChange({...l.state.value,options:g,correctIndex:x});},y=v=>{let g=l.state.value.correctIndex||[];if(g.includes(v))l.handleChange({...l.state.value,correctIndex:g.filter(L=>L!==v)});else {if(g.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...g,v]});}};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((v,g)=>{let x=!v.trim(),L=l.state.value.correctIndex?.includes(g),S=l.state.meta.isTouched&&x;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:()=>y(g),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${L?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:L&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${S?"border-red-500 bg-red-50":L?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${g+1}`,value:v,onChange:C=>f(g,C.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:()=>p(g),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"})})]},g)})}),jsx("button",{type:"button",onClick:h,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"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.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:f=>{l.handleChange(f.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(", ")})]})}),u==="long-answer"&&jsx(c.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:f=>{l.handleChange(f.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(c.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,f])=>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:f?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(d,n)},bc=Ib;var Sc=({text:e,position:o})=>{let t=be(),a=c=>{t(de()),t(Rt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+c))}));},n=c=>{t(de()),t(Rt({id:e.id,fill:c}));},r=()=>{t(de()),t(Rt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},i=()=>{t(de()),t(Rt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},u=()=>{t(de()),t(Rt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},s=c=>{t(de()),t(Rt({id:e.id,fontFamily:c}));};return jsxs("div",{className:"absolute 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:100,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:c=>c.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:c=>s(c.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:i,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:u,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:c=>n(c.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 Ic=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:n,scale:r,textareaRef:i})=>{let u=useRef(null),s=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]),c=useCallback(m=>{m.style.height="auto",m.style.height=`${m.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(m).font,d.style.fontSize=m.style.fontSize,d.style.fontFamily=m.style.fontFamily,d.style.fontWeight=m.style.fontWeight,d.style.fontStyle=m.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let l=m.value.split(`
|
|
4
|
+
`),f=0;document.body.appendChild(d);for(let p of l){d.textContent=p||" ";let y=d.offsetWidth;y>f&&(f=y);}document.body.removeChild(d);let h=10;m.style.width=`${Math.max(200,f+h+20)}px`;},[]);return useEffect(()=>{let m=u.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,c(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,c]),jsx("div",{style:{position:"absolute",top:`${n.top}px`,left:`${n.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(u.current=m,i.current=m,m){m.focus();let d=m.value.length;m.setSelectionRange(d,d),c(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:s},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Cc=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;r.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},kc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:i})=>{let u=useSelector(w=>w.toolbar.selectedTool),s=u==="pen"||u==="eraser",c=useRef(null),[m,d]=useState(""),[l,f]=useState(false),[h,p]=useState(null);useEffect(()=>{let w=c.current;if(w)return a.current.set(e.id,w),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",v=l&&m.trim().toLowerCase()===y,g=()=>{f(false),d("");},x=()=>v?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",L=()=>v?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},S=e.data.feedbackMode==="practice",C=useMemo(()=>{let D=S?48:0,W=12,B=30,U=e.width-48,N=Math.max(60,Cc(e.data.question,18,U,"bold")+20),q=l?Math.max(40,Cc(x(),12,U/2)+20):0,F=l?54:20,z=N+q+B+50+12+W+D+24;return {padding:24,questionHeight:N,questionFontSize:18,feedbackHeight:q,feedbackFontSize:12,inputY:F,inputHeight:50,inputMargin:12,buttonHeight:D,buttonTopMargin:W,placeholderHeight:B,contentWidth:U,totalHeight:z}},[e.width,e.data.question,l,v,S,x]);return jsxs(Group,{ref:c,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:C.totalHeight,name:"sa-element",...i,...s?{}:{onDragEnd:r,onClick:()=>o&&o(e.id),onTap:()=>o&&o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:C.totalHeight,onTransformEnd:w=>t(e.id,w),onContextMenu:w=>{w.cancelBubble=true,n(w.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:C.padding+8,y:C.padding,fontSize:C.questionFontSize,fontStyle:"bold",fill:"#111827",width:C.contentWidth,height:C.questionHeight-C.padding,wrap:"word",listening:false}),jsx(Rect,{x:C.padding,y:C.questionHeight+C.feedbackHeight+C.placeholderHeight-C.inputY,width:C.contentWidth+4,height:C.inputHeight+6,fill:"#ffffff",stroke:v?"#22c55e":l?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:C.padding,y:C.questionHeight+C.feedbackHeight+C.placeholderHeight-C.inputY},divProps:{style:{width:`${C.contentWidth-4}px`,height:`${C.inputHeight}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:m,onChange:w=>d(w.target.value),disabled:l,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:l?"none":"auto"}})}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:C.padding,y:C.questionHeight+80,width:e.width/2+24,height:C.feedbackHeight,fill:L().bg,cornerRadius:8}),jsx(Text,{x:36,y:C.questionHeight+80,width:C.contentWidth,height:C.feedbackHeight,text:x(),fontSize:C.feedbackFontSize,fontStyle:"bold",fill:L().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:C.questionHeight+C.feedbackHeight+C.placeholderHeight+C.inputHeight+C.inputMargin+C.buttonTopMargin,children:[jsxs(Group,{onMouseDown:w=>{w.cancelBubble=true,p("check");},onMouseUp:w=>{w.cancelBubble=true,p(null),m.length>0&&f(true);},onMouseLeave:w=>{w.cancelBubble=true,p(null);},onTouchStart:w=>{w.cancelBubble=true,p("check");},onTouchEnd:w=>{w.cancelBubble=true,p(null),m.length>0&&f(true);},scaleX:h==="check"?.95:1,scaleY:h==="check"?.95:1,children:[jsx(Rect,{x:C.padding+14,width:(C.contentWidth-24)/(l?2:1),height:C.buttonHeight,fill:m.length===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:C.padding+14,width:(C.contentWidth-24)/(l?2:1),height:C.buttonHeight,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-C.padding*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),g();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:C.padding,width:(C.contentWidth-8)/2,height:C.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:C.padding,width:(C.contentWidth-8)/2,height:C.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});kc.displayName="ShortAnswer";var Tc=kc;var Ac=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:i})=>{let{createHandlers:u}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>jsx(Tc,{shortAnswer:s,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,s.id),touchHandlers:u(s.id,"shortAnswer")},s.id))})};var Pc=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],n=useRef(new Map),r=useCallback((i,u)=>{let s=i.target;o(gr({id:u,x:s.x(),y:s.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:n,handleFillInTheBlanksDragEnd:r}};var Al=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;r.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},Ec=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:n,fibRefs:r,touchHandlers:i})=>{let u=useSelector(w=>w.toolbar.selectedTool),s=u==="pen"||u==="eraser",c=useRef(null),[m,d]=useState(""),[l,f]=useState(false),[h,p]=useState(null);useEffect(()=>{let w=c.current;if(w)return r.current.set(e.id,w),()=>{r.current.delete(e.id);}},[e.id,r]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",v=l&&m.trim().toLowerCase()===y,g=()=>{f(false),d("");},x=()=>{m.length>0&&f(true);},L=e.data.feedbackMode==="practice",S=useMemo(()=>{let B=e.width-48,U=(B-15)/2,N=24,q=N,F=Math.max(60,Al(e.data.question.replace("_____","________"),24,B,"bold")+20);N+=F;let z=N,_=Math.max(35,Al("Enter your answer in the blank.",16,B)+10);N+=_;let oe=N;N+=67;let V=N,j=l?Math.max(32,Al(v?"Right Answer, Great Job!":"Wrong Answer",14,B-40)+16):0;l&&(N+=j+16);let Z=N;return L&&(N+=64),N+=24,{padding:24,questionY:q,questionHeight:F,questionFontSize:24,helperTextY:z,helperTextHeight:_,helperTextFontSize:16,inputY:oe,inputHeight:51,feedbackY:V,feedbackHeight:j,feedbackFontSize:14,buttonsY:Z,buttonHeight:64,buttonGap:15,buttonWidth:U,contentWidth:B,totalHeight:N}},[e.width,e.data.question,l,v,L]),C=()=>l?v?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:c,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...i,...s?{}:{onDragEnd:w=>a(w,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:S.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:w=>t(e.id,w),onContextMenu:w=>{w.cancelBubble=true,n?.(w.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:S.padding,y:S.questionY,fontSize:S.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:S.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:S.padding,y:S.helperTextY,fontSize:S.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:S.contentWidth,height:S.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:S.padding,y:S.inputY,width:S.contentWidth,height:S.inputHeight,fill:"#ffffff",stroke:C(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:S.padding,y:S.inputY},divProps:{style:{width:`${S.contentWidth}px`,height:`${S.inputHeight}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:m,onChange:w=>d(w.target.value),disabled:l,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"}})}),l&&jsxs(Group,{y:S.feedbackY,children:[jsx(Rect,{x:S.padding,width:v?206:140,height:S.feedbackHeight,fill:v?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:v?"\u2713":"\u2717",x:S.padding+10,y:0,width:16,height:S.feedbackHeight,fontSize:S.feedbackFontSize,fill:v?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:v?"Right Answer, Great Job!":"Wrong Answer",x:S.padding+30,y:0,height:S.feedbackHeight,fontSize:S.feedbackFontSize,fontStyle:"600",fill:v?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),L&&jsxs(Group,{y:S.buttonsY,children:[jsxs(Group,{x:S.padding,onMouseDown:w=>{w.cancelBubble=true,p("reset");},onMouseUp:w=>{w.cancelBubble=true,p(null),g();},onMouseLeave:w=>{w.cancelBubble=true,p(null);},onTouchStart:w=>{w.cancelBubble=true,p("reset");},onTouchEnd:w=>{w.cancelBubble=true,p(null),g();},scaleX:h==="reset"?.98:1,scaleY:h==="reset"?.98:1,children:[jsx(Rect,{width:S.buttonWidth,height:S.buttonHeight,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:S.buttonWidth,height:S.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:S.padding+S.buttonWidth+S.buttonGap,onMouseDown:w=>{w.cancelBubble=true,p("submit");},onMouseUp:w=>{w.cancelBubble=true,p(null),x();},onMouseLeave:w=>{w.cancelBubble=true,p(null);},onTouchStart:w=>{w.cancelBubble=true,p("submit");},onTouchEnd:w=>{w.cancelBubble=true,p(null),x();},scaleX:h==="submit"?.98:1,scaleY:h==="submit"?.98:1,children:[jsx(Rect,{width:S.buttonWidth,height:S.buttonHeight,fill:m.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:S.buttonWidth,height:S.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ec.displayName="FillInTheBlanks";var Rc=Ec;var Fc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,onLongPress:r,fibRefs:i})=>{let{createHandlers:u}=qe({onLongPress:r});return jsx(Fragment,{children:e.map(s=>jsx(Rc,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,fibRefs:i,touchHandlers:u(s.id,"fillInTheBlanks")},s.id))})};var Rl=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let m=s?`${s} ${c}`:c;r.measureText(m).width>t&&s!==""?(u.push(s),s=c):s=m;}),s&&u.push(s),u.length*o*1.2},Fl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,touchHandlers:r,handleDragEnd:i})=>{let u=useSelector(C=>C.toolbar.selectedTool),s=u==="pen"||u==="eraser",c=useRef(null),[m,d]=useState(""),[l,f]=useState(false),[h,p]=useState(null);useEffect(()=>{let C=c.current;if(C)return a.current.set(e.id,C),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",v=l&&m.trim().toLowerCase()===y,g=()=>{f(false),d("");},x=()=>v?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",L=()=>v?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},S=useMemo(()=>{let B=e.width-48,U=Math.max(60,Rl(e.data.question,20,B,"bold")+20),N=l?Math.max(60,Rl(x(),14,B)+30):0,F=Math.max(30,Rl("Answer (Extended response):",14,B)+10),z=U+N+F+120+12+12+48+24;return {padding:24,questionHeight:U,questionFontSize:20,feedbackHeight:N,feedbackFontSize:14,placeholderHeight:F,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:B,totalHeight:z}},[e.width,e.data.question,l,v,x]);return jsxs(Group,{ref:c,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:S.totalHeight,...r,name:"la-element",...s?{}:{onDragEnd:i,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:C=>{let w=c.current?.getStage()?.getPointerPosition();if(!w||!n)return;let b={x:e.x,y:e.y,width:e.width,height:S.totalHeight};w.x>=b.x&&w.x<=b.x+b.width&&w.y>=b.y&&w.y<=b.y+b.height&&n(C.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:S.totalHeight,onTransformEnd:C=>t(e.id,C)}),jsx(Text,{text:e.data.question,x:S.padding+8,y:S.padding,fontSize:S.questionFontSize,fontStyle:"bold",fill:"#111827",width:S.contentWidth,height:S.questionHeight-S.padding,wrap:"word",listening:false}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:S.padding,y:S.questionHeight,width:S.contentWidth,height:S.feedbackHeight,fill:L().bg,cornerRadius:8}),jsx(Text,{x:S.padding,y:S.questionHeight,width:S.contentWidth,height:S.feedbackHeight,text:x(),fontSize:S.feedbackFontSize,fontStyle:"bold",fill:L().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:S.padding,y:S.questionHeight+S.feedbackHeight+S.textareaMargin,fontSize:S.placeholderFontSize,fill:"#6b7280",width:S.contentWidth,wrap:"word",listening:false}),jsx(Rect,{x:S.padding,y:S.questionHeight+S.feedbackHeight+S.placeholderHeight,width:S.contentWidth,height:S.textareaHeight,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:S.padding,y:S.questionHeight+S.feedbackHeight+S.placeholderHeight},divProps:{style:{width:`${S.contentWidth}px`,height:`${S.textareaHeight}px`,pointerEvents:l?"none":"auto"}},children:jsx("textarea",{value:m,onChange:C=>d(C.target.value),disabled:l,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:l?"none":"auto"}})}),jsx(Group,{y:I.questionHeight+I.feedbackHeight+I.placeholderHeight+I.textareaHeight+I.textareaMargin+I.buttonTopMargin,children:l&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),g();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:I.padding,width:I.contentWidth,height:I.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:k=>k.cancelBubble=true,onTap:k=>k.cancelBubble=true}),jsx(Text,{x:I.padding,width:I.contentWidth,height:I.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});El.displayName="LongAnswer";var Ec=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,onLongPress:i})=>{let{createHandlers:u}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>jsx(El,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id),touchHandlers:u(s.id,"longAnswer")},s.id))})};var ao=1600,oo=900,Bc=3200,Oc=1800,ov=e=>{let o=0,t=0,a=ao,r=oo;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:ao,height:oo};let n=(s,c,m,d)=>{o=Math.min(o,s),t=Math.min(t,c),a=Math.max(a,s+m),r=Math.max(r,c+d);};e.lines?.forEach(s=>{if(s.points&&s.points.length>=2){let c=s.x||0,m=s.y||0,d=s.scaleX||1,l=s.scaleY||1;for(let f=0;f<s.points.length;f+=2){let h=c+s.points[f]*d,p=m+s.points[f+1]*l;o=Math.min(o,h),t=Math.min(t,p),a=Math.max(a,h),r=Math.max(r,p);}}}),e.images?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.videos?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.shapes?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.texts?.forEach(s=>n(s.x,s.y,s.width||200,s.height||s.fontSize||24)),e.flashcards?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.photoFrames?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.multipleChoices?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.trueFalses?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.shortAnswers?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.LongAnswer?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.fillInTheBlanks?.forEach(s=>n(s.x,s.y,s.width,s.height));let i=Math.min(a-o,Bc),u=Math.min(r-t,Oc);return o=Math.max(o,a-Bc),t=Math.max(t,r-Oc),{minX:o,minY:t,maxX:a,maxY:r,width:i,height:u}},rv=(e,o,t={minX:0,minY:0,maxX:ao,maxY:oo,width:ao,height:oo})=>{let a=Math.max(t.width,ao),r=Math.max(t.height,oo),n=e/o,i=a/r,u,s,c,d=0;if(n>i){s=r,u=Math.round(s*n),c=o/s;}else {u=a,s=Math.round(u/n),c=e/u;let l=r*c;d=(o-l)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:d,baseWidth:u,baseHeight:s,contentOffsetX:t.minX,contentOffsetY:t.minY}},Nc=(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}},nv=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r={enabled:true}}={})=>{let n=tt(),i=Ve(),u=te(L=>L.toolbar.selectedTool),s=te(ge),c=te(ya),m=te(_n),l=(s?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),f=!!l,h=useCallback(()=>{l&&n(Wa(l.id));},[n,l]),p=s?.editingActivity,v=s?.showMcqForm,y=s?.lines||[],g=useRef(null),x=useRef(null),[w,I]=useState(null),[k,S]=useState(""),b=useRef(null),[C,M]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:ao,stageHeight:oo,offsetX:0,offsetY:0,baseWidth:ao,baseHeight:oo,contentOffsetX:0,contentOffsetY:0}),P=useMemo(()=>ov(s||null),[c]),[R,z]=useState(null),[B,U]=useState(null),[N,V]=useState(null),[F,W]=useState(null),[G,se]=useState(null),[q,_]=useState(null),[Z,Y]=useState(null),[oe,J]=useState(false),[ce,Se]=useState(null),[Te,Ie]=useState(false),De=useRef(null),At=useRef(null),Pt=useRef(null),{debouncedGenerateThumbnail:fo}=du(c,g);useEffect(()=>{let L=()=>{if(x.current){let E=x.current.getBoundingClientRect(),O=rv(E.width,E.height,P);M(O);}};L();let T=new ResizeObserver(L);return x.current&&T.observe(x.current),window.addEventListener("resize",L),()=>{T.disconnect(),window.removeEventListener("resize",L);}},[P]),useEffect(()=>{if(g.current){let L=g.current.container();L&&(L.style.cursor="");}},[u]);let ne=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(T=>T.batchDraw()),!m)try{let E=g.current.toDataURL({pixelRatio:.16666666666666666});S(E),fo();}catch(T){console.warn("Preview generation failed (CORS):",T);}});},[fo,m]),Jr=useRef(c);useEffect(()=>{Jr.current!==c&&(Jr.current=c,ne());},[c,ne]);let Qr=useRef(null),en=useRef(true);useEffect(()=>{if(!s)return;let L=(s.lines?.length||0)+(s.images?.length||0)+(s.videos?.length||0)+(s.shapes?.length||0)+(s.texts?.length||0)+(s.flashcards?.length||0)+(s.photoFrames?.length||0)+(s.multipleChoices?.length||0)+(s.trueFalses?.length||0)+(s.shortAnswers?.length||0)+(s.LongAnswer?.length||0)+(s.fillInTheBlanks?.length||0),T=Qr.current?.count!==L;!en.current&&T&&setTimeout(()=>{ne();},100),Qr.current={slideId:c,count:L},en.current=false;},[s,c,ne]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{Pt.current&&a&&a(Pt);},[a]);let{startDrawing:tn,draw:an,stopDrawing:on,setCanvasRef:Ua,tool:Ks,color:Gs,strokeWidth:js,isSketchMode:_s}=Od(ne),pa=useRef(new Map),{images:rn,getLoadedImage:Xs,imageRefs:mo,handleDragEnd:nn,handleImageTransformEnd:$s}=Wd(ne),{videos:Jo,videoRefs:po,handleVideoClick:sn,handleVideoDragEnd:A,handleVideoTransformEnd:ee}=jd(ne),{multipleChoice:Me,handleMcqTransform:xe,mcqRefs:ie,handleDragEnd:fe}=Kd(ne),{trueFalse:Oe,handleTrueFalseTransform:dt,trueFalseRefs:Et,handleTrueFalseDragEnd:Dt}=Gd(ne),{shortAnswers:Ne,saRefs:Ue,handleShortAnswerDragEnd:oa}=Jd(ne),{longAnswers:ha,handleLongAnswerDragEnd:Ys}=Qd(ne),{fillInTheBlanks:Zs,handleFillInTheBlanksDragEnd:ln,fibRefs:ut}=Cc(ne),{transformerRef:re,boundBoxFunc:_e}=nu(),{shapes:Fm,shapeRefs:dn,isDragging:vd,handleShapeDragEnd:Bm,handleShapeResizeEnd:Om}=$d(ne),{texts:Qo,textRefs:ga,handleDragEnd:Nm,handleTransformEnd:Hm,handleDoubleClick:qm,startEditing:un,editingTextId:he,editingValue:yd,handleEditingChange:wd,finishEditing:Js}=Zd(ne,De);useEffect(()=>{t&&t(un);},[t,un]);let cn=te(L=>L.canvas.editingTextId);useEffect(()=>{cn&&cn!==he&&un(cn);},[cn,he,un]);let{flashcards:Vm,flashcardRefs:fn,handleDragEnd:Um,handleFlashcardTransformEnd:zm,handleNext:Wm,handlePrevious:Km}=tu(ne),{photoFrames:Sd,photoFrameRefs:mn,handleDragEnd:Gm,handlePhotoFrameTransformEnd:jm,startCamera:_m,capturePhoto:Xm,cameraStreams:$m}=ru(ne);useEffect(()=>{if(re.current){if(he){re.current.nodes([]),re.current.getLayer()?.batchDraw();return}if(w&&!Jo.find(E=>E.id===w)?.isPlaying){let E=pa.current.get(w)||mo.current.get(w)||po.current.get(w)||dn.current.get(w)||ga.current.get(w)||ie.current.get(w)||fn.current.get(w)||mn.current.get(w)||Ue.current.get(w)||Et.current.get(w)||ut.current.get(w);if(E){let O=E.attrs?.locked;if(E.visible()&&O!==true){re.current.nodes([E]),re.current.getLayer()?.batchDraw();return}}}re.current.nodes([]),re.current.getLayer()?.batchDraw();}},[w,he,Jo,pa,mo,po,dn,ga,fn,mn,Sd,ie,Et,ut,re]);let ze=useCallback(L=>{I(L),o?.(L);},[o]),ho=useCallback(()=>{I(null),o?.(null),re.current&&(re.current.nodes([]),re.current.getLayer()?.batchDraw());},[re,o]),Ld=useCallback(L=>s?s.lines?.some(T=>T.id===L)?"line":s.images?.some(T=>T.id===L)?"image":s.videos?.some(T=>T.id===L)?"video":s.shapes?.some(T=>T.id===L)?"shape":s.texts?.some(T=>T.id===L)?"text":s.flashcards?.some(T=>T.id===L)?"flashcard":s.photoFrames?.some(T=>T.id===L)?"photoFrame":s.multipleChoices?.some(T=>T.id===L)?"mcq":s.trueFalses?.some(T=>T.id===L)?"trueFalse":s.shortAnswers?.some(T=>T.id===L)?"shortAnswer":s.LongAnswer?.some(T=>T.id===L)?"longAnswer":s.fillInTheBlanks?.some(T=>T.id===L)?"fillInTheBlanks":null:null,[s]),Id=useCallback((L,T)=>{switch(n(de()),T){case "line":n(Wn(L));break;case "image":n(hn(L));break;case "video":n(vn(L));break;case "shape":n(Sn(L));break;case "text":n(Ln(L));break;case "flashcard":n(Cn(L));break;case "photoFrame":n(Tn(L));break;case "mcq":n(An(L));break;case "trueFalse":n(En(L));break;case "shortAnswer":n(Rn(L));break;case "longAnswer":n(Bn(L));break;case "fillInTheBlanks":n(Nn(L));break}ho(),ne();},[n,ho,ne]);useEffect(()=>{let L=T=>{if(T.key!=="Delete"||!w||he)return;let E=document.activeElement;if(E instanceof HTMLInputElement||E instanceof HTMLTextAreaElement||E?.getAttribute("contenteditable")==="true")return;T.preventDefault();let ye=Ld(w);ye&&Id(w,ye);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[w,he,Ld,Id]),useEffect(()=>{let L=re.current;return ()=>{L&&L.nodes([]);}},[c]),useEffect(()=>{let L=T=>{he&&T.target.tagName!=="TEXTAREA"&&Js();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[he,Js]),useEffect(()=>{let L=he||w;if(!L||w&&he){U(null);return}let T=ga.current.get(L),E=g.current;if(!T||!E){U(null);return}let O=E.container().getBoundingClientRect(),ye=T.absolutePosition(),pe=E.scaleX();U({x:O.left+(ye.x+T.width()*pe/2)*pe+C.offsetX,y:O.top+ye.y*pe+C.offsetY-70});},[w,he,Qo,ga,C.offsetX,C.offsetY]),useEffect(()=>{if(!he){V(null);return}let L=ga.current.get(he),T=g.current;if(!L||!T){V(null);return}let E=L.getClientRect({relativeTo:T}),O=T.container().getBoundingClientRect(),ye=T.scaleX(),pe=T.position(),ae={top:O.top+pe.y+E.y*ye,left:O.left+pe.x+E.x*ye,scale:ye};V(ae),n(Rd(ae));},[he,Qo,ga,C.offsetY,C.offsetX]);let Cd=useCallback(L=>{let T=L.target.getClassName(),E=L.target===L.target.getStage(),O=T==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",ye=T==="Image",pe=T==="Text",ae=T==="Group"||L.target.getParent()?.getClassName()==="Group",ct=T==="Circle"||T==="Star"||T==="RegularPolygon"||T==="Ellipse"||T==="Ring"||T==="Wedge"||T==="Arrow"||T==="Line"||T==="Arc"||T==="Rect"&&L.target.attrs.id,ft=T==="Group";if(E&&!O&&!ye&&!pe&&!ae&&!ct&&!ft&&ho(),!(u==="pen"||u==="eraser")&&(ye||pe||O||ae||ct||ft))return;let We=L.target.getStage()?.getPointerPosition();if(!We)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let H=Nc(We,C);tn(H);}},[u,tn,ho,C]),kd=useCallback(L=>{if(vd)return;let T=L.target.getStage()?.getPointerPosition();if(!T)return;let E=Nc(T,C);an(E);},[an,vd,C]),Td=useCallback(()=>{on();},[on]),Ym=useCallback(L=>{nn(L,ne);},[nn,ne]),Zm=useCallback(L=>{sn(L),ze(L);},[sn,ze]),Rt=useCallback((L,T,E)=>{if(L.preventDefault(),!r.enabled)return;let O=L.clientX,ye=L.clientY,pe=b.current?.offsetHeight||450,ae=b.current?.offsetWidth||450,ct=window.innerHeight,ft=window.innerWidth,Qe=O,We=ye;ye+pe>ct&&(We=ye-pe),O+ae>ft&&(Qe=O-ae),ze(T),z({x:Qe,y:We,elementId:T,elementType:E});},[ze,r.enabled]),za=useRef(null),er=useRef(null),vt=useCallback((L,T)=>E=>{if(!r.enabled)return;E.preventDefault();let O=E.changedTouches[0];if(!O)return;let ye=O.clientX,pe=O.clientY,ae=b.current?.offsetHeight||200,ct=b.current?.offsetWidth||200,ft=window.innerHeight,Qe=window.innerWidth,We=ye,et=pe;pe+ae>ft&&(et=pe-ae),ye+ct>Qe&&(We=ye-ct),ze(L),z({x:We,y:et,elementId:L,elementType:T});},[ze,r.enabled]),Jm=useCallback((L,T)=>({onTouchStart:E=>{let O=E.evt.touches[0];er.current={x:O.clientX,y:O.clientY},za.current=setTimeout(()=>{vt(L,T)(E.evt);},500);},onTouchMove:E=>{if(!er.current)return;let O=E.evt.touches[0],ye=Math.abs(O.clientX-er.current.x),pe=Math.abs(O.clientY-er.current.y);(ye>10||pe>10)&&za.current&&(clearTimeout(za.current),za.current=null);},onTouchEnd:()=>{za.current&&(clearTimeout(za.current),za.current=null),er.current=null;}}),[vt]),Md=useCallback(L=>{n(ur(L)),n(va(true));},[n]),Qm=useCallback(L=>{n(sr(L)),n(Ga(true));},[n]),ep=useCallback((L,T)=>{if(!R)return;let{elementId:E,elementType:O}=R;switch(L){case "order":if(T){let D=T.target.getBoundingClientRect();W({x:D.right+5,y:D.top,type:"order"});}break;case "lock":if(T){let D=T.target.getBoundingClientRect();W({x:D.right+5,y:D.top,type:"lock"});}break;case "link":if(z(null),O==="line")break;let ye=s?O==="image"?s.images.find(D=>D.id===E):s.videos.find(D=>D.id===E):null;se({type:"link",defaultValue:ye?.link||""});break;case "voice":if(z(null),O==="line")break;let pe=s?O==="image"?s.images.find(D=>D.id===E):O==="video"?s.videos.find(D=>D.id===E):O==="text"?s.texts.find(D=>D.id===E):O==="flashcard"?s.flashcards.find(D=>D.id===E):O==="photoFrame"?s.photoFrames.find(D=>D.id===E):O==="mcq"?s.multipleChoices.find(D=>D.id===E):O==="fillInTheBlanks"?s.fillInTheBlanks.find(D=>D.id===E):O==="longAnswer"?s.LongAnswer.find(D=>D.id===E):O==="shortAnswer"?s.shortAnswers.find(D=>D.id===E):O==="trueFalse"?s.trueFalses.find(D=>D.id===E):O==="shape"?s.shapes.find(D=>D.id===E):null:null;Se({elementId:E,elementType:O,existingAudio:pe?.audioData});break;case "edit":z(null);let ae=null;O==="mcq"?ae=s?.multipleChoices.find(D=>D.id===E):O==="trueFalse"?ae=s?.trueFalses.find(D=>D.id===E):O==="shortAnswer"?ae=s?.shortAnswers.find(D=>D.id===E):O==="longAnswer"?ae=s?.LongAnswer.find(D=>D.id===E):O==="fillInTheBlanks"&&(ae=s?.fillInTheBlanks.find(D=>D.id===E)),ae&&Md(ae);break;case "editFlashcard":z(null);let ct=s?.flashcards.find(D=>D.id===E);ct&&Qm(ct);break;case "color":z(null);let ft=s?.shapes.find(D=>D.id===E);_({elementId:E,elementType:"shape",defaultColor:ft?.color||"#096B76"});break;case "crop":if(z(null),O==="image"){let D=s?.images.find(ip=>ip.id===E);D&&Y({elementId:E,imageSrc:D.src});}break;case "draw":z(null),O==="image"?n(mi(E)):O==="photoFrame"&&n(hi(E));break;case "duplicate":n(de()),O==="line"?n(Ti(E)):O==="image"?n(gn(E)):O==="video"?n(yn(E)):O==="shape"?n(wn(E)):O==="text"?n(In(E)):O==="flashcard"?n(kn(E)):O==="photoFrame"?n(Mn(E)):O==="mcq"?n(Pn(E)):O==="trueFalse"?n(Dn(E)):O==="shortAnswer"?n(Fn(E)):O==="fillInTheBlanks"?n(Hn(E)):O==="longAnswer"&&n(On(E)),ne();break;case "infinite-clone":n(de());let Qe=5;for(let D=0;D<Qe;D++)O==="image"?n(gn(E)):O==="video"?n(yn(E)):O==="shape"?n(wn(E)):O==="text"?n(In(E)):O==="flashcard"?n(kn(E)):O==="photoFrame"?n(Mn(E)):O==="mcq"?n(Pn(E)):O==="trueFalse"?n(Dn(E)):O==="shortAnswer"?n(Fn(E)):O==="fillInTheBlanks"?n(Hn(E)):O==="longAnswer"&&n(On(E));ne();break;case "make-response":if(z(null),O==="line")break;let We=`#response-${E}`;n(de()),n(qn({id:E,type:O,link:We})),(s?O==="image"?s.images.find(D=>D.id===E):O==="video"?s.videos.find(D=>D.id===E):O==="shape"?s.shapes.find(D=>D.id===E):O==="flashcard"?s.flashcards.find(D=>D.id===E):O==="photoFrame"?s.photoFrames.find(D=>D.id===E):s.multipleChoices.find(D=>D.id===E):null)?.altText||n(Vn({id:E,type:O,altText:"Interactive response area"})),ne(),console.log(`Element ${E} marked as interactive response area`);break;case "accessibility":if(z(null),O==="line")break;let H=s?O==="image"?s.images.find(D=>D.id===E):O==="video"?s.videos.find(D=>D.id===E):O==="shape"?s.shapes.find(D=>D.id===E):null:null;se({type:"altText",defaultValue:H?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),z(null),Ie(true),console.log("showLayersPanel state set to:",true);break;case "delete":n(de()),O==="line"?n(Wn(E)):O==="image"?n(hn(E)):O==="video"?n(vn(E)):O==="shape"?n(Sn(E)):O==="text"?n(Ln(E)):O==="flashcard"?n(Cn(E)):O==="photoFrame"?n(Tn(E)):O==="mcq"?n(An(E)):O==="trueFalse"?n(En(E)):O==="shortAnswer"?n(Rn(E)):O==="longAnswer"?n(Bn(E)):O==="fillInTheBlanks"&&n(Nn(E)),ho(),ne();break}},[R,n,ne,ho,s,Md]),tp=useCallback(()=>{z(null),W(null);},[]),Qs=useCallback(L=>{if(!R)return;let{elementId:T,elementType:E}=R;switch(n(de()),L){case "bring-to-front":E!=="line"&&n(Li({id:T,type:E}));break;case "send-to-back":E!=="line"&&n(Ii({id:T,type:E}));break;case "lock":case "unlock":E!=="line"&&n(Ci({id:T,type:E}));break}ne(),z(null),W(null);},[R,n,ne]),ap=useCallback(L=>{if(!R||!G)return;let{elementId:T,elementType:E}=R;n(de()),G.type==="link"&&E!=="line"?n(qn({id:T,type:E,link:L})):G.type==="altText"&&E!=="line"&&n(Vn({id:T,type:E,altText:L})),ne(),se(null);},[R,G,n,ne]),op=useCallback(L=>{if(!ce)return;let{elementId:T,elementType:E}=ce;n(de()),n(Un({id:T,type:E,audioData:L})),ne(),Se(null);},[ce,n,ne]),rp=useCallback(()=>{if(!ce)return;let{elementId:L,elementType:T}=ce;n(de()),n(Un({id:L,type:T,audioData:""})),ne();},[ce,n,ne]),np=useCallback(L=>{if(!q)return;let{elementId:T}=q;n(de()),n(bo({id:T,color:L})),ne(),_(null);},[q,n,ne]),sp=useCallback(L=>{if(!Z)return;let{elementId:T}=Z;n(de()),n(xo({id:T,src:L})),ne(),Y(null);},[Z,n,ne]);return jsxs("div",{ref:x,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Ud,{ref:L=>{if(At.current=L,Ua(L),L){let T=L.getCanvasElement();T&&(Pt.current=T,a&&a(Pt));}},width:C.baseWidth,height:C.baseHeight,tool:Ks,color:Gs,strokeWidth:js/C.scale,isSketchMode:_s,xOffset:C.contentOffsetX,yOffset:C.contentOffsetY-C.offsetY/C.scale,style:{width:C.stageWidth,height:C.stageHeight}}),jsxs(Stage,{ref:g,width:C.stageWidth,height:C.stageHeight,scaleX:C.scaleX,scaleY:C.scaleY,x:C.offsetX,y:0,onMouseDown:Cd,onMouseMove:kd,onMouseUp:Td,onTouchStart:Cd,onTouchMove:kd,onTouchEnd:Td,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:C.baseWidth,height:C.stageHeight/C.scale,fill:s?.backgroundColor||"white"})}),jsx(Layer,{x:-C.contentOffsetX,y:C.offsetY/C.scale-C.contentOffsetY,children:(()=>{let L=[];return y.forEach((T,E)=>{L.push({type:"line",timestamp:T.timestamp||E,element:{...T,id:T.id??`line-${E}`},index:E});}),Fm.forEach(T=>{L.push({type:"shape",timestamp:T.timestamp||0,element:T});}),rn.forEach(T=>{L.push({type:"image",timestamp:T.timestamp||0,element:T});}),Jo.forEach(T=>{L.push({type:"video",timestamp:T.timestamp||0,element:T});}),Qo.forEach(T=>{L.push({type:"text",timestamp:T.timestamp||0,element:T});}),Vm.forEach(T=>{L.push({type:"flashcard",timestamp:T.timestamp||0,element:T});}),Sd.forEach(T=>{L.push({type:"photoFrame",timestamp:T.timestamp||0,element:T});}),Me.forEach(T=>{L.push({type:"mcq",timestamp:T.timestamp||0,element:T});}),Oe.forEach(T=>{L.push({type:"trueFalse",timestamp:T.timestamp||0,element:T});}),Ne.forEach(T=>{L.push({type:"shortAnswer",timestamp:T.timestamp||0,element:T});}),ha.forEach(T=>{L.push({type:"longAnswer",timestamp:T.timestamp||0,element:T});}),Zs.forEach(T=>{L.push({type:"fillInTheBlanks",timestamp:T.timestamp||0,element:T});}),L.sort((T,E)=>T.timestamp-E.timestamp),L.map((T,E)=>{let O=`${T.type}-${"id"in T.element&&T.element.id||T.index||E}`,ye="id"in T.element?T.element.id:void 0,pe=ye&&w===ye;switch(T.type){case "line":let ae=T.element,ct=T.index||0,ft=ae.tool==="eraser",Qe=ae.isSketch&&ae.tool==="pen",We=ae.isSketch&&ft,et=ae.id||`line-${ct}`;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),u==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:Qe||We?void 0:ae.color,strokeWidth:Qe||We?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Qe||We?ft?"black":ae.color:void 0,closed:Qe||We,tension:0,globalCompositeOperation:ft?"destination-out":"source-over",listening:true,onClick:()=>{n(de()),n(pn(ct));},onTap:()=>{n(de()),n(pn(ct));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:H=>{let D=H.target.getStage();D&&(D.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:H=>{let D=H.target.getStage();D&&(D.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(ve__default.Fragment,{children:[jsx(Group,{id:et,ref:H=>{H?pa.current.set(et,H):pa.current.delete(et);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",et),ze(et));},onTap:()=>{u==="select"&&(console.log("Line tapped:",et),ze(et));},onDragEnd:H=>{n(de()),n(zn({id:et,x:H.target.x(),y:H.target.y(),scaleX:H.target.scaleX(),scaleY:H.target.scaleY(),rotation:H.target.rotation()})),ne();},onTransformEnd:H=>{n(de()),n(zn({id:et,x:H.target.x(),y:H.target.y(),scaleX:H.target.scaleX(),scaleY:H.target.scaleY(),rotation:H.target.rotation()})),ne();},onMouseEnter:H=>{if(u==="select"){let D=H.target.getStage();D&&(D.container().style.cursor="move");}},onMouseLeave:H=>{if(u==="select"){let D=H.target.getStage();D&&(D.container().style.cursor="default");}},onContextMenu:H=>{let D=H.evt;D.preventDefault(),Rt(D,et,"line");},...Jm(et,"line"),children:jsx(Line,{points:ae.points||[],stroke:Qe||We?void 0:ae.color,strokeWidth:Qe||We?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Qe||We?ft?"black":ae.color:void 0,closed:Qe||We,tension:0,globalCompositeOperation:ft?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=pa.current.get(w);console.log("Line Transformer - selectedId:",w,"node found:",!!D),D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(Gi,{onSelect:ze,shapes:[T.element],shapeRefs:dn,handleShapeDragEnd:Bm,handleShapeResizeEnd:Om,onContextMenu:Rt,onLongPress:vt}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=dn.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(Ui,{images:[T.element],getLoadedImage:Xs,imageRefs:mo,onDragEnd:Ym,onTransform:$s,onSelect:ze,onContextMenu:Rt,onLongPress:vt}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=mo.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(Ki,{videos:[T.element],selectedId:w,videoRefs:po,onVideoClick:Zm,onDragEnd:A,onTransformEnd:ee,onContextMenu:Rt,onLongPress:vt}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=po.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(wu,{texts:[T.element],textRefs:ga,onDragEnd:Nm,onTransformEnd:Hm,onSelect:ze,onContextMenu:Rt,onLongPress:vt,onDoubleClick:qm,editingTextId:he,editingValue:yd,onEditingChange:wd}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=ga.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(Xi,{flashcards:[T.element],flashcardRefs:fn,selectedId:w,onDragEnd:Um,onTransform:zm,onSelect:ze,onNext:Wm,onPrevious:Km,onContextMenu:Rt,onLongPress:vt}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=fn.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(el,{photoFrames:[T.element],photoFrameRefs:mn,selectedId:w,onDragEnd:Gm,onTransform:jm,onSelect:ze,onStartCamera:_m,onCapture:Xm,cameraStreams:$m,onContextMenu:Rt,onLongPress:vt}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=mn.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(Ju,{handleMcqTransform:xe,multipleChoice:[T.element],handleSelect:ze,mcqRefs:ie,handleDragEnd:fe,onContextMenu:Rt,onLongPress:vt}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=ie.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(ac,{trueFalses:[T.element],handleTrueFalseTransform:dt,handleSelect:ze,trueFalseRefs:Et,onContextMenu:Rt,onLongPress:vt,handleDragEnd:Dt}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=Et.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(Ic,{shortAnswers:[T.element],handleSelect:ze,handleTransform:xe,saRefs:Ue,onContextMenu:Rt,onLongPress:vt,handleDragEnd:oa}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=Ue.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(Ec,{longAnswer:[T.element],handleSelect:ze,handleTransform:xe,saRefs:Ue,onContextMenu:Rt,onLongPress:vt,handleDragEnd:Ys}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=Ue.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(ve__default.Fragment,{children:[jsx(Ac,{fillInTheBlanks:[T.element],handleSelect:ze,handleTransform:xe,onContextMenu:Rt,onLongPress:vt,handleDragEnd:ln,fibRefs:ut}),pe&&!he&&w&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let D=ut.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:_e,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(Fu,{menuRef:b,x:R.x,y:R.y,type:R.elementType,onAction:ep,onClose:tp,isDrawingMode:R.elementType==="image"?s?.images.find(L=>L.id===R.elementId)?.isDrawingMode:R.elementType==="photoFrame"?s?.photoFrames.find(L=>L.id===R.elementId)?.isDrawingMode:false}),F&&R&&jsx(Bu,{x:F.x,y:F.y,items:F.type==="order"?[{label:"Bring to Front",onClick:()=>Qs("bring-to-front")},{label:"Send to Back",onClick:()=>Qs("send-to-back")}]:[{label:s&&(R.elementType==="image"?s.images.find(L=>L.id===R.elementId)?.locked:s.videos.find(L=>L.id===R.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Qs(s&&(R.elementType==="image"?s.images.find(L=>L.id===R.elementId)?.locked:s.videos.find(L=>L.id===R.elementId)?.locked)?"unlock":"lock")}],onClose:()=>W(null)}),G&&jsx(Hu,{title:G.type==="link"?"Add Link":"Add Alt Text",label:G.type==="link"?"URL":"Alternative Text",placeholder:G.type==="link"?"https://example.com":"Describe this image/video",defaultValue:G.defaultValue,onSave:ap,onClose:()=>se(null)}),q&&jsx(ts,{defaultColor:q.defaultColor,onConfirm:np,onCancel:()=>_(null)}),Z&&jsx(zu,{imageSrc:Z.imageSrc,onConfirm:sp,onCancel:()=>Y(null)}),oe&&jsx(Sr,{onClose:()=>J(false),stageRef:g}),ce&&jsx(ju,{elementId:ce.elementId,elementType:ce.elementType,existingAudio:ce.existingAudio,onSave:op,onDelete:rp,onClose:()=>Se(null)}),Te&&jsx($u,{selectedElementId:w||void 0,onClose:()=>Ie(false),onSelectElement:L=>{ze(L),Ie(false);}}),s?.images.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.videos.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.shapes?.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.texts?.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Ot,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),v&&jsx(mc,{editElement:p}),B&&(()=>{let L=he||w;if(!L)return null;let T=Qo.find(E=>E.id===L);return T?jsx(xc,{text:T,position:B}):null})(),N&&he&&(()=>{let L=Qo.find(T=>T.id===he);return L?jsx(vc,{text:L,editingValue:yd,onEditingChange:wd,onFinish:Js,position:{top:N.top,left:N.left},scale:N.scale,textareaRef:De},he):null})(),f&&i&&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:h})}),jsx("button",{onClick:h,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"})})]}),i)]})},sv=nv;var lv="SchooplaVideoStorage";var ea="videos",ks=()=>new Promise((e,o)=>{let t=indexedDB.open(lv,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(ea)||r.createObjectStore(ea,{keyPath:"id"});};}),ro=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await ks(),n=a.transaction([ea],"readwrite").objectStore(ea),i={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,s)=>{let c=n.put(i);c.onsuccess=()=>u(!0),c.onerror=()=>s(c.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 Hc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await ks(),t=e.transaction([ea],"readonly").objectStore(ea);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let i=n.result,u=new Map;i.forEach(s=>{u.set(s.id,{blob:s.blob,thumbnailDataUrl:s.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),a(u);},n.onerror=()=>{e.close(),r(n.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 ks(),a=o.transaction([ea],"readwrite").objectStore(ea);await new Promise((r,n)=>{let i=a.delete(e);i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},qc=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await ks(),t=e.transaction([ea],"readwrite").objectStore(ea);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Vc=e=>URL.createObjectURL(e);function Fa(e,o=[]){let t=[];function a(n,i){let u=ve.createContext(i),s=t.length;t=[...t,i];let c=d=>{let{scope:l,children:f,...h}=d,p=l?.[e]?.[s]||u,v=ve.useMemo(()=>h,Object.values(h));return jsx(p.Provider,{value:v,children:f})};c.displayName=n+"Provider";function m(d,l){let f=l?.[e]?.[s]||u,h=ve.useContext(f);if(h)return h;if(i!==void 0)return i;throw new Error(`\`${d}\` must be used within \`${n}\``)}return [c,m]}let r=()=>{let n=t.map(i=>ve.createContext(i));return function(u){let s=u?.[e]||n;return ve.useMemo(()=>({[`__scope${e}`]:{...u,[e]:s}}),[u,s])}};return r.scopeName=e,[a,uv(r,...o)]}function uv(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(n){let i=a.reduce((u,{useScope:s,scopeName:c})=>{let d=s(n)[`__scope${c}`];return {...u,...d}},{});return ve.useMemo(()=>({[`__scope${o.scopeName}`]:i}),[i])}};return t.scopeName=o.scopeName,t}function Uc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Wr(...e){return o=>{let t=false,a=e.map(r=>{let n=Uc(r,o);return !t&&typeof n=="function"&&(t=true),n});if(t)return ()=>{for(let r=0;r<a.length;r++){let n=a[r];typeof n=="function"?n():Uc(e[r],null);}}}}function Ut(...e){return ve.useCallback(Wr(...e),e)}function Kc(e){let o=cv(e),t=ve.forwardRef((a,r)=>{let{children:n,...i}=a,u=ve.Children.toArray(n),s=u.find(mv);if(s){let c=s.props.children,m=u.map(d=>d===s?ve.Children.count(c)>1?ve.Children.only(null):ve.isValidElement(c)?c.props.children:null:d);return jsx(o,{...i,ref:r,children:ve.isValidElement(c)?ve.cloneElement(c,void 0,m):null})}return jsx(o,{...i,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function cv(e){let o=ve.forwardRef((t,a)=>{let{children:r,...n}=t;if(ve.isValidElement(r)){let i=hv(r),u=pv(n,r.props);return r.type!==ve.Fragment&&(u.ref=a?Wr(a,i):i),ve.cloneElement(r,u)}return ve.Children.count(r)>1?ve.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var fv=Symbol("radix.slottable");function mv(e){return ve.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===fv}function pv(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...u)=>{let s=n(...u);return r(...u),s}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function hv(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 bv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],xt=bv.reduce((e,o)=>{let t=Kc(`Primitive.${o}`),a=ve.forwardRef((r,n)=>{let{asChild:i,...u}=r,s=i?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(s,{...u,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function ot(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function Rl(e){let o=vv(e),t=ve.forwardRef((a,r)=>{let{children:n,...i}=a,u=ve.Children.toArray(n),s=u.find(wv);if(s){let c=s.props.children,m=u.map(d=>d===s?ve.Children.count(c)>1?ve.Children.only(null):ve.isValidElement(c)?c.props.children:null:d);return jsx(o,{...i,ref:r,children:ve.isValidElement(c)?ve.cloneElement(c,void 0,m):null})}return jsx(o,{...i,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function vv(e){let o=ve.forwardRef((t,a)=>{let{children:r,...n}=t;if(ve.isValidElement(r)){let i=Lv(r),u=Sv(n,r.props);return r.type!==ve.Fragment&&(u.ref=a?Wr(a,i):i),ve.cloneElement(r,u)}return ve.Children.count(r)>1?ve.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var yv=Symbol("radix.slottable");function wv(e){return ve.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===yv}function Sv(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...u)=>{let s=n(...u);return r(...u),s}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function Lv(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function Ts(e){let o=e+"CollectionProvider",[t,a]=Fa(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),i=p=>{let{scope:v,children:y}=p,g=ve__default.useRef(null),x=ve__default.useRef(new Map).current;return jsx(r,{scope:v,itemMap:x,collectionRef:g,children:y})};i.displayName=o;let u=e+"CollectionSlot",s=Rl(u),c=ve__default.forwardRef((p,v)=>{let{scope:y,children:g}=p,x=n(u,y),w=Ut(v,x.collectionRef);return jsx(s,{ref:w,children:g})});c.displayName=u;let m=e+"CollectionItemSlot",d="data-radix-collection-item",l=Rl(m),f=ve__default.forwardRef((p,v)=>{let{scope:y,children:g,...x}=p,w=ve__default.useRef(null),I=Ut(v,w),k=n(m,y);return ve__default.useEffect(()=>(k.itemMap.set(w,{ref:w,...x}),()=>void k.itemMap.delete(w))),jsx(l,{[d]:"",ref:I,children:g})});f.displayName=m;function h(p){let v=n(e+"CollectionConsumer",p);return ve__default.useCallback(()=>{let g=v.collectionRef.current;if(!g)return [];let x=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(v.itemMap.values()).sort((k,S)=>x.indexOf(k.ref.current)-x.indexOf(S.ref.current))},[v.collectionRef,v.itemMap])}return [{Provider:i,Slot:c,ItemSlot:f},h,a]}var zo=globalThis?.document?ve.useLayoutEffect:()=>{};var Iv=ve[" useId ".trim().toString()]||(()=>{}),Cv=0;function Xc(e){let[o,t]=ve.useState(Iv());return zo(()=>{t(a=>a??String(Cv++));},[e]),(o?`radix-${o}`:"")}function $c(e){let o=ve.useRef(e);return ve.useEffect(()=>{o.current=e;}),ve.useMemo(()=>(...t)=>o.current?.(...t),[])}var kv=ve[" useInsertionEffect ".trim().toString()]||zo;function sa({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,i]=Tv({defaultProp:o,onChange:t}),u=e!==void 0,s=u?e:r;{let m=ve.useRef(e!==void 0);ve.useEffect(()=>{let d=m.current;d!==u&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${u?"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=u;},[u,a]);}let c=ve.useCallback(m=>{if(u){let d=Mv(m)?m(e):m;d!==e&&i.current?.(d);}else n(m);},[u,e,n,i]);return [s,c]}function Tv({defaultProp:e,onChange:o}){let[t,a]=ve.useState(e),r=ve.useRef(t),n=ve.useRef(o);return kv(()=>{n.current=o;},[o]),ve.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function Mv(e){return typeof e=="function"}var Av=ve.createContext(void 0);function Ko(e){let o=ve.useContext(Av);return e||o||"ltr"}var Ol="rovingFocusGroup.onEntryFocus",Pv={bubbles:false,cancelable:true},Kr="RovingFocusGroup",[Nl,Yc,Ev]=Ts(Kr),[Dv,Hl]=Fa(Kr,[Ev]),[Rv,Fv]=Dv(Kr),Zc=ve.forwardRef((e,o)=>jsx(Nl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Nl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Bv,{...e,ref:o})})}));Zc.displayName=Kr;var Bv=ve.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:i,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:s,onEntryFocus:c,preventScrollOnEntryFocus:m=false,...d}=e,l=ve.useRef(null),f=Ut(o,l),h=Ko(n),[p,v]=sa({prop:i,defaultProp:u??null,onChange:s,caller:Kr}),[y,g]=ve.useState(false),x=$c(c),w=Yc(t),I=ve.useRef(false),[k,S]=ve.useState(0);return ve.useEffect(()=>{let b=l.current;if(b)return b.addEventListener(Ol,x),()=>b.removeEventListener(Ol,x)},[x]),jsx(Rv,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:p,onItemFocus:ve.useCallback(b=>v(b),[v]),onItemShiftTab:ve.useCallback(()=>g(true),[]),onFocusableItemAdd:ve.useCallback(()=>S(b=>b+1),[]),onFocusableItemRemove:ve.useCallback(()=>S(b=>b-1),[]),children:jsx(xt.div,{tabIndex:y||k===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:ot(e.onMouseDown,()=>{I.current=true;}),onFocus:ot(e.onFocus,b=>{let C=!I.current;if(b.target===b.currentTarget&&C&&!y){let M=new CustomEvent(Ol,Pv);if(b.currentTarget.dispatchEvent(M),!M.defaultPrevented){let P=w().filter(N=>N.focusable),R=P.find(N=>N.active),z=P.find(N=>N.id===p),U=[R,z,...P].filter(Boolean).map(N=>N.ref.current);ef(U,m);}}I.current=false;}),onBlur:ot(e.onBlur,()=>g(false))})})}),Jc="RovingFocusGroupItem",Qc=ve.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:i,...u}=e,s=Xc(),c=n||s,m=Fv(Jc,t),d=m.currentTabStopId===c,l=Yc(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:p}=m;return ve.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(Nl.ItemSlot,{scope:t,id:c,focusable:a,active:r,children:jsx(xt.span,{tabIndex:d?0:-1,"data-orientation":m.orientation,...u,ref:o,onMouseDown:ot(e.onMouseDown,v=>{a?m.onItemFocus(c):v.preventDefault();}),onFocus:ot(e.onFocus,()=>m.onItemFocus(c)),onKeyDown:ot(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){m.onItemShiftTab();return}if(v.target!==v.currentTarget)return;let y=Hv(v,m.orientation,m.dir);if(y!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let x=l().filter(w=>w.focusable).map(w=>w.ref.current);if(y==="last")x.reverse();else if(y==="prev"||y==="next"){y==="prev"&&x.reverse();let w=x.indexOf(v.currentTarget);x=m.loop?qv(x,w+1):x.slice(w+1);}setTimeout(()=>ef(x));}}),children:typeof i=="function"?i({isCurrentTabStop:d,hasTabStop:p!=null}):i})})});Qc.displayName=Jc;var Ov={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Nv(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Hv(e,o,t){let a=Nv(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Ov[a]}function ef(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function qv(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var tf=Zc,af=Qc;var rf="Toggle",ql=ve.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[i,u]=sa({prop:t,onChange:r,defaultProp:a??false,caller:rf});return jsx(xt.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:ot(e.onClick,()=>{e.disabled||u(!i);})})});ql.displayName=rf;var Ba="ToggleGroup",[sf]=Fa(Ba,[Hl]),lf=Hl(),Vl=ve__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(zv,{...a,ref:o});if(t==="multiple")return jsx(Wv,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Ba}\``)});Vl.displayName=Ba;var[df,uf]=sf(Ba),zv=ve__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[i,u]=sa({prop:t,defaultProp:a??"",onChange:r,caller:Ba});return jsx(df,{scope:e.__scopeToggleGroup,type:"single",value:ve__default.useMemo(()=>i?[i]:[],[i]),onItemActivate:u,onItemDeactivate:ve__default.useCallback(()=>u(""),[u]),children:jsx(cf,{...n,ref:o})})}),Wv=ve__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[i,u]=sa({prop:t,defaultProp:a??[],onChange:r,caller:Ba}),s=ve__default.useCallback(m=>u((d=[])=>[...d,m]),[u]),c=ve__default.useCallback(m=>u((d=[])=>d.filter(l=>l!==m)),[u]);return jsx(df,{scope:e.__scopeToggleGroup,type:"multiple",value:i,onItemActivate:s,onItemDeactivate:c,children:jsx(cf,{...n,ref:o})})});Vl.displayName=Ba;var[Kv,Gv]=sf(Ba),cf=ve__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:i,loop:u=true,...s}=e,c=lf(t),m=Ko(i),d={role:"group",dir:m,...s};return jsx(Kv,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(tf,{asChild:true,...c,orientation:n,dir:m,loop:u,children:jsx(xt.div,{...d,ref:o})}):jsx(xt.div,{...d,ref:o})})}),Ps="ToggleGroupItem",jv=ve__default.forwardRef((e,o)=>{let t=uf(Ps,e.__scopeToggleGroup),a=Gv(Ps,e.__scopeToggleGroup),r=lf(e.__scopeToggleGroup),n=t.value.includes(e.value),i=a.disabled||e.disabled,u={...e,pressed:n,disabled:i},s=ve__default.useRef(null);return a.rovingFocus?jsx(af,{asChild:true,...r,focusable:!i,active:n,ref:s,children:jsx(nf,{...u,ref:o})}):jsx(nf,{...u,ref:o})});jv.displayName=Ps;var nf=ve__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=uf(Ps,t),i={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=n.type==="single"?i:void 0;return jsx(ql,{...u,...r,ref:o,onPressedChange:s=>{s?n.onItemActivate(a):n.onItemDeactivate(a);}})}),ff=Vl;function mf(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(o=0;o<r;o++)e[o]&&(t=mf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Es(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=mf(e))&&(a&&(a+=" "),a+=o);return a}var Xv=(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},$v=(e,o)=>({classGroupId:e,validator:o}),bf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var pf=[],Yv="arbitrary..",Zv=e=>{let o=Qv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return Jv(i);let u=i.split("-"),s=u[0]===""&&u.length>1?1:0;return vf(u,s,o)},getConflictingClassGroupIds:(i,u)=>{if(u){let s=a[i],c=t[i];return s?c?Xv(c,s):s:c||pf}return t[i]||pf}}},vf=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let c=vf(e,o+1,n);if(c)return c}let i=t.validators;if(i===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),s=i.length;for(let c=0;c<s;c++){let m=i[c];if(m.validator(u))return m.classGroupId}},Jv=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?Yv+a:void 0})(),Qv=e=>{let{theme:o,classGroups:t}=e;return ey(t,o)},ey=(e,o)=>{let t=bf();for(let a in e){let r=e[a];Wl(r,t,a,o);}return t},Wl=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let i=e[n];ty(i,o,t,a);}},ty=(e,o,t,a)=>{if(typeof e=="string"){ay(e,o,t);return}if(typeof e=="function"){oy(e,o,t,a);return}ry(e,o,t,a);},ay=(e,o,t)=>{let a=e===""?o:yf(o,e);a.classGroupId=t;},oy=(e,o,t,a)=>{if(ny(e)){Wl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push($v(t,e));},ry=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let i=0;i<n;i++){let[u,s]=r[i];Wl(s,yf(o,u),t,a);}},yf=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let n=0;n<r;n++){let i=a[n],u=t.nextPart.get(i);u||(u=bf(),t.nextPart.set(i,u)),t=u;}return t},ny=e=>"isThemeGetter"in e&&e.isThemeGetter===true,sy=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(n,i)=>{t[n]=i,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(n){let i=t[n];if(i!==void 0)return i;if((i=a[n])!==void 0)return r(n,i),i},set(n,i){n in t?t[n]=i:r(n,i);}}};var iy=[],hf=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),ly=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],i=0,u=0,s=0,c,m=r.length;for(let p=0;p<m;p++){let v=r[p];if(i===0&&u===0){if(v===":"){n.push(r.slice(s,p)),s=p+1;continue}if(v==="/"){c=p;continue}}v==="["?i++:v==="]"?i--:v==="("?u++:v===")"&&u--;}let d=n.length===0?r:r.slice(s),l=d,f=false;d.endsWith("!")?(l=d.slice(0,-1),f=true):d.startsWith("!")&&(l=d.slice(1),f=true);let h=c&&c>s?c-s:void 0;return hf(n,f,l,h)};if(o){let r=o+":",n=a;a=i=>i.startsWith(r)?n(i.slice(r.length)):hf(iy,false,i,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},dy=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let n=0;n<t.length;n++){let i=t[n],u=i[0]==="[",s=o.has(i);u||s?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(i)):r.push(i);}return r.length>0&&(r.sort(),a.push(...r)),a}},uy=e=>({cache:sy(e.cacheSize),parseClassName:ly(e),sortModifiers:dy(e),...Zv(e)}),cy=/\s+/,fy=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,i=[],u=e.trim().split(cy),s="";for(let c=u.length-1;c>=0;c-=1){let m=u[c],{isExternal:d,modifiers:l,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:p}=t(m);if(d){s=m+(s.length>0?" "+s:s);continue}let v=!!p,y=a(v?h.substring(0,p):h);if(!y){if(!v){s=m+(s.length>0?" "+s:s);continue}if(y=a(h),!y){s=m+(s.length>0?" "+s:s);continue}v=false;}let g=l.length===0?"":l.length===1?l[0]:n(l).join(":"),x=f?g+"!":g,w=x+y;if(i.indexOf(w)>-1)continue;i.push(w);let I=r(y,v);for(let k=0;k<I.length;++k){let S=I[k];i.push(x+S);}s=m+(s.length>0?" "+s:s);}return s},my=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=wf(t))&&(r&&(r+=" "),r+=a);return r},wf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=wf(e[a]))&&(t&&(t+=" "),t+=o);return t},py=(e,...o)=>{let t,a,r,n,i=s=>{let c=o.reduce((m,d)=>d(m),e());return t=uy(c),a=t.cache.get,r=t.cache.set,n=u,u(s)},u=s=>{let c=a(s);if(c)return c;let m=fy(s,t);return r(s,m),m};return n=i,(...s)=>n(my(...s))},hy=[],je=e=>{let o=t=>t[e]||hy;return o.isThemeGetter=true,o},Sf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Lf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,gy=/^\d+\/\d+$/,xy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,by=/\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$/,vy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,yy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,wy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Go=e=>gy.test(e),le=e=>!!e&&!Number.isNaN(Number(e)),Oa=e=>!!e&&Number.isInteger(Number(e)),Ul=e=>e.endsWith("%")&&le(e.slice(0,-1)),ia=e=>xy.test(e),Sy=()=>true,Ly=e=>by.test(e)&&!vy.test(e),If=()=>false,Iy=e=>yy.test(e),Cy=e=>wy.test(e),ky=e=>!X(e)&&!$(e),Ty=e=>jo(e,Tf,If),X=e=>Sf.test(e),io=e=>jo(e,Mf,Ly),zl=e=>jo(e,Dy,le),gf=e=>jo(e,Cf,If),My=e=>jo(e,kf,Cy),Ds=e=>jo(e,Af,Iy),$=e=>Lf.test(e),Gr=e=>_o(e,Mf),Ay=e=>_o(e,Ry),xf=e=>_o(e,Cf),Py=e=>_o(e,Tf),Ey=e=>_o(e,kf),Rs=e=>_o(e,Af,true),jo=(e,o,t)=>{let a=Sf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},_o=(e,o,t=false)=>{let a=Lf.exec(e);return a?a[1]?o(a[1]):t:false},Cf=e=>e==="position"||e==="percentage",kf=e=>e==="image"||e==="url",Tf=e=>e==="length"||e==="size"||e==="bg-size",Mf=e=>e==="length",Dy=e=>e==="number",Ry=e=>e==="family-name",Af=e=>e==="shadow";var Fy=()=>{let e=je("color"),o=je("font"),t=je("text"),a=je("font-weight"),r=je("tracking"),n=je("leading"),i=je("breakpoint"),u=je("container"),s=je("spacing"),c=je("radius"),m=je("shadow"),d=je("inset-shadow"),l=je("text-shadow"),f=je("drop-shadow"),h=je("blur"),p=je("perspective"),v=je("aspect"),y=je("ease"),g=je("animate"),x=()=>["auto","avoid","all","avoid-page","page","left","right","column"],w=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...w(),$,X],k=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],b=()=>[$,X,s],C=()=>[Go,"full","auto",...b()],M=()=>[Oa,"none","subgrid",$,X],P=()=>["auto",{span:["full",Oa,$,X]},Oa,$,X],R=()=>[Oa,"auto",$,X],z=()=>["auto","min","max","fr",$,X],B=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],N=()=>["auto",...b()],V=()=>[Go,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],F=()=>[e,$,X],W=()=>[...w(),xf,gf,{position:[$,X]}],G=()=>["no-repeat",{repeat:["","x","y","space","round"]}],se=()=>["auto","cover","contain",Py,Ty,{size:[$,X]}],q=()=>[Ul,Gr,io],_=()=>["","none","full",c,$,X],Z=()=>["",le,Gr,io],Y=()=>["solid","dashed","dotted","double"],oe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[le,Ul,xf,gf],ce=()=>["","none",h,$,X],Se=()=>["none",le,$,X],Te=()=>["none",le,$,X],Ie=()=>[le,$,X],De=()=>[Go,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ia],breakpoint:[ia],color:[Sy],container:[ia],"drop-shadow":[ia],ease:["in","out","in-out"],font:[ky],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ia],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ia],shadow:[ia],spacing:["px",le],text:[ia],"text-shadow":[ia],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Go,X,$,v]}],container:["container"],columns:[{columns:[le,X,$,u]}],"break-after":[{"break-after":x()}],"break-before":[{"break-before":x()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:I()}],overflow:[{overflow:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:C()}],"inset-x":[{"inset-x":C()}],"inset-y":[{"inset-y":C()}],start:[{start:C()}],end:[{end:C()}],top:[{top:C()}],right:[{right:C()}],bottom:[{bottom:C()}],left:[{left:C()}],visibility:["visible","invisible","collapse"],z:[{z:[Oa,"auto",$,X]}],basis:[{basis:[Go,"full","auto",u,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[le,Go,"auto","initial","none",X]}],grow:[{grow:["",le,$,X]}],shrink:[{shrink:["",le,$,X]}],order:[{order:[Oa,"first","last","none",$,X]}],"grid-cols":[{"grid-cols":M()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":M()}],"row-start-end":[{row:P()}],"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":z()}],"auto-rows":[{"auto-rows":z()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...B(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...B()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":B()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:N()}],mx:[{mx:N()}],my:[{my:N()}],ms:[{ms:N()}],me:[{me:N()}],mt:[{mt:N()}],mr:[{mr:N()}],mb:[{mb:N()}],ml:[{ml:N()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:V()}],w:[{w:[u,"screen",...V()]}],"min-w":[{"min-w":[u,"screen","none",...V()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[i]},...V()]}],h:[{h:["screen","lh",...V()]}],"min-h":[{"min-h":["screen","lh","none",...V()]}],"max-h":[{"max-h":["screen","lh",...V()]}],"font-size":[{text:["base",t,Gr,io]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,zl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ul,X]}],"font-family":[{font:[Ay,X,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,$,X]}],"line-clamp":[{"line-clamp":[le,"none",$,zl]}],leading:[{leading:[n,...b()]}],"list-image":[{"list-image":["none",$,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:[le,"from-font","auto",$,io]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[le,"auto",$,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:W()}],"bg-repeat":[{bg:G()}],"bg-size":[{bg:se()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Oa,$,X],radial:["",$,X],conic:[Oa,$,X]},Ey,My]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:q()}],"gradient-via-pos":[{via:q()}],"gradient-to-pos":[{to:q()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:_()}],"rounded-s":[{"rounded-s":_()}],"rounded-e":[{"rounded-e":_()}],"rounded-t":[{"rounded-t":_()}],"rounded-r":[{"rounded-r":_()}],"rounded-b":[{"rounded-b":_()}],"rounded-l":[{"rounded-l":_()}],"rounded-ss":[{"rounded-ss":_()}],"rounded-se":[{"rounded-se":_()}],"rounded-ee":[{"rounded-ee":_()}],"rounded-es":[{"rounded-es":_()}],"rounded-tl":[{"rounded-tl":_()}],"rounded-tr":[{"rounded-tr":_()}],"rounded-br":[{"rounded-br":_()}],"rounded-bl":[{"rounded-bl":_()}],"border-w":[{border:Z()}],"border-w-x":[{"border-x":Z()}],"border-w-y":[{"border-y":Z()}],"border-w-s":[{"border-s":Z()}],"border-w-e":[{"border-e":Z()}],"border-w-t":[{"border-t":Z()}],"border-w-r":[{"border-r":Z()}],"border-w-b":[{"border-b":Z()}],"border-w-l":[{"border-l":Z()}],"divide-x":[{"divide-x":Z()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Z()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Y(),"hidden","none"]}],"divide-style":[{divide:[...Y(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...Y(),"none","hidden"]}],"outline-offset":[{"outline-offset":[le,$,X]}],"outline-w":[{outline:["",le,Gr,io]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",m,Rs,Ds]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",d,Rs,Ds]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:Z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[le,io]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":Z()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",l,Rs,Ds]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[le,$,X]}],"mix-blend":[{"mix-blend":[...oe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[le]}],"mask-image-linear-from-pos":[{"mask-linear-from":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[$,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":J()}],"mask-image-radial-to-pos":[{"mask-radial-to":J()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"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":w()}],"mask-image-conic-pos":[{"mask-conic":[le]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:W()}],"mask-repeat":[{mask:G()}],"mask-size":[{mask:se()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,X]}],filter:[{filter:["","none",$,X]}],blur:[{blur:ce()}],brightness:[{brightness:[le,$,X]}],contrast:[{contrast:[le,$,X]}],"drop-shadow":[{"drop-shadow":["","none",f,Rs,Ds]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",le,$,X]}],"hue-rotate":[{"hue-rotate":[le,$,X]}],invert:[{invert:["",le,$,X]}],saturate:[{saturate:[le,$,X]}],sepia:[{sepia:["",le,$,X]}],"backdrop-filter":[{"backdrop-filter":["","none",$,X]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[le,$,X]}],"backdrop-contrast":[{"backdrop-contrast":[le,$,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",le,$,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[le,$,X]}],"backdrop-invert":[{"backdrop-invert":["",le,$,X]}],"backdrop-opacity":[{"backdrop-opacity":[le,$,X]}],"backdrop-saturate":[{"backdrop-saturate":[le,$,X]}],"backdrop-sepia":[{"backdrop-sepia":["",le,$,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[le,"initial",$,X]}],ease:[{ease:["linear","initial",y,$,X]}],delay:[{delay:[le,$,X]}],animate:[{animate:["none",g,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,$,X]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:Se()}],"rotate-x":[{"rotate-x":Se()}],"rotate-y":[{"rotate-y":Se()}],"rotate-z":[{"rotate-z":Se()}],scale:[{scale:Te()}],"scale-x":[{"scale-x":Te()}],"scale-y":[{"scale-y":Te()}],"scale-z":[{"scale-z":Te()}],"scale-3d":["scale-3d"],skew:[{skew:Ie()}],"skew-x":[{"skew-x":Ie()}],"skew-y":[{"skew-y":Ie()}],transform:[{transform:[$,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:De()}],"translate-x":[{"translate-x":De()}],"translate-y":[{"translate-y":De()}],"translate-z":[{"translate-z":De()}],"translate-none":["translate-none"],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,X]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[le,Gr,io,zl]}],stroke:[{stroke:["none",...F()]}],"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=py(Fy);function Na(...e){return Pf(Es(e))}var Oy=ve.createContext({size:"default",variant:"default",spacing:0});function Ha({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(ff,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Na("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(Oy.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var Hy={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Bf=createSlice({name:"toolbar",initialState:Hy,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:ta,setPenColor:la,setStrokeWidth:jr,setFontSize:XE,setFontFamily:$E,setFontStyle:YE,setFontWeight:ZE,setTextDecoration:JE,setTextColor:QE}=Bf.actions,Gl=Bf.reducer;var Of=({onClose:e,onRecordingComplete:o})=>{let t=Ve(),[a,r]=useState(false),[n,i]=useState(null),[u,s]=useState(0),[c,m]=useState(null),[d,l]=useState(false),f=useRef(null),h=useRef([]),p=useRef(null),v=useRef(null),y=useRef(null);useEffect(()=>((async()=>{try{let C=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(C),l(!0),y.current&&(y.current.srcObject=C);}catch(C){console.error("Error accessing camera:",C),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),c&&c.getTracks().forEach(C=>C.stop());}),[]);let g=()=>{c&&(c.getTracks().forEach(b=>b.stop()),m(null),l(false));},x=async()=>{try{let b=null,C=null;try{b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(B){console.error("Error accessing camera for recording:",B),alert("Failed to access camera for recording.");return}try{C=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(B){console.warn("Microphone access denied:",B);}let M=[...b.getVideoTracks()];C&&M.push(...C.getAudioTracks());let P=new MediaStream(M),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 z=new MediaRecorder(P,{mimeType:R,videoBitsPerSecond:25e5});f.current=z,h.current=[],z.ondataavailable=B=>{B.data.size>0&&h.current.push(B.data);},z.onstop=()=>{let B=new Blob(h.current,{type:R}),U=document.createElement("video");U.src=URL.createObjectURL(B),U.muted=!0,U.currentTime=.1,U.onseeked=()=>{let N=document.createElement("canvas");N.width=U.videoWidth,N.height=U.videoHeight;let V=N.getContext("2d");V&&(V.drawImage(U,0,0),v.current=N.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(U.src);},P.getTracks().forEach(N=>N.stop()),b&&b.getTracks().forEach(N=>N.stop()),C&&C.getTracks().forEach(N=>N.stop()),p.current&&clearInterval(p.current),i(B),g();},z.onerror=B=>{console.error("MediaRecorder error:",B);},z.start(1e3),r(!0),s(0),p.current=setInterval(()=>{s(B=>B+1);},1e3);}catch(b){console.error("Error starting camera recording:",b),alert("Failed to start recording. Please check permissions.");}},w=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),r(false));},I=()=>{if(n){let b=URL.createObjectURL(n),C=document.createElement("a");C.href=b,C.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(b);}},k=b=>{let C=Math.floor(b/60),M=b%60;return `${C.toString().padStart(2,"0")}:${M.toString().padStart(2,"0")}`};if(!t)return null;let S=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:b=>{b.target===b.currentTarget&&e(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:b=>b.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:[!n&&jsxs(Fragment,{children:[jsx("video",{ref:y,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:x,disabled:!d,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"})})}),!d&&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:w,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:k(u)})]})]})]}),n&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(n),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",k(u)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{i(null),s(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:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&n&&v.current&&(o(n,v.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(S,t)};var da=40,Hf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,i]=useState(t?.order||"sequential"),[u,s]=useState(false),c=useRef(null),m=Ve(),d=useRef(null);useEffect(()=>{let x=w=>{w.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let l=x=>{let w=x.target.files;if(!w||w.length===0)return;let I=da-a.length;if(I<=0){alert(`You can only upload a maximum of ${da} images`);return}let k=Array.from(w).slice(0,I);k.length<w.length&&alert(`Only ${I} more images can be added (max ${da} total)`);let S=k.map(b=>new Promise((C,M)=>{let P=new FileReader;P.onload=R=>{R.target?.result?C(R.target.result):M(new Error("Failed to read file"));},P.onerror=M,P.readAsDataURL(b);}));Promise.all(S).then(b=>{r(C=>[...C,...b]),d.current&&(d.current.value="");});},f=x=>{x.preventDefault(),s(false);let w=Array.from(x.dataTransfer.files).filter(b=>b.type.startsWith("image/"));if(w.length===0)return;let I=da-a.length;if(I<=0){alert(`You can only upload a maximum of ${da} images`);return}let k=w.slice(0,I);k.length<w.length&&alert(`Only ${I} more images can be added (max ${da} total)`);let S=k.map(b=>new Promise((C,M)=>{let P=new FileReader;P.onload=R=>{R.target?.result?C(R.target.result):M(new Error("Failed to read file"));},P.onerror=M,P.readAsDataURL(b);}));Promise.all(S).then(b=>{r(C=>[...C,...b]);});},h=x=>{x.preventDefault(),s(true);},p=()=>{s(false);},v=x=>{r(w=>w.filter((I,k)=>k!==x));},y=x=>{if(x.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,n,t?.id);};if(!m)return null;let g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:y,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>=da?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",da," images"]}):jsxs("span",{children:[a.length,"/",da," images"]})})]}),jsx("input",{ref:d,type:"file",accept:"image/*",multiple:true,onChange:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:f,onDragOver:h,onDragLeave:p,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"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:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \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:()=>i("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>i("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((x,w)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${w+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(w),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:w+1})]},w))})]}),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(g,m)};var Fs={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},ew={enabled:true};function Xl(e){return e?{tools:{...Fs.tools,...e.tools},actions:{...Fs.actions,...e.actions}}:Fs}var tw={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},aw={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};function $l(e,[o,t]){return Math.min(t,Math.max(o,e))}function qf(e){let o=ve.useRef({value:e,previous:e});return ve.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Uf(e){let[o,t]=ve.useState(void 0);return zo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let n=r[0],i,u;if("borderBoxSize"in n){let s=n.borderBoxSize,c=Array.isArray(s)?s[0]:s;i=c.inlineSize,u=c.blockSize;}else i=e.offsetWidth,u=e.offsetHeight;t({width:i,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var zf=["PageUp","PageDown"],Wf=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Kf={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Xo="Slider",[Yl,rw,nw]=Ts(Xo),[Gf]=Fa(Xo,[nw]),[sw,Os]=Gf(Xo),jf=ve.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:i="horizontal",disabled:u=false,minStepsBetweenThumbs:s=0,defaultValue:c=[a],value:m,onValueChange:d=()=>{},onValueCommit:l=()=>{},inverted:f=false,form:h,...p}=e,v=ve.useRef(new Set),y=ve.useRef(0),x=i==="horizontal"?iw:lw,[w=[],I]=sa({prop:m,defaultProp:c,onChange:P=>{[...v.current][y.current]?.focus(),d(P);}}),k=ve.useRef(w);function S(P){let R=mw(w,P);M(P,R);}function b(P){M(P,y.current);}function C(){let P=k.current[y.current];w[y.current]!==P&&l(w);}function M(P,R,{commit:z}={commit:false}){let B=xw(n),U=bw(Math.round((P-a)/n)*n+a,B),N=$l(U,[a,r]);I((V=[])=>{let F=cw(V,N,R);if(gw(F,s*n)){y.current=F.indexOf(N);let W=String(F)!==String(V);return W&&z&&l(F),W?F:V}else return V});}return jsx(sw,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:r,valueIndexToChangeRef:y,thumbs:v.current,values:w,orientation:i,form:h,children:jsx(Yl.Provider,{scope:e.__scopeSlider,children:jsx(Yl.Slot,{scope:e.__scopeSlider,children:jsx(x,{"aria-disabled":u,"data-disabled":u?"":void 0,...p,ref:o,onPointerDown:ot(p.onPointerDown,()=>{u||(k.current=w);}),min:a,max:r,inverted:f,onSlideStart:u?void 0:S,onSlideMove:u?void 0:b,onSlideEnd:u?void 0:C,onHomeKeyDown:()=>!u&&M(a,0,{commit:true}),onEndKeyDown:()=>!u&&M(r,w.length-1,{commit:true}),onStepKeyDown:({event:P,direction:R})=>{if(!u){let U=zf.includes(P.key)||P.shiftKey&&Wf.includes(P.key)?10:1,N=y.current,V=w[N],F=n*U*R;M(V+F,N,{commit:true});}}})})})})});jf.displayName=Xo;var[_f,Xf]=Gf(Xo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),iw=ve.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:i,onSlideMove:u,onSlideEnd:s,onStepKeyDown:c,...m}=e,[d,l]=ve.useState(null),f=Ut(o,x=>l(x)),h=ve.useRef(void 0),p=Ko(r),v=p==="ltr",y=v&&!n||!v&&n;function g(x){let w=h.current||d.getBoundingClientRect(),I=[0,w.width],S=Ql(I,y?[t,a]:[a,t]);return h.current=w,S(x-w.left)}return jsx(_f,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx($f,{dir:p,"data-orientation":"horizontal",...m,ref:f,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:x=>{let w=g(x.clientX);i?.(w);},onSlideMove:x=>{let w=g(x.clientX);u?.(w);},onSlideEnd:()=>{h.current=void 0,s?.();},onStepKeyDown:x=>{let I=Kf[y?"from-left":"from-right"].includes(x.key);c?.({event:x,direction:I?-1:1});}})})}),lw=ve.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:i,onSlideEnd:u,onStepKeyDown:s,...c}=e,m=ve.useRef(null),d=Ut(o,m),l=ve.useRef(void 0),f=!r;function h(p){let v=l.current||m.current.getBoundingClientRect(),y=[0,v.height],x=Ql(y,f?[a,t]:[t,a]);return l.current=v,x(p-v.top)}return jsx(_f,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx($f,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:p=>{let v=h(p.clientY);n?.(v);},onSlideMove:p=>{let v=h(p.clientY);i?.(v);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:p=>{let y=Kf[f?"from-bottom":"from-top"].includes(p.key);s?.({event:p,direction:y?-1:1});}})})}),$f=ve.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:i,onEndKeyDown:u,onStepKeyDown:s,...c}=e,m=Os(Xo,t);return jsx(xt.span,{...c,ref:o,onKeyDown:ot(e.onKeyDown,d=>{d.key==="Home"?(i(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):zf.concat(Wf).includes(d.key)&&(s(d),d.preventDefault());}),onPointerDown:ot(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),m.thumbs.has(l)?l.focus():a(d);}),onPointerMove:ot(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d);}),onPointerUp:ot(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),n(d));})})}),Yf="SliderTrack",Zf=ve.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=Os(Yf,t);return jsx(xt.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});Zf.displayName=Yf;var Zl="SliderRange",Jf=ve.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=Os(Zl,t),n=Xf(Zl,t),i=ve.useRef(null),u=Ut(o,i),s=r.values.length,c=r.values.map(l=>tm(l,r.min,r.max)),m=s>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(xt.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:u,style:{...e.style,[n.startEdge]:m+"%",[n.endEdge]:d+"%"}})});Jf.displayName=Zl;var Jl="SliderThumb",Qf=ve.forwardRef((e,o)=>{let t=rw(e.__scopeSlider),[a,r]=ve.useState(null),n=Ut(o,u=>r(u)),i=ve.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(dw,{...e,ref:n,index:i})}),dw=ve.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,i=Os(Jl,t),u=Xf(Jl,t),[s,c]=ve.useState(null),m=Ut(o,g=>c(g)),d=s?i.form||!!s.closest("form"):true,l=Uf(s),f=i.values[a],h=f===void 0?0:tm(f,i.min,i.max),p=fw(a,i.values.length),v=l?.[u.size],y=v?pw(v,h,u.direction):0;return ve.useEffect(()=>{if(s)return i.thumbs.add(s),()=>{i.thumbs.delete(s);}},[s,i.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${y}px)`},children:[jsx(Yl.ItemSlot,{scope:e.__scopeSlider,children:jsx(xt.span,{role:"slider","aria-label":e["aria-label"]||p,"aria-valuemin":i.min,"aria-valuenow":f,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...n,ref:m,style:f===void 0?{display:"none"}:e.style,onFocus:ot(e.onFocus,()=>{i.valueIndexToChangeRef.current=a;})})}),d&&jsx(em,{name:r??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:f},a)]})});Qf.displayName=Jl;var uw="RadioBubbleInput",em=ve.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=ve.useRef(null),n=Ut(r,a),i=qf(o);return ve.useEffect(()=>{let u=r.current;if(!u)return;let s=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(s,"value").set;if(i!==o&&m){let d=new Event("input",{bubbles:true});m.call(u,o),u.dispatchEvent(d);}},[i,o]),jsx(xt.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});em.displayName=uw;function cw(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function tm(e,o,t){let n=100/(t-o)*(e-o);return $l(n,[0,100])}function fw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function mw(e,o){if(e.length===1)return 0;let t=e.map(r=>Math.abs(r-o)),a=Math.min(...t);return t.indexOf(a)}function pw(e,o,t){let a=e/2,n=Ql([0,50],[0,a]);return (a-n(o)*t)*t}function hw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function gw(e,o){if(o>0){let t=hw(e);return Math.min(...t)>=o}return true}function Ql(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 xw(e){return (String(e).split(".")[1]||"").length}function bw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var am=jf,om=Zf,rm=Jf,nm=Qf;function Ns({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:i,thumbClassName:u,...s}){let c=ve.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(am,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Na("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),...s,children:[jsx(om,{"data-slot":"slider-track",className:Na("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",i),children:jsx(rm,{"data-slot":"slider-range",className:Na("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:c.length},(m,d)=>jsx(nm,{"data-slot":"slider-thumb",className:Na("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",u)},d))]})}var jw=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a}={})=>{let r=be(),n=te(A=>A.canvas.slides.find(ee=>ee.id===A.canvas.currentSlideId)),i=n?.videos||[],u=n?.editingFlashcard,s=te(A=>A.toolbar.selectedTool),c=te(A=>A.toolbar.penColor),m=te(A=>A.toolbar.strokeWidth),d=te(A=>A.canvas.editingOverlayPosition),l=n?.showMcqForm,f=n?.showFlashcardForm,h=useRef(null);useEffect(()=>{let A=ee=>{(ee.ctrlKey||ee.metaKey)&&ee.key==="z"&&!ee.shiftKey&&(ee.preventDefault(),r(Kn())),(ee.ctrlKey&&ee.shiftKey&&ee.key==="Z"||ee.ctrlKey&&ee.key==="y")&&(ee.preventDefault(),r(Gn()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[r]);let p=useMemo(()=>Xl(a),[a]),{tools:v,actions:y}=p,g=i.some(A=>A.isRecorded&&A.isPlaying),x=te(A=>A.toolbar.fontSize),w=te(A=>A.toolbar.fontFamily),I=te(A=>A.toolbar.fontStyle),k=te(A=>A.toolbar.fontWeight),S=te(A=>A.toolbar.textDecoration),b=te(A=>A.toolbar.textColor),[C,M]=useState(false),[P,R]=useState(false),[z,B]=useState(false),[U,N]=useState(false),[V,F]=useState(false),[W,G]=useState(false),[se,q]=useState(false),[_,Z]=useState(false),[Y,oe]=useState(true),J=useRef(null),ce=useRef(null),Se=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],Te=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"style",icon:Palette,label:"Style",configKey:"style"},{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"}],[]),Ie=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"}],[]),De=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),At=useMemo(()=>Te.filter(A=>{let ee=v[A.configKey];return typeof ee=="boolean"?ee:Array.isArray(ee)?ee.length>0:true}),[v,Te]),Pt=useMemo(()=>{let A=v.shapes;return A===false?[]:A===true?Ie:Array.isArray(A)?Ie.filter(ee=>A.includes(ee.name)):Ie},[v.shapes,Ie]),fo=useMemo(()=>{let A=v.activities;return A===false?[]:A===true?De:Array.isArray(A)?De.filter(ee=>A.includes(ee.name)):De},[v.activities,De]),ne=useMemo(()=>{let A=v.media;return A===false?{photoFrame:false,image:false,video:false}:A===true?{photoFrame:true,image:true,video:true}:Array.isArray(A)?{photoFrame:A.includes("photo-frame"),image:A.includes("image"),video:A.includes("video")}:{photoFrame:true,image:true,video:true}},[v.media]),Jr=useMemo(()=>{let A=v.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[v.activities]),Qr=A=>{let ee=A.target.files;!ee||ee.length===0||(r(ta("select")),r(yt(false)),N(false),Array.from(ee).forEach(Me=>{let xe=new FileReader;xe.onload=ie=>{let fe=new window.Image;fe.src=ie.target?.result,fe.onload=()=>{let Oe=fe.width/fe.height,dt=300,Et=300,Dt=fe.width,Ne=fe.height;Dt>dt&&(Dt=dt,Ne=Dt/Oe),Ne>Et&&(Ne=Et,Dt=Ne*Oe),r(de());let Ue=d?.left||0,oa=d?.top||0;r(si({id:v4(),src:fe.src,x:Ue,y:oa,width:Dt,height:Ne,draggable:true,rotation:0}));};},xe.readAsDataURL(Me);}),A.target.value="");},en=async A=>{let ee=A.target.files;if(!(!ee||ee.length===0)){console.log("files",A),r(ta("select")),r(yt(false)),N(false);for(let Me of Array.from(ee))try{let xe=URL.createObjectURL(Me),ie=document.createElement("video");console.log("video",ie),ie.src=xe,ie.muted=!0,ie.playsInline=!0,ie.preload="auto",ie.load(),await new Promise((ut,re)=>{let _e=setTimeout(()=>re(new Error("Metadata load timeout")),1e4);ie.onloadedmetadata=()=>{clearTimeout(_e),ut();},ie.onerror=()=>{clearTimeout(_e),re(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ie.duration,width:ie.videoWidth,height:ie.videoHeight}),await new Promise((ut,re)=>{let _e=setTimeout(()=>re(new Error("Video load timeout")),1e4);ie.readyState>=2?(clearTimeout(_e),ut()):ie.onloadeddata=()=>{clearTimeout(_e),ut();};});let fe=Math.min(.8,ie.duration/2);console.log("Seeking to:",fe),ie.currentTime=fe,await new Promise(ut=>{let re=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),ut();},5e3);ie.onseeked=()=>{clearTimeout(re),console.log("Seek completed"),ut();};});let Oe=document.createElement("canvas"),dt=ie.videoWidth/ie.videoHeight,Et=400,Dt=400,Ne=ie.videoWidth,Ue=ie.videoHeight;Ne>Et&&(Ne=Et,Ue=Ne/dt),Ue>Dt&&(Ue=Dt,Ne=Ue*dt),Oe.width=Ne,Oe.height=Ue;let oa=Oe.getContext("2d",{willReadFrequently:!1});if(!oa)throw new Error("Failed to get canvas context");if(await new Promise(ut=>setTimeout(ut,100)),ie.videoWidth===0||ie.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ne,height:Ue}),oa.drawImage(ie,0,0,Ne,Ue);let ha=Oe.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",ha.length),r(de());let Ys=800-Ne/2,Zs=450-Ue/2,ln=v4();await ro(ln,Me,ha),r(xn({id:ln,objectUrl:xe,thumbnailDataUrl:ha,videoBlob:Me,x:Ys,y:Zs,width:Ne,height:Ue,draggable:!0,isPlaying:!1,rotation:0})),ie.src="",ie.load(),console.log(`Video uploaded: ${Me.name}`);}catch(xe){console.error("Error processing video:",xe),alert(`Failed to process video: ${Me.name}`);}A.target.value="";}},tn=(A,ee,Me)=>{r(de()),r(ta("select")),r(yt(false));let xe=300,ie=300,fe=800-xe/2,Oe=450-ie/2;r(Me?vo({id:Me,images:A,order:ee,x:fe,y:Oe,width:xe,height:ie,rotation:0,draggable:true}):di({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:ee,x:fe,y:Oe,width:xe,height:ie,rotation:0,draggable:true})),r(Ga(false));},an=()=>{r(de()),r(ta("select")),r(yt(false));let A=400,ee=300,Me=800-A/2,xe=450-ee/2;r(fi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Me,y:xe,width:A,height:ee,rotation:0,draggable:true,isCapturing:false})),N(false);},on=A=>{let fe={};switch(A.name){case "circle":case "ring":case "wedge":case "arc":fe.radius=50,(A.name==="ring"||A.name==="arc")&&(fe.innerRadius=25,fe.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(fe.angle=A.name==="wedge"?60:90);break;case "ellipse":fe.radiusX=60,fe.radiusY=40;break;case "triangle":fe.radius=50,fe.sides=3;break;case "polygon":fe.radius=50,fe.sides=6;break;case "star":fe.innerRadius=25,fe.outerRadius=50,fe.numPoints=5;break;case "arrow":case "line":fe.points=[0,0,100,0],A.name==="arrow"&&(fe.pointerLength=10,fe.pointerWidth=10);break}let Oe={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:c,...fe};r(de()),r(yt(false)),r(ta(A.name)),r(ii(Oe)),B(false);},Ua=A=>{if(r(ta(A)),A==="select")r(yt(false));else if(A==="text"){r(yt(false)),r(de());let ee=200,Me=50,xe=800-ee/2,ie=450-Me/2,Oe=window.innerWidth<768?Math.max(x,32):x,dt=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(li({id:dt,text:"",x:xe,y:ie,width:ee,height:Me,rotation:0,draggable:true,fontSize:Oe,fontFamily:w,fontStyle:I,fontWeight:k,textDecoration:S,fill:b,align:"left"})),setTimeout(()=>{r(fr(dt));},100),t&&t(dt);}else r(yt(true));},Ks=()=>{r(Mi()),r(yt(false));},Gs=()=>{e?e():o?M(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},js=()=>{R(true);},_s=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:an,enabled:ne.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>J.current?.click(),enabled:ne.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>ce.current?.click(),enabled:ne.video}],pa=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Kn()),enabled:y.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(Gn()),enabled:y.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:Gs,enabled:y.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:js,enabled:y.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:Ks,enabled:y.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],rn=async(A,ee)=>{try{r(ta("select")),r(yt(!1));let Me=URL.createObjectURL(A),xe=document.createElement("video");xe.src=Me,xe.muted=!0,xe.playsInline=!0,xe.preload="auto",await new Promise((Ue,oa)=>{let ha=setTimeout(()=>oa(new Error("Metadata load timeout")),1e4);xe.onloadedmetadata=()=>{clearTimeout(ha),Ue();},xe.onerror=()=>{clearTimeout(ha),oa(new Error("Failed to load video"));};});let ie=640,fe=xe.videoWidth/xe.videoHeight,Oe=ie,dt=Oe/fe;r(de());let Et=800-Oe/2,Dt=450-dt/2,Ne=v4();await ro(Ne,A,ee),r(xn({id:Ne,objectUrl:Me,thumbnailDataUrl:ee,videoBlob:A,x:Et,y:Dt,width:Oe,height:dt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),M(!1),R(!1);}catch(Me){console.error("Error adding recorded video to canvas:",Me),alert("Failed to add video to canvas. Please try again.");}},Xs=A=>{r(ta("select")),r(yt(false)),r(ur(null)),A&&r(Si(A)),r(va(!l));},mo=()=>{r(sr(null)),r(Ga(true)),F(false);},nn=()=>{B(!z);},$s=()=>{N(!U);},Jo=()=>{F(!V);},po=()=>{G(!W);},sn=()=>{oe(A=>{let ee=!A;return ee||(B(false),N(false),F(false),G(false),Z(false),q(false)),ee});};return useEffect(()=>{if(!_)return;let A=ee=>{h.current&&!h.current.contains(ee.target)&&Z(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[_]),g?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:sn,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:Y?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),Y&&jsxs("div",{className:"fixed top-[168px] left-4 z-50 flex flex-col gap-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(Ha,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:At.map((A,ee)=>jsx("div",{title:A.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.name===s?"bg-primary/10":A.name==="style"?"md:hidden":""}`,onClick:()=>{A.name==="image"?($s(),B(false),F(false),G(false),Ua(A.name)):A.name==="shapes"?(nn(),N(false),F(false),G(false),Ua(A.name)):A.name==="activities"?(Ua(A.name),Jo(),B(false),N(false),G(false)):A.name==="style"?(po(),B(false),N(false),F(false),Ua(A.name)):(Ua(A.name),B(false),N(false),F(false),G(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ee))}),z&&jsx(Ha,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:Pt.map((A,ee)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>on(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ee))}),U&&jsx(Ha,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:_s.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),V&&jsxs(Ha,{type:"single",className:"mx-1 mt-auto mb-10 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl lg:mb-11",children:[Jr&&jsx("div",{title:"Flashcard",onClick:()=>mo(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),fo.map((A,ee)=>jsx("div",{title:A.label,onClick:()=>Xs(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},ee))]}),W&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Ns,{value:[m],onValueChange:A=>{r(jr(A[0]));},max:28,min:6,step:1,className:"w-28",rangeClassName:"bg-gray-300",thumbClassName:"bg-gray-600 border-none h-4 w-4"}),jsx("div",{className:"h-5 w-5 rounded-full bg-gray-800"})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"COLOR"}),jsxs("div",{className:"flex flex-wrap gap-1",children:[Se.map(A=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${c===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{r(la(A.value)),G(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:c,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>r(la(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:c,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{r(nr(A.target.value)),G(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),pa.some(A=>A.enabled)&&jsx(Ha,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:pa.filter(A=>A.enabled).map(A=>jsx("button",{onClick:A.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.colorClass}`,title:A.title,children:jsx(A.icon,{weight:A.iconWeight,className:"text-primary text-lg md:text-xl"})},A.key))})]}),jsx("input",{ref:J,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:Qr}),jsx("input",{ref:ce,type:"file",accept:"video/*",className:"hidden",onChange:en}),!e&&C&&o&&jsx(Sr,{onClose:()=>M(false),stageRef:o,onRecordingComplete:rn}),P&&jsx(Of,{onClose:()=>R(false),onRecordingComplete:rn}),f&&jsx(Hf,{editingFlashcard:u,onConfirm:tn,onCancel:()=>r(Ga(false))}),se&&jsx(ts,{defaultColor:c,onConfirm:A=>{r(la(A)),q(false);},onCancel:()=>q(false)})]})},_w=jw;var nd=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let r=He(wa),n=He(Di),i=a?n:r,u=He(pr),m=(He(g=>g.canvas.slides.find(x=>x.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[d,l]=useState(false),[f,h]=useState(null),[p,v]=useState(null),y=async()=>{if(r.length===0){v({type:"error",message:"No slides to publish"});return}if(!e){v({type:"error",message:"No publish handler provided"});return}l(true),v(null);try{let g=await e(i,u,x=>{h(x);});g.success?v({type:"success",message:g.message}):v({type:"error",message:g.message});}catch(g){v({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),v(null);},3e3);}};return m?null:jsxs("button",{onClick:y,disabled:d||r.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var Jw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:r,onDescriptionChange:n,showPublishButton:i=true,showBackButton:u=true,editableTitle:s=true,editableDescription:c=true,className:m="",rightContent:d,leftContent:l,includeInactiveSlides:f=false})=>{let h=tt(),p=He(pr),v=He(Ri),y=e??(v?p.title:"")??"Untitled",g=o??(v?p.description:"")??"Add a description...",[x,w]=useState(false),[I,k]=useState(false),[S,b]=useState(y),[C,M]=useState(g),P=useRef(null),R=useRef(null);useEffect(()=>{b(y);},[y]),useEffect(()=>{M(g);},[g]),useEffect(()=>{x&&P.current&&(P.current.focus(),P.current.select());},[x]),useEffect(()=>{I&&R.current&&(R.current.focus(),R.current.select());},[I]);let z=()=>{s&&w(true);},B=()=>{c&&k(true);},U=()=>{w(false),S.trim()&&S!==y?r?r(S.trim()):h(Ai(S.trim())):S.trim()||b(y);},N=()=>{k(false),C.trim()&&C!==g?n?n(C.trim()):h(Pi(C.trim())):C.trim()||M(g);},V=W=>{W.key==="Enter"?U():W.key==="Escape"&&(b(y),w(false));},F=W=>{W.key==="Enter"?N():W.key==="Escape"&&(M(g),k(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-4",children:[u&&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:[x?jsx("input",{ref:P,type:"text",value:S,onChange:W=>b(W.target.value),onBlur:U,onKeyDown:V,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:z,title:S,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${s?"hover:border-primary cursor-text":""}`,children:S}),I?jsx("input",{ref:R,type:"text",value:C,onChange:W=>M(W.target.value),onBlur:N,onKeyDown:F,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:B,title:C,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${c?"hover:border-primary cursor-text":""}`,children:C})]})]}),d||i&&a&&jsx(nd,{onPublish:a,includeInactiveSlides:f})]})};var rS=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],nS=({colors:e=rS,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let[n,i]=useState(true),u=te(ge),s=te(l=>l.toolbar.penColor),c=te(l=>l.toolbar.strokeWidth),m=u?.backgroundColor,d=be();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:n?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-16 left-1/2 z-50 hidden w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-3 shadow-2xl md:bottom-6 md:flex md:p-5 2xl:px-8 2xl:py-6 ${r}`,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-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-black md:h-3 md:w-3"}),jsx(Ns,{defaultValue:[12],max:28,min:6,step:1,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:l=>d(jr(l[0]))}),jsx("div",{className:"h-5 w-5 rounded-full bg-black md:h-7 md:w-7 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-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"COLOR"}),jsxs(Ha,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${s===l.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:l.value},onClick:()=>d(la(l.value))},l.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>d(la("#2D2F50"))}),jsxs("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] md:h-10 md:w-10 lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(la(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-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:m},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(nr(l.target.value))})})]})}),jsx("div",{className:"absolute -top-6 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2 md:-top-4",children:jsx("button",{onClick:()=>i(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,{weight:"bold",className:"text-gray-600 md:text-xl"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>i(true),className:"fixed bottom-20 left-1/2 z-50 hidden -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 md:bottom-3 md:flex","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var fm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),sS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),id=e=>{let o=sS(e);return o.charAt(0).toUpperCase()+o.slice(1)},Us=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),mm=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var pm={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 gm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:i,...u},s)=>createElement("svg",{ref:s,...pm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Us("lucide",r),...!n&&!mm(u)&&{"aria-hidden":"true"},...u},[...i.map(([c,m])=>createElement(c,m)),...Array.isArray(n)?n:[n]]));var zs=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(gm,{ref:n,iconNode:o,className:Us(`lucide-${fm(id(e))}`,`lucide-${e}`,a),...r}));return t.displayName=id(e),t};var uS=[["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"}]],$r=zs("copy",uS);var cS=[["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"}]],Yr=zs("trash-2",cS);var bm=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:i})=>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:r,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:u=>{u.stopPropagation(),n();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx($r,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),i();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Yr,{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 hS=({softDelete:e=false})=>{let o=tt(),t=He(wa),a=He(ya),r=He(mr),[n,i]=useState(true),c=(He(h=>h.canvas.slides.find(p=>p.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),m=()=>{r&&o(tr());},d=h=>{o(rr(h));},l=h=>{o(or(h));},f=h=>{t.length>1&&o(ar({id:h,softDelete:e}));};return c?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:n?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>i(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((h,p)=>jsx(bm,{slide:h,index:p,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>l(h.id),onDelete:()=>f(h.id)},h.id))}),jsxs("button",{onClick:m,disabled:!r,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${r?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!n&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>i(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 $o=20,IS=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:i})=>jsxs("div",{className:`relative h-[122px] w-[166px] shrink-0 cursor-pointer rounded-lg border bg-[#fafafa] transition-all ${t?"border-[#096b76]":"border-black/10"}`,onClick:r,children:[jsx("div",{className:"absolute top-1 right-1 bottom-1 left-1 overflow-hidden rounded bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"size-full object-contain"}):jsx("div",{className:"flex size-full items-center justify-center",children:jsx("span",{className:"text-xs text-black/20",children:"No preview"})})}),jsx("div",{className:"absolute top-3 left-3 flex h-5 w-5 items-center justify-center rounded-full bg-[#333c48]",children:jsx("span",{className:"text-xs font-bold text-white",children:o+1})}),jsx("button",{onClick:u=>{u.stopPropagation(),n();},className:"absolute top-3 right-3 flex cursor-pointer items-center justify-center rounded-md bg-[#3B75E0] p-1.5 text-white transition-colors hover:bg-[#2d5fc0]",title:"Duplicate Page",children:jsx(Copy,{size:18,weight:"bold"})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),i();},className:"absolute right-3 bottom-6 flex cursor-pointer items-center justify-center rounded-md bg-[#E53935] p-1.5 text-white transition-colors hover:bg-[#c62828]",title:"Delete Page",children:jsx(Trash,{size:18,weight:"bold"})}),jsxs("p",{className:"absolute bottom-2 left-3 text-sm text-black/40",children:["Page ",o+1]})]}),CS=()=>{let e=tt(),o=He(wa),t=He(ya),a=He(mr),[r,n]=useState(false),[i,u]=useState(false),[s,c]=useState(false),m=useRef(null),f=(He(w=>w.canvas.slides.find(I=>I.id===w.canvas.currentSlideId))?.videos||[]).some(w=>w.isRecorded&&w.isPlaying),h=()=>{a&&o.length<$o&&e(tr());},p=w=>{e(rr(w));},v=w=>{o.length<$o&&e(or(w));},y=w=>{o.length>1&&e(ar(w));},g=()=>{if(!m.current)return;let{scrollLeft:w,scrollWidth:I,clientWidth:k}=m.current,S=I>k+5;u(S&&w>5),c(S&&w<I-k-5);},x=w=>{if(!m.current)return;let I=177,k=w==="left"?m.current.scrollLeft-I:m.current.scrollLeft+I;m.current.scrollTo({left:k,behavior:"smooth"});};return useEffect(()=>{if(r){let w=setTimeout(()=>{requestAnimationFrame(()=>{g();});},350);return ()=>clearTimeout(w)}},[o,r]),useEffect(()=>{let w=m.current;if(!(!w||!r))return w.addEventListener("scroll",g),window.addEventListener("resize",g),()=>{w.removeEventListener("scroll",g),window.removeEventListener("resize",g);}},[r]),f?null:jsx("div",{className:"fixed bottom-0 left-1/2 z-50 flex w-full -translate-x-1/2 flex-col gap-4 md:hidden",children:jsxs(AnimatePresence,{mode:"wait",children:[r&&jsxs(motion.div,{initial:{y:230,opacity:0},animate:{y:0,opacity:1},exit:{y:230,opacity:0},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},onAnimationComplete:()=>g(),className:"border bg-white md:hidden",children:[jsxs("div",{className:"flex w-full items-center justify-between px-4 py-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Cards,{size:24,weight:"fill",className:"text-[#096b76]"}),jsx("span",{className:"text-base font-bold text-black/80",children:"Pages"}),jsxs("span",{className:"text-base font-bold text-black/80",children:["(",o.length,"/",$o,")"]})]}),jsx("button",{onClick:()=>n(false),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretDown,{size:16,weight:"bold",className:"text-black/60"})})]}),jsxs("div",{className:"relative",children:[i&&jsx("button",{onClick:()=>x("left"),className:"absolute top-1/2 left-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll left",children:jsx(CaretLeft,{size:20,weight:"bold",className:"text-black/80"})}),s&&jsx("button",{onClick:()=>x("right"),className:"absolute top-1/2 right-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll right",children:jsx(CaretRight,{size:20,weight:"bold",className:"text-black/80"})}),jsx("div",{ref:m,className:"scrollbar-hide flex gap-[11px] overflow-x-auto px-4 pb-4",children:o.map((w,I)=>jsx(IS,{slide:w,index:I,isSelected:w.id===t,isSingleSlide:o.length===1,onSelect:()=>p(w.id),onDuplicate:()=>v(w.id),onDelete:()=>y(w.id)},w.id))})]}),jsx("button",{onClick:h,disabled:!a||o.length>=$o,className:`px-4 pb-4 text-base font-bold ${a&&o.length<$o?"cursor-pointer text-[#096b76]":"cursor-not-allowed text-black/30"}`,children:"+ Add Page"})]},"open"),!r&&jsxs(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{type:"tween",duration:.2},className:"flex cursor-pointer items-center justify-between gap-2 border border-black/10 bg-white px-4 py-3 shadow-lg md:hidden",children:[jsxs("div",{className:"flex gap-2",children:[jsx(Cards,{size:20,weight:"fill",className:"text-[#096b76]"}),jsxs("span",{className:"text-sm font-bold text-black/80",children:["Pages (",o.length,"/",$o,")"]})]}),jsx("button",{onClick:()=>n(true),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretUp,{size:16,weight:"bold",className:"text-black/60"})})]},"close")]})})},kS=CS;var TS="SchooplaEditorDB",MS=1,qa="slides",Va="metadata",dd="schoopla_current_slide_id",Im="presentation_metadata",Zr=()=>new Promise((e,o)=>{let t=indexedDB.open(TS,MS);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(qa)||r.createObjectStore(qa,{keyPath:"id"}),r.objectStoreNames.contains(Va)||r.createObjectStore(Va,{keyPath:"id"});};}),ud=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Zr(),a=o.transaction([qa],"readwrite").objectStore(qa);await new Promise((r,n)=>{let i=a.clear();i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);});for(let r of e)await new Promise((n,i)=>{let u=a.add(r);u.onsuccess=()=>n(!0),u.onerror=()=>i(u.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},cd=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Zr(),t=e.transaction([qa],"readonly").objectStore(qa);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let i=n.result;console.log("\u2705 Loaded from IndexedDB:",i.length,"slides"),i.length>0&&i[0].images&&console.log("First slide images:",i[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(i.length>0?i:null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Ws=async()=>{try{let e=await Zr(),o=e.transaction([qa,Va],"readwrite"),t=o.objectStore(qa),a=o.objectStore(Va);await new Promise((r,n)=>{let i=t.clear();i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);}),await new Promise((r,n)=>{let i=a.clear();i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(dd),localStorage.removeItem("schoopla_presentation_metadata"),await qc(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},fd=e=>{try{localStorage.setItem(dd,e);}catch(o){console.error("Error saving current slide ID:",o);}},md=()=>{try{return localStorage.getItem(dd)}catch(e){return console.error("Error loading current slide ID:",e),null}},pd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},hd=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await Zr(),a=o.transaction([Va],"readwrite").objectStore(Va);await new Promise((r,n)=>{let i=a.put({id:Im,...e});i.onsuccess=()=>r(!0),i.onerror=()=>n(i.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);}}},gd=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await Zr(),t=e.transaction([Va],"readonly").objectStore(Va);return new Promise((a,r)=>{let n=t.get(Im);n.onsuccess=()=>{e.close();let i=n.result;if(i){let{id:u,...s}=i;console.log("\u2705 Loaded presentation metadata:",s),a(s);}else console.log("No presentation metadata found"),a(null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var AS=["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"],PS=["canvas/clearCanvas"],ES=["canvas/setPresentationTitle","canvas/setPresentationDescription"],DS=pd((e,o)=>{ud(e),fd(o);},500),RS=pd(e=>{hd(e);},500),FS=(e,o)=>{ud(e),fd(o);},xd=false,Cm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let n=t.payload;Dl(n).catch(i=>{console.error("Error deleting video blob:",i);});}if(t.type==="canvas/deleteSlide"&&t.payload){let n=t.payload,u=e.getState().canvas.slides.find(s=>s.id===n);u&&u.videos&&u.videos.length>0&&u.videos.forEach(s=>{Dl(s.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let n=t.payload,i=e.getState(),s=i.canvas.slides.find(c=>c.id===i.canvas.currentSlideId)?.videos.find(c=>c.id===n);s&&s.videoBlob&&setTimeout(()=>{let c=e.getState(),d=c.canvas.slides.find(l=>l.id===c.canvas.currentSlideId)?.videos.find(l=>l.id!==n&&l.x===s.x+20&&l.y===s.y+20);d&&s.videoBlob&&ro(d.id,s.videoBlob,d.thumbnailDataUrl).catch(l=>{console.error("Error saving duplicated video blob:",l);});},0);}let a=o(t),r=e.getState();if(r.canvas.viewerMode)return a;if(t.type&&PS.includes(t.type)){if(!xd){xd=true;try{let{slides:n,currentSlideId:i}=r.canvas;FS(n,i);}finally{setTimeout(()=>{xd=false;},0);}}}else if(t.type&&AS.includes(t.type)){let{slides:n,currentSlideId:i}=r.canvas;DS(n,i);}else if(t.type&&ES.includes(t.type)){let{presentationMetadata:n}=r.canvas;RS(n);}return a});new QueryClient;var OS=configureStore({reducer:{toolbar:Gl,canvas:Fi},middleware:e=>e({serializableCheck:false}).concat(Cm)}),NS=()=>configureStore({reducer:{toolbar:Gl,canvas:Fi},middleware:e=>e({serializableCheck:false})});var HS=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:n=`slide-${Date.now()}`}=o;try{let i=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:i,quality:a,pixelRatio:r}),s=document.createElement("a");s.download=`${n}.${t}`,s.href=u,document.body.appendChild(s),s.click(),document.body.removeChild(s);}catch(i){throw console.error("Error exporting slide:",i),new Error("Failed to export slide")}},qS=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((n,i)=>{try{let u=t==="png"?"image/png":"image/jpeg",s=e.toDataURL({mimeType:u,quality:a,pixelRatio:r});fetch(s).then(c=>c.blob()).then(c=>n(c)).catch(c=>i(c));}catch(u){i(u);}})},VS=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,n=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:n,quality:a,pixelRatio:r})};var US=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let n=a*a+r*r,i=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/n)),u=o.x+i*a,s=o.y+i*r;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-s,2))},bd=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],n=e[e.length-1];for(let i=1;i<e.length-1;i++){let u=US(e[i],r,n);u>t&&(t=u,a=i);}if(t>o){let i=bd(e.slice(0,a+1),o),u=bd(e.slice(a),o);return [...i.slice(0,-1),...u]}return [r,n]},zS=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},WS=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Tm=(e,o=1.5)=>{if(e.length<=4)return e;let t=zS(e),a=bd(t,o);return WS(a)},Mm=(e,o=1.5)=>({...e,points:Tm(e.points,o)}),KS=(e,o=1.5)=>e.map(t=>Mm(t,o)),GS=(e,o)=>{let t=e.length/2,a=o.length/2,r=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${r}%`}};var jS=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Am=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((n,i)=>{let u=new Image;u.onload=()=>{let{width:s,height:c}=u;if(s>t||c>a){let h=s/c;s>c?(s=Math.min(s,t),c=s/h):(c=Math.min(c,a),s=c*h);}let m=document.createElement("canvas");m.width=s,m.height=c;let d=m.getContext("2d");if(!d){i(new Error("Failed to get canvas context"));return}d.drawImage(u,0,0,s,c);let l=jS(e),f=m.toDataURL(l,r);n(f);},u.onerror=i,u.src=e;})};var co=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return a.buffer},Yo=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Zo=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",_S=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,i=[],u=0;for(let s of e){let c=[],m=[],d=[];for(let l of s.images){let f=l.src;if(t&&f.startsWith("data:"))try{f=await Am(f,{maxWidth:a,maxHeight:r,quality:n});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=co(f),p=Yo(f);u+=h.byteLength;let v={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:h,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let y=co(l.audioData),g=Yo(l.audioData);u+=y.byteLength,v.audioBuffer=y,v.audioMimeType=g;}c.push(v);}}for(let l of s.videos){let f,h;if(l.videoBlob)f=await l.videoBlob.arrayBuffer(),h=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))f=co(l.videoData),h=Yo(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}u+=f.byteLength;let p={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:f,mimeType:h};if(l.audioData&&l.audioData.startsWith("data:")){let v=co(l.audioData),y=Yo(l.audioData);u+=v.byteLength,p.audioBuffer=v,p.audioMimeType=y;}m.push(p);}for(let l of s.photoFrames){let f={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 h=co(l.capturedImageUrl),p=Yo(l.capturedImageUrl);u+=h.byteLength,f.buffer=h,f.mimeType=p;}if(l.audioData&&l.audioData.startsWith("data:")){let h=co(l.audioData),p=Yo(l.audioData);u+=h.byteLength,f.audioBuffer=h,f.audioMimeType=p;}d.push(f);}i.push({...s,images:c,videos:m,photoFrames:d});}return {slides:i,totalSize:u}},XS=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},$S=e=>{let o=new FormData,t=e.slides.map((a,r)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((n,i)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,mimeType:n.mimeType,fileKey:`slide_${r}_image_${i}`,audioFileKey:n.audioBuffer?`slide_${r}_image_${i}_audio`:void 0,audioMimeType:n.audioMimeType})),videos:a.videos.map((n,i)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,isPlaying:n.isPlaying,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isRecorded:n.isRecorded,mimeType:n.mimeType,fileKey:`slide_${r}_video_${i}`,thumbnailFileKey:`slide_${r}_video_${i}_thumbnail`,audioFileKey:n.audioBuffer?`slide_${r}_video_${i}_audio`:void 0,audioMimeType:n.audioMimeType})),photoFrames:a.photoFrames.map((n,i)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,draggable:n.draggable,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isCapturing:n.isCapturing,mimeType:n.mimeType,fileKey:n.buffer?`slide_${r}_photoframe_${i}`:void 0,audioFileKey:n.audioBuffer?`slide_${r}_photoframe_${i}_audio`:void 0,audioMimeType:n.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((n,i)=>{let u=new Blob([n.buffer],{type:n.mimeType}),s=`${n.id}.${Zo(n.mimeType)}`;if(o.append(`slide_${r}_image_${i}`,u,s),n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),m=`${n.id}_audio.${Zo(n.audioMimeType)}`;o.append(`slide_${r}_image_${i}_audio`,c,m);}}),a.videos.forEach((n,i)=>{let u=new Blob([n.buffer],{type:n.mimeType}),s=`${n.id}.${Zo(n.mimeType)}`;if(o.append(`slide_${r}_video_${i}`,u,s),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let c=co(n.thumbnailDataUrl),m=new Blob([c],{type:"image/jpeg"}),d=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${i}_thumbnail`,m,d);}if(n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),m=`${n.id}_audio.${Zo(n.audioMimeType)}`;o.append(`slide_${r}_video_${i}_audio`,c,m);}}),a.photoFrames.forEach((n,i)=>{if(n.buffer&&n.mimeType){let u=new Blob([n.buffer],{type:n.mimeType}),s=`${n.id}.${Zo(n.mimeType)}`;o.append(`slide_${r}_photoframe_${i}`,u,s);}if(n.audioBuffer&&n.audioMimeType){let u=new Blob([n.audioBuffer],{type:n.audioMimeType}),s=`${n.id}_audio.${Zo(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${i}_audio`,u,s);}});}),o};var JS=()=>{let e=tt(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let r=await cd(),n=md(),i=await gd();if(r&&r.length>0){let u=await Hc(),s=r.map(m=>{if(m.videos&&m.videos.length>0){let d=m.videos.map(l=>{let f=u.get(l.id);if(f){let h=Vc(f.blob);return {...l,objectUrl:h,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return l});return {...m,videos:d}}return m}),c=n&&s.find(m=>m.id===n)?n:s[0].id;e(go({slides:s,currentSlideId:c}));}e(i?Ei({title:i.title,description:i.description}):jn(!0));}catch(r){console.error("Error loading persisted slides:",r),e(jn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var Em=e=>e.map(o=>({...o,lines:o.lines||[],shapes:o.shapes||[],images:o.images||[],videos:o.videos||[],flashcards:o.flashcards||[],photoFrames:o.photoFrames||[],texts:o.texts||[],multipleChoices:o.multipleChoices||[],trueFalses:o.trueFalses||[],shortAnswers:o.shortAnswers||[],LongAnswer:o.LongAnswer||[],fillInTheBlanks:o.fillInTheBlanks||[],createdAt:o.createdAt||Date.now(),updatedAt:o.updatedAt||Date.now(),showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,activityType:o.activityType||""})),Dm=new WeakSet,Rm=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 ro(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},QS=()=>{let e=tt(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Dm.has(a))return;Dm.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:i=true}=a;if(i)try{await Ws(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(c){console.error("Error clearing local data:",c);}let u=n&&r.find(c=>c.id===n)?n:r[0].id,s=Em(r);e(go({slides:s,currentSlideId:u})),await Rm(s);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:i=true}=a;if(i)try{await Ws(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=n&&r.find(c=>c.id===n)?n:r[0].id,s=Em(r);e(go({slides:s,currentSlideId:u})),await Rm(s);},[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:l?"none":"auto"}})}),jsx(Group,{y:S.questionHeight+S.feedbackHeight+S.placeholderHeight+S.textareaHeight+S.textareaMargin+S.buttonTopMargin,children:l&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),g();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:S.padding,width:S.contentWidth,height:S.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:C=>C.cancelBubble=true,onTap:C=>C.cancelBubble=true}),jsx(Text,{x:S.padding,width:S.contentWidth,height:S.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Fl.displayName="LongAnswer";var Oc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:i})=>{let{createHandlers:u}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>jsx(Fl,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,s.id),touchHandlers:u(s.id,"longAnswer")},s.id))})};var no=1600,so=900,Vc=3200,Uc=1800,lv=e=>{let o=0,t=0,a=no,n=so;if(!e)return {minX:o,minY:t,maxX:a,maxY:n,width:no,height:so};let r=(s,c,m,d)=>{o=Math.min(o,s),t=Math.min(t,c),a=Math.max(a,s+m),n=Math.max(n,c+d);};e.lines?.forEach(s=>{if(s.points&&s.points.length>=2){let c=s.x||0,m=s.y||0,d=s.scaleX||1,l=s.scaleY||1;for(let f=0;f<s.points.length;f+=2){let h=c+s.points[f]*d,p=m+s.points[f+1]*l;o=Math.min(o,h),t=Math.min(t,p),a=Math.max(a,h),n=Math.max(n,p);}}}),e.images?.forEach(s=>r(s.x,s.y,s.width,s.height)),e.videos?.forEach(s=>r(s.x,s.y,s.width,s.height)),e.shapes?.forEach(s=>r(s.x,s.y,s.width,s.height)),e.texts?.forEach(s=>r(s.x,s.y,s.width||200,s.height||s.fontSize||24)),e.flashcards?.forEach(s=>r(s.x,s.y,s.width,s.height)),e.photoFrames?.forEach(s=>r(s.x,s.y,s.width,s.height)),e.multipleChoices?.forEach(s=>r(s.x,s.y,s.width,s.height)),e.trueFalses?.forEach(s=>r(s.x,s.y,s.width,s.height)),e.shortAnswers?.forEach(s=>r(s.x,s.y,s.width,s.height)),e.LongAnswer?.forEach(s=>r(s.x,s.y,s.width,s.height)),e.fillInTheBlanks?.forEach(s=>r(s.x,s.y,s.width,s.height));let i=Math.min(a-o,Vc),u=Math.min(n-t,Uc);return o=Math.max(o,a-Vc),t=Math.max(t,n-Uc),{minX:o,minY:t,maxX:a,maxY:n,width:i,height:u}},dv=(e,o,t={minX:0,minY:0,maxX:no,maxY:so,width:no,height:so})=>{let a=Math.max(t.width,no),n=Math.max(t.height,so),r=e/o,i=a/n,u,s,c,d=0;if(r>i){s=n,u=Math.round(s*r),c=o/s;}else {u=a,s=Math.round(u/r),c=e/u;let l=n*c;d=(o-l)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:d,baseWidth:u,baseHeight:s,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}},uv=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:n={enabled:true}}={})=>{let r=_e(),i=Ve(),u=ee(I=>I.toolbar.selectedTool),s=ee(ge),c=ee(va),m=ee(Yn),l=(s?.videos||[]).find(I=>I.isRecorded&&I.isPlaying),f=!!l,h=useCallback(()=>{l&&r(Ga(l.id));},[r,l]),p=s?.editingActivity,y=s?.showMcqForm,v=s?.lines||[],g=useRef(null),x=useRef(null),[L,S]=useState(null),[C,w]=useState(""),b=useRef(null),[k,M]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:no,stageHeight:so,offsetX:0,offsetY:0,baseWidth:no,baseHeight:so,contentOffsetX:0,contentOffsetY:0}),P=useMemo(()=>lv(s||null),[c]),[D,W]=useState(null),[B,U]=useState(null),[N,q]=useState(null),[F,z]=useState(null),[_,oe]=useState(null),[V,j]=useState(null),[Z,Y]=useState(null),[ne,J]=useState(false),[ce,we]=useState(null),[Pe,Ee]=useState(false),Fe=useRef(null),nt=useRef(null),At=useRef(null),{debouncedGenerateThumbnail:po}=pu(c,g);useEffect(()=>{let I=()=>{if(x.current){let E=x.current.getBoundingClientRect(),O=dv(E.width,E.height,P);M(O);}};I();let T=new ResizeObserver(I);return x.current&&T.observe(x.current),window.addEventListener("resize",I),()=>{T.disconnect(),window.removeEventListener("resize",I);}},[P]),useEffect(()=>{if(g.current){let I=g.current.container();I&&(I.style.cursor="");}},[u]);let se=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(T=>T.batchDraw()),!m)try{let E=g.current.toDataURL({pixelRatio:.16666666666666666});w(E),po();}catch(T){console.warn("Preview generation failed (CORS):",T);}});},[po,m]),ho=useRef(c);useEffect(()=>{ho.current!==c&&(ho.current=c,se());},[c,se]);let nn=useRef(null),sn=useRef(true);useEffect(()=>{if(!s)return;let I=(s.lines?.length||0)+(s.images?.length||0)+(s.videos?.length||0)+(s.shapes?.length||0)+(s.texts?.length||0)+(s.flashcards?.length||0)+(s.photoFrames?.length||0)+(s.multipleChoices?.length||0)+(s.trueFalses?.length||0)+(s.shortAnswers?.length||0)+(s.LongAnswer?.length||0)+(s.fillInTheBlanks?.length||0),T=nn.current?.count!==I;!sn.current&&T&&setTimeout(()=>{se();},100),nn.current={slideId:c,count:I},sn.current=false;},[s,c,se]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{At.current&&a&&a(At);},[a]);let{startDrawing:ln,draw:dn,stopDrawing:un,setCanvasRef:Xs,tool:Va,color:$s,strokeWidth:Ys,isSketchMode:Zs}=Ud(se),Ua=useRef(new Map),{images:cn,getLoadedImage:fn,imageRefs:go,handleDragEnd:mn,handleImageTransformEnd:Js}=Xd(se),{videos:nr,videoRefs:xo,handleVideoClick:pn,handleVideoDragEnd:Qs,handleVideoTransformEnd:A}=Zd(se),{multipleChoice:ae,handleMcqTransform:Se,mcqRefs:xe,handleDragEnd:le}=$d(se),{trueFalse:fe,handleTrueFalseTransform:He,trueFalseRefs:Ye,handleTrueFalseDragEnd:ta}=Yd(se),{shortAnswers:Pt,saRefs:Ce,handleShortAnswerDragEnd:st}=ou(se),{longAnswers:aa,handleLongAnswerDragEnd:pa}=ru(se),{fillInTheBlanks:ei,handleFillInTheBlanksDragEnd:ti,fibRefs:Wa}=Pc(se),{transformerRef:re,boundBoxFunc:Ue}=uu(),{shapes:za,shapeRefs:hn,isDragging:Id,handleShapeDragEnd:Vm,handleShapeResizeEnd:Um}=eu(se),{texts:sr,textRefs:ha,handleDragEnd:Wm,handleTransformEnd:zm,handleDoubleClick:Km,startEditing:gn,editingTextId:he,editingValue:Cd,handleEditingChange:kd,finishEditing:ai}=au(se,Fe);useEffect(()=>{t&&t(gn);},[t,gn]);let xn=ee(I=>I.canvas.editingTextId);useEffect(()=>{xn&&xn!==he&&gn(xn);},[xn,he,gn]);let{flashcards:Gm,flashcardRefs:bn,handleDragEnd:jm,handleFlashcardTransformEnd:_m,handleNext:Xm,handlePrevious:$m}=su(se),{photoFrames:Td,photoFrameRefs:vn,handleDragEnd:Ym,handlePhotoFrameTransformEnd:Zm,startCamera:Jm,capturePhoto:Qm,cameraStreams:ep}=du(se);useEffect(()=>{if(re.current){if(he){re.current.nodes([]),re.current.getLayer()?.batchDraw();return}if(L&&!nr.find(E=>E.id===L)?.isPlaying){let E=Ua.current.get(L)||go.current.get(L)||xo.current.get(L)||hn.current.get(L)||ha.current.get(L)||xe.current.get(L)||bn.current.get(L)||vn.current.get(L)||Ce.current.get(L)||Ye.current.get(L)||Wa.current.get(L);if(E){let O=E.attrs?.locked;if(E.visible()&&O!==true){re.current.nodes([E]),re.current.getLayer()?.batchDraw();return}}}re.current.nodes([]),re.current.getLayer()?.batchDraw();}},[L,he,nr,Ua,go,xo,hn,ha,bn,vn,Td,xe,Ye,Wa,re]);let We=useCallback(I=>{S(I),o?.(I);},[o]),bo=useCallback(()=>{S(null),o?.(null),re.current&&(re.current.nodes([]),re.current.getLayer()?.batchDraw());},[re,o]),Md=useCallback(I=>s?s.lines?.some(T=>T.id===I)?"line":s.images?.some(T=>T.id===I)?"image":s.videos?.some(T=>T.id===I)?"video":s.shapes?.some(T=>T.id===I)?"shape":s.texts?.some(T=>T.id===I)?"text":s.flashcards?.some(T=>T.id===I)?"flashcard":s.photoFrames?.some(T=>T.id===I)?"photoFrame":s.multipleChoices?.some(T=>T.id===I)?"mcq":s.trueFalses?.some(T=>T.id===I)?"trueFalse":s.shortAnswers?.some(T=>T.id===I)?"shortAnswer":s.LongAnswer?.some(T=>T.id===I)?"longAnswer":s.fillInTheBlanks?.some(T=>T.id===I)?"fillInTheBlanks":null:null,[s]),Ad=useCallback((I,T)=>{switch(r(de()),T){case "line":r(Xn(I));break;case "image":r(wn(I));break;case "video":r(In(I));break;case "shape":r(Tn(I));break;case "text":r(Mn(I));break;case "flashcard":r(Pn(I));break;case "photoFrame":r(Rn(I));break;case "mcq":r(Fn(I));break;case "trueFalse":r(On(I));break;case "shortAnswer":r(Hn(I));break;case "longAnswer":r(Vn(I));break;case "fillInTheBlanks":r(Wn(I));break}bo(),se();},[r,bo,se]);useEffect(()=>{let I=T=>{if(T.key!=="Delete"||!L||he)return;let E=document.activeElement;if(E instanceof HTMLInputElement||E instanceof HTMLTextAreaElement||E?.getAttribute("contenteditable")==="true")return;T.preventDefault();let ye=Md(L);ye&&Ad(L,ye);};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[L,he,Md,Ad]),useEffect(()=>{let I=re.current;return ()=>{I&&I.nodes([]);}},[c]),useEffect(()=>{let I=T=>{he&&T.target.tagName!=="TEXTAREA"&&ai();};return document.addEventListener("mousedown",I),()=>{document.removeEventListener("mousedown",I);}},[he,ai]),useEffect(()=>{let I=he||L;if(!I||L&&he){U(null);return}let T=ha.current.get(I),E=g.current;if(!T||!E){U(null);return}let O=E.container().getBoundingClientRect(),ye=T.absolutePosition(),pe=E.scaleX();U({x:O.left+(ye.x+T.width()*pe/2)*pe+k.offsetX,y:O.top+ye.y*pe+k.offsetY-70});},[L,he,sr,ha,k.offsetX,k.offsetY]),useEffect(()=>{if(!he){q(null);return}let I=ha.current.get(he),T=g.current;if(!I||!T){q(null);return}let E=I.getClientRect({relativeTo:T}),O=T.container().getBoundingClientRect(),ye=T.scaleX(),pe=T.position(),te={top:O.top+pe.y+E.y*ye,left:O.left+pe.x+E.x*ye,scale:ye};q(te),r(Hd(te));},[he,sr,ha,k.offsetY,k.offsetX]);let Pd=useCallback(I=>{let T=I.target.getClassName(),E=I.target===I.target.getStage(),O=T==="Transformer"||I.target.getParent()?.getClassName()==="Transformer",ye=T==="Image",pe=T==="Text",te=T==="Group"||I.target.getParent()?.getClassName()==="Group",ct=T==="Circle"||T==="Star"||T==="RegularPolygon"||T==="Ellipse"||T==="Ring"||T==="Wedge"||T==="Arrow"||T==="Line"||T==="Arc"||T==="Rect"&&I.target.attrs.id,ft=T==="Group";if(E&&!O&&!ye&&!pe&&!te&&!ct&&!ft&&bo(),!(u==="pen"||u==="eraser")&&(ye||pe||O||te||ct||ft))return;let ze=I.target.getStage()?.getPointerPosition();if(!ze)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let H=Wc(ze,k);ln(H);}},[u,ln,bo,k]),Ed=useCallback(I=>{if(Id)return;let T=I.target.getStage()?.getPointerPosition();if(!T)return;let E=Wc(T,k);dn(E);},[dn,Id,k]),Rd=useCallback(()=>{un();},[un]),tp=useCallback(I=>{mn(I,se);},[mn,se]),ap=useCallback(I=>{pn(I),We(I);},[pn,We]),Et=useCallback((I,T,E)=>{if(I.preventDefault(),!n.enabled)return;let O=I.clientX,ye=I.clientY,pe=b.current?.offsetHeight||450,te=b.current?.offsetWidth||450,ct=window.innerHeight,ft=window.innerWidth,et=O,ze=ye;ye+pe>ct&&(ze=ye-pe),O+te>ft&&(et=O-te),We(T),W({x:et,y:ze,elementId:T,elementType:E});},[We,n.enabled]),Ka=useRef(null),ir=useRef(null),vt=useCallback((I,T)=>E=>{if(!n.enabled)return;E.preventDefault();let O=E.changedTouches[0];if(!O)return;let ye=O.clientX,pe=O.clientY,te=b.current?.offsetHeight||200,ct=b.current?.offsetWidth||200,ft=window.innerHeight,et=window.innerWidth,ze=ye,tt=pe;pe+te>ft&&(tt=pe-te),ye+ct>et&&(ze=ye-ct),We(I),W({x:ze,y:tt,elementId:I,elementType:T});},[We,n.enabled]),op=useCallback((I,T)=>({onTouchStart:E=>{let O=E.evt.touches[0];ir.current={x:O.clientX,y:O.clientY},Ka.current=setTimeout(()=>{vt(I,T)(E.evt);},500);},onTouchMove:E=>{if(!ir.current)return;let O=E.evt.touches[0],ye=Math.abs(O.clientX-ir.current.x),pe=Math.abs(O.clientY-ir.current.y);(ye>10||pe>10)&&Ka.current&&(clearTimeout(Ka.current),Ka.current=null);},onTouchEnd:()=>{Ka.current&&(clearTimeout(Ka.current),Ka.current=null),ir.current=null;}}),[vt]),Dd=useCallback(I=>{r(xr(I)),r(ba(true));},[r]),rp=useCallback(I=>{r(mr(I)),r(_a(true));},[r]),np=useCallback((I,T)=>{if(!D)return;let{elementId:E,elementType:O}=D;switch(I){case "order":if(T){let R=T.target.getBoundingClientRect();z({x:R.right+5,y:R.top,type:"order"});}break;case "lock":if(T){let R=T.target.getBoundingClientRect();z({x:R.right+5,y:R.top,type:"lock"});}break;case "link":if(W(null),O==="line")break;let ye=s?O==="image"?s.images.find(R=>R.id===E):s.videos.find(R=>R.id===E):null;oe({type:"link",defaultValue:ye?.link||""});break;case "voice":if(W(null),O==="line")break;let pe=s?O==="image"?s.images.find(R=>R.id===E):O==="video"?s.videos.find(R=>R.id===E):O==="text"?s.texts.find(R=>R.id===E):O==="flashcard"?s.flashcards.find(R=>R.id===E):O==="photoFrame"?s.photoFrames.find(R=>R.id===E):O==="mcq"?s.multipleChoices.find(R=>R.id===E):O==="fillInTheBlanks"?s.fillInTheBlanks.find(R=>R.id===E):O==="longAnswer"?s.LongAnswer.find(R=>R.id===E):O==="shortAnswer"?s.shortAnswers.find(R=>R.id===E):O==="trueFalse"?s.trueFalses.find(R=>R.id===E):O==="shape"?s.shapes.find(R=>R.id===E):null:null;we({elementId:E,elementType:O,existingAudio:pe?.audioData});break;case "edit":W(null);let te=null;O==="mcq"?te=s?.multipleChoices.find(R=>R.id===E):O==="trueFalse"?te=s?.trueFalses.find(R=>R.id===E):O==="shortAnswer"?te=s?.shortAnswers.find(R=>R.id===E):O==="longAnswer"?te=s?.LongAnswer.find(R=>R.id===E):O==="fillInTheBlanks"&&(te=s?.fillInTheBlanks.find(R=>R.id===E)),te&&Dd(te);break;case "editFlashcard":W(null);let ct=s?.flashcards.find(R=>R.id===E);ct&&rp(ct);break;case "color":W(null);let ft=s?.shapes.find(R=>R.id===E);j({elementId:E,elementType:"shape",defaultColor:ft?.color||"#096B76"});break;case "crop":if(W(null),O==="image"){let R=s?.images.find(fp=>fp.id===E);R&&Y({elementId:E,imageSrc:R.src});}break;case "draw":W(null),O==="image"?r(xi(E)):O==="photoFrame"&&r(vi(E));break;case "duplicate":r(de()),O==="line"?r(Ei(E)):O==="image"?r(Sn(E)):O==="video"?r(Cn(E)):O==="shape"?r(kn(E)):O==="text"?r(An(E)):O==="flashcard"?r(En(E)):O==="photoFrame"?r(Dn(E)):O==="mcq"?r(Bn(E)):O==="trueFalse"?r(Nn(E)):O==="shortAnswer"?r(qn(E)):O==="fillInTheBlanks"?r(zn(E)):O==="longAnswer"&&r(Un(E)),se();break;case "infinite-clone":r(de());let et=5;for(let R=0;R<et;R++)O==="image"?r(Sn(E)):O==="video"?r(Cn(E)):O==="shape"?r(kn(E)):O==="text"?r(An(E)):O==="flashcard"?r(En(E)):O==="photoFrame"?r(Dn(E)):O==="mcq"?r(Bn(E)):O==="trueFalse"?r(Nn(E)):O==="shortAnswer"?r(qn(E)):O==="fillInTheBlanks"?r(zn(E)):O==="longAnswer"&&r(Un(E));se();break;case "make-response":if(W(null),O==="line")break;let ze=`#response-${E}`;r(de()),r(Kn({id:E,type:O,link:ze})),(s?O==="image"?s.images.find(R=>R.id===E):O==="video"?s.videos.find(R=>R.id===E):O==="shape"?s.shapes.find(R=>R.id===E):O==="flashcard"?s.flashcards.find(R=>R.id===E):O==="photoFrame"?s.photoFrames.find(R=>R.id===E):s.multipleChoices.find(R=>R.id===E):null)?.altText||r(Gn({id:E,type:O,altText:"Interactive response area"})),se(),console.log(`Element ${E} marked as interactive response area`);break;case "accessibility":if(W(null),O==="line")break;let H=s?O==="image"?s.images.find(R=>R.id===E):O==="video"?s.videos.find(R=>R.id===E):O==="shape"?s.shapes.find(R=>R.id===E):null:null;oe({type:"altText",defaultValue:H?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),W(null),Ee(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(de()),O==="line"?r(Xn(E)):O==="image"?r(wn(E)):O==="video"?r(In(E)):O==="shape"?r(Tn(E)):O==="text"?r(Mn(E)):O==="flashcard"?r(Pn(E)):O==="photoFrame"?r(Rn(E)):O==="mcq"?r(Fn(E)):O==="trueFalse"?r(On(E)):O==="shortAnswer"?r(Hn(E)):O==="longAnswer"?r(Vn(E)):O==="fillInTheBlanks"&&r(Wn(E)),bo(),se();break}},[D,r,se,bo,s,Dd]),sp=useCallback(()=>{W(null),z(null);},[]),oi=useCallback(I=>{if(!D)return;let{elementId:T,elementType:E}=D;switch(r(de()),I){case "bring-to-front":E!=="line"&&r(Ti({id:T,type:E}));break;case "send-to-back":E!=="line"&&r(Mi({id:T,type:E}));break;case "lock":case "unlock":E!=="line"&&r(Ai({id:T,type:E}));break}se(),W(null),z(null);},[D,r,se]),ip=useCallback(I=>{if(!D||!_)return;let{elementId:T,elementType:E}=D;r(de()),_.type==="link"&&E!=="line"?r(Kn({id:T,type:E,link:I})):_.type==="altText"&&E!=="line"&&r(Gn({id:T,type:E,altText:I})),se(),oe(null);},[D,_,r,se]),lp=useCallback(I=>{if(!ce)return;let{elementId:T,elementType:E}=ce;r(de()),r(jn({id:T,type:E,audioData:I})),se(),we(null);},[ce,r,se]),dp=useCallback(()=>{if(!ce)return;let{elementId:I,elementType:T}=ce;r(de()),r(jn({id:I,type:T,audioData:""})),se();},[ce,r,se]),up=useCallback(I=>{if(!V)return;let{elementId:T}=V;r(de()),r(So({id:T,color:I})),se(),j(null);},[V,r,se]),cp=useCallback(I=>{if(!Z)return;let{elementId:T}=Z;r(de()),r(yo({id:T,src:I})),se(),Y(null);},[Z,r,se]);return jsxs("div",{ref:x,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(jd,{ref:I=>{if(nt.current=I,Xs(I),I){let T=I.getCanvasElement();T&&(At.current=T,a&&a(At));}},width:k.baseWidth,height:k.baseHeight,tool:Va,color:$s,strokeWidth:Ys/k.scale,isSketchMode:Zs,xOffset:k.contentOffsetX,yOffset:k.contentOffsetY-k.offsetY/k.scale,style:{width:k.stageWidth,height:k.stageHeight}}),jsxs(Stage,{ref:g,width:k.stageWidth,height:k.stageHeight,scaleX:k.scaleX,scaleY:k.scaleY,x:k.offsetX,y:0,onMouseDown:Pd,onMouseMove:Ed,onMouseUp:Rd,onTouchStart:Pd,onTouchMove:Ed,onTouchEnd:Rd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:k.baseWidth,height:k.stageHeight/k.scale,fill:s?.backgroundColor||"white"})}),jsx(Layer,{x:-k.contentOffsetX,y:k.offsetY/k.scale-k.contentOffsetY,children:(()=>{let I=[];return v.forEach((T,E)=>{I.push({type:"line",timestamp:T.timestamp||E,element:{...T,id:T.id??`line-${E}`},index:E});}),za.forEach(T=>{I.push({type:"shape",timestamp:T.timestamp||0,element:T});}),cn.forEach(T=>{I.push({type:"image",timestamp:T.timestamp||0,element:T});}),nr.forEach(T=>{I.push({type:"video",timestamp:T.timestamp||0,element:T});}),sr.forEach(T=>{I.push({type:"text",timestamp:T.timestamp||0,element:T});}),Gm.forEach(T=>{I.push({type:"flashcard",timestamp:T.timestamp||0,element:T});}),Td.forEach(T=>{I.push({type:"photoFrame",timestamp:T.timestamp||0,element:T});}),ae.forEach(T=>{I.push({type:"mcq",timestamp:T.timestamp||0,element:T});}),fe.forEach(T=>{I.push({type:"trueFalse",timestamp:T.timestamp||0,element:T});}),Pt.forEach(T=>{I.push({type:"shortAnswer",timestamp:T.timestamp||0,element:T});}),aa.forEach(T=>{I.push({type:"longAnswer",timestamp:T.timestamp||0,element:T});}),ei.forEach(T=>{I.push({type:"fillInTheBlanks",timestamp:T.timestamp||0,element:T});}),I.sort((T,E)=>T.timestamp-E.timestamp),I.map((T,E)=>{let O=`${T.type}-${"id"in T.element&&T.element.id||T.index||E}`,ye="id"in T.element?T.element.id:void 0,pe=ye&&L===ye;switch(T.type){case "line":let te=T.element,ct=T.index||0,ft=te.tool==="eraser",et=te.isSketch&&te.tool==="pen",ze=te.isSketch&&ft,tt=te.id||`line-${ct}`;return te.x===void 0&&(te.x=0),te.y===void 0&&(te.y=0),te.scaleX===void 0&&(te.scaleX=1),te.scaleY===void 0&&(te.scaleY=1),te.rotation===void 0&&(te.rotation=0),u==="eraser"?jsx(Group,{x:te.x||0,y:te.y||0,scaleX:te.scaleX||1,scaleY:te.scaleY||1,rotation:te.rotation||0,children:jsx(Line,{points:te.points||[],stroke:et||ze?void 0:te.color,strokeWidth:et||ze?0:te.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:et||ze?ft?"black":te.color:void 0,closed:et||ze,tension:0,globalCompositeOperation:ft?"destination-out":"source-over",listening:true,onClick:()=>{r(de()),r(yn(ct));},onTap:()=>{r(de()),r(yn(ct));},hitStrokeWidth:Math.max(20,(te.strokeWidth??0)*2),onMouseEnter:H=>{let R=H.target.getStage();R&&(R.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:H=>{let R=H.target.getStage();R&&(R.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(ve__default.Fragment,{children:[jsx(Group,{id:tt,ref:H=>{H?Ua.current.set(tt,H):Ua.current.delete(tt);},x:te.x||0,y:te.y||0,scaleX:te.scaleX||1,scaleY:te.scaleY||1,rotation:te.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",tt),We(tt));},onTap:()=>{u==="select"&&(console.log("Line tapped:",tt),We(tt));},onDragEnd:H=>{r(de()),r(_n({id:tt,x:H.target.x(),y:H.target.y(),scaleX:H.target.scaleX(),scaleY:H.target.scaleY(),rotation:H.target.rotation()})),se();},onTransformEnd:H=>{r(de()),r(_n({id:tt,x:H.target.x(),y:H.target.y(),scaleX:H.target.scaleX(),scaleY:H.target.scaleY(),rotation:H.target.rotation()})),se();},onMouseEnter:H=>{if(u==="select"){let R=H.target.getStage();R&&(R.container().style.cursor="move");}},onMouseLeave:H=>{if(u==="select"){let R=H.target.getStage();R&&(R.container().style.cursor="default");}},onContextMenu:H=>{let R=H.evt;R.preventDefault(),Et(R,tt,"line");},...op(tt,"line"),children:jsx(Line,{points:te.points||[],stroke:et||ze?void 0:te.color,strokeWidth:et||ze?0:te.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:et||ze?ft?"black":te.color:void 0,closed:et||ze,tension:0,globalCompositeOperation:ft?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=Ua.current.get(L);console.log("Line Transformer - selectedId:",L,"node found:",!!R),R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(Xi,{onSelect:We,shapes:[T.element],shapeRefs:hn,handleShapeDragEnd:Vm,handleShapeResizeEnd:Um,onContextMenu:Et,onLongPress:vt}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=hn.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(Ki,{images:[T.element],getLoadedImage:fn,imageRefs:go,onDragEnd:tp,onTransform:Js,onSelect:We,onContextMenu:Et,onLongPress:vt}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=go.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(_i,{videos:[T.element],selectedId:L,videoRefs:xo,onVideoClick:ap,onDragEnd:Qs,onTransformEnd:A,onContextMenu:Et,onLongPress:vt}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=xo.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(ku,{texts:[T.element],textRefs:ha,onDragEnd:Wm,onTransformEnd:zm,onSelect:We,onContextMenu:Et,onLongPress:vt,onDoubleClick:Km,editingTextId:he,editingValue:Cd,onEditingChange:kd}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=ha.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(Zi,{flashcards:[T.element],flashcardRefs:bn,selectedId:L,onDragEnd:jm,onTransform:_m,onSelect:We,onNext:Xm,onPrevious:$m,onContextMenu:Et,onLongPress:vt}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=bn.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(ol,{photoFrames:[T.element],photoFrameRefs:vn,selectedId:L,onDragEnd:Ym,onTransform:Zm,onSelect:We,onStartCamera:Jm,onCapture:Qm,cameraStreams:ep,onContextMenu:Et,onLongPress:vt}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=vn.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(oc,{handleMcqTransform:Se,multipleChoice:[T.element],handleSelect:We,mcqRefs:xe,handleDragEnd:le,onContextMenu:Et,onLongPress:vt}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=xe.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(ic,{trueFalses:[T.element],handleTrueFalseTransform:He,handleSelect:We,trueFalseRefs:Ye,onContextMenu:Et,onLongPress:vt,handleDragEnd:ta}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=Ye.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(Ac,{shortAnswers:[T.element],handleSelect:We,handleTransform:Se,saRefs:Ce,onContextMenu:Et,onLongPress:vt,handleDragEnd:st}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=Ce.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(Oc,{longAnswer:[T.element],handleSelect:We,handleTransform:Se,saRefs:Ce,onContextMenu:Et,onLongPress:vt,handleDragEnd:pa}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=Ce.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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(ve__default.Fragment,{children:[jsx(Fc,{fillInTheBlanks:[T.element],handleSelect:We,handleTransform:Se,onContextMenu:Et,onLongPress:vt,handleDragEnd:ti,fibRefs:Wa}),pe&&!he&&L&&jsx(Transformer,{ref:H=>{if(H&&re.current!==H){re.current=H;let R=Wa.current.get(L);R&&R.visible()&&(H.nodes([R]),H.getLayer()?.batchDraw());}},boundBoxFunc:Ue,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}})})()})]}),D&&jsx(qu,{menuRef:b,x:D.x,y:D.y,type:D.elementType,onAction:np,onClose:sp,isDrawingMode:D.elementType==="image"?s?.images.find(I=>I.id===D.elementId)?.isDrawingMode:D.elementType==="photoFrame"?s?.photoFrames.find(I=>I.id===D.elementId)?.isDrawingMode:false}),F&&D&&jsx(Vu,{x:F.x,y:F.y,items:F.type==="order"?[{label:"Bring to Front",onClick:()=>oi("bring-to-front")},{label:"Send to Back",onClick:()=>oi("send-to-back")}]:[{label:s&&(D.elementType==="image"?s.images.find(I=>I.id===D.elementId)?.locked:s.videos.find(I=>I.id===D.elementId)?.locked)?"Unlock":"Lock",onClick:()=>oi(s&&(D.elementType==="image"?s.images.find(I=>I.id===D.elementId)?.locked:s.videos.find(I=>I.id===D.elementId)?.locked)?"unlock":"lock")}],onClose:()=>z(null)}),_&&jsx(zu,{title:_.type==="link"?"Add Link":"Add Alt Text",label:_.type==="link"?"URL":"Alternative Text",placeholder:_.type==="link"?"https://example.com":"Describe this image/video",defaultValue:_.defaultValue,onSave:ip,onClose:()=>oe(null)}),V&&jsx(rs,{defaultColor:V.defaultColor,onConfirm:up,onCancel:()=>j(null)}),Z&&jsx(_u,{imageSrc:Z.imageSrc,onConfirm:cp,onCancel:()=>Y(null)}),ne&&jsx(Xa,{onClose:()=>J(false),stageRef:g}),ce&&jsx(Zu,{elementId:ce.elementId,elementType:ce.elementType,existingAudio:ce.existingAudio,onSave:lp,onDelete:dp,onClose:()=>we(null)}),Pe&&jsx(ec,{selectedElementId:L||void 0,onClose:()=>Ee(false),onSelectElement:I=>{We(I),Ee(false);}}),s?.images.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.videos.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.shapes?.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.texts?.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.flashcards?.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.photoFrames?.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.multipleChoices?.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.trueFalses?.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.shortAnswers?.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.LongAnswer?.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),s?.fillInTheBlanks?.filter(I=>I.audioData).map(I=>jsx(Ft,{audioData:I.audioData,x:I.x,y:I.y,width:I.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${I.id}`)),y&&jsx(bc,{editElement:p}),B&&(()=>{let I=he||L;if(!I)return null;let T=sr.find(E=>E.id===I);return T?jsx(Sc,{text:T,position:B}):null})(),N&&he&&(()=>{let I=sr.find(T=>T.id===he);return I?jsx(Ic,{text:I,editingValue:Cd,onEditingChange:kd,onFinish:ai,position:{top:N.top,left:N.left},scale:N.scale,textareaRef:Fe},he):null})(),f&&i&&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:h})}),jsx("button",{onClick:h,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"})})]}),i)]})},cv=uv;var mv="SchooplaVideoStorage";var Jt="videos",As=()=>new Promise((e,o)=>{let t=indexedDB.open(mv,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(Jt)||n.createObjectStore(Jt,{keyPath:"id"});};}),ra=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await As(),r=a.transaction([Jt],"readwrite").objectStore(Jt),i={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,s)=>{let c=r.put(i);c.onsuccess=()=>u(!0),c.onerror=()=>s(c.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 zc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await As(),t=e.transaction([Jt],"readonly").objectStore(Jt);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let i=r.result,u=new Map;i.forEach(s=>{u.set(s.id,{blob:s.blob,thumbnailDataUrl:s.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),a(u);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Bl=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await As(),a=o.transaction([Jt],"readwrite").objectStore(Jt);await new Promise((n,r)=>{let i=a.delete(e);i.onsuccess=()=>n(!0),i.onerror=()=>r(i.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Kc=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await As(),t=e.transaction([Jt],"readwrite").objectStore(Jt);await new Promise((a,n)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>n(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}},Gc=e=>URL.createObjectURL(e);function Da(e,o=[]){let t=[];function a(r,i){let u=ve.createContext(i),s=t.length;t=[...t,i];let c=d=>{let{scope:l,children:f,...h}=d,p=l?.[e]?.[s]||u,y=ve.useMemo(()=>h,Object.values(h));return jsx(p.Provider,{value:y,children:f})};c.displayName=r+"Provider";function m(d,l){let f=l?.[e]?.[s]||u,h=ve.useContext(f);if(h)return h;if(i!==void 0)return i;throw new Error(`\`${d}\` must be used within \`${r}\``)}return [c,m]}let n=()=>{let r=t.map(i=>ve.createContext(i));return function(u){let s=u?.[e]||r;return ve.useMemo(()=>({[`__scope${e}`]:{...u,[e]:s}}),[u,s])}};return n.scopeName=e,[a,hv(n,...o)]}function hv(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(n=>({useScope:n(),scopeName:n.scopeName}));return function(r){let i=a.reduce((u,{useScope:s,scopeName:c})=>{let d=s(r)[`__scope${c}`];return {...u,...d}},{});return ve.useMemo(()=>({[`__scope${o.scopeName}`]:i}),[i])}};return t.scopeName=o.scopeName,t}function jc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Yr(...e){return o=>{let t=false,a=e.map(n=>{let r=jc(n,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let n=0;n<a.length;n++){let r=a[n];typeof r=="function"?r():jc(e[n],null);}}}}function qt(...e){return ve.useCallback(Yr(...e),e)}function $c(e){let o=gv(e),t=ve.forwardRef((a,n)=>{let{children:r,...i}=a,u=ve.Children.toArray(r),s=u.find(bv);if(s){let c=s.props.children,m=u.map(d=>d===s?ve.Children.count(c)>1?ve.Children.only(null):ve.isValidElement(c)?c.props.children:null:d);return jsx(o,{...i,ref:n,children:ve.isValidElement(c)?ve.cloneElement(c,void 0,m):null})}return jsx(o,{...i,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function gv(e){let o=ve.forwardRef((t,a)=>{let{children:n,...r}=t;if(ve.isValidElement(n)){let i=yv(n),u=vv(r,n.props);return n.type!==ve.Fragment&&(u.ref=a?Yr(a,i):i),ve.cloneElement(n,u)}return ve.Children.count(n)>1?ve.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var xv=Symbol("radix.slottable");function bv(e){return ve.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===xv}function vv(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let s=r(...u);return n(...u),s}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function yv(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 Lv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],xt=Lv.reduce((e,o)=>{let t=$c(`Primitive.${o}`),a=ve.forwardRef((n,r)=>{let{asChild:i,...u}=n,s=i?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(s,{...u,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function ot(e,o,{checkForDefaultPrevented:t=true}={}){return function(n){if(e?.(n),t===false||!n.defaultPrevented)return o?.(n)}}function Ol(e){let o=Iv(e),t=ve.forwardRef((a,n)=>{let{children:r,...i}=a,u=ve.Children.toArray(r),s=u.find(kv);if(s){let c=s.props.children,m=u.map(d=>d===s?ve.Children.count(c)>1?ve.Children.only(null):ve.isValidElement(c)?c.props.children:null:d);return jsx(o,{...i,ref:n,children:ve.isValidElement(c)?ve.cloneElement(c,void 0,m):null})}return jsx(o,{...i,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Iv(e){let o=ve.forwardRef((t,a)=>{let{children:n,...r}=t;if(ve.isValidElement(n)){let i=Mv(n),u=Tv(r,n.props);return n.type!==ve.Fragment&&(u.ref=a?Yr(a,i):i),ve.cloneElement(n,u)}return ve.Children.count(n)>1?ve.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Cv=Symbol("radix.slottable");function kv(e){return ve.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Cv}function Tv(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let s=r(...u);return n(...u),s}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function Mv(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 Ps(e){let o=e+"CollectionProvider",[t,a]=Da(o),[n,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),i=p=>{let{scope:y,children:v}=p,g=ve__default.useRef(null),x=ve__default.useRef(new Map).current;return jsx(n,{scope:y,itemMap:x,collectionRef:g,children:v})};i.displayName=o;let u=e+"CollectionSlot",s=Ol(u),c=ve__default.forwardRef((p,y)=>{let{scope:v,children:g}=p,x=r(u,v),L=qt(y,x.collectionRef);return jsx(s,{ref:L,children:g})});c.displayName=u;let m=e+"CollectionItemSlot",d="data-radix-collection-item",l=Ol(m),f=ve__default.forwardRef((p,y)=>{let{scope:v,children:g,...x}=p,L=ve__default.useRef(null),S=qt(y,L),C=r(m,v);return ve__default.useEffect(()=>(C.itemMap.set(L,{ref:L,...x}),()=>void C.itemMap.delete(L))),jsx(l,{[d]:"",ref:S,children:g})});f.displayName=m;function h(p){let y=r(e+"CollectionConsumer",p);return ve__default.useCallback(()=>{let g=y.collectionRef.current;if(!g)return [];let x=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(y.itemMap.values()).sort((C,w)=>x.indexOf(C.ref.current)-x.indexOf(w.ref.current))},[y.collectionRef,y.itemMap])}return [{Provider:i,Slot:c,ItemSlot:f},h,a]}var Xo=globalThis?.document?ve.useLayoutEffect:()=>{};var Av=ve[" useId ".trim().toString()]||(()=>{}),Pv=0;function Qc(e){let[o,t]=ve.useState(Av());return Xo(()=>{t(a=>a??String(Pv++));},[e]),(o?`radix-${o}`:"")}function ef(e){let o=ve.useRef(e);return ve.useEffect(()=>{o.current=e;}),ve.useMemo(()=>(...t)=>o.current?.(...t),[])}var Ev=ve[" useInsertionEffect ".trim().toString()]||Xo;function sa({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[n,r,i]=Rv({defaultProp:o,onChange:t}),u=e!==void 0,s=u?e:n;{let m=ve.useRef(e!==void 0);ve.useEffect(()=>{let d=m.current;d!==u&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${u?"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=u;},[u,a]);}let c=ve.useCallback(m=>{if(u){let d=Dv(m)?m(e):m;d!==e&&i.current?.(d);}else r(m);},[u,e,r,i]);return [s,c]}function Rv({defaultProp:e,onChange:o}){let[t,a]=ve.useState(e),n=ve.useRef(t),r=ve.useRef(o);return Ev(()=>{r.current=o;},[o]),ve.useEffect(()=>{n.current!==t&&(r.current?.(t),n.current=t);},[t,n]),[t,a,r]}function Dv(e){return typeof e=="function"}var Fv=ve.createContext(void 0);function Yo(e){let o=ve.useContext(Fv);return e||o||"ltr"}var ql="rovingFocusGroup.onEntryFocus",Bv={bubbles:false,cancelable:true},Zr="RovingFocusGroup",[Vl,tf,Ov]=Ps(Zr),[Nv,Ul]=Da(Zr,[Ov]),[Hv,qv]=Nv(Zr),af=ve.forwardRef((e,o)=>jsx(Vl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Vl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Vv,{...e,ref:o})})}));af.displayName=Zr;var Vv=ve.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:n=false,dir:r,currentTabStopId:i,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:s,onEntryFocus:c,preventScrollOnEntryFocus:m=false,...d}=e,l=ve.useRef(null),f=qt(o,l),h=Yo(r),[p,y]=sa({prop:i,defaultProp:u??null,onChange:s,caller:Zr}),[v,g]=ve.useState(false),x=ef(c),L=tf(t),S=ve.useRef(false),[C,w]=ve.useState(0);return ve.useEffect(()=>{let b=l.current;if(b)return b.addEventListener(ql,x),()=>b.removeEventListener(ql,x)},[x]),jsx(Hv,{scope:t,orientation:a,dir:h,loop:n,currentTabStopId:p,onItemFocus:ve.useCallback(b=>y(b),[y]),onItemShiftTab:ve.useCallback(()=>g(true),[]),onFocusableItemAdd:ve.useCallback(()=>w(b=>b+1),[]),onFocusableItemRemove:ve.useCallback(()=>w(b=>b-1),[]),children:jsx(xt.div,{tabIndex:v||C===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:ot(e.onMouseDown,()=>{S.current=true;}),onFocus:ot(e.onFocus,b=>{let k=!S.current;if(b.target===b.currentTarget&&k&&!v){let M=new CustomEvent(ql,Bv);if(b.currentTarget.dispatchEvent(M),!M.defaultPrevented){let P=L().filter(N=>N.focusable),D=P.find(N=>N.active),W=P.find(N=>N.id===p),U=[D,W,...P].filter(Boolean).map(N=>N.ref.current);nf(U,m);}}S.current=false;}),onBlur:ot(e.onBlur,()=>g(false))})})}),of="RovingFocusGroupItem",rf=ve.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:n=false,tabStopId:r,children:i,...u}=e,s=Qc(),c=r||s,m=qv(of,t),d=m.currentTabStopId===c,l=tf(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:p}=m;return ve.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(Vl.ItemSlot,{scope:t,id:c,focusable:a,active:n,children:jsx(xt.span,{tabIndex:d?0:-1,"data-orientation":m.orientation,...u,ref:o,onMouseDown:ot(e.onMouseDown,y=>{a?m.onItemFocus(c):y.preventDefault();}),onFocus:ot(e.onFocus,()=>m.onItemFocus(c)),onKeyDown:ot(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){m.onItemShiftTab();return}if(y.target!==y.currentTarget)return;let v=zv(y,m.orientation,m.dir);if(v!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let x=l().filter(L=>L.focusable).map(L=>L.ref.current);if(v==="last")x.reverse();else if(v==="prev"||v==="next"){v==="prev"&&x.reverse();let L=x.indexOf(y.currentTarget);x=m.loop?Kv(x,L+1):x.slice(L+1);}setTimeout(()=>nf(x));}}),children:typeof i=="function"?i({isCurrentTabStop:d,hasTabStop:p!=null}):i})})});rf.displayName=of;var Uv={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Wv(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function zv(e,o,t){let a=Wv(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Uv[a]}function nf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Kv(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var sf=af,lf=rf;var uf="Toggle",Wl=ve.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:n,...r}=e,[i,u]=sa({prop:t,onChange:n,defaultProp:a??false,caller:uf});return jsx(xt.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:ot(e.onClick,()=>{e.disabled||u(!i);})})});Wl.displayName=uf;var Fa="ToggleGroup",[ff]=Da(Fa,[Ul]),mf=Ul(),zl=ve__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(_v,{...a,ref:o});if(t==="multiple")return jsx(Xv,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Fa}\``)});zl.displayName=Fa;var[pf,hf]=ff(Fa),_v=ve__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[i,u]=sa({prop:t,defaultProp:a??"",onChange:n,caller:Fa});return jsx(pf,{scope:e.__scopeToggleGroup,type:"single",value:ve__default.useMemo(()=>i?[i]:[],[i]),onItemActivate:u,onItemDeactivate:ve__default.useCallback(()=>u(""),[u]),children:jsx(gf,{...r,ref:o})})}),Xv=ve__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[i,u]=sa({prop:t,defaultProp:a??[],onChange:n,caller:Fa}),s=ve__default.useCallback(m=>u((d=[])=>[...d,m]),[u]),c=ve__default.useCallback(m=>u((d=[])=>d.filter(l=>l!==m)),[u]);return jsx(pf,{scope:e.__scopeToggleGroup,type:"multiple",value:i,onItemActivate:s,onItemDeactivate:c,children:jsx(gf,{...r,ref:o})})});zl.displayName=Fa;var[$v,Yv]=ff(Fa),gf=ve__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:n=true,orientation:r,dir:i,loop:u=true,...s}=e,c=mf(t),m=Yo(i),d={role:"group",dir:m,...s};return jsx($v,{scope:t,rovingFocus:n,disabled:a,children:n?jsx(sf,{asChild:true,...c,orientation:r,dir:m,loop:u,children:jsx(xt.div,{...d,ref:o})}):jsx(xt.div,{...d,ref:o})})}),Ds="ToggleGroupItem",Zv=ve__default.forwardRef((e,o)=>{let t=hf(Ds,e.__scopeToggleGroup),a=Yv(Ds,e.__scopeToggleGroup),n=mf(e.__scopeToggleGroup),r=t.value.includes(e.value),i=a.disabled||e.disabled,u={...e,pressed:r,disabled:i},s=ve__default.useRef(null);return a.rovingFocus?jsx(lf,{asChild:true,...n,focusable:!i,active:r,ref:s,children:jsx(cf,{...u,ref:o})}):jsx(cf,{...u,ref:o})});Zv.displayName=Ds;var cf=ve__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...n}=e,r=hf(Ds,t),i={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=r.type==="single"?i:void 0;return jsx(Wl,{...u,...n,ref:o,onPressedChange:s=>{s?r.onItemActivate(a):r.onItemDeactivate(a);}})}),xf=zl;function bf(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var n=e.length;for(o=0;o<n;o++)e[o]&&(t=bf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Fs(){for(var e,o,t=0,a="",n=arguments.length;t<n;t++)(e=arguments[t])&&(o=bf(e))&&(a&&(a+=" "),a+=o);return a}var Qv=(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},ey=(e,o)=>({classGroupId:e,validator:o}),Lf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var vf=[],ty="arbitrary..",ay=e=>{let o=ry(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return oy(i);let u=i.split("-"),s=u[0]===""&&u.length>1?1:0;return If(u,s,o)},getConflictingClassGroupIds:(i,u)=>{if(u){let s=a[i],c=t[i];return s?c?Qv(c,s):s:c||vf}return t[i]||vf}}},If=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let n=e[o],r=t.nextPart.get(n);if(r){let c=If(e,o+1,r);if(c)return c}let i=t.validators;if(i===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),s=i.length;for(let c=0;c<s;c++){let m=i[c];if(m.validator(u))return m.classGroupId}},oy=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?ty+a:void 0})(),ry=e=>{let{theme:o,classGroups:t}=e;return ny(t,o)},ny=(e,o)=>{let t=Lf();for(let a in e){let n=e[a];jl(n,t,a,o);}return t},jl=(e,o,t,a)=>{let n=e.length;for(let r=0;r<n;r++){let i=e[r];sy(i,o,t,a);}},sy=(e,o,t,a)=>{if(typeof e=="string"){iy(e,o,t);return}if(typeof e=="function"){ly(e,o,t,a);return}dy(e,o,t,a);},iy=(e,o,t)=>{let a=e===""?o:Cf(o,e);a.classGroupId=t;},ly=(e,o,t,a)=>{if(uy(e)){jl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(ey(t,e));},dy=(e,o,t,a)=>{let n=Object.entries(e),r=n.length;for(let i=0;i<r;i++){let[u,s]=n[i];jl(s,Cf(o,u),t,a);}},Cf=(e,o)=>{let t=e,a=o.split("-"),n=a.length;for(let r=0;r<n;r++){let i=a[r],u=t.nextPart.get(i);u||(u=Lf(),t.nextPart.set(i,u)),t=u;}return t},uy=e=>"isThemeGetter"in e&&e.isThemeGetter===true,cy=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),n=(r,i)=>{t[r]=i,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let i=t[r];if(i!==void 0)return i;if((i=a[r])!==void 0)return n(r,i),i},set(r,i){r in t?t[r]=i:n(r,i);}}};var fy=[],yf=(e,o,t,a,n)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:n}),my=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=n=>{let r=[],i=0,u=0,s=0,c,m=n.length;for(let p=0;p<m;p++){let y=n[p];if(i===0&&u===0){if(y===":"){r.push(n.slice(s,p)),s=p+1;continue}if(y==="/"){c=p;continue}}y==="["?i++:y==="]"?i--:y==="("?u++:y===")"&&u--;}let d=r.length===0?n:n.slice(s),l=d,f=false;d.endsWith("!")?(l=d.slice(0,-1),f=true):d.startsWith("!")&&(l=d.slice(1),f=true);let h=c&&c>s?c-s:void 0;return yf(r,f,l,h)};if(o){let n=o+":",r=a;a=i=>i.startsWith(n)?r(i.slice(n.length)):yf(fy,false,i,void 0,true);}if(t){let n=a;a=r=>t({className:r,parseClassName:n});}return a},py=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],n=[];for(let r=0;r<t.length;r++){let i=t[r],u=i[0]==="[",s=o.has(i);u||s?(n.length>0&&(n.sort(),a.push(...n),n=[]),a.push(i)):n.push(i);}return n.length>0&&(n.sort(),a.push(...n)),a}},hy=e=>({cache:cy(e.cacheSize),parseClassName:my(e),sortModifiers:py(e),...ay(e)}),gy=/\s+/,xy=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:n,sortModifiers:r}=o,i=[],u=e.trim().split(gy),s="";for(let c=u.length-1;c>=0;c-=1){let m=u[c],{isExternal:d,modifiers:l,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:p}=t(m);if(d){s=m+(s.length>0?" "+s:s);continue}let y=!!p,v=a(y?h.substring(0,p):h);if(!v){if(!y){s=m+(s.length>0?" "+s:s);continue}if(v=a(h),!v){s=m+(s.length>0?" "+s:s);continue}y=false;}let g=l.length===0?"":l.length===1?l[0]:r(l).join(":"),x=f?g+"!":g,L=x+v;if(i.indexOf(L)>-1)continue;i.push(L);let S=n(v,y);for(let C=0;C<S.length;++C){let w=S[C];i.push(x+w);}s=m+(s.length>0?" "+s:s);}return s},by=(...e)=>{let o=0,t,a,n="";for(;o<e.length;)(t=e[o++])&&(a=kf(t))&&(n&&(n+=" "),n+=a);return n},kf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=kf(e[a]))&&(t&&(t+=" "),t+=o);return t},vy=(e,...o)=>{let t,a,n,r,i=s=>{let c=o.reduce((m,d)=>d(m),e());return t=hy(c),a=t.cache.get,n=t.cache.set,r=u,u(s)},u=s=>{let c=a(s);if(c)return c;let m=xy(s,t);return n(s,m),m};return r=i,(...s)=>r(by(...s))},yy=[],je=e=>{let o=t=>t[e]||yy;return o.isThemeGetter=true,o},Tf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Mf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,wy=/^\d+\/\d+$/,Sy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Ly=/\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$/,Iy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Cy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ky=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Zo=e=>wy.test(e),ie=e=>!!e&&!Number.isNaN(Number(e)),Ba=e=>!!e&&Number.isInteger(Number(e)),Kl=e=>e.endsWith("%")&&ie(e.slice(0,-1)),ia=e=>Sy.test(e),Ty=()=>true,My=e=>Ly.test(e)&&!Iy.test(e),Af=()=>false,Ay=e=>Cy.test(e),Py=e=>ky.test(e),Ey=e=>!X(e)&&!$(e),Ry=e=>Jo(e,Rf,Af),X=e=>Tf.test(e),uo=e=>Jo(e,Df,My),Gl=e=>Jo(e,Ny,ie),wf=e=>Jo(e,Pf,Af),Dy=e=>Jo(e,Ef,Py),Bs=e=>Jo(e,Ff,Ay),$=e=>Mf.test(e),Jr=e=>Qo(e,Df),Fy=e=>Qo(e,Hy),Sf=e=>Qo(e,Pf),By=e=>Qo(e,Rf),Oy=e=>Qo(e,Ef),Os=e=>Qo(e,Ff,true),Jo=(e,o,t)=>{let a=Tf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Qo=(e,o,t=false)=>{let a=Mf.exec(e);return a?a[1]?o(a[1]):t:false},Pf=e=>e==="position"||e==="percentage",Ef=e=>e==="image"||e==="url",Rf=e=>e==="length"||e==="size"||e==="bg-size",Df=e=>e==="length",Ny=e=>e==="number",Hy=e=>e==="family-name",Ff=e=>e==="shadow";var qy=()=>{let e=je("color"),o=je("font"),t=je("text"),a=je("font-weight"),n=je("tracking"),r=je("leading"),i=je("breakpoint"),u=je("container"),s=je("spacing"),c=je("radius"),m=je("shadow"),d=je("inset-shadow"),l=je("text-shadow"),f=je("drop-shadow"),h=je("blur"),p=je("perspective"),y=je("aspect"),v=je("ease"),g=je("animate"),x=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],S=()=>[...L(),$,X],C=()=>["auto","hidden","clip","visible","scroll"],w=()=>["auto","contain","none"],b=()=>[$,X,s],k=()=>[Zo,"full","auto",...b()],M=()=>[Ba,"none","subgrid",$,X],P=()=>["auto",{span:["full",Ba,$,X]},Ba,$,X],D=()=>[Ba,"auto",$,X],W=()=>["auto","min","max","fr",$,X],B=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],N=()=>["auto",...b()],q=()=>[Zo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],F=()=>[e,$,X],z=()=>[...L(),Sf,wf,{position:[$,X]}],_=()=>["no-repeat",{repeat:["","x","y","space","round"]}],oe=()=>["auto","cover","contain",By,Ry,{size:[$,X]}],V=()=>[Kl,Jr,uo],j=()=>["","none","full",c,$,X],Z=()=>["",ie,Jr,uo],Y=()=>["solid","dashed","dotted","double"],ne=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[ie,Kl,Sf,wf],ce=()=>["","none",h,$,X],we=()=>["none",ie,$,X],Pe=()=>["none",ie,$,X],Ee=()=>[ie,$,X],Fe=()=>[Zo,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ia],breakpoint:[ia],color:[Ty],container:[ia],"drop-shadow":[ia],ease:["in","out","in-out"],font:[Ey],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ia],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ia],shadow:[ia],spacing:["px",ie],text:[ia],"text-shadow":[ia],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Zo,X,$,y]}],container:["container"],columns:[{columns:[ie,X,$,u]}],"break-after":[{"break-after":x()}],"break-before":[{"break-before":x()}],"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:S()}],overflow:[{overflow:C()}],"overflow-x":[{"overflow-x":C()}],"overflow-y":[{"overflow-y":C()}],overscroll:[{overscroll:w()}],"overscroll-x":[{"overscroll-x":w()}],"overscroll-y":[{"overscroll-y":w()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:k()}],"inset-x":[{"inset-x":k()}],"inset-y":[{"inset-y":k()}],start:[{start:k()}],end:[{end:k()}],top:[{top:k()}],right:[{right:k()}],bottom:[{bottom:k()}],left:[{left:k()}],visibility:["visible","invisible","collapse"],z:[{z:[Ba,"auto",$,X]}],basis:[{basis:[Zo,"full","auto",u,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ie,Zo,"auto","initial","none",X]}],grow:[{grow:["",ie,$,X]}],shrink:[{shrink:["",ie,$,X]}],order:[{order:[Ba,"first","last","none",$,X]}],"grid-cols":[{"grid-cols":M()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":D()}],"col-end":[{"col-end":D()}],"grid-rows":[{"grid-rows":M()}],"row-start-end":[{row:P()}],"row-start":[{"row-start":D()}],"row-end":[{"row-end":D()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":W()}],"auto-rows":[{"auto-rows":W()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...B(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...B()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":B()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:N()}],mx:[{mx:N()}],my:[{my:N()}],ms:[{ms:N()}],me:[{me:N()}],mt:[{mt:N()}],mr:[{mr:N()}],mb:[{mb:N()}],ml:[{ml:N()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],w:[{w:[u,"screen",...q()]}],"min-w":[{"min-w":[u,"screen","none",...q()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[i]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",t,Jr,uo]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,Gl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Kl,X]}],"font-family":[{font:[Fy,X,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[n,$,X]}],"line-clamp":[{"line-clamp":[ie,"none",$,Gl]}],leading:[{leading:[r,...b()]}],"list-image":[{"list-image":["none",$,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:[ie,"from-font","auto",$,uo]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[ie,"auto",$,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:_()}],"bg-size":[{bg:oe()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ba,$,X],radial:["",$,X],conic:[Ba,$,X]},Oy,Dy]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:V()}],"gradient-via-pos":[{via:V()}],"gradient-to-pos":[{to:V()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:j()}],"rounded-s":[{"rounded-s":j()}],"rounded-e":[{"rounded-e":j()}],"rounded-t":[{"rounded-t":j()}],"rounded-r":[{"rounded-r":j()}],"rounded-b":[{"rounded-b":j()}],"rounded-l":[{"rounded-l":j()}],"rounded-ss":[{"rounded-ss":j()}],"rounded-se":[{"rounded-se":j()}],"rounded-ee":[{"rounded-ee":j()}],"rounded-es":[{"rounded-es":j()}],"rounded-tl":[{"rounded-tl":j()}],"rounded-tr":[{"rounded-tr":j()}],"rounded-br":[{"rounded-br":j()}],"rounded-bl":[{"rounded-bl":j()}],"border-w":[{border:Z()}],"border-w-x":[{"border-x":Z()}],"border-w-y":[{"border-y":Z()}],"border-w-s":[{"border-s":Z()}],"border-w-e":[{"border-e":Z()}],"border-w-t":[{"border-t":Z()}],"border-w-r":[{"border-r":Z()}],"border-w-b":[{"border-b":Z()}],"border-w-l":[{"border-l":Z()}],"divide-x":[{"divide-x":Z()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Z()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Y(),"hidden","none"]}],"divide-style":[{divide:[...Y(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...Y(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ie,$,X]}],"outline-w":[{outline:["",ie,Jr,uo]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",m,Os,Bs]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",d,Os,Bs]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:Z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[ie,uo]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":Z()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",l,Os,Bs]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[ie,$,X]}],"mix-blend":[{"mix-blend":[...ne(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ne()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ie]}],"mask-image-linear-from-pos":[{"mask-linear-from":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[$,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":J()}],"mask-image-radial-to-pos":[{"mask-radial-to":J()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[ie]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:_()}],"mask-size":[{mask:oe()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,X]}],filter:[{filter:["","none",$,X]}],blur:[{blur:ce()}],brightness:[{brightness:[ie,$,X]}],contrast:[{contrast:[ie,$,X]}],"drop-shadow":[{"drop-shadow":["","none",f,Os,Bs]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",ie,$,X]}],"hue-rotate":[{"hue-rotate":[ie,$,X]}],invert:[{invert:["",ie,$,X]}],saturate:[{saturate:[ie,$,X]}],sepia:[{sepia:["",ie,$,X]}],"backdrop-filter":[{"backdrop-filter":["","none",$,X]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[ie,$,X]}],"backdrop-contrast":[{"backdrop-contrast":[ie,$,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ie,$,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ie,$,X]}],"backdrop-invert":[{"backdrop-invert":["",ie,$,X]}],"backdrop-opacity":[{"backdrop-opacity":[ie,$,X]}],"backdrop-saturate":[{"backdrop-saturate":[ie,$,X]}],"backdrop-sepia":[{"backdrop-sepia":["",ie,$,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ie,"initial",$,X]}],ease:[{ease:["linear","initial",v,$,X]}],delay:[{delay:[ie,$,X]}],animate:[{animate:["none",g,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,$,X]}],"perspective-origin":[{"perspective-origin":S()}],rotate:[{rotate:we()}],"rotate-x":[{"rotate-x":we()}],"rotate-y":[{"rotate-y":we()}],"rotate-z":[{"rotate-z":we()}],scale:[{scale:Pe()}],"scale-x":[{"scale-x":Pe()}],"scale-y":[{"scale-y":Pe()}],"scale-z":[{"scale-z":Pe()}],"scale-3d":["scale-3d"],skew:[{skew:Ee()}],"skew-x":[{"skew-x":Ee()}],"skew-y":[{"skew-y":Ee()}],transform:[{transform:[$,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:S()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Fe()}],"translate-x":[{"translate-x":Fe()}],"translate-y":[{"translate-y":Fe()}],"translate-z":[{"translate-z":Fe()}],"translate-none":["translate-none"],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,X]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[ie,Jr,uo,Gl]}],stroke:[{stroke:["none",...F()]}],"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 Bf=vy(qy);function Oa(...e){return Bf(Fs(e))}var Uy=ve.createContext({size:"default",variant:"default",spacing:0});function Na({className:e,variant:o,size:t,spacing:a=1,children:n,...r}){return jsx(xf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Oa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Uy.Provider,{value:{variant:o,size:t,spacing:a},children:n})})}var zy={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Vf=createSlice({name:"toolbar",initialState:zy,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:Qt,setPenColor:la,setStrokeWidth:Qr,setFontSize:cR,setFontFamily:fR,setFontStyle:mR,setFontWeight:pR,setTextDecoration:hR,setTextColor:gR}=Vf.actions,Xl=Vf.reducer;var Ns=({onClose:e,onRecordingComplete:o})=>{let t=Ve(),[a,n]=useState(false),[r,i]=useState(null),[u,s]=useState(0),[c,m]=useState(null),[d,l]=useState(false),f=useRef(null),h=useRef([]),p=useRef(null),y=useRef(null),v=useRef(null);useEffect(()=>((async()=>{try{let k=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(k),l(!0),v.current&&(v.current.srcObject=k);}catch(k){console.error("Error accessing camera:",k),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),c&&c.getTracks().forEach(k=>k.stop());}),[]);let g=()=>{c&&(c.getTracks().forEach(b=>b.stop()),m(null),l(false));},x=async()=>{try{let b=null,k=null;try{b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(B){console.error("Error accessing camera for recording:",B),alert("Failed to access camera for recording.");return}try{k=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(B){console.warn("Microphone access denied:",B);}let M=[...b.getVideoTracks()];k&&M.push(...k.getAudioTracks());let P=new MediaStream(M),D="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?D="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?D="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?D="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(D="video/webm;codecs=vp8");let W=new MediaRecorder(P,{mimeType:D,videoBitsPerSecond:25e5});f.current=W,h.current=[],W.ondataavailable=B=>{B.data.size>0&&h.current.push(B.data);},W.onstop=()=>{let B=new Blob(h.current,{type:D}),U=document.createElement("video");U.src=URL.createObjectURL(B),U.muted=!0,U.currentTime=.1,U.onseeked=()=>{let N=document.createElement("canvas");N.width=U.videoWidth,N.height=U.videoHeight;let q=N.getContext("2d");q&&(q.drawImage(U,0,0),y.current=N.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(U.src);},P.getTracks().forEach(N=>N.stop()),b&&b.getTracks().forEach(N=>N.stop()),k&&k.getTracks().forEach(N=>N.stop()),p.current&&clearInterval(p.current),i(B),g();},W.onerror=B=>{console.error("MediaRecorder error:",B);},W.start(1e3),n(!0),s(0),p.current=setInterval(()=>{s(B=>B+1);},1e3);}catch(b){console.error("Error starting camera recording:",b),alert("Failed to start recording. Please check permissions.");}},L=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),n(false));},S=()=>{if(r){let b=URL.createObjectURL(r),k=document.createElement("a");k.href=b,k.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(k),k.click(),document.body.removeChild(k),URL.revokeObjectURL(b);}},C=b=>{let k=Math.floor(b/60),M=b%60;return `${k.toString().padStart(2,"0")}:${M.toString().padStart(2,"0")}`};if(!t)return null;let w=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:b=>{b.target===b.currentTarget&&e(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:b=>b.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:v,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:x,disabled:!d,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"})})}),!d&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:L,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:C(u)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",C(u)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{i(null),s(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:S,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&y.current&&(o(r,y.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(w,t)};var da=40,Wf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,n]=useState(t?.images||[]),[r,i]=useState(t?.order||"sequential"),[u,s]=useState(false),c=useRef(null),m=Ve(),d=useRef(null);useEffect(()=>{let x=L=>{L.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let l=x=>{let L=x.target.files;if(!L||L.length===0)return;let S=da-a.length;if(S<=0){alert(`You can only upload a maximum of ${da} images`);return}let C=Array.from(L).slice(0,S);C.length<L.length&&alert(`Only ${S} more images can be added (max ${da} total)`);let w=C.map(b=>new Promise((k,M)=>{let P=new FileReader;P.onload=D=>{D.target?.result?k(D.target.result):M(new Error("Failed to read file"));},P.onerror=M,P.readAsDataURL(b);}));Promise.all(w).then(b=>{n(k=>[...k,...b]),d.current&&(d.current.value="");});},f=x=>{x.preventDefault(),s(false);let L=Array.from(x.dataTransfer.files).filter(b=>b.type.startsWith("image/"));if(L.length===0)return;let S=da-a.length;if(S<=0){alert(`You can only upload a maximum of ${da} images`);return}let C=L.slice(0,S);C.length<L.length&&alert(`Only ${S} more images can be added (max ${da} total)`);let w=C.map(b=>new Promise((k,M)=>{let P=new FileReader;P.onload=D=>{D.target?.result?k(D.target.result):M(new Error("Failed to read file"));},P.onerror=M,P.readAsDataURL(b);}));Promise.all(w).then(b=>{n(k=>[...k,...b]);});},h=x=>{x.preventDefault(),s(true);},p=()=>{s(false);},y=x=>{n(L=>L.filter((S,C)=>C!==x));},v=x=>{if(x.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 g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:v,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>=da?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",da," images"]}):jsxs("span",{children:[a.length,"/",da," images"]})})]}),jsx("input",{ref:d,type:"file",accept:"image/*",multiple:true,onChange:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:f,onDragOver:h,onDragLeave:p,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"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:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \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:()=>i("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:()=>i("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((x,L)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${L+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>y(L),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:L+1})]},L))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(g,m)};var Hs={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},nw={enabled:true};function Zl(e){return e?{tools:{...Hs.tools,...e.tools},actions:{...Hs.actions,...e.actions}}:Hs}var sw={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},iw={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};function Jl(e,[o,t]){return Math.min(t,Math.max(o,e))}function zf(e){let o=ve.useRef({value:e,previous:e});return ve.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Gf(e){let[o,t]=ve.useState(void 0);return Xo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(n=>{if(!Array.isArray(n)||!n.length)return;let r=n[0],i,u;if("borderBoxSize"in r){let s=r.borderBoxSize,c=Array.isArray(s)?s[0]:s;i=c.inlineSize,u=c.blockSize;}else i=e.offsetWidth,u=e.offsetHeight;t({width:i,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var jf=["PageUp","PageDown"],_f=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Xf={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},er="Slider",[Ql,dw,uw]=Ps(er),[$f]=Da(er,[uw]),[cw,Vs]=$f(er),Yf=ve.forwardRef((e,o)=>{let{name:t,min:a=0,max:n=100,step:r=1,orientation:i="horizontal",disabled:u=false,minStepsBetweenThumbs:s=0,defaultValue:c=[a],value:m,onValueChange:d=()=>{},onValueCommit:l=()=>{},inverted:f=false,form:h,...p}=e,y=ve.useRef(new Set),v=ve.useRef(0),x=i==="horizontal"?fw:mw,[L=[],S]=sa({prop:m,defaultProp:c,onChange:P=>{[...y.current][v.current]?.focus(),d(P);}}),C=ve.useRef(L);function w(P){let D=bw(L,P);M(P,D);}function b(P){M(P,v.current);}function k(){let P=C.current[v.current];L[v.current]!==P&&l(L);}function M(P,D,{commit:W}={commit:false}){let B=Sw(r),U=Lw(Math.round((P-a)/r)*r+a,B),N=Jl(U,[a,n]);S((q=[])=>{let F=gw(q,N,D);if(ww(F,s*r)){v.current=F.indexOf(N);let z=String(F)!==String(q);return z&&W&&l(F),z?F:q}else return q});}return jsx(cw,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:n,valueIndexToChangeRef:v,thumbs:y.current,values:L,orientation:i,form:h,children:jsx(Ql.Provider,{scope:e.__scopeSlider,children:jsx(Ql.Slot,{scope:e.__scopeSlider,children:jsx(x,{"aria-disabled":u,"data-disabled":u?"":void 0,...p,ref:o,onPointerDown:ot(p.onPointerDown,()=>{u||(C.current=L);}),min:a,max:n,inverted:f,onSlideStart:u?void 0:w,onSlideMove:u?void 0:b,onSlideEnd:u?void 0:k,onHomeKeyDown:()=>!u&&M(a,0,{commit:true}),onEndKeyDown:()=>!u&&M(n,L.length-1,{commit:true}),onStepKeyDown:({event:P,direction:D})=>{if(!u){let U=jf.includes(P.key)||P.shiftKey&&_f.includes(P.key)?10:1,N=v.current,q=L[N],F=r*U*D;M(q+F,N,{commit:true});}}})})})})});Yf.displayName=er;var[Zf,Jf]=$f(er,{startEdge:"left",endEdge:"right",size:"width",direction:1}),fw=ve.forwardRef((e,o)=>{let{min:t,max:a,dir:n,inverted:r,onSlideStart:i,onSlideMove:u,onSlideEnd:s,onStepKeyDown:c,...m}=e,[d,l]=ve.useState(null),f=qt(o,x=>l(x)),h=ve.useRef(void 0),p=Yo(n),y=p==="ltr",v=y&&!r||!y&&r;function g(x){let L=h.current||d.getBoundingClientRect(),S=[0,L.width],w=ad(S,v?[t,a]:[a,t]);return h.current=L,w(x-L.left)}return jsx(Zf,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:jsx(Qf,{dir:p,"data-orientation":"horizontal",...m,ref:f,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:x=>{let L=g(x.clientX);i?.(L);},onSlideMove:x=>{let L=g(x.clientX);u?.(L);},onSlideEnd:()=>{h.current=void 0,s?.();},onStepKeyDown:x=>{let S=Xf[v?"from-left":"from-right"].includes(x.key);c?.({event:x,direction:S?-1:1});}})})}),mw=ve.forwardRef((e,o)=>{let{min:t,max:a,inverted:n,onSlideStart:r,onSlideMove:i,onSlideEnd:u,onStepKeyDown:s,...c}=e,m=ve.useRef(null),d=qt(o,m),l=ve.useRef(void 0),f=!n;function h(p){let y=l.current||m.current.getBoundingClientRect(),v=[0,y.height],x=ad(v,f?[a,t]:[t,a]);return l.current=y,x(p-y.top)}return jsx(Zf,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(Qf,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:p=>{let y=h(p.clientY);r?.(y);},onSlideMove:p=>{let y=h(p.clientY);i?.(y);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:p=>{let v=Xf[f?"from-bottom":"from-top"].includes(p.key);s?.({event:p,direction:v?-1:1});}})})}),Qf=ve.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:n,onSlideEnd:r,onHomeKeyDown:i,onEndKeyDown:u,onStepKeyDown:s,...c}=e,m=Vs(er,t);return jsx(xt.span,{...c,ref:o,onKeyDown:ot(e.onKeyDown,d=>{d.key==="Home"?(i(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):jf.concat(_f).includes(d.key)&&(s(d),d.preventDefault());}),onPointerDown:ot(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),m.thumbs.has(l)?l.focus():a(d);}),onPointerMove:ot(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&n(d);}),onPointerUp:ot(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),r(d));})})}),em="SliderTrack",tm=ve.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Vs(em,t);return jsx(xt.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...a,ref:o})});tm.displayName=em;var ed="SliderRange",am=ve.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Vs(ed,t),r=Jf(ed,t),i=ve.useRef(null),u=qt(o,i),s=n.values.length,c=n.values.map(l=>nm(l,n.min,n.max)),m=s>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(xt.span,{"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,...a,ref:u,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:d+"%"}})});am.displayName=ed;var td="SliderThumb",om=ve.forwardRef((e,o)=>{let t=dw(e.__scopeSlider),[a,n]=ve.useState(null),r=qt(o,u=>n(u)),i=ve.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(pw,{...e,ref:r,index:i})}),pw=ve.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:n,...r}=e,i=Vs(td,t),u=Jf(td,t),[s,c]=ve.useState(null),m=qt(o,g=>c(g)),d=s?i.form||!!s.closest("form"):true,l=Gf(s),f=i.values[a],h=f===void 0?0:nm(f,i.min,i.max),p=xw(a,i.values.length),y=l?.[u.size],v=y?vw(y,h,u.direction):0;return ve.useEffect(()=>{if(s)return i.thumbs.add(s),()=>{i.thumbs.delete(s);}},[s,i.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${v}px)`},children:[jsx(Ql.ItemSlot,{scope:e.__scopeSlider,children:jsx(xt.span,{role:"slider","aria-label":e["aria-label"]||p,"aria-valuemin":i.min,"aria-valuenow":f,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...r,ref:m,style:f===void 0?{display:"none"}:e.style,onFocus:ot(e.onFocus,()=>{i.valueIndexToChangeRef.current=a;})})}),d&&jsx(rm,{name:n??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:f},a)]})});om.displayName=td;var hw="RadioBubbleInput",rm=ve.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let n=ve.useRef(null),r=qt(n,a),i=zf(o);return ve.useEffect(()=>{let u=n.current;if(!u)return;let s=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(s,"value").set;if(i!==o&&m){let d=new Event("input",{bubbles:true});m.call(u,o),u.dispatchEvent(d);}},[i,o]),jsx(xt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});rm.displayName=hw;function gw(e=[],o,t){let a=[...e];return a[t]=o,a.sort((n,r)=>n-r)}function nm(e,o,t){let r=100/(t-o)*(e-o);return Jl(r,[0,100])}function xw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function bw(e,o){if(e.length===1)return 0;let t=e.map(n=>Math.abs(n-o)),a=Math.min(...t);return t.indexOf(a)}function vw(e,o,t){let a=e/2,r=ad([0,50],[0,a]);return (a-r(o)*t)*t}function yw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function ww(e,o){if(o>0){let t=yw(e);return Math.min(...t)>=o}return true}function ad(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 Sw(e){return (String(e).split(".")[1]||"").length}function Lw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var sm=Yf,im=tm,lm=am,dm=om;function Us({className:e,defaultValue:o,value:t,min:a=0,max:n=100,rangeClassName:r,trackClassName:i,thumbClassName:u,...s}){let c=ve.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,n],[t,o,a,n]);return jsxs(sm,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:n,className:Oa("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),...s,children:[jsx(im,{"data-slot":"slider-track",className:Oa("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",i),children:jsx(lm,{"data-slot":"slider-range",className:Oa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(m,d)=>jsx(dm,{"data-slot":"slider-thumb",className:Oa("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",u)},d))]})}var Zw=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a,onVisibilityChange:n}={})=>{let r=be(),i=ee(A=>A.canvas.slides.find(ae=>ae.id===A.canvas.currentSlideId)),u=i?.videos||[],s=i?.editingFlashcard,c=ee(A=>A.toolbar.selectedTool),m=ee(A=>A.toolbar.penColor),d=ee(A=>A.toolbar.strokeWidth),l=ee(A=>A.canvas.editingOverlayPosition),f=i?.showMcqForm,h=i?.showFlashcardForm,p=useRef(null);useEffect(()=>{let A=ae=>{(ae.ctrlKey||ae.metaKey)&&ae.key==="z"&&!ae.shiftKey&&(ae.preventDefault(),r(Io())),(ae.ctrlKey&&ae.shiftKey&&ae.key==="Z"||ae.ctrlKey&&ae.key==="y")&&(ae.preventDefault(),r(Co()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[r]);let y=useMemo(()=>Zl(a),[a]),{tools:v,actions:g}=y,x=u.some(A=>A.isRecorded&&A.isPlaying),L=ee(A=>A.toolbar.fontSize),S=ee(A=>A.toolbar.fontFamily),C=ee(A=>A.toolbar.fontStyle),w=ee(A=>A.toolbar.fontWeight),b=ee(A=>A.toolbar.textDecoration),k=ee(A=>A.toolbar.textColor),[M,P]=useState(false),[D,W]=useState(false),[B,U]=useState(false),[N,q]=useState(false),[F,z]=useState(false),[_,oe]=useState(false),[V,j]=useState(false),[Z,Y]=useState(false),[ne,J]=useState(true),ce=useRef(null),we=useRef(null),Pe=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],Ee=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"style",icon:Palette,label:"Style",configKey:"style"},{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"}],[]),Fe=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"}],[]),nt=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),At=useMemo(()=>Ee.filter(A=>{let ae=v[A.configKey];return typeof ae=="boolean"?ae:Array.isArray(ae)?ae.length>0:true}),[v,Ee]),po=useMemo(()=>{let A=v.shapes;return A===false?[]:A===true?Fe:Array.isArray(A)?Fe.filter(ae=>A.includes(ae.name)):Fe},[v.shapes,Fe]),se=useMemo(()=>{let A=v.activities;return A===false?[]:A===true?nt:Array.isArray(A)?nt.filter(ae=>A.includes(ae.name)):nt},[v.activities,nt]),ho=useMemo(()=>{let A=v.media;return A===false?{photoFrame:false,image:false,video:false}:A===true?{photoFrame:true,image:true,video:true}:Array.isArray(A)?{photoFrame:A.includes("photo-frame"),image:A.includes("image"),video:A.includes("video")}:{photoFrame:true,image:true,video:true}},[v.media]),nn=useMemo(()=>{let A=v.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[v.activities]),sn=A=>{let ae=A.target.files;!ae||ae.length===0||(r(Qt("select")),r(yt(false)),q(false),Array.from(ae).forEach(Se=>{let xe=new FileReader;xe.onload=le=>{let fe=new window.Image;fe.src=le.target?.result,fe.onload=()=>{let He=fe.width/fe.height,Ye=300,ta=300,Pt=fe.width,Ce=fe.height;Pt>Ye&&(Pt=Ye,Ce=Pt/He),Ce>ta&&(Ce=ta,Pt=Ce*He),r(de());let st=l?.left||0,aa=l?.top||0;r(ui({id:v4(),src:fe.src,x:st,y:aa,width:Pt,height:Ce,draggable:true,rotation:0}));};},xe.readAsDataURL(Se);}),A.target.value="");},ln=async A=>{let ae=A.target.files;if(!(!ae||ae.length===0)){console.log("files",A),r(Qt("select")),r(yt(false)),q(false);for(let Se of Array.from(ae))try{let xe=URL.createObjectURL(Se),le=document.createElement("video");console.log("video",le),le.src=xe,le.muted=!0,le.playsInline=!0,le.preload="auto",le.load(),await new Promise((re,Ue)=>{let za=setTimeout(()=>Ue(new Error("Metadata load timeout")),1e4);le.onloadedmetadata=()=>{clearTimeout(za),re();},le.onerror=()=>{clearTimeout(za),Ue(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:le.duration,width:le.videoWidth,height:le.videoHeight}),await new Promise((re,Ue)=>{let za=setTimeout(()=>Ue(new Error("Video load timeout")),1e4);le.readyState>=2?(clearTimeout(za),re()):le.onloadeddata=()=>{clearTimeout(za),re();};});let fe=Math.min(.8,le.duration/2);console.log("Seeking to:",fe),le.currentTime=fe,await new Promise(re=>{let Ue=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),re();},5e3);le.onseeked=()=>{clearTimeout(Ue),console.log("Seek completed"),re();};});let He=document.createElement("canvas"),Ye=le.videoWidth/le.videoHeight,ta=400,Pt=400,Ce=le.videoWidth,st=le.videoHeight;Ce>ta&&(Ce=ta,st=Ce/Ye),st>Pt&&(st=Pt,Ce=st*Ye),He.width=Ce,He.height=st;let aa=He.getContext("2d",{willReadFrequently:!1});if(!aa)throw new Error("Failed to get canvas context");if(await new Promise(re=>setTimeout(re,100)),le.videoWidth===0||le.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ce,height:st}),aa.drawImage(le,0,0,Ce,st);let pa=He.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",pa.length),r(de());let ei=800-Ce/2,ti=450-st/2,Wa=v4();await ra(Wa,Se,pa),r(wo({id:Wa,objectUrl:xe,thumbnailDataUrl:pa,videoBlob:Se,x:ei,y:ti,width:Ce,height:st,draggable:!0,isPlaying:!1,rotation:0})),le.src="",le.load(),console.log(`Video uploaded: ${Se.name}`);}catch(xe){console.error("Error processing video:",xe),alert(`Failed to process video: ${Se.name}`);}A.target.value="";}},dn=(A,ae,Se)=>{r(de()),r(Qt("select")),r(yt(false));let xe=300,le=300,fe=800-xe/2,He=450-le/2;r(Se?Lo({id:Se,images:A,order:ae,x:fe,y:He,width:xe,height:le,rotation:0,draggable:true}):mi({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:ae,x:fe,y:He,width:xe,height:le,rotation:0,draggable:true})),r(_a(false));},un=()=>{r(de()),r(Qt("select")),r(yt(false));let A=400,ae=300,Se=800-A/2,xe=450-ae/2;r(gi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Se,y:xe,width:A,height:ae,rotation:0,draggable:true,isCapturing:false})),q(false);},Xs=A=>{let fe={};switch(A.name){case "circle":case "ring":case "wedge":case "arc":fe.radius=50,(A.name==="ring"||A.name==="arc")&&(fe.innerRadius=25,fe.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(fe.angle=A.name==="wedge"?60:90);break;case "ellipse":fe.radiusX=60,fe.radiusY=40;break;case "triangle":fe.radius=50,fe.sides=3;break;case "polygon":fe.radius=50,fe.sides=6;break;case "star":fe.innerRadius=25,fe.outerRadius=50,fe.numPoints=5;break;case "arrow":case "line":fe.points=[0,0,100,0],A.name==="arrow"&&(fe.pointerLength=10,fe.pointerWidth=10);break}let He={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:m,...fe};r(de()),r(yt(false)),r(Qt(A.name)),r(ci(He)),U(false);},Va=A=>{if(r(Qt(A)),A==="select")r(yt(false));else if(A==="text"){r(yt(false)),r(de());let ae=200,Se=50,xe=800-ae/2,le=450-Se/2,He=window.innerWidth<768?Math.max(L,32):L,Ye=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(fi({id:Ye,text:"",x:xe,y:le,width:ae,height:Se,rotation:0,draggable:true,fontSize:He,fontFamily:S,fontStyle:C,fontWeight:w,textDecoration:b,fill:k,align:"left"})),setTimeout(()=>{r(yr(Ye));},100),t&&t(Ye);}else r(yt(true));},$s=()=>{r(vr()),r(yt(false));},Ys=()=>{e?e():o?P(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Zs=()=>{W(true);},Ua=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:un,enabled:ho.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>ce.current?.click(),enabled:ho.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>we.current?.click(),enabled:ho.video}],cn=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Io()),enabled:g.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(Co()),enabled:g.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:Ys,enabled:g.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:Zs,enabled:g.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:$s,enabled:g.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],fn=async(A,ae)=>{try{r(Qt("select")),r(yt(!1));let Se=URL.createObjectURL(A),xe=document.createElement("video");xe.src=Se,xe.muted=!0,xe.playsInline=!0,xe.preload="auto",await new Promise((st,aa)=>{let pa=setTimeout(()=>aa(new Error("Metadata load timeout")),1e4);xe.onloadedmetadata=()=>{clearTimeout(pa),st();},xe.onerror=()=>{clearTimeout(pa),aa(new Error("Failed to load video"));};});let le=640,fe=xe.videoWidth/xe.videoHeight,He=le,Ye=He/fe;r(de());let ta=800-He/2,Pt=450-Ye/2,Ce=v4();await ra(Ce,A,ae),r(wo({id:Ce,objectUrl:Se,thumbnailDataUrl:ae,videoBlob:A,x:ta,y:Pt,width:He,height:Ye,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),P(!1),W(!1);}catch(Se){console.error("Error adding recorded video to canvas:",Se),alert("Failed to add video to canvas. Please try again.");}},go=A=>{r(Qt("select")),r(yt(false)),r(xr(null)),A&&r(ki(A)),r(ba(!f));},mn=()=>{r(mr(null)),r(_a(true)),z(false);},Js=()=>{U(!B);},nr=()=>{q(!N);},xo=()=>{z(!F);},pn=()=>{oe(!_);},Qs=()=>{let A=!ne;A||(U(false),q(false),z(false),oe(false),Y(false),j(false)),J(A),n?.(A);};return useEffect(()=>{if(!Z)return;let A=ae=>{p.current&&!p.current.contains(ae.target)&&Y(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[Z]),x?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:Qs,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:ne?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),ne&&jsxs("div",{className:"fixed top-[168px] left-4 z-50 flex flex-col gap-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(Na,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:At.map((A,ae)=>jsx("div",{title:A.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.name===c?"bg-primary/10":A.name==="style"?"md:hidden":""}`,onClick:()=>{A.name==="image"?(nr(),U(false),z(false),oe(false),Va(A.name)):A.name==="shapes"?(Js(),q(false),z(false),oe(false),Va(A.name)):A.name==="activities"?(Va(A.name),xo(),U(false),q(false),oe(false)):A.name==="style"?(pn(),U(false),q(false),z(false),Va(A.name)):(Va(A.name),U(false),q(false),z(false),oe(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ae))}),B&&jsx(Na,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:po.map((A,ae)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Xs(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ae))}),N&&jsx(Na,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:Ua.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),F&&jsxs(Na,{type:"single",className:"mx-1 mt-auto mb-10 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl lg:mb-11",children:[nn&&jsx("div",{title:"Flashcard",onClick:()=>mn(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),se.map((A,ae)=>jsx("div",{title:A.label,onClick:()=>go(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},ae))]}),_&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Us,{value:[d],onValueChange:A=>{r(Qr(A[0]));},max:28,min:6,step:1,className:"w-28",rangeClassName:"bg-gray-300",thumbClassName:"bg-gray-600 border-none h-4 w-4"}),jsx("div",{className:"h-5 w-5 rounded-full bg-gray-800"})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"COLOR"}),jsxs("div",{className:"flex flex-wrap gap-1",children:[Pe.map(A=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${m===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{r(la(A.value)),oe(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:m,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>r(la(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:m,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{r(fr(A.target.value)),oe(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),cn.some(A=>A.enabled)&&jsx(Na,{type:"single",className:"hidden flex-col border bg-white p-1 shadow-xl md:flex",children:cn.filter(A=>A.enabled).map(A=>jsx("button",{onClick:A.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.colorClass}`,title:A.title,children:jsx(A.icon,{weight:A.iconWeight,className:"text-lg md:text-xl"})},A.key))})]}),jsx("input",{ref:ce,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:sn}),jsx("input",{ref:we,type:"file",accept:"video/*",className:"hidden",onChange:ln}),!e&&M&&o&&jsx(Xa,{onClose:()=>P(false),stageRef:o,onRecordingComplete:fn}),D&&jsx(Ns,{onClose:()=>W(false),onRecordingComplete:fn}),h&&jsx(Wf,{editingFlashcard:s,onConfirm:dn,onCancel:()=>r(_a(false))}),V&&jsx(rs,{defaultColor:m,onConfirm:A=>{r(la(A)),j(false);},onCancel:()=>j(false)})]})},Jw=Zw;var ld=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let n=Re(ya),r=Re(Bi),i=a?r:n,u=Re(Sr),m=(Re(g=>g.canvas.slides.find(x=>x.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[d,l]=useState(false),[f,h]=useState(null),[p,y]=useState(null),v=async()=>{if(n.length===0){y({type:"error",message:"No slides to publish"});return}if(!e){y({type:"error",message:"No publish handler provided"});return}l(true),y(null);try{let g=await e(i,u,x=>{h(x);});g.success?y({type:"success",message:g.message}):y({type:"error",message:g.message});}catch(g){y({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),y(null);},3e3);}};return m?null:jsxs("button",{onClick:v,disabled:d||n.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 oS=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:n,onDescriptionChange:r,showPublishButton:i=true,showBackButton:u=true,editableTitle:s=true,editableDescription:c=true,className:m="",rightContent:d,leftContent:l,includeInactiveSlides:f=false})=>{let h=_e(),p=Re(Sr),y=Re(Oi),v=e??(y?p.title:"")??"Untitled",g=o??(y?p.description:"")??"Add a description...",[x,L]=useState(false),[S,C]=useState(false),[w,b]=useState(v),[k,M]=useState(g),P=useRef(null),D=useRef(null);useEffect(()=>{b(v);},[v]),useEffect(()=>{M(g);},[g]),useEffect(()=>{x&&P.current&&(P.current.focus(),P.current.select());},[x]),useEffect(()=>{S&&D.current&&(D.current.focus(),D.current.select());},[S]);let W=()=>{s&&L(true);},B=()=>{c&&C(true);},U=()=>{L(false),w.trim()&&w!==v?n?n(w.trim()):h(Ri(w.trim())):w.trim()||b(v);},N=()=>{C(false),k.trim()&&k!==g?r?r(k.trim()):h(Di(k.trim())):k.trim()||M(g);},q=z=>{z.key==="Enter"?U():z.key==="Escape"&&(b(v),L(false));},F=z=>{z.key==="Enter"?N():z.key==="Escape"&&(M(g),C(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-4",children:[u&&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:[x?jsx("input",{ref:P,type:"text",value:w,onChange:z=>b(z.target.value),onBlur:U,onKeyDown:q,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:W,title:w,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${s?"hover:border-primary cursor-text":""}`,children:w}),S?jsx("input",{ref:D,type:"text",value:k,onChange:z=>M(z.target.value),onBlur:N,onKeyDown:F,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:B,title:k,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${c?"hover:border-primary cursor-text":""}`,children:k})]})]}),d||i&&a&&jsx(ld,{onPublish:a,includeInactiveSlides:f})]})};var dS=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],uS=({colors:e=dS,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:n=""})=>{let[r,i]=useState(true),u=ee(ge),s=ee(l=>l.toolbar.penColor),c=ee(l=>l.toolbar.strokeWidth),m=u?.backgroundColor,d=be();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-16 left-1/2 z-50 hidden w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-3 shadow-2xl md:bottom-6 md:flex md:p-5 2xl:px-8 2xl:py-6 ${n}`,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-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-black md:h-3 md:w-3"}),jsx(Us,{defaultValue:[12],max:28,min:6,step:1,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:l=>d(Qr(l[0]))}),jsx("div",{className:"h-5 w-5 rounded-full bg-black md:h-7 md:w-7 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-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"COLOR"}),jsxs(Na,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${s===l.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:l.value},onClick:()=>d(la(l.value))},l.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>d(la("#2D2F50"))}),jsxs("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] md:h-10 md:w-10 lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(la(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-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:m},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(fr(l.target.value))})})]})}),jsx("div",{className:"absolute -top-6 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2 md:-top-4",children:jsx("button",{onClick:()=>i(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,{weight:"bold",className:"text-gray-600 md:text-xl"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>i(true),className:"fixed bottom-20 left-1/2 z-50 hidden -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 md:bottom-3 md:flex","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var gm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),cS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),ud=e=>{let o=cS(e);return o.charAt(0).toUpperCase()+o.slice(1)},Gs=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),xm=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var bm={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 ym=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:n="",children:r,iconNode:i,...u},s)=>createElement("svg",{ref:s,...bm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Gs("lucide",n),...!r&&!xm(u)&&{"aria-hidden":"true"},...u},[...i.map(([c,m])=>createElement(c,m)),...Array.isArray(r)?r:[r]]));var js=(e,o)=>{let t=forwardRef(({className:a,...n},r)=>createElement(ym,{ref:r,iconNode:o,className:Gs(`lucide-${gm(ud(e))}`,`lucide-${e}`,a),...n}));return t.displayName=ud(e),t};var hS=[["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"}]],an=js("copy",hS);var gS=[["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"}]],on=js("trash-2",gS);var Sm=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:i})=>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:n,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(an,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),i();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(on,{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 yS=({softDelete:e=false})=>{let o=_e(),t=Re(ya),a=Re(va),n=Re(wr),[r,i]=useState(true),c=(Re(h=>h.canvas.slides.find(p=>p.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),m=()=>{n&&o(lr());},d=h=>{o(cr(h));},l=h=>{o(ur(h));},f=h=>{t.length>1&&o(dr({id:h,softDelete:e}));};return c?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:()=>i(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((h,p)=>jsx(Sm,{slide:h,index:p,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>l(h.id),onDelete:()=>f(h.id)},h.id))}),jsxs("button",{onClick:m,disabled:!n,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${n?"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:()=>i(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 tr=20,AS=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:i})=>jsxs("div",{className:`relative h-[122px] w-[166px] shrink-0 cursor-pointer rounded-lg border bg-[#fafafa] transition-all ${t?"border-[#096b76]":"border-black/10"}`,onClick:n,children:[jsx("div",{className:"absolute top-1 right-1 bottom-1 left-1 overflow-hidden rounded bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"size-full object-contain"}):jsx("div",{className:"flex size-full items-center justify-center",children:jsx("span",{className:"text-xs text-black/20",children:"No preview"})})}),jsx("div",{className:"absolute top-3 left-3 flex h-5 w-5 items-center justify-center rounded-full bg-[#333c48]",children:jsx("span",{className:"text-xs font-bold text-white",children:o+1})}),jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"absolute top-3 right-3 flex cursor-pointer items-center justify-center rounded-md bg-[#3B75E0] p-1.5 text-white transition-colors hover:bg-[#2d5fc0]",title:"Duplicate Page",children:jsx(Copy,{size:18,weight:"bold"})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),i();},className:"absolute right-3 bottom-6 flex cursor-pointer items-center justify-center rounded-md bg-[#E53935] p-1.5 text-white transition-colors hover:bg-[#c62828]",title:"Delete Page",children:jsx(Trash,{size:18,weight:"bold"})}),jsxs("p",{className:"absolute bottom-2 left-3 text-sm text-black/40",children:["Page ",o+1]})]}),PS=({softDelete:e=false})=>{let o=_e(),t=Re(ya),a=Re(va),n=Re(wr),[r,i]=useState(false),[u,s]=useState(false),[c,m]=useState(false),d=useRef(null),h=(Re(S=>S.canvas.slides.find(C=>C.id===S.canvas.currentSlideId))?.videos||[]).some(S=>S.isRecorded&&S.isPlaying),p=()=>{n&&t.length<tr&&o(lr());},y=S=>{o(cr(S));},v=S=>{t.length<tr&&o(ur(S));},g=S=>{t.length>1&&o(dr({id:S,softDelete:e}));},x=()=>{if(!d.current)return;let{scrollLeft:S,scrollWidth:C,clientWidth:w}=d.current,b=C>w+5;s(b&&S>5),m(b&&S<C-w-5);},L=S=>{if(!d.current)return;let C=177,w=S==="left"?d.current.scrollLeft-C:d.current.scrollLeft+C;d.current.scrollTo({left:w,behavior:"smooth"});};return useEffect(()=>{if(r){let S=setTimeout(()=>{requestAnimationFrame(()=>{x();});},350);return ()=>clearTimeout(S)}},[t,r]),useEffect(()=>{let S=d.current;if(!(!S||!r))return S.addEventListener("scroll",x),window.addEventListener("resize",x),()=>{S.removeEventListener("scroll",x),window.removeEventListener("resize",x);}},[r]),h?null:jsx("div",{className:"fixed bottom-0 left-1/2 z-50 flex w-full -translate-x-1/2 flex-col gap-4 md:hidden",children:jsxs(AnimatePresence,{mode:"wait",children:[r&&jsxs(motion.div,{initial:{y:230,opacity:0},animate:{y:0,opacity:1},exit:{y:230,opacity:0},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},onAnimationComplete:()=>x(),className:"border bg-white md:hidden",children:[jsxs("div",{className:"flex w-full items-center justify-between px-4 py-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Cards,{size:24,weight:"fill",className:"text-[#096b76]"}),jsx("span",{className:"text-base font-bold text-black/80",children:"Pages"}),jsxs("span",{className:"text-base font-bold text-black/80",children:["(",t.length,"/",tr,")"]})]}),jsx("button",{onClick:()=>i(false),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretDown,{size:16,weight:"bold",className:"text-black/60"})})]}),jsxs("div",{className:"relative",children:[u&&jsx("button",{onClick:()=>L("left"),className:"absolute top-1/2 left-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll left",children:jsx(CaretLeft,{size:20,weight:"bold",className:"text-black/80"})}),c&&jsx("button",{onClick:()=>L("right"),className:"absolute top-1/2 right-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll right",children:jsx(CaretRight,{size:20,weight:"bold",className:"text-black/80"})}),jsx("div",{ref:d,className:"scrollbar-hide flex gap-[11px] overflow-x-auto px-4 pb-4",children:t.map((S,C)=>jsx(AS,{slide:S,index:C,isSelected:S.id===a,isSingleSlide:t.length===1,onSelect:()=>y(S.id),onDuplicate:()=>v(S.id),onDelete:()=>g(S.id)},S.id))})]}),jsx("button",{onClick:p,disabled:!n||t.length>=tr,className:`px-4 pb-4 text-base font-bold ${n&&t.length<tr?"cursor-pointer text-[#096b76]":"cursor-not-allowed text-black/30"}`,children:"+ Add Page"})]},"open"),!r&&jsxs(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{type:"tween",duration:.2},className:"flex cursor-pointer items-center justify-between gap-2 border border-black/10 bg-white px-4 py-3 shadow-lg md:hidden",children:[jsxs("div",{className:"flex gap-2",children:[jsx(Cards,{size:20,weight:"fill",className:"text-[#096b76]"}),jsxs("span",{className:"text-sm font-bold text-black/80",children:["Pages (",t.length,"/",tr,")"]})]}),jsx("button",{onClick:()=>i(true),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretUp,{size:16,weight:"bold",className:"text-black/60"})})]},"close")]})})},fd=PS;var NS=({stageRef:e,onScreenRecord:o,visible:t=true,config:a={}})=>{let n=_e(),[r,i]=useState(false),[u,s]=useState(false),d=(Re(x=>x.canvas.slides.find(L=>L.id===x.canvas.currentSlideId))?.videos||[]).some(x=>x.isRecorded&&x.isPlaying),l={undo:a.undo??true,redo:a.redo??true,screenRecord:a.screenRecord??true,cameraRecord:a.cameraRecord??true,clear:a.clear??true},f=()=>{o?o():i(true);},h=()=>{s(true);},p=()=>{n(vr());},y=async(x,L)=>{let S=v4(),C=URL.createObjectURL(x),w=document.createElement("video");w.src=C,w.muted=true,w.playsInline=true,w.preload="auto",await new Promise((D,W)=>{let B=setTimeout(()=>W(new Error("Metadata load timeout")),1e4);w.onloadedmetadata=()=>{clearTimeout(B),D();},w.onerror=()=>{clearTimeout(B),W(new Error("Failed to load video"));};});let b=640,k=w.videoWidth/w.videoHeight,M=b,P=M/k;await ra(S,x,L),n(wo({id:S,objectUrl:C,thumbnailDataUrl:L,videoBlob:x,x:100,y:100,width:M,height:P,draggable:true,isPlaying:false,rotation:0,isRecorded:true}));},g=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>n(Io()),enabled:l.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>n(Co()),enabled:l.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:f,enabled:l.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:h,enabled:l.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:p,enabled:l.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}].filter(x=>x.enabled);return !t||d||g.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-x-0 bottom-18 z-50 flex justify-center px-4 md:hidden",children:jsx("div",{className:"flex w-full max-w-md items-center justify-between rounded-md border bg-white px-4 py-1 shadow-lg",children:g.map(x=>jsx("button",{onClick:x.onClick,className:`flex size-10 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-black/5 ${x.colorClass}`,title:x.title,children:jsx(x.icon,{weight:x.iconWeight,className:"text-xl"})},x.key))})}),!o&&r&&e&&jsx(Xa,{onClose:()=>i(false),stageRef:e,onRecordingComplete:y}),u&&jsx(Ns,{onClose:()=>s(false),onRecordingComplete:y})]})},md=NS;var VS=({stageRef:e,onScreenRecord:o,softDelete:t=false,actionButtonsVisible:a=true,actionButtonsConfig:n})=>jsxs(Fragment,{children:[jsx(md,{stageRef:e,onScreenRecord:o,visible:a,config:n}),jsx(fd,{softDelete:t})]}),US=VS;var KS="SchooplaEditorDB",GS=1,Ha="slides",qa="metadata",pd="schoopla_current_slide_id",Pm="presentation_metadata",rn=()=>new Promise((e,o)=>{let t=indexedDB.open(KS,GS);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(Ha)||n.createObjectStore(Ha,{keyPath:"id"}),n.objectStoreNames.contains(qa)||n.createObjectStore(qa,{keyPath:"id"});};}),hd=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await rn(),a=o.transaction([Ha],"readwrite").objectStore(Ha);await new Promise((n,r)=>{let i=a.clear();i.onsuccess=()=>n(!0),i.onerror=()=>r(i.error);});for(let n of e)await new Promise((r,i)=>{let u=a.add(n);u.onsuccess=()=>r(!0),u.onerror=()=>i(u.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},gd=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await rn(),t=e.transaction([Ha],"readonly").objectStore(Ha);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let i=r.result;console.log("\u2705 Loaded from IndexedDB:",i.length,"slides"),i.length>0&&i[0].images&&console.log("First slide images:",i[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(i.length>0?i:null);},r.onerror=()=>{e.close(),n(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}}},_s=async()=>{try{let e=await rn(),o=e.transaction([Ha,qa],"readwrite"),t=o.objectStore(Ha),a=o.objectStore(qa);await new Promise((n,r)=>{let i=t.clear();i.onsuccess=()=>n(!0),i.onerror=()=>r(i.error);}),await new Promise((n,r)=>{let i=a.clear();i.onsuccess=()=>n(!0),i.onerror=()=>r(i.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(pd),localStorage.removeItem("schoopla_presentation_metadata"),await Kc(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},xd=e=>{try{localStorage.setItem(pd,e);}catch(o){console.error("Error saving current slide ID:",o);}},bd=()=>{try{return localStorage.getItem(pd)}catch(e){return console.error("Error loading current slide ID:",e),null}},vd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},yd=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await rn(),a=o.transaction([qa],"readwrite").objectStore(qa);await new Promise((n,r)=>{let i=a.put({id:Pm,...e});i.onsuccess=()=>n(!0),i.onerror=()=>r(i.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);}}},wd=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await rn(),t=e.transaction([qa],"readonly").objectStore(qa);return new Promise((a,n)=>{let r=t.get(Pm);r.onsuccess=()=>{e.close();let i=r.result;if(i){let{id:u,...s}=i;console.log("\u2705 Loaded presentation metadata:",s),a(s);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),n(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 jS=["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"],_S=["canvas/clearCanvas"],XS=["canvas/setPresentationTitle","canvas/setPresentationDescription"],$S=vd((e,o)=>{hd(e),xd(o);},500),YS=vd(e=>{yd(e);},500),ZS=(e,o)=>{hd(e),xd(o);},Sd=false,Em=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Bl(r).catch(i=>{console.error("Error deleting video blob:",i);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,u=e.getState().canvas.slides.find(s=>s.id===r);u&&u.videos&&u.videos.length>0&&u.videos.forEach(s=>{Bl(s.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,i=e.getState(),s=i.canvas.slides.find(c=>c.id===i.canvas.currentSlideId)?.videos.find(c=>c.id===r);s&&s.videoBlob&&setTimeout(()=>{let c=e.getState(),d=c.canvas.slides.find(l=>l.id===c.canvas.currentSlideId)?.videos.find(l=>l.id!==r&&l.x===s.x+20&&l.y===s.y+20);d&&s.videoBlob&&ra(d.id,s.videoBlob,d.thumbnailDataUrl).catch(l=>{console.error("Error saving duplicated video blob:",l);});},0);}let a=o(t),n=e.getState();if(n.canvas.viewerMode)return a;if(t.type&&_S.includes(t.type)){if(!Sd){Sd=true;try{let{slides:r,currentSlideId:i}=n.canvas;ZS(r,i);}finally{setTimeout(()=>{Sd=false;},0);}}}else if(t.type&&jS.includes(t.type)){let{slides:r,currentSlideId:i}=n.canvas;$S(r,i);}else if(t.type&&XS.includes(t.type)){let{presentationMetadata:r}=n.canvas;YS(r);}return a});new QueryClient;var QS=configureStore({reducer:{toolbar:Xl,canvas:Ni},middleware:e=>e({serializableCheck:false}).concat(Em)}),eL=()=>configureStore({reducer:{toolbar:Xl,canvas:Ni},middleware:e=>e({serializableCheck:false})});var tL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2,fileName:r=`slide-${Date.now()}`}=o;try{let i=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:i,quality:a,pixelRatio:n}),s=document.createElement("a");s.download=`${r}.${t}`,s.href=u,document.body.appendChild(s),s.click(),document.body.removeChild(s);}catch(i){throw console.error("Error exporting slide:",i),new Error("Failed to export slide")}},aL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o;return new Promise((r,i)=>{try{let u=t==="png"?"image/png":"image/jpeg",s=e.toDataURL({mimeType:u,quality:a,pixelRatio:n});fetch(s).then(c=>c.blob()).then(c=>r(c)).catch(c=>i(c));}catch(u){i(u);}})},oL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:n})};var rL=(e,o,t)=>{let a=t.x-o.x,n=t.y-o.y;if(a===0&&n===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+n*n,i=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*n)/r)),u=o.x+i*a,s=o.y+i*n;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-s,2))},Ld=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,n=e[0],r=e[e.length-1];for(let i=1;i<e.length-1;i++){let u=rL(e[i],n,r);u>t&&(t=u,a=i);}if(t>o){let i=Ld(e.slice(0,a+1),o),u=Ld(e.slice(a),o);return [...i.slice(0,-1),...u]}return [n,r]},nL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},sL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Dm=(e,o=1.5)=>{if(e.length<=4)return e;let t=nL(e),a=Ld(t,o);return sL(a)},Fm=(e,o=1.5)=>({...e,points:Dm(e.points,o)}),iL=(e,o=1.5)=>e.map(t=>Fm(t,o)),lL=(e,o)=>{let t=e.length/2,a=o.length/2,n=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${n}%`}};var dL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Bm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:n=.85}=o;return new Promise((r,i)=>{let u=new Image;u.onload=()=>{let{width:s,height:c}=u;if(s>t||c>a){let h=s/c;s>c?(s=Math.min(s,t),c=s/h):(c=Math.min(c,a),s=c*h);}let m=document.createElement("canvas");m.width=s,m.height=c;let d=m.getContext("2d");if(!d){i(new Error("Failed to get canvas context"));return}d.drawImage(u,0,0,s,c);let l=dL(e),f=m.toDataURL(l,n);r(f);},u.onerror=i,u.src=e;})};var mo=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let n=0;n<t.length;n++)a[n]=t.charCodeAt(n);return a.buffer},or=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",rr=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",uL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:n=1080,imageQuality:r=.85}=o,i=[],u=0;for(let s of e){let c=[],m=[],d=[];for(let l of s.images){let f=l.src;if(t&&f.startsWith("data:"))try{f=await Bm(f,{maxWidth:a,maxHeight:n,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=mo(f),p=or(f);u+=h.byteLength;let y={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:h,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let v=mo(l.audioData),g=or(l.audioData);u+=v.byteLength,y.audioBuffer=v,y.audioMimeType=g;}c.push(y);}}for(let l of s.videos){let f,h;if(l.videoBlob)f=await l.videoBlob.arrayBuffer(),h=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))f=mo(l.videoData),h=or(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}u+=f.byteLength;let p={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:f,mimeType:h};if(l.audioData&&l.audioData.startsWith("data:")){let y=mo(l.audioData),v=or(l.audioData);u+=y.byteLength,p.audioBuffer=y,p.audioMimeType=v;}m.push(p);}for(let l of s.photoFrames){let f={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 h=mo(l.capturedImageUrl),p=or(l.capturedImageUrl);u+=h.byteLength,f.buffer=h,f.mimeType=p;}if(l.audioData&&l.audioData.startsWith("data:")){let h=mo(l.audioData),p=or(l.audioData);u+=h.byteLength,f.audioBuffer=h,f.audioMimeType=p;}d.push(f);}i.push({...s,images:c,videos:m,photoFrames:d});}return {slides:i,totalSize:u}},cL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},fL=e=>{let o=new FormData,t=e.slides.map((a,n)=>({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,i)=>({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_${n}_image_${i}`,audioFileKey:r.audioBuffer?`slide_${n}_image_${i}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,i)=>({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_${n}_video_${i}`,thumbnailFileKey:`slide_${n}_video_${i}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${n}_video_${i}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,i)=>({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_${n}_photoframe_${i}`:void 0,audioFileKey:r.audioBuffer?`slide_${n}_photoframe_${i}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,n)=>{a.images.forEach((r,i)=>{let u=new Blob([r.buffer],{type:r.mimeType}),s=`${r.id}.${rr(r.mimeType)}`;if(o.append(`slide_${n}_image_${i}`,u,s),r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${rr(r.audioMimeType)}`;o.append(`slide_${n}_image_${i}_audio`,c,m);}}),a.videos.forEach((r,i)=>{let u=new Blob([r.buffer],{type:r.mimeType}),s=`${r.id}.${rr(r.mimeType)}`;if(o.append(`slide_${n}_video_${i}`,u,s),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let c=mo(r.thumbnailDataUrl),m=new Blob([c],{type:"image/jpeg"}),d=`${r.id}_thumbnail.jpg`;o.append(`slide_${n}_video_${i}_thumbnail`,m,d);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${rr(r.audioMimeType)}`;o.append(`slide_${n}_video_${i}_audio`,c,m);}}),a.photoFrames.forEach((r,i)=>{if(r.buffer&&r.mimeType){let u=new Blob([r.buffer],{type:r.mimeType}),s=`${r.id}.${rr(r.mimeType)}`;o.append(`slide_${n}_photoframe_${i}`,u,s);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),s=`${r.id}_audio.${rr(r.audioMimeType)}`;o.append(`slide_${n}_photoframe_${i}_audio`,u,s);}});}),o};var hL=()=>{let e=_e(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let n=await gd(),r=bd(),i=await wd();if(n&&n.length>0){let u=await zc(),s=n.map(m=>{if(m.videos&&m.videos.length>0){let d=m.videos.map(l=>{let f=u.get(l.id);if(f){let h=Gc(f.blob);return {...l,objectUrl:h,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return l});return {...m,videos:d}}return m}),c=r&&s.find(m=>m.id===r)?r:s[0].id;e(vo({slides:s,currentSlideId:c}));}e(i?Fi({title:i.title,description:i.description}):$n(!0));}catch(n){console.error("Error loading persisted slides:",n),e($n(true));}finally{t(false);}})();},[e]),{isLoading:o}};var Nm=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||""})),Hm=new WeakSet,qm=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 ra(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},gL=()=>{let e=_e(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Hm.has(a))return;Hm.add(a);let{slides:n,currentSlideId:r,skipLocalPersistence:i=true}=a;if(i)try{await _s(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,s=Nm(n);e(vo({slides:s,currentSlideId:u})),await qm(s);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:n,currentSlideId:r,skipLocalPersistence:i=true}=a;if(i)try{await _s(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,s=Nm(n);e(vo({slides:s,currentSlideId:u})),await qm(s);},[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{
|
|
21
|
+
*/export{iw as BASIC_EDITOR_TOOLBAR_CONFIG,uS as BottomToolbar,cv as Canvas,nw as DEFAULT_CONTEXT_MENU_CONFIG,Hs as DEFAULT_TOOLBAR_CONFIG,Sg as EditorRoot,md as MobileActionButtons,US as MobileBottomSection,fd as MobilePrevPanel,ld as PublishButton,Xa as ScreenRecorder,yS as SlideNavigation,Jw as Toolbar,oS as TopNavBar,sw as VIEWER_TOOLBAR_CONFIG,Ci as addFillInTheBlanks,mi as addFlashcard,ui as addImage,bi as addImageAnnotation,di as addLine,Ii as addLongAnswer,wi as addMultipleChoice,gi as addPhotoFrame,yi as addPhotoFrameAnnotation,ci as addShape,Li as addShortAnswer,lr as addSlide,fi as addText,Si as addTrueFalse,wo as addVideo,cL as arrayBufferToBase64,Ti as bringToFront,vr as clearCanvas,yp as clearImageAnnotations,_s as clearLocalData,Sp as clearPhotoFrameAnnotations,ii as createEmptySlide,eL as createViewerStore,Wn as deleteFillInTheBlanks,Pn as deleteFlashcard,wn as deleteImage,Xn as deleteLineById,Vn as deleteLongAnswer,Fn as deleteMultipleChoice,Rn as deletePhotoFrame,Tn as deleteShape,Hn as deleteShortAnswer,dr as deleteSlide,Mn as deleteText,On as deleteTrueFalse,In as deleteVideo,zn as duplicateFillInTheBlanks,En as duplicateFlashcard,Sn as duplicateImage,Ei as duplicateLine,Un as duplicateLongAnswer,Bn as duplicateMultipleChoice,Dn as duplicatePhotoFrame,kn as duplicateShape,qn as duplicateShortAnswer,ur as duplicateSlide,An as duplicateText,Nn as duplicateTrueFalse,Cn as duplicateVideo,mr as editFlashcard,Lp as editMultipleChoice,aL as exportSlideAsBlob,tL as exportSlideAsImage,Pi as finalizeDrawing,lL as getCompressionStats,oL as getSlideDataURL,bd as loadCurrentSlideId,gd as loadFromIndexedDB,Fi as loadPresentationMetadata,wd as loadPresentationMetadataFromDB,vo as loadSlides,Zl as mergeToolbarConfig,pi as nextFlashcard,fL as prepareFormData,uL as prepareSlidesForPublishing,hi as previousFlashcard,Co as redo,yn as removeLine,bp as reorderSlides,yd as savePresentationMetadata,de as saveToHistory,ya as selectAllSlides,Bi as selectAllSlidesIncludingInactive,wr as selectCanAddSlide,ge as selectCurrentSlide,va as selectCurrentSlideId,Oi as selectMetadataLoaded,Sr as selectPresentationMetadata,Mp as selectSlideById,Mi as sendToBack,ki as setActivityType,Gn as setAltText,jn as setAudioData,fr as setBackgroundColor,cr as setCurrentSlide,xr as setEditingActivity,yr as setEditingTextId,Cp as setLines,Kn as setLink,$n as setMetadataLoaded,la as setPenColor,Di as setPresentationDescription,Ri as setPresentationTitle,_a as setShowFlashcardForm,ba as setShowMcqForm,yt as setSketchMode,Qr as setStrokeWidth,Qt as setTool,xp as setViewerMode,Dm as simplifyFlatPoints,Fm as simplifyLine,iL as simplifyLines,QS as store,xi as toggleImageDrawingMode,Ai as toggleLock,vi as togglePhotoFrameDrawingMode,Tp as toggleSketchMode,Ga as toggleVideoPlaying,Io as undo,br as updateElementOrder,gr as updateFillInTheBlanks,Lo as updateFlashcard,yo as updateImage,vp as updateImageAnnotation,Ip as updateLastLine,kp as updateLinePosition,_n as updateLineTransform,hr as updateLongAnswer,ga as updateMultipleChoice,ja as updatePhotoFrame,wp as updatePhotoFrameAnnotation,So as updateShape,pr as updateShortAnswer,li as updateSlideThumbnail,Rt as updateText,xa as updateTrueFalse,Ln as updateVideo,be as useDispatch,gL as useInitialSlides,rl as useModalPortal,ee as useSelector,hL as useSlidesPersistence};//# sourceMappingURL=index.js.map
|
|
22
22
|
//# sourceMappingURL=index.js.map
|