@turnix-co/konva-editor 3.0.17 → 3.0.19
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 +2 -1
- 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 be from'react';import be__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,useState,useMemo,createElement,useId,useLayoutEffect}from'react';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import wd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X as X$1,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,ToggleRight,Textbox,TextUnderline,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,Export,CaretLeft,Plus,CaretDown,CaretUp,SidebarSimple,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Pen}from'@phosphor-icons/react/dist/ssr';import {EyeIcon,Stack as Stack$1,X as X$2,DotsSixVertical,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {createPortal}from'react-dom';import yu from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var cd=e=>{throw TypeError(e)};var fd=(e,o,t)=>o.has(e)||cd("Cannot "+t);var j=(e,o,t)=>(fd(e,o,"read from private field"),t?t.call(e):o.get(e)),Pe=(e,o,t)=>o.has(e)?cd("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Ce=(e,o,t,a)=>(fd(e,o,"write to private field"),o.set(e,t),t);var md=(e,o,t,a)=>({set _(r){Ce(e,o,r);},get _(){return j(e,o,a)}});var xe=()=>useDispatch(),Q=e=>useSelector(e),at=xe,ut=Q;var Fn=20,On=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}),En=On("Slide 1"),Om={slides:[En],currentSlideId:En.id,history:{[En.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false},pd=createSlice({name:"canvas",initialState:Om,reducers:{addSlide:e=>{if(e.slides.length>=Fn)return;let o=On(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(i=>i.isActive).length<=1)return;let s=e.slides.findIndex(i=>i.id===t);if(s===-1)return;let n=e.slides[s];if(a?(n.isActive=false,n.updatedAt=Date.now()):(e.slides.splice(s,1),delete e.history[t]),e.currentSlideId===t){let i=e.slides.filter(l=>l.isActive);i.length>0&&(e.currentSlideId=i[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=Fn)return;let t=e.slides.findIndex(s=>s.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);},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:s}=o.payload;switch(r){case "image":let n=t.images.find(x=>x.id===a);n&&(n.timestamp=s);break;case "video":let i=t.videos.find(x=>x.id===a);i&&(i.timestamp=s);break;case "shape":let l=t.shapes.find(x=>x.id===a);l&&(l.timestamp=s);break;case "text":let d=t.texts.find(x=>x.id===a);d&&(d.timestamp=s);break;case "flashcard":let f=t.flashcards.find(x=>x.id===a);f&&(f.timestamp=s);break;case "photoFrame":let u=t.photoFrames.find(x=>x.id===a);u&&(u.timestamp=s);break;case "mcq":let c=t.multipleChoices.find(x=>x.id===a);c&&(c.timestamp=s);break;case "trueFalse":let m=t.trueFalses.find(x=>x.id===a);m&&(m.timestamp=s);break;case "shortAnswer":let p=t.shortAnswers.find(x=>x.id===a);p&&(p.timestamp=s);break;case "longAnswer":let v=t.LongAnswer.find(x=>x.id===a);v&&(v.timestamp=s);break;case "fillInTheBlanks":let h=t.fillInTheBlanks.find(x=>x.id===a);h&&(h.timestamp=s);break;case "line":let b=t.lines.find(x=>x.id===a);b&&(b.timestamp=s);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 s=t.images.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.images.splice(s,1);t.images.push(n);}}else if(r==="video"){let s=t.videos.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.videos.splice(s,1);t.videos.push(n);}}else if(r==="shape"){let s=t.shapes.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.shapes.splice(s,1);t.shapes.push(n);}}else if(r==="flashcard"){let s=t.flashcards.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.flashcards.splice(s,1);t.flashcards.push(n);}}else if(r==="photoFrame"){let s=t.photoFrames.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.photoFrames.splice(s,1);t.photoFrames.push(n);}}else if(r==="text"){let s=t.texts.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.texts.splice(s,1);t.texts.push(n);}}else if(r==="trueFalse"){let s=t.trueFalses.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.trueFalses.splice(s,1);t.trueFalses.push(n);}}else if(r==="shortAnswer"){let s=t.shortAnswers.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.shortAnswers.splice(s,1);t.shortAnswers.push(n);}}else if(r==="fillInTheBlanks"){let s=t.fillInTheBlanks.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.fillInTheBlanks.splice(s,1);t.fillInTheBlanks.push(n);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let s=t.images.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.images.splice(s,1);t.images.unshift(n);}}else if(r==="video"){let s=t.videos.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.videos.splice(s,1);t.videos.unshift(n);}}else if(r==="shape"){let s=t.shapes.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.shapes.splice(s,1);t.shapes.unshift(n);}}else if(r==="flashcard"){let s=t.flashcards.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.flashcards.splice(s,1);t.flashcards.unshift(n);}}else if(r==="photoFrame"){let s=t.photoFrames.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.photoFrames.splice(s,1);t.photoFrames.unshift(n);}}else if(r==="text"){let s=t.texts.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.texts.splice(s,1);t.texts.unshift(n);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload,n=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);n&&(n.locked=!n.locked,"draggable"in n&&(n.draggable=!n.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,link:s}=o.payload,i=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="mcq"?t.multipleChoices:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(l=>l.id===a);i&&(i.link=s,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:s}=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(l=>l.id===a);i&&(i.altText=s,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:s}=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(l=>l.id===a);i&&(i.audioData=s,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(r=>r.id===o.payload);if(a){let r={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(r),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a){let r={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(r),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let r=a.images.map((s,n)=>n).filter(s=>s!==a.currentIndex);if(r.length>0){let s=r[Math.floor(Math.random()*r.length)];a.navigationHistory.push(s),a.currentIndex=s;}}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:Nn,deleteSlide:Vn,duplicateSlide:qn,setCurrentSlide:Hn,updateSlideThumbnail:Un,setBackgroundColor:Wn,reorderSlides:Nm,loadSlides:no,addLine:zn,removeLine:$r,addImage:Gn,updateImage:io,deleteImage:Yr,duplicateImage:Jr,addVideo:Zr,updateVideo:Qr,deleteVideo:es,duplicateVideo:ts,toggleVideoPlaying:_o,addShape:Kn,updateShape:lo,duplicateShape:as,deleteShape:os,addText:_n,updateText:Lt,deleteText:rs,duplicateText:ss,addFlashcard:jn,updateFlashcard:uo,deleteFlashcard:ns,duplicateFlashcard:is,editFlashcard:jo,nextFlashcard:Xn,previousFlashcard:$n,addPhotoFrame:Yn,updatePhotoFrame:Fa,deletePhotoFrame:ls,duplicatePhotoFrame:ds,toggleImageDrawingMode:Jn,addImageAnnotation:Zn,updateImageAnnotation:Vm,clearImageAnnotations:qm,togglePhotoFrameDrawingMode:Qn,addPhotoFrameAnnotation:ei,updatePhotoFrameAnnotation:Hm,clearPhotoFrameAnnotations:Um,addMultipleChoice:ti,updateMultipleChoice:ca,editMultipleChoice:Wm,deleteMultipleChoice:us,duplicateMultipleChoice:cs,addTrueFalse:ai,updateTrueFalse:fa,deleteTrueFalse:fs,duplicateTrueFalse:ms,addShortAnswer:oi,updateShortAnswer:Xo,deleteShortAnswer:ps,duplicateShortAnswer:hs,addLongAnswer:ri,updateLongAnswer:$o,deleteLongAnswer:gs,duplicateLongAnswer:xs,addFillInTheBlanks:si,updateFillInTheBlanks:Yo,deleteFillInTheBlanks:bs,duplicateFillInTheBlanks:vs,setShowMcqForm:ma,setShowFlashcardForm:Ba,setActivityType:ni,setEditingActivity:Jo,bringToFront:ii,sendToBack:li,toggleLock:di,setLink:ys,setAltText:ws,setAudioData:Ss,updateLastLine:zm,finalizeDrawing:ui,setLines:Gm,updateLinePosition:Km,updateLineTransform:Ls,deleteLineById:Is,duplicateLine:ci,updateElementOrder:Zo,clearCanvas:fi,undo:mi,redo:pi,saveToHistory:ce,toggleSketchMode:_m,setSketchMode:ct,setEditingTextId:Qo,setPresentationTitle:hi,setPresentationDescription:gi,loadPresentationMetadata:xi,setMetadataLoaded:Cs}=pd.actions;var hd=e=>e.canvas.slides,co=e=>e.canvas.currentSlideId,he=createSelector([hd,co],(e,o)=>e.find(t=>t.id===o)),fo=createSelector([hd],e=>e.filter(o=>o.isActive!==false)),bi=e=>e.canvas.slides,vi=createSelector([fo],e=>e.length<Fn),jm=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},er=e=>e.canvas.presentationMetadata,yi=e=>e.canvas.metadataLoaded,gd=pd.reducer;var bd=e=>{let o=xe(),t=useRef(null),a=useRef(false),r=Q(m=>m.toolbar.selectedTool),s=Q(m=>m.toolbar.penColor),n=Q(m=>m.toolbar.strokeWidth),i=Q(m=>m.canvas.isSketchMode),l=Q(m=>m.canvas.slides.find(v=>v.id===m.canvas.currentSlideId)?.lines||[]),d=useCallback(m=>{t.current=m;},[]),f=useCallback(m=>{r==="pen"&&t.current&&(o(ce()),t.current.startDrawing(m),a.current=true);},[r,o]),u=useCallback(m=>{!t.current||!a.current||t.current.draw(m);},[]),c=useCallback(()=>{if(!t.current||!a.current)return;let m=t.current.stopDrawing();a.current=false,m&&m.points.length>=4&&o(zn(m)),o(ui()),e?.();},[o,e]);return {lines:l,tool:r,color:s,strokeWidth:n,isSketchMode:i,setCanvasRef:d,startDrawing:f,draw:u,stopDrawing:c}};var Sd=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:r,isSketchMode:s,style:n,xOffset:i=0,yOffset:l=0},d)=>{let f=useRef(null),u=useRef(false),c=useRef([]),m=useRef([]),p=useRef(null),v=useRef(t),h=useRef(a),b=useRef(r),x=useRef(s),g=useRef(i),S=useRef(l);useEffect(()=>{v.current=t,h.current=a,b.current=r,x.current=s,g.current=i,S.current=l;},[t,a,r,s,i,l]);let k=useCallback(()=>{let L=f.current;if(!L)return;let y=L.getContext("2d");y&&y.clearRect(0,0,L.width,L.height);},[]),C=useCallback(()=>{let L=f.current,y=m.current;if(!L||y.length<1)return;let M=L.getContext("2d");if(!M)return;if(M.clearRect(0,0,L.width,L.height),v.current==="eraser"?(M.globalCompositeOperation="destination-out",M.fillStyle="rgba(0,0,0,1)"):(M.globalCompositeOperation="source-over",M.fillStyle=h.current),y.length===1){M.beginPath(),M.arc(y[0].x,y[0].y,b.current/2,0,Math.PI*2),M.fill();return}let D=wd(y,{size:b.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:q=>q,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(D.length<2)){M.beginPath(),M.moveTo(D[0][0],D[0][1]);for(let q=1;q<D.length;q++)M.lineTo(D[q][0],D[q][1]);M.closePath(),M.fill();}},[]);return useImperativeHandle(d,()=>({startDrawing:L=>{u.current=true;let y={x:L.x-g.current,y:L.y-S.current};c.current=[{x:L.x,y:L.y}],m.current=[y],p.current=L,C();},draw:L=>{if(!u.current||!p.current)return;let y=L.x-p.current.x,M=L.y-p.current.y;if(Math.sqrt(y*y+M*M)<2)return;let D={x:L.x-g.current,y:L.y-S.current};c.current.push({x:L.x,y:L.y}),m.current.push(D),p.current=L,C();},stopDrawing:()=>{if(!u.current)return null;if(u.current=false,c.current.length<2)return c.current=[],m.current=[],p.current=null,k(),null;let y=wd(c.current,{size:b.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:O=>O,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(O=>[O[0],O[1]]),M={tool:v.current,points:y,color:h.current,strokeWidth:b.current,isSketch:true};return c.current=[],m.current=[],p.current=null,k(),M},clear:()=>{k(),c.current=[],m.current=[],p.current=null,u.current=false;},isDrawing:()=>u.current,getCanvasElement:()=>f.current}),[k,C]),useEffect(()=>{let L=f.current;L&&(L.width=e,L.height=o);},[e,o]),jsx("canvas",{ref:f,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...n}})});Sd.displayName="DirectDrawingCanvas";var Ld=Sd;var Cd=e=>{let o=xe(),a=Q(he)?.images||[],r=useRef(new Map),s=useRef(new Map),n=useRef(new Set);useEffect(()=>{let f=new Set(a.map(u=>u.id));n.current.forEach(u=>{if(!f.has(u)){let c=s.current.get(u);c&&(c.src="",s.current.delete(u)),r.current.delete(u);}}),n.current=f;},[a]),useEffect(()=>()=>{s.current.forEach(f=>{f.src="";}),s.current.clear(),r.current.clear();},[]);let i=useCallback(f=>{if(s.current.has(f.id))return s.current.get(f.id);let u=new window.Image;return (f.src.startsWith("http://")||f.src.startsWith("https://"))&&(u.crossOrigin="anonymous"),u.src=f.src,s.current.set(f.id,u),u},[]),l=useCallback((f,u)=>{let c=f.target,m=c.id();a.find(v=>v.id===m)&&(o(io({id:m,x:c.x(),y:c.y(),width:c.width(),height:c.height(),rotation:c.rotation()})),u?.());},[a,o]),d=useCallback((f,u)=>{let c=u.target,m=r.current.get(f);if(!m){console.error("\u274C Image node not found for id:",f);return}let p=c.scaleX(),v=c.scaleY(),h=c.rotation(),b=m.width(),x=m.height(),g=Math.max(5,b*p),S=Math.max(5,x*v);c.scaleX(1),c.scaleY(1),m.width(g),m.height(S),o(io({id:f,width:g,height:S,x:c.x(),y:c.y(),rotation:h})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:i,imageRefs:r,handleDragEnd:l,handleImageTransformEnd:d}};var kd=e=>{let o=useDispatch(),t=useSelector(he),a=useRef(new Map),r=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),s=useCallback((i,l)=>{let d=l.target,f=d.scaleX(),u=d.scaleY(),c=d.rotation(),m=Math.max(5,d.width()*f),p=Math.max(5,d.height()*u);d.scaleX(1),d.scaleY(1),d.width(m),d.height(p),o(ca({id:i,width:m,height:p,x:d.x(),y:d.y(),rotation:c})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:s,mcqRefs:a,handleDragEnd:(i,l)=>{o(ca({id:l,x:i.target.x(),y:i.target.y()})),e?.();}}};var Md=e=>{let o=useDispatch(),t=useSelector(he),a=useRef(new Map),r=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),s=useCallback((i,l)=>{let d=l.target,f=d.scaleX(),u=d.scaleY(),c=d.rotation(),m=Math.max(5,d.width()*f),p=Math.max(5,d.height()*u);d.scaleX(1),d.scaleY(1),d.width(m),d.height(p),o(fa({id:i,width:m,height:p,x:d.x(),y:d.y(),rotation:c})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:s,handleTrueFalseDragEnd:(i,l)=>{o(fa({id:l,x:i.target.x(),y:i.target.y()})),e?.();},trueFalseRefs:a}};var Td=e=>{let o=xe(),a=Q(he)?.videos||[],r=useRef(new Map),s=useCallback(l=>{o(_o(l));},[o]),n=useCallback((l,d)=>{let f=d.target;o(Qr({id:l,x:f.x(),y:f.y()})),e?.();},[o,e]),i=useCallback((l,d)=>{let f=d.target,u=f.scaleX(),c=f.scaleY(),m=f.rotation(),p=Math.max(5,f.width()*u),v=Math.max(5,f.height()*c);f.scaleX(1),f.scaleY(1),f.width(p),f.height(v),o(Qr({id:l,width:p,height:v,x:f.x(),y:f.y(),rotation:m})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:r,handleVideoClick:s,handleVideoDragEnd:n,handleVideoTransformEnd:i}};var Dd=e=>{let o=xe(),a=Q(he)?.shapes||[],r=useRef(new Map),s=useRef(new Map),[n,i]=useState(false),l=useCallback((f,u)=>{let c=u.target;o(lo({id:f,x:c.x(),y:c.y()})),e?.();},[o,e]),d=useCallback((f,u)=>{let c=u.target,m=a.find(g=>g.id===f);if(!m)return;let p=c.scaleX(),v=c.scaleY(),h=m.type?.toLowerCase();h==="arrow"||h==="line"||(c.scaleX(1),c.scaleY(1));let x={id:f,x:c.x(),y:c.y(),width:Math.max(5,c.width()*p),height:Math.max(5,c.height()*v),rotation:c.rotation()};switch(h){case "circle":x.radius=c.width()*p/2;break;case "star":x.innerRadius=c.width()*p/4,x.outerRadius=c.width()*p/2;break;case "triangle":x.radius=c.width()*p/2;break;case "ellipse":x.radiusX=c.width()*p/2,x.radiusY=c.height()*v/2;break;case "polygon":x.radius=c.width()*p/2;break;case "ring":let g=p;x.innerRadius=m.innerRadius&&m.innerRadius*g,x.outerRadius=m.outerRadius&&m.outerRadius*g;break;case "wedge":x.radius=m.radius&&m.radius*p;break;case "arc":x.innerRadius=m.innerRadius&&m.innerRadius*p,x.outerRadius=m.outerRadius&&m.outerRadius*p;break;case "arrow":case "line":{x.scaleX=p,x.scaleY=v,delete x.width,delete x.height;break}}o(lo(x)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:r,isDragging:n,loadedShapesRef:s,handleShapeDragEnd:l,handleShapeResizeEnd:d}};var Ed=(e,o)=>{let t=at(),r=Q(he)?.texts||[],s=useRef(new Map),[n,i]=useState(null),[l,d]=useState("");return {texts:r,textRefs:s,handleDragEnd:(h,b)=>{let x=h.target;t(ce()),t(Lt({id:b,x:x.x(),y:x.y()})),e();},handleTransformEnd:h=>{let b=s.current.get(h);if(!b)return;let x=b.scaleX(),g=b.scaleY(),S=r.find(C=>C.id===h);if(!S)return;let k=(x+g)/2;b.scaleX(1),b.scaleY(1),t(ce()),t(Lt({id:h,x:b.x(),y:b.y(),width:Math.max(5,(S.width||100)*x),height:Math.max(5,(S.height||50)*g),fontSize:Math.round(Math.max(8,S.fontSize*k)),rotation:b.rotation()})),e();},handleDoubleClick:h=>{let b=r.find(x=>x.id===h);b&&!b.locked&&(i(h),d(b.text));},startEditing:h=>{let b=r.find(x=>x.id===h);b&&!b.locked&&(i(h),d(b.text));},editingTextId:n,editingValue:l,handleEditingChange:h=>{d(h);},finishEditing:()=>{if(n){let h=s.current.get(n),b=r.find(g=>g.id===n);t(ce());let x={id:n,text:l};if(b&&(b.fontWeight!==void 0&&(x.fontWeight=b.fontWeight),b.fontStyle!==void 0&&(x.fontStyle=b.fontStyle),b.textDecoration!==void 0&&(x.textDecoration=b.textDecoration)),o?.current&&l.trim()){let g=o.current,S=g.offsetWidth,k=g.offsetHeight,C=1;if(h){let W=h.getStage();W&&(C=W.scaleX());}let L=14,y=(S-L)/C,M=(k-L)/C,O=l.split(`
|
|
3
|
-
`).length,q=r.find(W=>W.id===n)?.fontSize||24,A=O*q*1.2+10;x.width=Math.max(200,y),x.height=Math.max(50,M,A);}else if(h&&l.trim()){let g=h.text(),S=h.width();h.text(l),h.width(void 0);let k=h.width(),C=h.height();h.text(g),h.width(S),x.width=Math.max(200,k+20),x.height=Math.max(50,C+20);}t(Lt(x)),i(null),d(""),t(Qo(null)),e();}}}};var Fd=e=>{let o=useDispatch(),a=useSelector(he)?.shortAnswers||[],r=useRef(new Map),s=useCallback((n,i)=>{let l=n.target;o(Xo({id:i,x:l.x(),y:l.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:s}};var Bd=e=>{let o=useDispatch(),t=useSelector(he),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((s,n)=>{let i=s.target;o($o({id:n,x:i.x(),y:i.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var Nd=e=>{let o=xe(),a=Q(he)?.flashcards||[],r=useRef(new Map),s=useRef(new Map),n=useCallback((u,c)=>{if(s.current.has(c))return s.current.get(c);let m=new window.Image;return m.src=u,s.current.set(c,m),m},[]),i=useCallback((u,c)=>{let m=u.target,p=m.id();a.find(h=>h.id===p)&&(o(uo({id:p,x:m.x(),y:m.y()})),c?.());},[a,o]),l=useCallback((u,c)=>{let m=c.target,p=m.scaleX(),v=m.scaleY(),h=m.rotation(),b=Math.max(50,m.width()*p),x=Math.max(50,m.height()*v);m.scaleX(1),m.scaleY(1),m.width(b),m.height(x),o(uo({id:u,width:b,height:x,x:m.x(),y:m.y(),rotation:h})),m.getLayer()?.batchDraw(),e?.();},[o,e]),d=useCallback(u=>{o(Xn(u)),e?.();},[o,e]),f=useCallback(u=>{o($n(u)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:r,handleDragEnd:i,handleFlashcardTransformEnd:l,handleNext:d,handlePrevious:f}};var Hd=e=>{let o=xe(),a=Q(he)?.photoFrames||[],r=useRef(new Map),[s,n]=useState(new Map),i=useCallback((m,p)=>{console.log("handleDragEnd"),o(Fa({id:p,x:m.target.x(),y:m.target.y()})),e?.();},[o,e]),l=useCallback((m,p)=>{let v=p.target,h=v.scaleX(),b=v.scaleY(),x=v.rotation(),g=a.find(C=>C.id===m);if(!g)return;let S=Math.max(100,g.width*h),k=Math.max(100,g.height*b);v.scaleX(1),v.scaleY(1),o(Fa({id:m,width:S,height:k,x:v.x(),y:v.y(),rotation:x})),v.getLayer()?.batchDraw(),e?.();},[o,e,a]),d=useCallback(async m=>{try{let p=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(v=>{let h=new Map(v);return h.set(m,p),h}),o(Fa({id:m,isCapturing:!0})),e?.(),p}catch(p){return console.error("Error accessing camera:",p),null}},[o,e]),f=useCallback(m=>{let p=s.get(m);p&&(p.getTracks().forEach(v=>v.stop()),n(v=>{let h=new Map(v);return h.delete(m),h}),o(Fa({id:m,isCapturing:false})),e?.());},[s,o,e]),u=useCallback((m,p)=>{let v=document.createElement("canvas");v.width=p.videoWidth,v.height=p.videoHeight;let h=v.getContext("2d");if(h){h.drawImage(p,0,0,v.width,v.height);let b=v.toDataURL("image/jpeg",.8);return o(Fa({id:m,capturedImageUrl:b,isCapturing:false})),f(m),e?.(),b}return null},[o,f,e]),c=useRef(s);return useEffect(()=>{c.current=s;},[s]),useEffect(()=>()=>{c.current.forEach(m=>{m.getTracks().forEach(p=>p.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:i,handlePhotoFrameTransformEnd:l,startCamera:d,stopCamera:f,capturePhoto:u,cameraStreams:s}};var Ud=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((s,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),a=useCallback((s,n,i,l,d,f,u,c=[])=>{if(e.current){if(s&&!c.find(v=>v.id===s)?.isPlaying){let v=n.get(s)||i.get(s)||l.get(s)||d.get(s)||f.get(s)||(u?u.get(s):null);if(v){e.current.boundBoxFunc(t),e.current.nodes([v]),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 wp=(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])},Kd=(e,o)=>{let t=at(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let n=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});n&&n.startsWith("data:")&&t(Un({id:a.current,thumbnail:n}));}catch(n){console.warn("Could not generate thumbnail (likely CORS issue with images):",n);}},[o,t]),s=wp(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var Lp=e=>e.flatMap(o=>[o[0],o[1]]),Ms=(e,o)=>{let t=wd(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 Lp(t)};var _d=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[s,n]=useState(null),i=Q(g=>g.toolbar.selectedTool),l=Q(g=>g.toolbar.penColor),d=Q(g=>g.toolbar.strokeWidth),f=Q(g=>g.canvas.isSketchMode),u=Q(g=>g.canvas.slides.find(k=>k.id===g.canvas.currentSlideId)?.images.find(k=>k.id===e)),c=u?.annotations||[],m=u?.isDrawingMode||false,p=u?.width||1,v=u?.height||1,h=useCallback(g=>{if(i!=="pen"&&i!=="eraser")return;t.current=true,a.current=false,r.current=[{x:g.x,y:g.y}];let S=g.x/p,k=g.y/v;n({tool:i,points:[S,k],color:l,strokeWidth:d/p,isSketch:f});},[i,l,d,f,p,v]),b=useCallback(g=>{if(!t.current||!s)return;a.current=true;let S=r.current[r.current.length-1];if(Math.sqrt(Math.pow(g.x-S.x,2)+Math.pow(g.y-S.y,2))<2)return;r.current.push({x:g.x,y:g.y});let C;if(f)C=Ms(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((y,M)=>M%2===0?y/p:y/v);else {let L=g.x/p,y=g.y/v;C=[...s.points,L,y];}n(L=>L?{...L,points:C}:null);},[f,d,s,p,v]),x=useCallback(()=>{t.current&&(s&&s.points.length>0&&o(Zn({imageId:e,line:s})),n(null),t.current=false,a.current=false,r.current=[]);},[o,e,s]);return {annotations:c,activeLine:s,isDrawingMode:m,startDrawing:h,draw:b,stopDrawing:x,tool:i}};var Yd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:s,onContextMenu:n})=>{let{annotations:i,activeLine:l,stopDrawing:c,tool:m}=_d(e.id);useEffect(()=>{let x=t.current.get(e.id);x&&(x.width()!==e.width||x.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:x.width(),konvaHeight:x.height()}),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[c,p]);let v=x=>{{s(e.id);return}},h=x=>{return;},b=x=>{};return jsxs(Group,{listening:m!=="pen"&&m!=="eraser",children:[jsx(Image$1,{id:e.id,ref:x=>{if(x){t.current.set(e.id,x),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw();let g=x.getStage()?.container();if(g){let S=k=>{let C=x.getStage()?.getPointerPosition();if(C){let L={x:e.x,y:e.y,width:e.width,height:e.height};C.x>=L.x&&C.x<=L.x+L.width&&C.y>=L.y&&C.y<=L.y+L.height&&n(k,e.id,"image");}};g.addEventListener("contextmenu",S),x._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",S);};}}else {let g=t.current.get(e.id);g?._contextMenuCleanup&&g._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:m!=="pen"&&m!=="eraser",onDragEnd:a,onTransformEnd:x=>r(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...m!=="pen"&&m!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onTouchStart:v,onMouseMove:h,onTouchMove:h,onMouseUp:b,onTouchEnd:b}:{}}),i?.map((x,g)=>{let S=x.points.map((C,L)=>L%2===0?C*e.width+e.x:C*e.height+e.y),k=x.strokeWidth*e.width;return jsx(Line,{points:S,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},g)}),l&&jsx(Line,{points:l.points.map((x,g)=>g%2===0?x*e.width+e.x:x*e.height+e.y),stroke:l.tool==="eraser"?"white":l.color,strokeWidth:l.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:l.tool==="eraser"?"destination-out":"source-over",fill:l.isSketch?l.color:void 0,closed:l.isSketch,listening:false},"active")]})});Yd.displayName="ImageWithDrawing";var Mi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:s,onContextMenu:n})=>jsx(Fragment,{children:e.map(i=>{let l=o(i);return l?jsx(Yd,{img:i,loadedImage:l,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:s,onContextMenu:n},i.id):null})}));Mi.displayName="ImageLayer";var Ep=({src:e,x:o,id:t,y:a,width:r,height:s,isSelected:n,rotation:i=0,onTransformEnd:l,onDragEnd:d})=>{let f=xe(),u=useRef(null),c=m=>{f(_o(m));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:s,rotation:i,onDragEnd:d,onTransformEnd:l,children:[jsx(Rect,{width:r,height:s,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${s}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:u,src:e,controls:true,autoPlay:true,onClick:()=>c(t),onSeeking:m=>m.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Jd=Ep;var Up=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,nodeRef:n})=>{let[i,l]=useState(null),d=useSelector(v=>v.toolbar.selectedTool),f=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let v=new window.Image;v.src=e.thumbnailDataUrl,v.onload=()=>{l(v);};}},[e.thumbnailDataUrl]),!i)return null;let u=e.width/2,c=e.height/2,m=Math.min(e.width,e.height)*.08,p=Math.max(40,Math.min(m,80));return jsxs(Group,{draggable:!f,listening:!f,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...f?{}:{onDragEnd:a,onTransformEnd:r},ref:v=>{if(n(v),v){let h=v.getStage()?.container();if(h){let b=x=>{let g=v.getStage()?.getPointerPosition();if(g){let S={x:e.x,y:e.y,width:e.width,height:e.height};g.x>=S.x&&g.x<=S.x+S.width&&g.y>=S.y&&g.y<=S.y+S.height&&s(x);}};h.addEventListener("contextmenu",b),v._contextMenuCleanup=()=>{h.removeEventListener("contextmenu",b);};}}},children:[jsx(Image$1,{image:i,width:e.width,height:e.height,listening:!f,...f?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:u,y:c,radius:p,fill:"white",listening:!f,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...f?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:u,y:c,radius:p*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!f,...f?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:u+p*.1,y:c,sides:3,radius:p*.35,fill:"white",rotation:90,listening:!f,...f?{}:{onClick:t,onTap:t}})]})},Qd=Up;var Pi=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:s,onContextMenu:n})=>jsx(Fragment,{children:e.map(i=>jsxs(be__default.Fragment,{children:[jsx(Qd,{video:i,isSelected:!i.isPlaying&&o===i.id,onClick:()=>a(i.id),onDragEnd:l=>r(i.id,l),onTransformEnd:l=>s(i.id,l),onContextMenu:l=>n(l,i.id,"video"),nodeRef:l=>{l?t.current.set(i.id,l):t.current.delete(i.id);}}),i.isPlaying&&(()=>{let l=i.x,d=i.y;if(i.isRecorded){let f=typeof window<"u"?window.innerWidth:i.width,u=typeof window<"u"?window.innerHeight:i.height;l=(f-i.width)/2,d=(u-i.height)/2;}return jsx(Jd,{id:i.id,src:i.objectUrl,x:l,y:d,width:i.width,height:i.height,isSelected:false,rotation:i.rotation,onTransformEnd:f=>s(i.id,f),onDragEnd:f=>r(i.id,f)})})()]},i.id))}));Pi.displayName="VideoLayer";var Di=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:s,onContextMenu:n})=>{let i=useSelector(d=>d.toolbar.selectedTool),l=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map((d,f)=>{let u=d.id||f,c={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!l,listening:!l,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},radius:d.radius||d.width/2,width:d.width,height:d.width},u);case "star":return jsx(Star,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "triangle":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},sides:3,radius:d.radius||d.width/2},u);case "polygon":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},sides:d.sides||6,radius:d.radius||d.width/2},u);case "ellipse":return jsx(Ellipse,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},u);case "ring":return jsx(Ring,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "wedge":return jsx(Wedge,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},radius:d.radius||d.width/2,angle:d.angle||60},u);case "arrow":return jsx(Arrow,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "line":return jsx(Line,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "arc":return jsx(Arc,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},u);case "rectangle":default:return jsx(Rect,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{s?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");}},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},u)}})})});Di.displayName="ShapeLayer";var au=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:s,onDoubleClick:n,editingTextId:i})=>{let l=useSelector(f=>f.toolbar.selectedTool),d=l==="pen"||l==="eraser";return jsx(Fragment,{children:e.map(f=>{let u=f.id===i,c=f.fontWeight==="bold",m=c?Math.max(1,f.fontSize/25):0;return jsx(Text,{id:f.id,ref:p=>{p?o.current.set(f.id,p):o.current.delete(f.id);},text:f.text,x:f.x,y:f.y,width:f.width,height:f.height,rotation:f.rotation,draggable:!f.locked&&!u&&!d,listening:!d,fontSize:f.fontSize,fontFamily:f.fontFamily,fontStyle:f.fontStyle,fontWeight:f.fontWeight,textDecoration:f.textDecoration,fill:f.fill,stroke:c?f.fill:void 0,strokeWidth:m,align:f.align,wrap:"none",lineHeight:1.2,opacity:u?0:1,visible:!u,...d?{}:{onClick:()=>r(f.id),onTap:()=>r(f.id),onDblClick:()=>n(f.id),onDblTap:()=>n(f.id),onDragEnd:p=>t(p,f.id),onTransformEnd:()=>a(f.id),onContextMenu:p=>{p.evt.preventDefault();let v=p.evt;s(v,f.id,"text");}}},f.id)})})};var fh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,onNext:n,onPrevious:i,nodeRef:l})=>{let[d,f]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let h=new window.Image;h.src=e.images[e.currentIndex],h.onload=()=>{f(h);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let u=8,c=2,m=Math.min(e.width,e.height)*.08,p=Math.max(16,Math.min(m,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:r,ref:h=>{if(l(h),h){let b=h.getStage()?.container();if(b){let x=g=>{let S=h.getStage()?.getPointerPosition();if(S){let k={x:e.x,y:e.y,width:e.width,height:e.height};S.x>=k.x&&S.x<=k.x+k.width&&S.y>=k.y&&S.y<=k.y+k.height&&s(g);}};b.addEventListener("contextmenu",x),h._contextMenuCleanup=()=>{b.removeEventListener("contextmenu",x);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:u,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:u,stroke:"#E5E7EB",strokeWidth:c,listening:false}),jsx(Image$1,{x:c+4,y:c+4,image:d,width:e.width-(c+4)*2,height:e.height-(c+4)*2,cornerRadius:u-c,onClick:t,onTap:t}),jsx(Rect,{x:c,y:e.height-50,width:e.width-c*2,height:50,cornerRadius:[0,0,u-c,u-c],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:v+p,y:e.height/2,onClick:h=>{h.cancelBubble=true,i();},onTap:h=>{h.cancelBubble=true,i();},children:[jsx(Circle,{radius:p,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-v-p,y:e.height/2,onClick:h=>{h.cancelBubble=true,n();},onTap:h=>{h.cancelBubble=true,n();},children:[jsx(Circle,{radius:p,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},su=fh;var Fi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:s,onNext:n,onPrevious:i,onContextMenu:l})=>jsx(Fragment,{children:e.map(d=>jsx(su,{flashcard:d,isSelected:t===d.id,onClick:()=>s(d.id),onDragEnd:a,onTransformEnd:f=>r(d.id,f),onContextMenu:f=>l(f,d.id,"flashcard"),onNext:()=>n(d.id),onPrevious:()=>i(d.id),nodeRef:f=>{f?o.current.set(d.id,f):o.current.delete(d.id);}},d.id))}));Fi.displayName="FlashcardLayer";var iu=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[s,n]=useState(null);Q(g=>g.toolbar.selectedTool);let l=Q(g=>g.toolbar.penColor),d=Q(g=>g.toolbar.strokeWidth),f=Q(g=>g.canvas.isSketchMode),u=Q(g=>g.canvas.slides.find(k=>k.id===g.canvas.currentSlideId)?.photoFrames.find(k=>k.id===e)),c=u?.annotations||[],m=u?.isDrawingMode||false,p=u?.width||1,v=u?.height||1,h=useCallback(g=>{if(!m)return;t.current=true,a.current=false,r.current=[{x:g.x,y:g.y}];let S=g.x/p,k=g.y/v;n({tool:"pen",points:[S,k],color:l,strokeWidth:d/p,isSketch:f});},[m,l,d,f,p,v]),b=useCallback(g=>{if(!t.current||!s)return;a.current=true;let S=r.current[r.current.length-1];if(Math.sqrt(Math.pow(g.x-S.x,2)+Math.pow(g.y-S.y,2))<2)return;r.current.push({x:g.x,y:g.y});let C;if(f)C=Ms(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((y,M)=>M%2===0?y/p:y/v);else {let L=g.x/p,y=g.y/v;C=[...s.points,L,y];}n(L=>L?{...L,points:C}:null);},[f,d,s,p,v]),x=useCallback(()=>{t.current&&(s&&s.points.length>0&&o(ei({frameId:e,line:s})),n(null),t.current=false,a.current=false,r.current=[]);},[o,e,s]);return {annotations:c,activeLine:s,isDrawingMode:m,startDrawing:h,draw:b,stopDrawing:x}};var yh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,onStartCamera:n,onCapture:i,cameraStream:l,nodeRef:d})=>{let[f,u]=useState(null),[c,m]=useState(null),p=useRef(null),v=useRef(null),h=useRef(null),b=useRef(null),x=useRef(0),g=33,S=useSelector(V=>V.toolbar.selectedTool),k=S==="pen"||S==="eraser",{annotations:C,activeLine:L,isDrawingMode:y,startDrawing:M,draw:O,stopDrawing:D}=iu(e.id);useEffect(()=>{if(!y)return;let V=()=>{D();},_=()=>{D();};return window.addEventListener("mouseup",V),window.addEventListener("touchend",_),()=>{window.removeEventListener("mouseup",V),window.removeEventListener("touchend",_);}},[D,y]),useEffect(()=>{if(e.capturedImageUrl){let V=new window.Image;V.src=e.capturedImageUrl,V.onload=()=>{u(V);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&l){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),v.current||(v.current=document.createElement("canvas"));let V=p.current,_=v.current;V.srcObject=l;let H=()=>{_.width=V.videoWidth||640,_.height=V.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",_.width,_.height);let K=te=>{if(te-x.current<g){h.current=requestAnimationFrame(K);return}x.current=te;let Z=_.getContext("2d");if(Z&&V.readyState===V.HAVE_ENOUGH_DATA){Z.drawImage(V,0,0,_.width,_.height);let J=_.toDataURL("image/jpeg",.6),le=new window.Image;le.onload=()=>{m(le);},le.src=J;}h.current=requestAnimationFrame(K);};h.current=requestAnimationFrame(K);};return V.onloadedmetadata=H,V.readyState>=V.HAVE_METADATA&&H(),V.play().catch(K=>console.error("Error playing video:",K)),()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null);}}return ()=>{m(null),b.current&&(b.current.src="");}},[e.isCapturing,l]);let q=()=>{p.current&&e.isCapturing&&i(p.current);},U=V=>{if(e.capturedImageUrl){if(!y){t();return}let _=V.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);M(Z);}V.cancelBubble=true;}else t();},A=V=>{if(!y||!e.capturedImageUrl)return;let _=V.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);O(Z);}},W=()=>{!y||!e.capturedImageUrl||D();},E=e.isCapturing?c:f,ne=Math.min(e.width,e.height)*.12,N=Math.max(25,Math.min(ne,50)),re=e.width/2,G=e.height/2;return jsxs(Group,{id:e.id,draggable:!y&&!k,listening:true,x:e.x,y:e.y,...k?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:V=>{if(d(V),V){let _=V.getStage()?.container();if(_){let H=K=>{let te=V.getStage()?.getPointerPosition();if(te){let Z={x:e.x,y:e.y,width:e.width,height:e.height};te.x>=Z.x&&te.x<=Z.x+Z.width&&te.y>=Z.y&&te.y<=Z.y+Z.height&&s(K);}};_.addEventListener("contextmenu",H),V._contextMenuCleanup=()=>{_.removeEventListener("contextmenu",H);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:E?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),E&&jsx(Image$1,{image:E,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:U,onTap:U,onMouseDown:U,onTouchStart:U,onMouseMove:A,onTouchMove:A,onMouseUp:W,onTouchEnd:W,...k?{}:{onDragEnd:a,onTransformEnd:r}}),C?.map((V,_)=>{let H=V.points.map((te,Z)=>Z%2===0?te*e.width:te*e.height),K=V.strokeWidth*e.width;return jsx(Line,{points:H,stroke:V.tool==="eraser"?"white":V.color,strokeWidth:K,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},_)}),L&&jsx(Line,{points:L.points.map((V,_)=>_%2===0?V*e.width:V*e.height),stroke:L.tool==="eraser"?"white":L.color,strokeWidth:L.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:L.tool==="eraser"?"destination-out":"source-over",fill:L.isSketch?L.color:void 0,closed:L.isSketch,listening:false},"active"),!E&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:G-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:re-N+6,y:G-60,width:N*1.6,height:N*1.6,radius:N,fill:"white",cornerRadius:8,listening:true,onClick:V=>{V.cancelBubble=true,e.isCapturing?q():n();},onTap:V=>{V.cancelBubble=true,e.isCapturing?q():n();}}),jsx(Html,{groupProps:{x:re-12,y:G-40,width:N*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:V=>{V.stopPropagation(),e.isCapturing?q():n();}})})]}),jsx(Text,{x:0,y:G,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:G+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:re-24,y:G+104,width:N*1.6,height:N*1.6,radius:N,fill:"#096B76",cornerRadius:N,listening:true,onClick:V=>{V.cancelBubble=true,e.isCapturing?q():n();},onTap:V=>{V.cancelBubble=true,e.isCapturing?q():n();}}),jsx(Html,{groupProps:{x:re-8,y:G+120,width:N*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:V=>{V.stopPropagation(),e.isCapturing?q():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:re-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:V=>{V.stopPropagation(),q();},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})})})})]})]})},cu=yh;var Hi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:s,onStartCamera:n,onCapture:i,cameraStreams:l,onContextMenu:d})=>jsx(Fragment,{children:e.map(f=>jsx(cu,{photoFrame:f,isSelected:t===f.id,onClick:()=>s(f.id),onDragEnd:u=>a(u,f.id),onTransformEnd:u=>r(f.id,u),onContextMenu:u=>d(u,f.id,"photoFrame"),onStartCamera:()=>n(f.id),onCapture:u=>i(f.id,u),cameraStream:l.get(f.id),nodeRef:u=>{u?o.current.set(f.id,u):o.current.delete(f.id);}},f.id))}));Hi.displayName="PhotoFrameLayer";var hu=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:s="",isDrawingMode:n,menuRef:i})=>{useEffect(()=>{let u=m=>{i?.current&&!i.current.contains(m.target)&&a();},c=m=>{m.key==="Escape"&&a();};return document.addEventListener("mousedown",u),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",u),document.removeEventListener("keydown",c);}},[a]);let l=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:n?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(c=>!(c.showForTypes&&!c.showForTypes.includes(r)||c.hideForTypes&&c.hideForTypes.includes(r))),[r,n]),d=(u,c)=>{u==="order"||u==="lock"?t(u,c):(t(u),a());},f=jsx("div",{ref:i,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:l.map((u,c)=>jsxs("button",{onClick:m=>d(u.action,m),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${u.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[u.icon,jsx("span",{className:`font-medium ${u.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:u.label})]}),u.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},c))})});return createPortal(f,document.body)};var gu=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let s=n=>{r.current&&!r.current.contains(n.target)&&a();};return document.addEventListener("mousedown",s),()=>{document.removeEventListener("mousedown",s);}},[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((s,n)=>jsx("button",{onClick:()=>{s.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:s.label})},n))})})};var xu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:s})=>{let[n,i]=useState(a),l=useRef(null);useEffect(()=>{l.current?.focus();},[]);let d=()=>{r(n),s();},f=c=>{c.key==="Enter"?d():c.key==="Escape"&&s();};return createPortal(jsx("div",{className:"konva-editor-root",children:jsx("div",{className:"fixed inset-0 z-9999 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:s,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:l,type:"text",value:n,onChange:c=>i(c.target.value),onKeyDown:f,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:s,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:d,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})})}),document.body)};var Es=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),s=useRef(null);useEffect(()=>{let f=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let n=f=>{f.preventDefault(),o(a);},i=(f,u,c)=>{c/=100;let m=u*Math.min(c,1-c)/100,p=v=>{let h=(v+f/30)%12,b=c-m*Math.max(Math.min(h-3,9-h,1),-1);return Math.round(255*b).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},d=jsx("div",{className:"konva-editor-root",children:jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black/50",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:s,className:"max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:n,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:f=>r(f.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:f=>r(f.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:f=>{let u=parseInt(f.target.value),c=i(u,100,50);r(c);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"].map(f=>jsx("button",{type:"button",onClick:()=>r(f),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===f.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:f},title:f},f))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})})});return createPortal(d,document.body)};var rg=({imageSrc:e,onCrop:o})=>{let[t]=yu(e),a=useRef(null),r=useRef(null),s=useRef(null),n=useMemo(()=>{if(!t)return {width:600,height:400};let p=Math.min(600/t.width,400/t.height);return {width:t.width*p,height:t.height*p}},[t]),i=useMemo(()=>{let c=n.width*.5,m=n.height*.5,p=(n.width-c)/2,v=(n.height-m)/2;return {x:p,y:v,width:c,height:m}},[n]),[l,d]=useState(i);useEffect(()=>{d(i);},[i]),useEffect(()=>{s.current&&r.current&&(s.current.nodes([r.current]),s.current.getLayer()?.batchDraw());},[l]),useEffect(()=>{o(l.x,l.y,l.width,l.height);},[l,o]);let f=()=>{let c=r.current;if(!c)return;let m=c.scaleX(),p=c.scaleY();c.scaleX(1),c.scaleY(1),d({x:c.x(),y:c.y(),width:Math.max(20,c.width()*m),height:Math.max(20,c.height()*p)});},u=()=>{let c=r.current;c&&d({x:c.x(),y:c.y(),width:c.width(),height:c.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:l.x,y:l.y,width:l.width,height:l.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:l.x,y:l.y,width:l.width,height:l.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:u,onTransformEnd:f,dragBoundFunc:c=>{let m=Math.max(0,Math.min(c.x,n.width-l.width)),p=Math.max(0,Math.min(c.y,n.height-l.height));return {x:m,y:p}}}),jsx(Transformer,{ref:s,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:(c,m)=>m.width<20||m.height<20||m.x<0||m.y<0||m.x+m.width>n.width||m.y+m.height>n.height?c:m})]})})},wu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,s]=useState({x:0,y:0,width:0,height:0}),[n]=yu(e);return useEffect(()=>{let f=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]),createPortal(jsx("div",{className:"konva-editor-root",children:jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black/50",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(rg,{imageSrc:e,onCrop:(f,u,c,m)=>{s({x:f,y:u,width:c,height:m});}})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:()=>{if(!n)return;let c=Math.min(600/n.width,400/n.height),m=r.x/c,p=r.y/c,v=r.width/c,h=r.height/c,b=document.createElement("canvas");b.width=v,b.height=h;let x=b.getContext("2d");if(!x)return;x.drawImage(n,m,p,v,h,0,0,v,h);let g=b.toDataURL("image/png");o(g);},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})})}),document.body)};var lr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[r,s]=useState(false),[n,i]=useState(null),[l,d]=useState(0),[f,u]=useState(true),c=useRef(null),m=useRef([]),p=useRef(null),v=useRef(null),h=useRef(null),b=useRef(null),x=useRef(null),g=useRef(null);useEffect(()=>()=>{h.current&&cancelAnimationFrame(h.current),p.current&&clearInterval(p.current),v.current&&v.current.getTracks().forEach(y=>y.stop());},[]);let S=async()=>{try{let y,M=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let A=o.current.getLayers();console.log("Konva layers:",A.length),A.forEach((_,H)=>{let K=_.getChildren();console.log(`Layer ${H} children count:`,K.length);});let W=document.createElement("canvas");W.width=o.current.width(),W.height=o.current.height();let E=W.getContext("2d",{willReadFrequently:!1});if(!E){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",W.width,"x",W.height),x.current=W;let ne=()=>{if(E.clearRect(0,0,W.width,W.height),A.forEach(_=>{let H=_.getCanvas()._canvas;H&&E.drawImage(H,0,0);}),a?.current){let _=a.current;E.drawImage(_,0,0);}};g.current=ne,o.current.draw(),ne(),await new Promise(_=>setTimeout(_,100)),console.log("Creating captureStream..."),y=W.captureStream(30),console.log("Canvas stream created, tracks:",y.getTracks().length);let re=y.getVideoTracks()[0];re&&console.log("Video track:",re.label,"state:",re.readyState);let G=0,V=()=>{ne(),o?.current&&(o.current.getLayers().forEach(H=>{H.batchDraw();}),G++,G%60===0&&console.log("Drawing frame:",G)),h.current=requestAnimationFrame(V);};V();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(A){console.warn("Microphone access denied:",A);}let O=[...y.getVideoTracks()];M&&O.push(...M.getAudioTracks());let D=new MediaStream(O);v.current=D;let q="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?q="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?q="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?q="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(q="video/webm;codecs=vp8"),console.log("Using mimeType:",q);let U=new MediaRecorder(D,{mimeType:q,videoBitsPerSecond:25e5});c.current=U,m.current=[],U.ondataavailable=A=>{console.log("Data available, size:",A.data.size),A.data.size>0&&m.current.push(A.data);},U.onstop=()=>{console.log("Recording stopped, chunks:",m.current.length);let A=new Blob(m.current,{type:q});console.log("Final blob size:",A.size),o?.current&&g.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(E=>{E.batchDraw();}),g.current(),b.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",b.current.length)),D.getTracks().forEach(W=>W.stop()),p.current&&clearInterval(p.current),h.current&&(cancelAnimationFrame(h.current),h.current=null),i(A);},U.onerror=A=>{console.error("MediaRecorder error:",A);},console.log("Starting recording..."),U.start(1e3),s(!0),d(0),p.current=setInterval(()=>{d(A=>A+1);},1e3);}catch(y){console.error("Error starting screen recording:",y),alert("Failed to start recording. Please ensure you granted permission.");}},k=()=>{c.current&&r&&(console.log("Stopping recording, state:",c.current.state),c.current.state!=="inactive"&&(c.current.requestData(),setTimeout(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop();},100)),s(false));},C=()=>{if(n){let y=URL.createObjectURL(n),M=document.createElement("a");M.href=y,M.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(y);}},L=y=>{let M=Math.floor(y/60),O=y%60;return `${M.toString().padStart(2,"0")}:${O.toString().padStart(2,"0")}`};return r?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:L(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick: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"]})]}):jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!n&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>u(!f),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${f?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:f?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick: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"]})]})]}),n&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(n),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",L(l)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&n&&b.current&&(t(n,b.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:C,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),d(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})})};var Iu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let[s,n]=useState(false),[i,l]=useState(null),[d,f]=useState(false),[u,c]=useState(0),m=useRef(null),p=useRef([]),v=useRef(null),h=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(M=>M.blob()).then(M=>l(M)).catch(M=>console.error("Error loading audio:",M));},[o,i]);let b=async()=>{try{let M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),O=new MediaRecorder(M);m.current=O,p.current=[],O.ondataavailable=D=>{D.data.size>0&&p.current.push(D.data);},O.onstop=()=>{let D=new Blob(p.current,{type:"audio/webm"});l(D),M.getTracks().forEach(q=>q.stop()),v.current&&clearInterval(v.current);},O.start(),n(!0),c(0),v.current=setInterval(()=>{c(D=>D+1);},1e3);}catch(M){console.error("Error starting audio recording:",M),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{m.current&&s&&(m.current.stop(),n(false));},g=()=>{if(i){let M=URL.createObjectURL(i),O=new Audio(M);h.current=O,O.onended=()=>{f(false),URL.revokeObjectURL(M);},O.play(),f(true);}},S=()=>{h.current&&(h.current.pause(),h.current.currentTime=0,f(false));},k=async()=>{if(i){let M=new FileReader;M.onloadend=()=>{let O=M.result;t(O),r();},M.readAsDataURL(i);}},C=()=>{l(null),a();},L=M=>{let O=Math.floor(M/60),D=M%60;return `${O.toString().padStart(2,"0")}:${D.toString().padStart(2,"0")}`};if(s){let M=jsx("div",{className:"konva-editor-root",children:jsx("div",{className:"pointer-events-none fixed inset-0 z-9999",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:L(u)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:x,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]})})});return createPortal(M,document.body)}let y=jsx("div",{className:"konva-editor-root",children:jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:b,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:d?S:g,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),d?"Playing...":"Play Audio"]}),jsx("button",{onClick:C,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(y,document.body)};var Ct=({audioData:e,x:o,y:t,width:a,scale:r=1,offsetX:s=0,offsetY:n=0,containerTop:i=90,containerRight:l=320})=>{let[d,f]=useState(false),u=useRef(null),c=v=>{if(v.stopPropagation(),d&&u.current)u.current.pause(),u.current.currentTime=0,f(false);else {let h=new Audio(e);u.current=h,h.onended=()=>{f(false);},h.onerror=()=>{console.error("Error playing audio"),f(false);},h.play(),f(true);}},m=(o+a)*r+s-15,p=t*r+n+i-15;return jsx("button",{onClick:c,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${d?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${m}px`,top:`${p}px`,width:"30px",height:"30px",zIndex:99},title:d?"Stop Audio":"Play Audio",children:d?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var Mu=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=Q(he),s=useMemo(()=>{if(!r)return [];let h=[];return r.images?.forEach(b=>{h.push({id:b.id,type:"image",name:"Image",timestamp:b.timestamp||0});}),r.videos?.forEach(b=>{h.push({id:b.id,type:"video",name:"Video",timestamp:b.timestamp||0});}),r.shapes?.forEach(b=>{h.push({id:b.id,type:"shape",name:`${b.type} Shape`,timestamp:b.timestamp||0});}),r.texts?.forEach(b=>{h.push({id:b.id,type:"text",name:b.text.substring(0,20)+(b.text.length>20?"...":""),timestamp:b.timestamp||0});}),r.flashcards?.forEach(b=>{h.push({id:b.id,type:"flashcard",name:`Flashcard (${b.images.length} images)`,timestamp:b.timestamp||0});}),r.photoFrames?.forEach(b=>{h.push({id:b.id,type:"photoFrame",name:"Photo Frame",timestamp:b.timestamp||0});}),r.multipleChoices?.forEach(b=>{h.push({id:b.id,type:"mcq",name:"Multiple Choice",timestamp:b.timestamp||0});}),r.trueFalses?.forEach(b=>{h.push({id:b.id,type:"trueFalse",name:"True/False",timestamp:b.timestamp||0});}),r.shortAnswers?.forEach(b=>{h.push({id:b.id,type:"shortAnswer",name:"Short Answer",timestamp:b.timestamp||0});}),r.LongAnswer?.forEach(b=>{h.push({id:b.id,type:"longAnswer",name:"Long Answer",timestamp:b.timestamp||0});}),r.fillInTheBlanks?.forEach(b=>{h.push({id:b.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:b.timestamp||0});}),r.lines?.forEach(b=>{b.id&&h.push({id:b.id,type:"line",name:"Drawn Line",timestamp:b.timestamp||0});}),h.sort((b,x)=>x.timestamp-b.timestamp)},[r]),[n,i]=useState(s),[l,d]=useState(false);useEffect(()=>{l||i(s);},[s]);let f=h=>{let b="h-5 w-5";switch(h){case "image":return jsx(Image$3,{className:b});case "video":return jsx(VideoCamera,{className:b});case "shape":return jsx(Shapes$1,{className:b});case "text":return jsx(TextT,{className:b});case "flashcard":return jsx(Cards$1,{className:b});case "photoFrame":return jsx(FrameCorners,{className:b});case "line":return jsx(Pen,{className:b});default:return jsx(Question,{className:b})}},m=h=>{d(true),i(h);},p=()=>{d(false);let h=Date.now();n.forEach((b,x)=>{let g=h-x;a(Zo({id:b.id,type:b.type,newTimestamp:g}));});},v=jsxs("div",{className:"konva-editor-root",children:[jsx("div",{className:"fixed inset-0 z-9999 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-10000 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$2,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:n.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:n,onReorder:m,className:"space-y-1",children:n.map(h=>{let b=h.id===e;return jsxs(Reorder.Item,{value:h,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${b?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(h.id,h.type),className:`font-medium ${b?"text-[#096B76]":"text-[#00000099]"}`,children:h.name})}),jsx("div",{className:`${b?"text-[#096B76]":"text-[#00000099]"}`,children:f(h.type)})]},h.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[n.length," Layers"]})]})]})]});return createPortal(v,document.body)};var Tu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:s})=>{let n=useSelector(G=>G.toolbar.selectedTool),i=n==="pen"||n==="eraser",[l,d]=useState(new Set),[f,u]=useState(false),[c,m]=useState(null),p=useRef(null);useEffect(()=>{let G=p.current;if(G)return a.current.set(e.id,G),()=>{a.current.delete(e.id);}},[e.id]);let v=new Set(e.data.responseOptions.correctIndex),h=v.size>1,b=G=>{f||d(h?V=>{let _=new Set(V);return _.has(G)?_.delete(G):_.add(G),_}:new Set([G]));},x=()=>{l.size>0&&u(true);},g=()=>{u(false),d(new Set);},S=l.size===v.size&&Array.from(l).every(G=>v.has(G)),k=Array.from(l).filter(G=>v.has(G)),C=h&&k.length>0&&!S,L=()=>S?"\u2713 Correct! Great job! \u{1F389}":C?`\u26A0 Partially correct (${k.length}/${v.size})`:"\u2717 Try again!",y=()=>S?{bg:"#dcfce7",text:"#166534"}:C?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},M=55,O=8,D=24,q=60,U=60,A=h&&!f?25:0,W=e.data.feedbackMode==="practice"?48:0,E=12,ne=q+A+(f?U:0),N=e.data.responseOptions.options.length*(M+O),re=ne+N+E+W+D;return jsxs(Group,{ref:p,name:"mcq-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:r,onClick:G=>t(e.id),onTap:G=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:re,width:e.width,onTransformEnd:G=>o(e.id,G),onContextMenu:G=>{G.cancelBubble=true,s(G.evt,e.id,"mcq");}}),jsx(Text,{x:D+8,y:D,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-D*2,listening:false}),h&&!f&&e.data.feedbackMode==="practice"?jsx(Text,{x:D,y:D+35,text:`Select ${v.size} answers (${l.size}/${v.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-D*2,listening:false}):null,f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:D+24,y:q+A,width:e.width-D*2-40,height:U-20,fill:y().bg,cornerRadius:8}),jsx(Text,{x:D,y:q+A,width:e.width-D*2,height:U-20,text:L(),fontSize:16,fontStyle:"bold",fill:y().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((G,V)=>{let _=v.has(V),H=l.has(V),K=ne+V*(M+O),te="#e5e7eb",Z="#ffffff",J="#111827";return f&&_?(te="#22c55e",Z="#dcfce7",J="#1B9D2C"):f&&H&&!_?(te="#ef4444",Z="#fee2e2",J="#ef4444"):H&&(te="#096B76",Z="#ECFFF8",J="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:D+12,y:K+(M-20)/2,width:20,height:20,fill:H?"#096B76":"white",stroke:H?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:h?4:10,onClick:le=>{le.cancelBubble=true,b(V);},onTap:le=>{le.cancelBubble=true,b(V);}}),H&&jsx(Text,{x:D+12,y:K+(M-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:D+44,y:K,width:e.width-D*2-60,height:M,fill:Z,stroke:te,strokeWidth:2,cornerRadius:8,onClick:le=>{le.cancelBubble=true,b(V);},onTap:le=>{le.cancelBubble=true,b(V);}}),jsx(Text,{x:D+60,y:K,width:e.width-D*2-80,height:M,text:G,fontSize:16,fill:J,verticalAlign:"middle",listening:false})]},V)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:ne+e.data.responseOptions.options.length*(M+O)+12,children:[jsxs(Group,{onMouseDown:G=>{G.cancelBubble=true,m("check");},onMouseUp:G=>{G.cancelBubble=true,m(null),x();},onMouseLeave:G=>{G.cancelBubble=true,m(null);},onTouchStart:G=>{G.cancelBubble=true,m("check");},onTouchEnd:G=>{G.cancelBubble=true,m(null),x();},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:D+14,width:(e.width-D*2-24)/(f?2:1),height:48,fill:l.size===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:D+14,width:(e.width-D*2-24)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-D*2)/2+8,onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),g();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),g();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:D,width:(e.width-D*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:D,width:(e.width-D*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Tu.displayName="MultipleChoice";var Au=Tu;var Gi=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:r})=>{let s=useDispatch(),n=useSelector(H=>H.toolbar.selectedTool),i=n==="pen"||n==="eraser",[l,d]=useState(false),[f,u]=useState(new Set),[c,m]=useState(false),[p,v]=useState(false),[h,b]=useState(0),x=340,g=100,S=window.innerWidth*.4,k=window.innerHeight*.5,C=x+20,L=g+60,y=S-40,M=k-300,O=useRef(null);useEffect(()=>{let H=O.current;if(H)return r.current.set(e.id,H),()=>{r.current.delete(e.id);}},[e.id]);let D=H=>{s(ca({id:e.id,x:H.target.x(),y:H.target.y()}));},q=H=>{let K=H.target,te=K.x(),Z=K.y(),J=window.innerWidth*.2,Ie=te+J>C&&te<C+y&&Z+50>L&&Z<L+M;d(Ie);},U=(H,K)=>{let te=K.target,Z=te.x(),J=te.y(),le=window.innerWidth*.2,Y=Z+le>C&&Z<C+y&&J+50>L&&J<L+M;u(Y?Me=>new Set(Me).add(H):Me=>{let Be=new Set(Me);return Be.delete(H),Be}),d(false);},A=()=>{m(true);},W=()=>{m(false),u(new Set),b(H=>H+1);},E=new Set(e.data.responseOptions.correctIndex),ne=f.size===E.size&&Array.from(f).every(H=>E.has(H)),N=Array.from(f).filter(H=>E.has(H)),re=N.length>0&&!ne,G=()=>ne?"\u2713 Correct! Great job!":re?`\u26A0 Partially correct (${N.length}/${E.size})`:"\u2717 Try again!",V=()=>ne?{bg:"#dcfce7",text:"#166534"}:re?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},_=()=>c?ne?"#4CAF50":re?"#f59e0b":"#ef4444":l?"#4CAF50":"#075560";return jsxs(Group,{ref:O,name:"mcq-element",width:S,height:k,draggable:!i,listening:!i,...i?{}:{onClick:H=>a(e.id),onTap:H=>a(e.id),onContextMenu:H=>{H.evt.preventDefault(),o(H.evt,e.id,"mcq");}},children:[jsxs(Group,{x,y:g,rotation:e.rotation,onDragEnd:D,children:[jsx(Rect,{fill:"white",stroke:l?"#4CAF50":"#e5e7eb",strokeWidth:l?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?k-100:k-50,width:S,shadowColor:l?"#4CAF50":"transparent",shadowBlur:l?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:80,width:y,height:M,fill:"#EBF6F7",stroke:_(),strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:M+18,width:y-5,height:60,fill:V().bg,cornerRadius:8}),jsx(Text,{x:20,y:M+20,width:y,height:60,text:G(),fontSize:18,fontStyle:"bold",fill:V().text,align:"center",verticalAlign:"middle"})]}),f.size===0&&!c&&jsx(Text,{x:20,y:60,width:y,height:M-60,text:E.size>1?`Drop ${E.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:c?k-200:k-160,children:[jsxs(Group,{onMouseDown:()=>{v(true),A();},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),A();},onTouchEnd:()=>v(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:y}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:y,height:40,align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{y:50,onMouseDown:W,onTouchStart:W,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:y}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:y,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((H,K)=>{let te=K%2,Z=Math.floor(K/2),J=window.innerWidth*.2,le=50,Ie=10,Y=f.has(K),Me=E.has(K),Be=c&&Y,Rt="transparent";return Be?Rt=Me?"#4CAF50":"#ef4444":Y&&(Rt="#4CAF50"),jsxs(Group,{x:340+te*(J+Ie),y:g+k-80+Z*(le+Ie),draggable:!c,onDragMove:q,onDragEnd:ao=>U(K,ao),opacity:c&&!Y?.5:1,children:[jsx(Rect,{width:J-20,height:le,fill:"white",stroke:Rt,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:J-20,height:le,text:H,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${K}-${h}`)})]})};Gi.displayName="MultipleChoiceDragAndDrop";var Pu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Au,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:i=>r(i,n.id),onContextMenu:s},n.id):jsx(Gi,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:s},n.id))});var Du=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s})=>{let n=useSelector(E=>E.toolbar.selectedTool),i=n==="pen"||n==="eraser",[l,d]=useState(null),[f,u]=useState(false),[c,m]=useState(null),p=useRef(null);useEffect(()=>{let E=p.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id]);let v=()=>{l!==null&&u(true);},h=()=>{u(false),d(null);},b=e.data.responseOptions.correctAnswer,x=l===b,g=E=>{f||d(E);},S=()=>x?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",k=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},C=70,L=12,y=24,M=60,O=60,D=e.data.feedbackMode==="practice"?48:0,q=12,U=M+(f?O:0),A=2*(C+L),W=U+A+q+D+y;return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:E=>s(E,e.id),onClick:E=>t(e.id),onTap:E=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:W-20,width:e.width,onTransformEnd:E=>o(e.id,E),onContextMenu:E=>{E.cancelBubble=true,r(E.evt,e.id,"trueFalse");}}),jsx(Text,{x:y,y,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:y,y:M,width:e.width-y*2,height:O-10,fill:k().bg,cornerRadius:8}),jsx(Text,{x:y,y:M,width:e.width-y*2,height:O-10,text:S(),fontSize:16,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((E,ne)=>{let N=b===E.value,re=l===E.value,G=(e.width-y*3)/2,V=y+ne*(G+y),_=U,H=E.value===true,K=H?"#10b981":"#ef4444",te="#ffffff",Z="#ffffff",J="#e5e7eb";return f&&(N?(Z=H?"#f0fdf4":"#fef2f2",J=H?"#86efac":"#fecaca"):re&&!N&&(Z="#fee2e2",J="#ef4444")),re&&!f&&(J="#096B76",Z="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:V,y:_,width:G,height:C+50,fill:Z,stroke:J,strokeWidth:2,cornerRadius:12,onClick:le=>{le.cancelBubble=true,g(E.value);},onTap:le=>{le.cancelBubble=true,g(E.value);}}),jsx(Circle,{x:V+G/2,y:_+40,radius:28,fill:K,listening:false}),H?jsx(Text,{x:V+G/2-14,y:_+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:V+G/2-14,y:_+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:V,y:_+85,width:G,height:30,text:E.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},E.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:U+2*(C+L),children:[jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,m("check");},onMouseUp:E=>{E.cancelBubble=true,m(null),v();},onMouseLeave:E=>{E.cancelBubble=true,m(null);},onTouchStart:E=>{E.cancelBubble=true,m("check");},onTouchEnd:E=>{E.cancelBubble=true,m(null),v();},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:y,width:(e.width-y*2-8)/(f?2:1),height:48,fill:l===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:(e.width-y*2-8)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-y*2)/2+8,onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),h();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),h();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:y,width:(e.width-y*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:(e.width-y*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Du.displayName="TrueFalse";var Ru=Du;var ax="#FFFFFF",ji=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),r=useSelector(K=>K.toolbar.selectedTool),s=r==="pen"||r==="eraser",[n,i]=useState(false),[l,d]=useState(null),[f,u]=useState(false),[c,m]=useState(false),[p,v]=useState(0),[h,b]=useState(false),x=340,g=100,S=window.innerWidth*.4,k=window.innerHeight*.5,C=S-40,L=k-300,y=20,M=60,O=C,D=L,q=S*.2-40,U=50,A=useRef(null),W=K=>{a(fa({id:e.id,x:K.target.x(),y:K.target.y()}));},E=K=>{let te=K.target,Z=te.x(),J=te.y(),le=Math.max(0,Math.min(Z+q,y+O)-Math.max(Z,y)),Ie=Math.max(0,Math.min(J+U,M+D)-Math.max(J,M)),Y=le*Ie,Me=q*U;i(Y/Me>=.5);},ne=(K,te)=>{let Z=te.target,J=Z.x(),le=Z.y(),Ie=Math.max(0,Math.min(J+q,y+O)-Math.max(J,y)),Y=Math.max(0,Math.min(le+U,M+D)-Math.max(le,M)),Me=Ie*Y,Be=q*U;if(Me/Be>=.5)d(K);else return;i(false);},N=()=>{u(true);},re=()=>{u(false),d(null),v(K=>K+1);},G=e.data.responseOptions.correctAnswer,V=l===G,_=()=>V?"\u2713 Correct! Great job!":"\u2717 Try again!",H=()=>V?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:A,name:"trueFalse-element",width:S,height:k,draggable:!s,listening:!s,...s?{}:{onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:g,rotation:e.rotation,onDragEnd:W,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:f?k:e.data.feedbackMode==="practice"?k-50:k-100,width:S,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?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:C,height:L,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:C,height:60,fill:H().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:C,height:60,text:_(),fontSize:18,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle"})]}),l===null&&!f&&jsx(Text,{x:20,y:60,width:C,height:L-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:()=>{l!==null&&(m(true),N());},onMouseUp:()=>m(false),onMouseLeave:()=>m(false),onTouchStart:()=>{l!==null&&(m(true),N());},onTouchEnd:()=>m(false),scaleX:c?.95:1,scaleY:c?.95:1,children:[jsx(Rect,{fill:l===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:C}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:C,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:re,onTouchStart:re,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:C}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:C,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((K,te)=>{let Z=window.innerWidth*.2,J=50,le=10,Ie=l===K.value,Y=G===K.value,Me=f&&Ie,Be="transparent";return Me?Be=Y?"#4CAF50":"#ef4444":Ie&&(Be="#4CAF50"),jsxs(Group,{x:16+te*(Z+le),y:g+k-300,draggable:!f,onDragMove:E,onDragEnd:Rt=>ne(K.value,Rt),opacity:f&&!Ie?.5:1,children:[jsx(Rect,{width:Z-40,height:J,fill:"#075560",stroke:Be,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z-40,height:J,text:K.label,fontSize:18,fontStyle:"bold",fill:ax,align:"center",verticalAlign:"middle",listening:false})]},`${K.value}-${p}`)})]})})};ji.displayName="TrueFalseDragAndDrop";var Eu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Ru,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r},n.id):jsx(ji,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s},n.id))});var ga=new WeakMap,Co=new WeakMap,pr={current:[]},$i=false,mr=0,fr=new Set,qs=new Map;function Fu(e){let o=Array.from(e).sort((t,a)=>t instanceof Vt&&t.options.deps.includes(a)?1:a instanceof Vt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(pr.current.includes(t))continue;pr.current.push(t),t.recompute();let a=Co.get(t);if(a)for(let r of a){let s=ga.get(r);s&&Fu(s);}}}function sx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function nx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Hs(e){if(mr>0&&!qs.has(e)&&qs.set(e,e.prevState),fr.add(e),!(mr>0)&&!$i)try{for($i=!0;fr.size>0;){let o=Array.from(fr);fr.clear();for(let t of o){let a=qs.get(t)??t.prevState;t.prevState=a,sx(t);}for(let t of o){let a=ga.get(t);a&&(pr.current.push(t),Fu(a));}for(let t of o){let a=ga.get(t);if(a)for(let r of a)nx(r);}}}finally{$i=false,pr.current=[],qs.clear();}}function pt(e){mr++;try{e();}finally{if(mr--,mr===0){let o=fr.values().next().value;o&&Hs(o);}}}function Bu(e){return typeof e=="function"}var _t=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,s;this.listeners.add(a);let n=(s=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:s.call(r,a,this);return ()=>{this.listeners.delete(a),n?.();}},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):Bu(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),Hs(this);}};var Vt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),r=new Array(t);for(let s=0;s<t;s++){let n=this.options.deps[s];a[s]=n.prevState,r[s]=n.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 s of this.options.deps)s instanceof e&&s.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let s=0;s<r.length;s++)if(r[s]!==a[s]){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 s=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),s?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof _t){let a=ga.get(t);a||(a=new Set,ga.set(t,a)),a.add(this);let r=Co.get(this);r||(r=new Set,Co.set(this,r)),r.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof _t){let a=ga.get(t);a&&a.delete(this);let r=Co.get(this);r&&r.delete(t);}}};function ix(e){return typeof e=="function"}function Yi(e,...o){return ix(e)?e(...o):e}function Ou(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var xa,rt,et,hr,ba,qa,Zt,ko,gr,Us,xr,Mo,Ha=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Pe(this,xa,true);Pe(this,rt);Pe(this,et);Pe(this,hr);Pe(this,ba);Pe(this,qa);Pe(this,Zt);Pe(this,ko);Pe(this,gr,0);Pe(this,Us,5);Pe(this,xr,()=>{this.debugLog("Connected to event bus"),Ce(this,qa,true),this.debugLog("Emitting queued events",j(this,ba)),j(this,ba).forEach(o=>this.emitEventToBus(o)),Ce(this,ba,[]),this.stopConnectLoop(),j(this,et).call(this).removeEventListener("tanstack-connect-success",j(this,xr));});Pe(this,Mo,()=>{if(j(this,et).call(this).addEventListener("tanstack-connect-success",j(this,xr)),j(this,gr)<j(this,Us)){md(this,gr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}j(this,et).call(this).removeEventListener("tanstack-connect",j(this,Mo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Ce(this,rt,o),Ce(this,xa,a),Ce(this,et,this.getGlobalTarget),Ce(this,hr,t),this.debugLog(" Initializing event subscription for plugin",j(this,rt)),Ce(this,ba,[]),Ce(this,qa,false),Ce(this,Zt,null),Ce(this,ko,r);}startConnectLoop(){j(this,Zt)!==null||j(this,qa)||(this.debugLog(`Starting connect loop (every ${j(this,ko)}ms)`),Ce(this,Zt,setInterval(j(this,Mo),j(this,ko))));}stopConnectLoop(){j(this,Zt)!==null&&(clearInterval(j(this,Zt)),Ce(this,Zt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){j(this,hr)&&console.log(`\u{1F334} [tanstack-devtools:${j(this,rt)}-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,rt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});j(this,et).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{j(this,et).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!j(this,xa)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!j(this,qa)){this.debugLog("Bus not available, will be pushed as soon as connected"),j(this,ba).push({type:`${j(this,rt)}:${o}`,payload:t,pluginId:j(this,rt)}),typeof CustomEvent<"u"&&(j(this,Mo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${j(this,rt)}:${o}`,payload:t,pluginId:j(this,rt)})}on(o,t){let a=`${j(this,rt)}:${o}`;if(!j(this,xa))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=s=>{this.debugLog("Received event from bus",s.detail),t(s.detail);};return j(this,et).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{j(this,et).call(this).removeEventListener(a,r);}}onAll(o){if(!j(this,xa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return j(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!j(this,xa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;j(this,rt)&&r.pluginId!==j(this,rt)||o(r);};return j(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}};xa=new WeakMap,rt=new WeakMap,et=new WeakMap,hr=new WeakMap,ba=new WeakMap,qa=new WeakMap,Zt=new WeakMap,ko=new WeakMap,gr=new WeakMap,Us=new WeakMap,xr=new WeakMap,Mo=new WeakMap;var Ji=class extends Ha{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Nu=(e,o)=>{Zi.emit(e,o);},Zi=new Ji;function Vu(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var lx={enabled:true,leading:true,trailing:true,wait:0},va,ht,Ua,Wa,za,To,Ws=class{constructor(o,t){Pe(this,va);Pe(this,ht);Pe(this,Ua);Pe(this,Wa);Pe(this,za);Pe(this,To);this.fn=o,this.store=new _t(Vu()),this.setOptions=a=>{this.options={...this.options,...a},j(this,Ua).call(this)||this.cancel();},Ce(this,ht,a=>{this.store.setState(r=>{let s={...r,...a},{isPending:n}=s;return {...s,status:j(this,Ua).call(this)?n?"pending":"idle":"disabled"}}),Nu("Throttler",this);}),Ce(this,Ua,()=>!!Yi(this.options.enabled,this)),Ce(this,Wa,()=>Yi(this.options.wait,this)),this.maybeExecute=(...a)=>{j(this,ht).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),s=r-this.store.state.lastExecutionTime,n=j(this,Wa).call(this);if(this.options.leading&&s>=n)j(this,za).call(this,...a);else if(j(this,ht).call(this,{lastArgs:a}),!j(this,va)&&this.options.trailing){let i=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,l=n-i;j(this,ht).call(this,{isPending:true}),Ce(this,va,setTimeout(()=>{let{lastArgs:d}=this.store.state;d!==void 0&&j(this,za).call(this,...d);},l));}},Ce(this,za,(...a)=>{if(!j(this,Ua).call(this))return;this.fn(...a);let r=Date.now(),s=r+j(this,Wa).call(this);j(this,To).call(this),j(this,ht).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:s,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||j(this,ht).call(this,{nextExecutionTime:void 0});},j(this,Wa).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&j(this,za).call(this,...this.store.state.lastArgs);},Ce(this,To,()=>{j(this,va)&&(clearTimeout(j(this,va)),Ce(this,va,void 0));}),this.cancel=()=>{j(this,To).call(this),j(this,ht).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{j(this,ht).call(this,Vu());},this.key=Ou(t.key),this.options={...lx,...t},j(this,ht).call(this,this.options.initialState??{}),Zi.on("d-Throttler",a=>{a.payload.key===this.key&&(j(this,ht).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};va=new WeakMap,ht=new WeakMap,Ua=new WeakMap,Wa=new WeakMap,za=new WeakMap,To=new WeakMap;function Qi(e,o){return new Ws(e,o).maybeExecute}function ya(e,o){return typeof e=="function"?e(o):e}function wa(e,o){return _s(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function Ao(e,o,t){let a=_s(o);function r(s){if(!a.length)return ya(t,s);let n=a.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(s))return typeof s=="object"?(s===null&&(s={}),{...s,[n]:r(s[n])}):{[n]:r()};if(Array.isArray(s)&&typeof n=="number"){let i=s.slice(0,n);return [...i.length?i:new Array(n),r(s[n]),...s.slice(n+1)]}return [...new Array(n),r()]}return r(e)}function tl(e,o){let t=_s(o);function a(r){if(!r)return;if(t.length===1){let n=t[0];if(Array.isArray(r)&&typeof n=="number")return r.filter((d,f)=>f!==n);let{[n]:i,...l}=r;return l}let s=t.shift();if(typeof s=="string"&&typeof r=="object")return {...r,[s]:a(r[s])};if(typeof s=="number"&&Array.isArray(r)){if(s>=r.length)return r;let n=r.slice(0,s);return [...n.length?n:new Array(s),a(r[s]),...r.slice(s+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var dx=/^(\d+)$/gm,ux=/\.(\d+)(?=\.)/gm,cx=/^(\d+)\./gm,fx=/\.(\d+$)/gm,mx=/\.{2,}/gm,el="__int__",zs=`${el}$1`;function _s(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(dx,zs).replace(ux,`.${zs}.`).replace(cx,`${zs}.`).replace(fx,`.${zs}`).replace(mx,".").split(".").map(o=>{if(o.startsWith(el)){let t=o.substring(el.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function al(e){return !(Array.isArray(e)&&e.length===0)}function Po(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 Do(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:s}=o.validators||{},n=t??0,i=l=>l.validators.filter(Boolean).map(d=>{let f=d?.cause||e,u=n;switch(f){case "change":u=r??n;break;case "blur":u=a??n;break;case "dynamic":u=s??n;break;case "submit":u=0;break}return e==="submit"&&(u=0),{cause:f,validate:d.fn,debounceMs:u}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:i})}var br=e=>!!e&&typeof e=="object"&&"fields"in e;function Sa(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[r,s]of e)if(!o.has(r)||!Object.is(s,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)||!Sa(e[r],o[r]))return false;return true}var js=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},Xs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function $e(e,o){return e==null?o:{...e,...o}}var Ga=256,Ks=[],Gs;for(;Ga--;)Ks[Ga]=(Ga+256).toString(16).substring(1);function ol(){let e=0,o,t="";if(!Gs||Ga+16>256){for(Gs=new Array(256),e=256;e--;)Gs[e]=256*Math.random()|0;e=0,Ga=0;}for(;e<16;e++)o=Gs[Ga+e],e===6?t+=Ks[o&15|64]:e===8?t+=Ks[o&63|128]:t+=Ks[o],e&1&&e>1&&e<11&&(t+="-");return Ga++,t}var La=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"},s={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,r,s,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,n],form:e.form});case "change":return e.runValidation({validators:[a,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function px(e,o){let t=new Map;for(let a of e){let r=a.path??[],s=o,n="";for(let i=0;i<r.length;i++){let l=r[i];if(l===void 0)continue;let d=typeof l=="object"?l.key:l,f=Number(d);Array.isArray(s)&&!Number.isNaN(f)?n+=`[${f}]`:n+=(i>0?".":"")+String(d),typeof s=="object"&&s!==null?s=s[d]:s=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var qu=(e,o)=>{let t=px(e,o);return {form:t,fields:t}},Ia={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:qu(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:qu(a.issues,e)}},$s=e=>!!e&&"~standard"in e;var Ro={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function vr(e){function o(u,c,m,p){let v=a(u,c,m,p);({insert:()=>i(v,u,c),remove:()=>l(v),swap:()=>p!==void 0&&f(v,u,c,p),move:()=>p!==void 0&&d(v,u,c,p)})[m]();}function t(u,c){return `${u}[${c}]`}function a(u,c,m,p){let v=[t(u,c)];if(m==="swap")v.push(t(u,p));else if(m==="move"){let[h,b]=[Math.min(c,p),Math.max(c,p)];for(let x=h;x<=b;x++)v.push(t(u,x));}else {let h=e.getFieldValue(u),b=Array.isArray(h)?h.length:0;for(let x=c+1;x<b;x++)v.push(t(u,x));}return Object.keys(e.fieldInfo).filter(h=>v.some(b=>h.startsWith(b)))}function r(u,c){return u.replace(/\[(\d+)\]/,(m,p)=>{let v=parseInt(p,10);return `[${c==="up"?v+1:Math.max(0,v-1)}]`})}function s(u,c){(c==="up"?u:[...u].reverse()).forEach(p=>{let v=r(p.toString(),c),h=e.getFieldMeta(v);h?e.setFieldMeta(p,h):e.setFieldMeta(p,n());});}let n=()=>Ro,i=(u,c,m)=>{s(u,"down"),u.forEach(p=>{p.toString().startsWith(t(c,m))&&e.setFieldMeta(p,n());});},l=u=>{s(u,"up");},d=(u,c,m,p)=>{let v=new Map(Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(c,m))).map(h=>[h,e.getFieldMeta(h)]));s(u,m<p?"up":"down"),Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(c,p))).forEach(h=>{let b=h.replace(t(c,p),t(c,m)),x=v.get(b);x&&e.setFieldMeta(h,x);});},f=(u,c,m,p)=>{u.forEach(v=>{if(!v.toString().startsWith(t(c,m)))return;let h=v.toString().replace(t(c,m),t(c,p)),[b,x]=[e.getFieldMeta(v),e.getFieldMeta(h)];b&&e.setFieldMeta(h,b),x&&e.setFieldMeta(v,x);});};return {handleArrayFieldMetaShift:o}}var rl=class extends Ha{constructor(){super({pluginId:"form-devtools"});}},gt=new rl;function sl(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(),r=this.store.mount(),s=()=>{a(),r(),gt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return gt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),s},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let s=!!a.transform?.deps?.some((l,d)=>l!==this.prevTransformArray[d]),n=a.defaultValues&&!Sa(a.defaultValues,r.defaultValues)&&!this.state.isTouched,i=!Sa(a.defaultState,r.defaultState)&&!this.state.isTouched;!n&&!i&&!s||(pt(()=>{this.baseStore.setState(()=>sl(Object.assign({},this.state,i?a.defaultState:{},n?{values:a.defaultValues}:{},s?{_force_re_eval:!this.state._force_re_eval}:{})));}),gt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:s}=this.state,n=this.resetFieldMeta(s);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>sl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let r=[];return pt(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let i=n.instance;r.push(Promise.resolve().then(()=>i.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(l=>({...l,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,s)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null,l=[`${a}[${r}]`];for(let c=r+1;c<=(i??0);c++)l.push(`${a}[${c}]`);let d=Object.keys(this.fieldInfo).filter(c=>l.some(m=>c.startsWith(m))),f=[];return pt(()=>{d.forEach(c=>{f.push(Promise.resolve().then(()=>this.validateField(c,s)));});}),(await Promise.all(f)).flat()},this.validateField=(a,r)=>{let s=this.fieldInfo[a]?.instance;return s?(s.state.meta.isTouched||s.setMeta(n=>({...n,isTouched:true})),s.validate(r)):[]},this.validateSync=a=>{let r=Po(a,{...this.options,form:this,validationLogic:this.options.validationLogic||La}),s=false,n={};return pt(()=>{for(let d of r){if(!d.validate)continue;let f=this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:u,fieldErrors:c}=Ys(f),m=yr(d.cause);for(let p of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[p]===void 0)continue;let v=this.getFieldMeta(p);if(!v)continue;let{errorMap:h,errorSourceMap:b}=v,x=c?.[p],{newErrorValue:g,newSource:S}=js({newFormValidatorError:x,isPreviousErrorFromFormValidator:b?.[m]==="form",previousErrorValue:h?.[m]});S==="form"&&(n[p]={...n[p],[m]:x}),h?.[m]!==g&&this.setFieldMeta(p,k=>({...k,errorMap:{...k.errorMap,[m]:g},errorSourceMap:{...k.errorSourceMap,[m]:S}}));}this.state.errorMap?.[m]!==u&&this.baseStore.setState(p=>({...p,errorMap:{...p.errorMap,[m]:u}})),(u||c)&&(s=!0);}let i=yr("submit");this.state.errorMap?.[i]&&a!=="submit"&&!s&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[i]:void 0}}));let l=yr("server");this.state.errorMap?.[l]&&a!=="server"&&!s&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[l]:void 0}}));}),{hasErrored:s,fieldsErrorMap:n}},this.validateAsync=async a=>{let r=Do(a,{...this.options,form:this,validationLogic:this.options.validationLogic||La});this.state.isFormValidating||this.baseStore.setState(d=>({...d,isFormValidating:true}));let s=[],n;for(let d of r){if(!d.validate)continue;let f=yr(d.cause);this.state.validationMetaMap[f]?.lastAbortController.abort();let c=new AbortController;this.state.validationMetaMap[f]={lastAbortController:c},s.push(new Promise(async m=>{let p;try{p=await new Promise((x,g)=>{setTimeout(async()=>{if(c.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:c.signal},type:"validateAsync"}));}catch(S){g(S);}},d.debounceMs);});}catch(x){p=x;}let{formError:v,fieldErrors:h}=Ys(p);h&&(n=n?{...n,...h}:h);let b=yr(d.cause);for(let x of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[x]===void 0)continue;let g=this.getFieldMeta(x);if(!g)continue;let{errorMap:S,errorSourceMap:k}=g,C=n?.[x],{newErrorValue:L,newSource:y}=js({newFormValidatorError:C,isPreviousErrorFromFormValidator:k?.[b]==="form",previousErrorValue:S?.[b]});S?.[b]!==L&&this.setFieldMeta(x,M=>({...M,errorMap:{...M.errorMap,[b]:L},errorSourceMap:{...M.errorSourceMap,[b]:y}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.errorMap,[b]:v}})),m(n?{fieldErrors:n,errorMapKey:b}:void 0);}));}let i=[],l={};if(s.length){i=await Promise.all(s);for(let d of i)if(d?.fieldErrors){let{errorMapKey:f}=d;for(let[u,c]of Object.entries(d.fieldErrors)){let p={...l[u]||{},[f]:c};l[u]=p;}}}return this.baseStore.setState(d=>({...d,isFormValidating:false})),l},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:s}=this.validateSync(a);return r&&!this.options.asyncAlways?s:this.validateAsync(a)},this.getFieldValue=a=>wa(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(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:ya(r,s.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,s)=>{let n=s;return r[n]=Ro,r},{}),this.setFieldValue=(a,r,s)=>{let n=s?.dontUpdateMeta??false,i=s?.dontRunListeners??false,l=s?.dontValidate??false;pt(()=>{n||this.setFieldMeta(a,d=>({...d,isTouched:!0,isDirty:!0,errorMap:{...d?.errorMap,onMount:void 0}})),this.baseStore.setState(d=>({...d,values:Ao(d.values,a,r)}));}),i||this.getFieldInfo(a).instance?.triggerOnChangeListener(),l||this.validateField(a,"change");},this.deleteField=a=>{let s=[...Object.keys(this.fieldInfo).filter(n=>{let i=a.toString();return n!==i&&n.startsWith(i)}),a];this.baseStore.setState(n=>{let i={...n};return s.forEach(l=>{i.values=tl(i.values,l),delete this.fieldInfo[l],delete i.fieldMetaBase[l];}),i});},this.pushFieldValue=(a,r,s)=>{this.setFieldValue(a,n=>[...Array.isArray(n)?n:[],r],s);},this.insertFieldValue=async(a,r,s,n)=>{this.setFieldValue(a,l=>[...l.slice(0,r),s,...l.slice(r)],$e(n,{dontValidate:true}));let i=n?.dontValidate??false;i||await this.validateField(a,"change"),vr(this).handleArrayFieldMetaShift(a,r,"insert"),i||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,s,n)=>{this.setFieldValue(a,l=>l.map((d,f)=>f===r?s:d),$e(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,s)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,d=>d.filter((f,u)=>u!==r),$e(s,{dontValidate:true})),vr(this).handleArrayFieldMetaShift(a,r,"remove"),i!==null){let d=`${a}[${i}]`;this.deleteField(d);}(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,s,n)=>{this.setFieldValue(a,l=>{let d=l[r],f=l[s];return Ao(Ao(l,`${r}`,f),`${s}`,d)},$e(n,{dontValidate:true})),vr(this).handleArrayFieldMetaShift(a,r,"swap",s),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${s}]`,"change"));},this.moveFieldValues=(a,r,s,n)=>{this.setFieldValue(a,l=>{let d=[...l];return d.splice(s,0,d.splice(r,1)[0]),d},$e(n,{dontValidate:true})),vr(this).handleArrayFieldMetaShift(a,r,"move",s),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${s}]`,"change"));},this.clearFieldValues=(a,r)=>{let s=this.getFieldValue(a),n=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,[],$e(r,{dontValidate:true})),n!==null)for(let l=0;l<=n;l++){let d=`${a}[${l}]`;this.deleteField(d);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Ro},values:this.options.defaultValues?Ao(r.values,a,wa(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,s])=>(Object.keys(s).length&&s.errors.length&&(a[r]={errors:s.errors,errorMap:s.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Ia.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ia.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??ol(),this._devtoolsSubmissionOverride=false,this.baseStore=new _t(sl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Vt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:s})=>{let n=s,i=a?.[0],l=r[0],d=0,f={};for(let u of Object.keys(l.fieldMetaBase)){let c=l.fieldMetaBase[u],m=i?.fieldMetaBase[u],p=n?.[u],v=wa(l.values,u),h=p?.errors;if(!m||c.errorMap!==m.errorMap){h=Object.values(c.errorMap??{}).filter(k=>k!==void 0);let S=this.getFieldInfo(u)?.instance;S&&!S.options.disableErrorFlat&&(h=h?.flat(1));}let b=!al(h??[]),x=!c.isDirty,g=Sa(v,wa(this.options.defaultValues,u))||Sa(v,this.getFieldInfo(u)?.instance?.options.defaultValue);if(p&&p.isPristine===x&&p.isValid===b&&p.isDefaultValue===g&&p.errors===h&&c===m){f[u]=p,d++;continue}f[u]={...c,errors:h,isPristine:x,isValid:b,isDefaultValue:g};}return Object.keys(l.fieldMetaBase).length&&n&&d===Object.keys(l.fieldMetaBase).length?n:f}}),this.store=new Vt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:s})=>{let n=s,i=a?.[0],l=r[0],d=r[1],f=Object.values(d).filter(Boolean),u=f.some(A=>A.isValidating),c=f.every(A=>A.isValid),m=f.some(A=>A.isTouched),p=f.some(A=>A.isBlurred),v=f.every(A=>A.isDefaultValue),h=m&&l.errorMap?.onMount,b=f.some(A=>A.isDirty),x=!b,g=!!(l.errorMap?.onMount||f.some(A=>A?.errorMap?.onMount)),S=!!u,k=n?.errors??[];(!i||l.errorMap!==i.errorMap)&&(k=Object.values(l.errorMap).reduce((A,W)=>W===void 0?A:W&&br(W)?(A.push(W.form),A):(A.push(W),A),[]));let C=k.length===0,L=c&&C,y=this.options.canSubmitWhenInvalid??false,M=l.submissionAttempts===0&&!m&&!g||!S&&!l.isSubmitting&&L||y,O=l.errorMap;if(h&&(k=k.filter(A=>A!==l.errorMap.onMount),O=Object.assign(O,{onMount:void 0})),n&&i&&n.errorMap===O&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===k&&n.isFieldsValidating===u&&n.isFieldsValid===c&&n.isFormValid===C&&n.isValid===L&&n.canSubmit===M&&n.isTouched===m&&n.isBlurred===p&&n.isPristine===x&&n.isDefaultValue===v&&n.isDirty===b&&Sa(i,l))return n;let D={...l,errorMap:O,fieldMeta:this.fieldMetaDerived.state,errors:k,isFieldsValidating:u,isFieldsValid:c,isFormValid:C,isValid:L,canSubmit:M,isTouched:m,isBlurred:p,isPristine:x,isDefaultValue:v,isDirty:b},q=this.options.transform?.deps??[];if(q.length!==this.prevTransformArray.length||q.some((A,W)=>A!==this.prevTransformArray[W])){let A=Object.assign({},this,{state:D});this.options.transform?.fn(A),D=A.state,this.prevTransformArray=q;}return D}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Qi(a=>gt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),gt.on("request-form-state",a=>{a.payload.id===this._formId&>.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),gt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),gt.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 $s(o.validate)?Ia[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})),pt(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(s=>({...s,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}),gt.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}),gt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}pt(()=>{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}),pt(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),gt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(s=>({...s,isSubmitSuccessful:false})),gt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){pt(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(br(a)){let{formError:s,fieldErrors:n}=Ys(a);for(let i of Object.keys(this.fieldInfo))this.getFieldMeta(i)&&this.setFieldMeta(i,d=>({...d,errorMap:{...d.errorMap,[r]:n?.[i]},errorSourceMap:{...d.errorSourceMap,[r]:"form"}}));this.baseStore.setState(i=>({...i,errorMap:{...i.errorMap,[r]:s}}));}else this.baseStore.setState(s=>({...s,errorMap:{...s.errorMap,[r]:a}}));});});}};function Ys(e){if(e){if(br(e)){let o=Ys(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function yr(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}var Sr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let s=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});s&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:s},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let r=wa(t.form.options.defaultValues,t.name),s=t.defaultValue??r;a?this.setValue(n=>n||s,{dontUpdateMeta:true}):s!==void 0&&this.setValue(s,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,$e(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,$e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,$e(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,$e(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,$e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,$e(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,$e(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,$e(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),r=[];for(let s of a){if(!s.instance)continue;let{onChangeListenTo:n,onBlurListenTo:i}=s.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&r.push(s.instance),t==="blur"&&i?.includes(this.name)&&r.push(s.instance);}return r},this.validateSync=(t,a)=>{let r=Po(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||La}),n=this.getLinkedFields(t).reduce((d,f)=>{let u=Po(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||La});return u.forEach(c=>{c.field=f;}),d.concat(u)},[]),i=false;pt(()=>{let d=(f,u)=>{let c=Js(u.cause),m=u.validate?Hu(f.runValidator({validate:u.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,p=a[c],{newErrorValue:v,newSource:h}=Xs({formLevelError:p,fieldLevelError:m});f.state.meta.errorMap?.[c]!==v&&f.setMeta(b=>({...b,errorMap:{...b.errorMap,[c]:v},errorSourceMap:{...b.errorSourceMap,[c]:h}})),v&&(i=!0);};for(let f of r)d(this,f);for(let f of n)f.validate&&d(f.field,f);});let l=Js("submit");return this.state.meta.errorMap?.[l]&&t!=="submit"&&!i&&this.setMeta(d=>({...d,errorMap:{...d.errorMap,[l]:void 0},errorSourceMap:{...d.errorSourceMap,[l]:void 0}})),{hasErrored:i}},this.validateAsync=async(t,a)=>{let r=Do(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||La}),s=await a,n=this.getLinkedFields(t),i=n.reduce((c,m)=>{let p=Do(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||La});return p.forEach(v=>{v.field=m;}),c.concat(p)},[]);this.state.meta.isValidating||this.setMeta(c=>({...c,isValidating:true}));for(let c of n)c.setMeta(m=>({...m,isValidating:true}));let l=[],d=[],f=(c,m,p)=>{let v=Js(m.cause);c.getInfo().validationMetaMap[v]?.lastAbortController.abort();let b=new AbortController;this.getInfo().validationMetaMap[v]={lastAbortController:b},p.push(new Promise(async x=>{let g;try{g=await new Promise((y,M)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(b.signal.aborted)return y(void 0);try{y(await this.runValidator({validate:m.validate,value:{value:c.store.state.value,fieldApi:c,signal:b.signal,validationSource:"field"},type:"validateAsync"}));}catch(O){M(O);}},m.debounceMs);});}catch(y){g=y;}if(b.signal.aborted)return x(void 0);let S=Hu(g),k=s[this.name]?.[v],{newErrorValue:C,newSource:L}=Xs({formLevelError:k,fieldLevelError:S});c.setMeta(y=>({...y,errorMap:{...y?.errorMap,[v]:C},errorSourceMap:{...y.errorSourceMap,[v]:L}})),x(C);}));};for(let c of r)c.validate&&f(this,c,l);for(let c of i)c.validate&&f(c.field,c,d);let u=[];(l.length||d.length)&&(u=await Promise.all(l),await Promise.all(d)),this.setMeta(c=>({...c,isValidating:false}));for(let c of n)c.setMeta(m=>({...m,isValidating:false}));return u.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:s}=this.validateSync(t,r[this.name]??{});if(s&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Js(t)]?.lastAbortController.abort(),this.state.meta.errors;let n=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,n)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Ia.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ia.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Vt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Ro,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return $s(o.validate)?Ia[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 Hu(e){if(e)return e}function Js(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 Zs(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,gx)}function gx(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=Uu(e);if(t.length!==Uu(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 Uu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Eo=typeof window<"u"?useLayoutEffect:useEffect;function Lx(e){let[o]=useState(()=>{let a=new Sr({...e,form:e.form,name:e.name});return a.Field=nl,a});return Eo(o.mount,[o]),Eo(()=>{o.update(e);}),Zs(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var nl=(({children:e,...o})=>{let t=Lx(o),a=useMemo(()=>ya(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function kx({form:e,selector:o,children:t}){let a=Zs(e.store,o);return ya(t,a)}function il(e){let o=useId(),[t]=useState(()=>{let a=new wr({...e,formId:o}),r=a;return r.Field=function(n){return jsx(nl,{...n,form:a})},r.Subscribe=function(n){return jsx(kx,{form:a,selector:n.selector,children:n.children})},r});return Eo(t.mount,[]),Eo(()=>{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 Ox=({editElement:e})=>{let o=useDispatch(),t=useSelector(he),a=useRef(null),r=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[n,i]=useState(s),l=il({defaultValues:{questionType:s,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:u})=>{if(u.questionType==="true-false"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctAnswer:u.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?fa(c):ai(c));}else if(u.questionType==="multiple-choice"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctIndex:u.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?ca(c):ti(c));}else if(u.questionType==="short-answer"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Xo(c):oi(c));}else if(u.questionType==="fill-in-the-blank"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Yo(c):si(c));}else if(u.questionType==="long-answer"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctLongAnswer:u.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?$o(c):ri(c));}o(ma(false));}}),d=()=>{o(ma(false));},f=jsx("div",{className:"konva-editor-root",children:jsx("div",{className:"fixed inset-0 z-9999 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:u=>{u.preventDefault(),u.stopPropagation(),l.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:()=>{d();},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(l.Field,{name:"questionType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:c=>{u.handleChange(c.target.value),i(c.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(ll,{field:u})]})}),n&&!["short-answer","fill-in-the-blank","long-answer"].includes(n)&&jsx(l.Field,{name:"responseType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:c=>u.handleChange(c.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(ll,{field:u})]})})]}),jsx(l.Field,{name:"feedbackMode",children:u=>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 ${n==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:n==="long-answer",onClick:()=>u.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 ${u.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:n==="long-answer",onClick:()=>u.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 ${u.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"})]})]}),n==="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:u})]})}),jsx(l.Field,{name:"question",validators:{onChange:({value:u})=>u?void 0:"A question is required"},children:u=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:u.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:u.state.value,onChange:c=>u.handleChange(c.target.value),onBlur:u.handleBlur,placeholder:"Enter Your Question"})}),u.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:u.state.meta.errors.join(", ")})]})}),n==="true-false"&&jsx(l.Field,{name:"responseOptions.correctAnswer",children:u=>{let c=u.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:()=>u.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${c===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),c===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>u.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${c===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),c===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),n==="multiple-choice"&&jsx(l.Field,{name:"responseOptions",validators:{onChange:({value:u})=>{if(u.options.filter(m=>!m.trim()).length>0)return "All options must have text";if(!u.correctIndex||u.correctIndex.length===0)return "Please select at least one correct answer"}},children:u=>{let c=(h,b)=>{let x=[...u.state.value.options];x[h]=b,u.handleChange({...u.state.value,options:x});},m=()=>{if(u.state.value.options.length>=6){alert("Maximum 6 options allowed");return}u.handleChange({...u.state.value,options:[...u.state.value.options,""]});},p=h=>{if(u.state.value.options.length<=2){alert("Minimum 2 options required");return}let b=u.state.value.options.filter((g,S)=>S!==h),x=u.state.value.correctIndex?.filter(g=>g!==h).map(g=>g>h?g-1:g);u.handleChange({...u.state.value,options:b,correctIndex:x});},v=h=>{let b=u.state.value.correctIndex||[];if(b.includes(h))u.handleChange({...u.state.value,correctIndex:b.filter(g=>g!==h)});else {if(b.length>=6){alert("Maximum 6 correct answers allowed");return}u.handleChange({...u.state.value,correctIndex:[...b,h]});}};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:u.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:u.state.value.options.map((h,b)=>{let x=!h.trim(),g=u.state.value.correctIndex?.includes(b),S=u.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(b),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${g?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:g&&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":g?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${b+1}`,value:h,onChange:k=>c(b,k.target.value),onBlur:u.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"})}),u.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>p(b),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},b)})}),jsx("button",{type:"button",onClick:m,disabled:u.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"}),u.state.value.correctIndex.length===0||u.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:u.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",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"})]})]})}}),(n==="short-answer"||n==="fill-in-the-blank")&&jsx(l.Field,{name:"responseOptions.correctShortAnswer",children:u=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:u.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:u.state.value,onChange:c=>{u.handleChange(c.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:u.state.meta.errors.join(", ")})]})}),n==="long-answer"&&jsx(l.Field,{name:"responseOptions.correctLongAnswer",children:u=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:u.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:u.state.value,onChange:c=>{u.handleChange(c.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:u.state.meta.errors.join(", ")})]})}),jsx(l.Subscribe,{selector:u=>[u.canSubmit,u.isSubmitting],children:([u,c])=>jsx("button",{type:"submit",disabled:!u,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:c?"Saving...":r?"Update Question":"Save Question"})})]})})})});return createPortal(f,document.body)},Gu=Ox;var Xu=({text:e,position:o})=>{let t=xe(),a=d=>{t(ce()),t(Lt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+d))}));},r=d=>{t(ce()),t(Lt({id:e.id,fill:d}));},s=()=>{t(ce()),t(Lt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ce()),t(Lt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},i=()=>{t(ce()),t(Lt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},l=d=>{t(ce()),t(Lt({id:e.id,fontFamily:d}));};return jsxs("div",{className:"fixed z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:"50%",top:`${Math.max(60,o.y-60)}px`,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:d=>d.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:d=>l(d.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:s,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:[jsx(TextB,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextB,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:n,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:i,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:[jsx(TextUnderline,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextUnderline,{size:16,weight:"bold",className:"hidden sm:block"})]})]}),jsx("div",{className:"border-l border-gray-200 pl-1",children:jsx("input",{type:"color",value:e.fill,onChange:d=>r(d.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var Yu=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:s,textareaRef:n})=>{let i=useRef(null),l=useMemo(()=>({fontSize:`${e.fontSize*s}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,s]),d=useCallback(f=>{f.style.height="auto",f.style.height=`${f.scrollHeight}px`;let u=document.createElement("span");u.style.font=window.getComputedStyle(f).font,u.style.fontSize=f.style.fontSize,u.style.fontFamily=f.style.fontFamily,u.style.fontWeight=f.style.fontWeight,u.style.fontStyle=f.style.fontStyle,u.style.visibility="hidden",u.style.position="absolute",u.style.whiteSpace="pre";let c=f.value.split(`
|
|
4
|
-
`),m=0;document.body.appendChild(u);for(let v of c){u.textContent=v||" ";let h=u.offsetWidth;h>m&&(m=h);}document.body.removeChild(u);let p=10;f.style.width=`${Math.max(200,m+p+20)}px`;},[]);return useEffect(()=>{let f=i.current;f&&(f.style.fontSize=`${e.fontSize*s}px`,f.style.fontFamily=e.fontFamily,f.style.fontStyle=e.fontStyle,f.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",f.style.textDecoration=e.textDecoration,f.style.color=e.fill,d(f));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,s,d]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:f=>{if(i.current=f,n.current=f,f){f.focus();let u=f.value.length;f.setSelectionRange(u,u),d(f);}},value:o,onChange:f=>{t(f.target.value);},onKeyDown:f=>{f.key==="Escape"&&a();},style:l},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Ju=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>{let n=useSelector(A=>A.toolbar.selectedTool),i=n==="pen"||n==="eraser",l=useRef(null),[d,f]=useState(""),[u,c]=useState(false),[m,p]=useState(null);useEffect(()=>{let A=l.current;if(A)return a.current.set(e.id,A),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===v,b=()=>{c(false),f("");},x=()=>h?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",g=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},S=24,k=60,C=u?40:0,L=u?54:20,y=50,M=12,O=e.data.feedbackMode==="practice"?48:0,D=12,q=30,U=k+C+q+y+M+D+O+S;return jsxs(Group,{ref:l,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:U,name:"sa-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:U,onTransformEnd:A=>t(e.id,A),onContextMenu:A=>{A.cancelBubble=true,r(A.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:S,y:S,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-S*2,listening:false}),jsx(Rect,{x:S,y:k+C+q-L,width:e.width-S*2+4,height:y+6,fill:"#ffffff",stroke:h?"#22c55e":u?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:S,y:k+C+q-L},divProps:{style:{width:`${e.width-S*2-4}px`,height:`${y}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:A=>f(A.target.value),disabled:u,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:u?"none":"auto"}})}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:S,y:k+80,width:e.width/2+24,height:C,fill:g().bg,cornerRadius:8}),jsx(Text,{x:36,y:k+80,width:e.width-S*2,height:C,text:x(),fontSize:12,fontStyle:"bold",fill:g().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:k+C+q+y+M+D,children:[jsxs(Group,{onMouseDown:A=>{A.cancelBubble=true,p("check");},onMouseUp:A=>{A.cancelBubble=true,p(null),d.length>0&&c(true);},onMouseLeave:A=>{A.cancelBubble=true,p(null);},onTouchStart:A=>{A.cancelBubble=true,p("check");},onTouchEnd:A=>{A.cancelBubble=true,p(null),d.length>0&&c(true);},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:S,width:(e.width-S*2-8)/(u?2:1),height:48,fill:d.length===0||u?"#9ca3af":"#096B76",cornerRadius:8,onClick:A=>A.cancelBubble=true,onTap:A=>A.cancelBubble=true}),jsx(Text,{x:S,width:(e.width-S*2-8)/(u?2:1),height:48,text:u?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),u&&jsxs(Group,{x:(e.width-S*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),b();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),b();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:S,width:(e.width-S*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:A=>A.cancelBubble=true,onTap:A=>A.cancelBubble=true}),jsx(Text,{x:S,width:(e.width-S*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ju.displayName="ShortAnswer";var Zu=Ju;var ec=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>jsx(Fragment,{children:e.map(n=>jsx(Zu,{shortAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>s(i,n.id)},n.id))});var tc=e=>{let o=useDispatch(),a=useSelector(he)?.fillInTheBlanks||[],r=useRef(new Map),s=useCallback((n,i)=>{let l=n.target;o(Yo({id:i,x:l.x(),y:l.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:s}};var Mt=24,cl=51,Tr=64,ac=15,tn=32,oc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:s})=>{let n=useSelector(y=>y.toolbar.selectedTool),i=n==="pen"||n==="eraser",l=useRef(null),[d,f]=useState(""),[u,c]=useState(false),[m,p]=useState(null);useEffect(()=>{let y=l.current;if(y)return s.current.set(e.id,y),()=>{s.current.delete(e.id);}},[e.id,s]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===v,b=()=>{c(false),f("");},x=()=>{d.length>0&&c(true);},g=e.width-Mt*2,S=(g-ac)/2,k=e.data.feedbackMode==="practice",C=useMemo(()=>{let y=Mt,M=y;y+=60;let O=y;y+=35;let D=y;y+=cl+16;let q=y;u&&(y+=tn+16);let U=y;return k&&(y+=Tr),y+=Mt,{questionY:M,helperTextY:O,inputY:D,feedbackY:q,buttonsY:U,totalHeight:y}},[u,k]),L=()=>u?h?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:l,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...i?{}:{onDragEnd:y=>a(y,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:C.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:y=>t(e.id,y),onContextMenu:y=>{y.cancelBubble=true,r?.(y.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Mt,y:C.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:g,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Mt,y:C.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:g,listening:false}),jsx(Rect,{x:Mt,y:C.inputY,width:g,height:cl,fill:"#ffffff",stroke:L(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Mt,y:C.inputY},divProps:{style:{width:`${g}px`,height:`${cl}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:y=>f(y.target.value),disabled:u,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),u&&jsxs(Group,{y:C.feedbackY,children:[jsx(Rect,{x:Mt,width:h?206:140,height:tn,fill:h?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:h?"\u2713":"\u2717",x:Mt+10,y:0,width:16,height:tn,fontSize:14,fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:h?"Right Answer, Great Job!":"Wrong Answer",x:Mt+30,y:0,height:tn,fontSize:14,fontStyle:"600",fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),k&&jsxs(Group,{y:C.buttonsY,children:[jsxs(Group,{x:Mt,onMouseDown:y=>{y.cancelBubble=true,p("reset");},onMouseUp:y=>{y.cancelBubble=true,p(null),b();},onMouseLeave:y=>{y.cancelBubble=true,p(null);},onTouchStart:y=>{y.cancelBubble=true,p("reset");},onTouchEnd:y=>{y.cancelBubble=true,p(null),b();},scaleX:m==="reset"?.98:1,scaleY:m==="reset"?.98:1,children:[jsx(Rect,{width:S,height:Tr,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:S,height:Tr,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Mt+S+ac,onMouseDown:y=>{y.cancelBubble=true,p("submit");},onMouseUp:y=>{y.cancelBubble=true,p(null),x();},onMouseLeave:y=>{y.cancelBubble=true,p(null);},onTouchStart:y=>{y.cancelBubble=true,p("submit");},onTouchEnd:y=>{y.cancelBubble=true,p(null),x();},scaleX:m==="submit"?.98:1,scaleY:m==="submit"?.98:1,children:[jsx(Rect,{width:S,height:Tr,fill:d.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:S,height:Tr,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});oc.displayName="FillInTheBlanks";var rc=oc;var nc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:s})=>jsx(Fragment,{children:e.map(n=>jsx(rc,{fillInTheBlank:n,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:s},n.id))});var hl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>{let n=useSelector(U=>U.toolbar.selectedTool),i=n==="pen"||n==="eraser",l=useRef(null),[d,f]=useState(""),[u,c]=useState(false),[m,p]=useState(null);useEffect(()=>{let U=l.current;if(U)return a.current.set(e.id,U),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===v,b=()=>{c(false),f("");},x=()=>h?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",g=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},S=24,k=60,C=u?60:0,L=120,y=12,M=48,O=12,D=30,q=k+C+D+L+y+O+M+S;return jsxs(Group,{ref:l,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:U=>{let A=l.current?.getStage()?.getPointerPosition();if(!A||!r)return;let W={x:e.x,y:e.y,width:e.width,height:e.height};A.x>=W.x&&A.x<=W.x+W.width&&A.y>=W.y&&A.y<=W.y+W.height&&r(U.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:q,onTransformEnd:U=>t(e.id,U)}),jsx(Text,{text:e.data.question,x:S,y:S,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-S*2,listening:false}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:S,y:k,width:e.width-S*2,height:C,fill:g().bg,cornerRadius:8}),jsx(Text,{x:S,y:k,width:e.width-S*2,height:C,text:x(),fontSize:14,fontStyle:"bold",fill:g().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:S,y:k+C+y,fontSize:14,fill:"#6b7280",width:e.width-S*2,listening:false}),jsx(Rect,{x:S,y:k+C+D,width:e.width-S*2,height:L,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:S,y:k+C+D},divProps:{style:{width:`${e.width-S*2}px`,height:`${L}px`,pointerEvents:u?"none":"auto"}},children:jsx("textarea",{value:d,onChange:U=>f(U.target.value),disabled:u,placeholder:`Type your extended answer here...\r
|
|
2
|
+
export{default as Konva}from'konva';import*as be from'react';import be__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,createContext,useState,useMemo,createElement,useContext,useId,useLayoutEffect}from'react';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import Sd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X as X$1,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,ToggleRight,Textbox,TextUnderline,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,Export,CaretLeft,Plus,CaretDown,CaretUp,SidebarSimple,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Pen}from'@phosphor-icons/react/dist/ssr';import {EyeIcon,Stack as Stack$1,X as X$2,DotsSixVertical,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {createPortal}from'react-dom';import Iu from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var md=e=>{throw TypeError(e)};var pd=(e,o,t)=>o.has(e)||md("Cannot "+t);var j=(e,o,t)=>(pd(e,o,"read from private field"),t?t.call(e):o.get(e)),Pe=(e,o,t)=>o.has(e)?md("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Ce=(e,o,t,a)=>(pd(e,o,"write to private field"),o.set(e,t),t);var hd=(e,o,t,a)=>({set _(s){Ce(e,o,s);},get _(){return j(e,o,a)}});var xe=()=>useDispatch(),Q=e=>useSelector(e),at=xe,ct=Q;var Bn=20,Nn=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now(),isActive:true}),Fn=Nn("Slide 1"),Hm={slides:[Fn],currentSlideId:Fn.id,history:{[Fn.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false},gd=createSlice({name:"canvas",initialState:Hm,reducers:{addSlide:e=>{if(e.slides.length>=Bn)return;let o=Nn(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(l=>l.isActive).length<=1)return;let r=e.slides.findIndex(l=>l.id===t);if(r===-1)return;let n=e.slides[r];if(a?(n.isActive=false,n.updatedAt=Date.now()):(e.slides.splice(r,1),delete e.history[t]),e.currentSlideId===t){let l=e.slides.filter(d=>d.isActive);l.length>0&&(e.currentSlideId=l[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=Bn)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],s={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),isActive:true,lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,s),e.currentSlideId=s.id,e.history[s.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[s]=e.slides.splice(t,1);e.slides.splice(a,0,s);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(s=>s.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(s=>s.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(s=>s.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(s=>s.id===o.payload);if(a){let s={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(s),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,newTimestamp:r}=o.payload;switch(s){case "image":let n=t.images.find(b=>b.id===a);n&&(n.timestamp=r);break;case "video":let l=t.videos.find(b=>b.id===a);l&&(l.timestamp=r);break;case "shape":let d=t.shapes.find(b=>b.id===a);d&&(d.timestamp=r);break;case "text":let u=t.texts.find(b=>b.id===a);u&&(u.timestamp=r);break;case "flashcard":let m=t.flashcards.find(b=>b.id===a);m&&(m.timestamp=r);break;case "photoFrame":let f=t.photoFrames.find(b=>b.id===a);f&&(f.timestamp=r);break;case "mcq":let i=t.multipleChoices.find(b=>b.id===a);i&&(i.timestamp=r);break;case "trueFalse":let c=t.trueFalses.find(b=>b.id===a);c&&(c.timestamp=r);break;case "shortAnswer":let p=t.shortAnswers.find(b=>b.id===a);p&&(p.timestamp=r);break;case "longAnswer":let y=t.LongAnswer.find(b=>b.id===a);y&&(y.timestamp=r);break;case "fillInTheBlanks":let h=t.fillInTheBlanks.find(b=>b.id===a);h&&(h.timestamp=r);break;case "line":let x=t.lines.find(b=>b.id===a);x&&(x.timestamp=r);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(s=>s.id===o.payload);if(a){let s={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(s),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(s=>s.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(s=>s.id===o.payload);if(a){let s={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(s),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(s=>s.id===o.payload);if(a){let s={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(s),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let s=t.multipleChoices[t.multipleChoices.length-1];a.x=s.x+20,a.y=s.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(s=>s.id===o.payload);if(a){let s={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(s),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let s=t.trueFalses[t.trueFalses.length-1];a.x=s.x+20,a.y=s.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(s=>s.id===o.payload);if(a){let s={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(s),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let s=t.shortAnswers[t.shortAnswers.length-1];a.x=s.x+20,a.y=s.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(s=>s.id===o.payload);if(a){let s={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(s),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let s=t.LongAnswer[t.LongAnswer.length-1];a.x=s.x+20,a.y=s.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(s=>s.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(s=>s.id===o.payload);if(a){let s={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(s),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let s=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=s.x+20,a.y=s.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(s=>s.id===o.payload);if(a){let s={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(s),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s}=o.payload;if(s==="image"){let r=t.images.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.images.splice(r,1);t.images.push(n);}}else if(s==="video"){let r=t.videos.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.videos.splice(r,1);t.videos.push(n);}}else if(s==="shape"){let r=t.shapes.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shapes.splice(r,1);t.shapes.push(n);}}else if(s==="flashcard"){let r=t.flashcards.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.flashcards.splice(r,1);t.flashcards.push(n);}}else if(s==="photoFrame"){let r=t.photoFrames.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.photoFrames.splice(r,1);t.photoFrames.push(n);}}else if(s==="text"){let r=t.texts.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.texts.splice(r,1);t.texts.push(n);}}else if(s==="trueFalse"){let r=t.trueFalses.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.trueFalses.splice(r,1);t.trueFalses.push(n);}}else if(s==="shortAnswer"){let r=t.shortAnswers.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shortAnswers.splice(r,1);t.shortAnswers.push(n);}}else if(s==="fillInTheBlanks"){let r=t.fillInTheBlanks.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.fillInTheBlanks.splice(r,1);t.fillInTheBlanks.push(n);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s}=o.payload;if(s==="image"){let r=t.images.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.images.splice(r,1);t.images.unshift(n);}}else if(s==="video"){let r=t.videos.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.videos.splice(r,1);t.videos.unshift(n);}}else if(s==="shape"){let r=t.shapes.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shapes.splice(r,1);t.shapes.unshift(n);}}else if(s==="flashcard"){let r=t.flashcards.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.flashcards.splice(r,1);t.flashcards.unshift(n);}}else if(s==="photoFrame"){let r=t.photoFrames.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.photoFrames.splice(r,1);t.photoFrames.unshift(n);}}else if(s==="text"){let r=t.texts.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.texts.splice(r,1);t.texts.unshift(n);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s}=o.payload,n=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(l=>l.id===a);n&&(n.locked=!n.locked,"draggable"in n&&(n.draggable=!n.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,link:r}=o.payload,l=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="mcq"?t.multipleChoices:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(d=>d.id===a);l&&(l.link=r,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,altText:r}=o.payload,l=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(d=>d.id===a);l&&(l.altText=r,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,audioData:r}=o.payload,l=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(d=>d.id===a);l&&(l.audioData=r,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(s=>s.id===o.payload);if(a){let s={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(s),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(s=>s.id===o.payload);if(a){let s={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(s),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(s=>s.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let s=a.images.map((r,n)=>n).filter(r=>r!==a.currentIndex);if(s.length>0){let r=s[Math.floor(Math.random()*s.length)];a.navigationHistory.push(r),a.currentIndex=r;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(s=>s.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(s=>s.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(s=>s.id===o.payload);if(a){let s={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(s),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(s=>s.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(s=>s.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(s=>s.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(s=>s.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(s=>s.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(s=>s.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(s=>s.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(s=>s.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let s=o.past.pop();e.slides[t]=s;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let s=o.future.shift();e.slides[t]=s;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let s=JSON.parse(JSON.stringify(t));a.past.push(s),a.future=[],a.past.length>20&&a.past.shift();}catch(s){console.warn("Failed to save to history - data too large:",s),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;}}}),{addSlide:Vn,deleteSlide:qn,duplicateSlide:Hn,setCurrentSlide:Un,updateSlideThumbnail:Wn,setBackgroundColor:zn,reorderSlides:Um,loadSlides:io,addLine:Gn,removeLine:Yr,addImage:Kn,updateImage:lo,deleteImage:Jr,duplicateImage:Zr,addVideo:Qr,updateVideo:es,deleteVideo:ts,duplicateVideo:as,toggleVideoPlaying:jo,addShape:_n,updateShape:uo,duplicateShape:os,deleteShape:rs,addText:jn,updateText:It,deleteText:ss,duplicateText:ns,addFlashcard:Xn,updateFlashcard:co,deleteFlashcard:is,duplicateFlashcard:ls,editFlashcard:Xo,nextFlashcard:$n,previousFlashcard:Yn,addPhotoFrame:Jn,updatePhotoFrame:Ba,deletePhotoFrame:ds,duplicatePhotoFrame:us,toggleImageDrawingMode:Zn,addImageAnnotation:Qn,updateImageAnnotation:Wm,clearImageAnnotations:zm,togglePhotoFrameDrawingMode:ei,addPhotoFrameAnnotation:ti,updatePhotoFrameAnnotation:Gm,clearPhotoFrameAnnotations:Km,addMultipleChoice:ai,updateMultipleChoice:ca,editMultipleChoice:_m,deleteMultipleChoice:cs,duplicateMultipleChoice:fs,addTrueFalse:oi,updateTrueFalse:fa,deleteTrueFalse:ms,duplicateTrueFalse:ps,addShortAnswer:ri,updateShortAnswer:$o,deleteShortAnswer:hs,duplicateShortAnswer:gs,addLongAnswer:si,updateLongAnswer:Yo,deleteLongAnswer:xs,duplicateLongAnswer:bs,addFillInTheBlanks:ni,updateFillInTheBlanks:Jo,deleteFillInTheBlanks:vs,duplicateFillInTheBlanks:ys,setShowMcqForm:ma,setShowFlashcardForm:Oa,setActivityType:ii,setEditingActivity:Zo,bringToFront:li,sendToBack:di,toggleLock:ui,setLink:ws,setAltText:Ls,setAudioData:Ss,updateLastLine:jm,finalizeDrawing:ci,setLines:Xm,updateLinePosition:$m,updateLineTransform:Is,deleteLineById:Cs,duplicateLine:fi,updateElementOrder:Qo,clearCanvas:mi,undo:pi,redo:hi,saveToHistory:ce,toggleSketchMode:Ym,setSketchMode:ft,setEditingTextId:er,setPresentationTitle:gi,setPresentationDescription:xi,loadPresentationMetadata:bi,setMetadataLoaded:ks}=gd.actions;var xd=e=>e.canvas.slides,fo=e=>e.canvas.currentSlideId,he=createSelector([xd,fo],(e,o)=>e.find(t=>t.id===o)),mo=createSelector([xd],e=>e.filter(o=>o.isActive!==false)),vi=e=>e.canvas.slides,yi=createSelector([mo],e=>e.length<Bn),Jm=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},tr=e=>e.canvas.presentationMetadata,wi=e=>e.canvas.metadataLoaded,bd=gd.reducer;var yd=e=>{let o=xe(),t=useRef(null),a=useRef(false),s=Q(c=>c.toolbar.selectedTool),r=Q(c=>c.toolbar.penColor),n=Q(c=>c.toolbar.strokeWidth),l=Q(c=>c.canvas.isSketchMode),d=Q(c=>c.canvas.slides.find(y=>y.id===c.canvas.currentSlideId)?.lines||[]),u=useCallback(c=>{t.current=c;},[]),m=useCallback(c=>{s==="pen"&&t.current&&(o(ce()),t.current.startDrawing(c),a.current=true);},[s,o]),f=useCallback(c=>{!t.current||!a.current||t.current.draw(c);},[]),i=useCallback(()=>{if(!t.current||!a.current)return;let c=t.current.stopDrawing();a.current=false,c&&c.points.length>=4&&o(Gn(c)),o(ci()),e?.();},[o,e]);return {lines:d,tool:s,color:r,strokeWidth:n,isSketchMode:l,setCanvasRef:u,startDrawing:m,draw:f,stopDrawing:i}};var Id=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:s,isSketchMode:r,style:n,xOffset:l=0,yOffset:d=0},u)=>{let m=useRef(null),f=useRef(false),i=useRef([]),c=useRef([]),p=useRef(null),y=useRef(t),h=useRef(a),x=useRef(s),b=useRef(r),g=useRef(l),L=useRef(d);useEffect(()=>{y.current=t,h.current=a,x.current=s,b.current=r,g.current=l,L.current=d;},[t,a,s,r,l,d]);let C=useCallback(()=>{let k=m.current;if(!k)return;let v=k.getContext("2d");v&&v.clearRect(0,0,k.width,k.height);},[]),S=useCallback(()=>{let k=m.current,v=c.current;if(!k||v.length<1)return;let M=k.getContext("2d");if(!M)return;if(M.clearRect(0,0,k.width,k.height),y.current==="eraser"?(M.globalCompositeOperation="destination-out",M.fillStyle="rgba(0,0,0,1)"):(M.globalCompositeOperation="source-over",M.fillStyle=h.current),v.length===1){M.beginPath(),M.arc(v[0].x,v[0].y,x.current/2,0,Math.PI*2),M.fill();return}let D=Sd(v,{size:x.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:O=>O,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(D.length<2)){M.beginPath(),M.moveTo(D[0][0],D[0][1]);for(let O=1;O<D.length;O++)M.lineTo(D[O][0],D[O][1]);M.closePath(),M.fill();}},[]);return useImperativeHandle(u,()=>({startDrawing:k=>{f.current=true;let v={x:k.x-g.current,y:k.y-L.current};i.current=[{x:k.x,y:k.y}],c.current=[v],p.current=k,S();},draw:k=>{if(!f.current||!p.current)return;let v=k.x-p.current.x,M=k.y-p.current.y;if(Math.sqrt(v*v+M*M)<2)return;let D={x:k.x-g.current,y:k.y-L.current};i.current.push({x:k.x,y:k.y}),c.current.push(D),p.current=k,S();},stopDrawing:()=>{if(!f.current)return null;if(f.current=false,i.current.length<2)return i.current=[],c.current=[],p.current=null,C(),null;let v=Sd(i.current,{size:x.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:B=>B,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(B=>[B[0],B[1]]),M={tool:y.current,points:v,color:h.current,strokeWidth:x.current,isSketch:true};return i.current=[],c.current=[],p.current=null,C(),M},clear:()=>{C(),i.current=[],c.current=[],p.current=null,f.current=false;},isDrawing:()=>f.current,getCanvasElement:()=>m.current}),[C,S]),useEffect(()=>{let k=m.current;k&&(k.width=e,k.height=o);},[e,o]),jsx("canvas",{ref:m,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...n}})});Id.displayName="DirectDrawingCanvas";var Cd=Id;var Md=e=>{let o=xe(),a=Q(he)?.images||[],s=useRef(new Map),r=useRef(new Map),n=useRef(new Set);useEffect(()=>{let m=new Set(a.map(f=>f.id));n.current.forEach(f=>{if(!m.has(f)){let i=r.current.get(f);i&&(i.src="",r.current.delete(f)),s.current.delete(f);}}),n.current=m;},[a]),useEffect(()=>()=>{r.current.forEach(m=>{m.src="";}),r.current.clear(),s.current.clear();},[]);let l=useCallback(m=>{if(r.current.has(m.id))return r.current.get(m.id);let f=new window.Image;return (m.src.startsWith("http://")||m.src.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=m.src,r.current.set(m.id,f),f},[]),d=useCallback((m,f)=>{let i=m.target,c=i.id();a.find(y=>y.id===c)&&(o(lo({id:c,x:i.x(),y:i.y(),width:i.width(),height:i.height(),rotation:i.rotation()})),f?.());},[a,o]),u=useCallback((m,f)=>{let i=f.target,c=s.current.get(m);if(!c){console.error("\u274C Image node not found for id:",m);return}let p=i.scaleX(),y=i.scaleY(),h=i.rotation(),x=c.width(),b=c.height(),g=Math.max(5,x*p),L=Math.max(5,b*y);i.scaleX(1),i.scaleY(1),c.width(g),c.height(L),o(lo({id:m,width:g,height:L,x:i.x(),y:i.y(),rotation:h})),i.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:l,imageRefs:s,handleDragEnd:d,handleImageTransformEnd:u}};var Td=e=>{let o=useDispatch(),t=useSelector(he),a=useRef(new Map),s=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((l,d)=>{let u=d.target,m=u.scaleX(),f=u.scaleY(),i=u.rotation(),c=Math.max(5,u.width()*m),p=Math.max(5,u.height()*f);u.scaleX(1),u.scaleY(1),u.width(c),u.height(p),o(ca({id:l,width:c,height:p,x:u.x(),y:u.y(),rotation:i})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:s,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(l,d)=>{o(ca({id:d,x:l.target.x(),y:l.target.y()})),e?.();}}};var Ad=e=>{let o=useDispatch(),t=useSelector(he),a=useRef(new Map),s=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((l,d)=>{let u=d.target,m=u.scaleX(),f=u.scaleY(),i=u.rotation(),c=Math.max(5,u.width()*m),p=Math.max(5,u.height()*f);u.scaleX(1),u.scaleY(1),u.width(c),u.height(p),o(fa({id:l,width:c,height:p,x:u.x(),y:u.y(),rotation:i})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:s,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(l,d)=>{o(fa({id:d,x:l.target.x(),y:l.target.y()})),e?.();},trueFalseRefs:a}};var Pd=e=>{let o=xe(),a=Q(he)?.videos||[],s=useRef(new Map),r=useCallback(d=>{o(jo(d));},[o]),n=useCallback((d,u)=>{let m=u.target;o(es({id:d,x:m.x(),y:m.y()})),e?.();},[o,e]),l=useCallback((d,u)=>{let m=u.target,f=m.scaleX(),i=m.scaleY(),c=m.rotation(),p=Math.max(5,m.width()*f),y=Math.max(5,m.height()*i);m.scaleX(1),m.scaleY(1),m.width(p),m.height(y),o(es({id:d,width:p,height:y,x:m.x(),y:m.y(),rotation:c})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:s,handleVideoClick:r,handleVideoDragEnd:n,handleVideoTransformEnd:l}};var Ed=e=>{let o=xe(),a=Q(he)?.shapes||[],s=useRef(new Map),r=useRef(new Map),[n,l]=useState(false),d=useCallback((m,f)=>{let i=f.target;o(uo({id:m,x:i.x(),y:i.y()})),e?.();},[o,e]),u=useCallback((m,f)=>{let i=f.target,c=a.find(g=>g.id===m);if(!c)return;let p=i.scaleX(),y=i.scaleY(),h=c.type?.toLowerCase();h==="arrow"||h==="line"||(i.scaleX(1),i.scaleY(1));let b={id:m,x:i.x(),y:i.y(),width:Math.max(5,i.width()*p),height:Math.max(5,i.height()*y),rotation:i.rotation()};switch(h){case "circle":b.radius=i.width()*p/2;break;case "star":b.innerRadius=i.width()*p/4,b.outerRadius=i.width()*p/2;break;case "triangle":b.radius=i.width()*p/2;break;case "ellipse":b.radiusX=i.width()*p/2,b.radiusY=i.height()*y/2;break;case "polygon":b.radius=i.width()*p/2;break;case "ring":let g=p;b.innerRadius=c.innerRadius&&c.innerRadius*g,b.outerRadius=c.outerRadius&&c.outerRadius*g;break;case "wedge":b.radius=c.radius&&c.radius*p;break;case "arc":b.innerRadius=c.innerRadius&&c.innerRadius*p,b.outerRadius=c.outerRadius&&c.outerRadius*p;break;case "arrow":case "line":{b.scaleX=p,b.scaleY=y,delete b.width,delete b.height;break}}o(uo(b)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:s,isDragging:n,loadedShapesRef:r,handleShapeDragEnd:d,handleShapeResizeEnd:u}};var Bd=(e,o)=>{let t=at(),s=Q(he)?.texts||[],r=useRef(new Map),[n,l]=useState(null),[d,u]=useState("");return {texts:s,textRefs:r,handleDragEnd:(h,x)=>{let b=h.target;t(ce()),t(It({id:x,x:b.x(),y:b.y()})),e();},handleTransformEnd:h=>{let x=r.current.get(h);if(!x)return;let b=x.scaleX(),g=x.scaleY(),L=s.find(S=>S.id===h);if(!L)return;let C=(b+g)/2;x.scaleX(1),x.scaleY(1),t(ce()),t(It({id:h,x:x.x(),y:x.y(),width:Math.max(5,(L.width||100)*b),height:Math.max(5,(L.height||50)*g),fontSize:Math.round(Math.max(8,L.fontSize*C)),rotation:x.rotation()})),e();},handleDoubleClick:h=>{let x=s.find(b=>b.id===h);x&&!x.locked&&(l(h),u(x.text));},startEditing:h=>{let x=s.find(b=>b.id===h);x&&!x.locked&&(l(h),u(x.text));},editingTextId:n,editingValue:d,handleEditingChange:h=>{u(h);},finishEditing:()=>{if(n){let h=r.current.get(n),x=s.find(g=>g.id===n);t(ce());let b={id:n,text:d};if(x&&(x.fontWeight!==void 0&&(b.fontWeight=x.fontWeight),x.fontStyle!==void 0&&(b.fontStyle=x.fontStyle),x.textDecoration!==void 0&&(b.textDecoration=x.textDecoration)),o?.current&&d.trim()){let g=o.current,L=g.offsetWidth,C=g.offsetHeight,S=1;if(h){let U=h.getStage();U&&(S=U.scaleX());}let k=14,v=(L-k)/S,M=(C-k)/S,B=d.split(`
|
|
3
|
+
`).length,O=s.find(U=>U.id===n)?.fontSize||24,T=B*O*1.2+10;b.width=Math.max(200,v),b.height=Math.max(50,M,T);}else if(h&&d.trim()){let g=h.text(),L=h.width();h.text(d),h.width(void 0);let C=h.width(),S=h.height();h.text(g),h.width(L),b.width=Math.max(200,C+20),b.height=Math.max(50,S+20);}t(It(b)),l(null),u(""),t(er(null)),e();}}}};var Od=e=>{let o=useDispatch(),a=useSelector(he)?.shortAnswers||[],s=useRef(new Map),r=useCallback((n,l)=>{let d=n.target;o($o({id:l,x:d.x(),y:d.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:s,handleShortAnswerDragEnd:r}};var Nd=e=>{let o=useDispatch(),t=useSelector(he),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),s=useCallback((r,n)=>{let l=r.target;o(Yo({id:n,x:l.x(),y:l.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:s}};var qd=e=>{let o=xe(),a=Q(he)?.flashcards||[],s=useRef(new Map),r=useRef(new Map),n=useCallback((f,i)=>{if(r.current.has(i))return r.current.get(i);let c=new window.Image;return c.src=f,r.current.set(i,c),c},[]),l=useCallback((f,i)=>{let c=f.target,p=c.id();a.find(h=>h.id===p)&&(o(co({id:p,x:c.x(),y:c.y()})),i?.());},[a,o]),d=useCallback((f,i)=>{let c=i.target,p=c.scaleX(),y=c.scaleY(),h=c.rotation(),x=Math.max(50,c.width()*p),b=Math.max(50,c.height()*y);c.scaleX(1),c.scaleY(1),c.width(x),c.height(b),o(co({id:f,width:x,height:b,x:c.x(),y:c.y(),rotation:h})),c.getLayer()?.batchDraw(),e?.();},[o,e]),u=useCallback(f=>{o($n(f)),e?.();},[o,e]),m=useCallback(f=>{o(Yn(f)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:s,handleDragEnd:l,handleFlashcardTransformEnd:d,handleNext:u,handlePrevious:m}};var Wd=e=>{let o=xe(),a=Q(he)?.photoFrames||[],s=useRef(new Map),[r,n]=useState(new Map),l=useCallback((c,p)=>{console.log("handleDragEnd"),o(Ba({id:p,x:c.target.x(),y:c.target.y()})),e?.();},[o,e]),d=useCallback((c,p)=>{let y=p.target,h=y.scaleX(),x=y.scaleY(),b=y.rotation(),g=a.find(S=>S.id===c);if(!g)return;let L=Math.max(100,g.width*h),C=Math.max(100,g.height*x);y.scaleX(1),y.scaleY(1),o(Ba({id:c,width:L,height:C,x:y.x(),y:y.y(),rotation:b})),y.getLayer()?.batchDraw(),e?.();},[o,e,a]),u=useCallback(async c=>{try{let p=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(y=>{let h=new Map(y);return h.set(c,p),h}),o(Ba({id:c,isCapturing:!0})),e?.(),p}catch(p){return console.error("Error accessing camera:",p),null}},[o,e]),m=useCallback(c=>{let p=r.get(c);p&&(p.getTracks().forEach(y=>y.stop()),n(y=>{let h=new Map(y);return h.delete(c),h}),o(Ba({id:c,isCapturing:false})),e?.());},[r,o,e]),f=useCallback((c,p)=>{let y=document.createElement("canvas");y.width=p.videoWidth,y.height=p.videoHeight;let h=y.getContext("2d");if(h){h.drawImage(p,0,0,y.width,y.height);let x=y.toDataURL("image/jpeg",.8);return o(Ba({id:c,capturedImageUrl:x,isCapturing:false})),m(c),e?.(),x}return null},[o,m,e]),i=useRef(r);return useEffect(()=>{i.current=r;},[r]),useEffect(()=>()=>{i.current.forEach(c=>{c.getTracks().forEach(p=>p.stop());});},[]),{photoFrames:a,photoFrameRefs:s,handleDragEnd:l,handlePhotoFrameTransformEnd:d,startCamera:u,stopCamera:m,capturePhoto:f,cameraStreams:r}};var zd=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),a=useCallback((r,n,l,d,u,m,f,i=[])=>{if(e.current){if(r&&!i.find(y=>y.id===r)?.isPlaying){let y=n.get(r)||l.get(r)||d.get(r)||u.get(r)||m.get(r)||(f?f.get(r):null);if(y){e.current.boundBoxFunc(t),e.current.nodes([y]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),s=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:s,boundBoxFunc:t}};var Cp=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},jd=(e,o)=>{let t=at(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let s=useCallback(()=>{if(o.current)try{let n=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});n&&n.startsWith("data:")&&t(Wn({id:a.current,thumbnail:n}));}catch(n){console.warn("Could not generate thumbnail (likely CORS issue with images):",n);}},[o,t]),r=Cp(s,500);return {generateThumbnail:s,debouncedGenerateThumbnail:r}};var Mp=e=>e.flatMap(o=>[o[0],o[1]]),Ts=(e,o)=>{let t=Sd(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:a=>a,start:{taper:0,cap:true},end:{taper:0,cap:true}});return Mp(t)};var Xd=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null),l=Q(g=>g.toolbar.selectedTool),d=Q(g=>g.toolbar.penColor),u=Q(g=>g.toolbar.strokeWidth),m=Q(g=>g.canvas.isSketchMode),f=Q(g=>g.canvas.slides.find(C=>C.id===g.canvas.currentSlideId)?.images.find(C=>C.id===e)),i=f?.annotations||[],c=f?.isDrawingMode||false,p=f?.width||1,y=f?.height||1,h=useCallback(g=>{if(l!=="pen"&&l!=="eraser")return;t.current=true,a.current=false,s.current=[{x:g.x,y:g.y}];let L=g.x/p,C=g.y/y;n({tool:l,points:[L,C],color:d,strokeWidth:u/p,isSketch:m});},[l,d,u,m,p,y]),x=useCallback(g=>{if(!t.current||!r)return;a.current=true;let L=s.current[s.current.length-1];if(Math.sqrt(Math.pow(g.x-L.x,2)+Math.pow(g.y-L.y,2))<2)return;s.current.push({x:g.x,y:g.y});let S;if(m)S=Ts(s.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((v,M)=>M%2===0?v/p:v/y);else {let k=g.x/p,v=g.y/y;S=[...r.points,k,v];}n(k=>k?{...k,points:S}:null);},[m,u,r,p,y]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(Qn({imageId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:i,activeLine:r,isDrawingMode:c,startDrawing:h,draw:x,stopDrawing:b,tool:l}};var Zd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>{let{annotations:l,activeLine:d,stopDrawing:i,tool:c}=Xd(e.id);useEffect(()=>{let b=t.current.get(e.id);b&&(b.width()!==e.width||b.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:b.width(),konvaHeight:b.height()}),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[i,p]);let y=b=>{{r(e.id);return}},h=b=>{return;},x=b=>{};return jsxs(Group,{listening:c!=="pen"&&c!=="eraser",children:[jsx(Image$1,{id:e.id,ref:b=>{if(b){t.current.set(e.id,b),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw();let g=b.getStage()?.container();if(g){let L=C=>{let S=b.getStage()?.getPointerPosition();if(S){let k={x:e.x,y:e.y,width:e.width,height:e.height};S.x>=k.x&&S.x<=k.x+k.width&&S.y>=k.y&&S.y<=k.y+k.height&&n(C,e.id,"image");}};g.addEventListener("contextmenu",L),b._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",L);};}}else {let g=t.current.get(e.id);g?._contextMenuCleanup&&g._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:c!=="pen"&&c!=="eraser",onDragEnd:a,onTransformEnd:b=>s(e.id,b),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...c!=="pen"&&c!=="eraser"?{onClick:y,onTap:y,onMouseDown:y,onTouchStart:y,onMouseMove:h,onTouchMove:h,onMouseUp:x,onTouchEnd:x}:{}}),l?.map((b,g)=>{let L=b.points.map((S,k)=>k%2===0?S*e.width+e.x:S*e.height+e.y),C=b.strokeWidth*e.width;return jsx(Line,{points:L,stroke:b.tool==="eraser"?"white":b.color,strokeWidth:C,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},g)}),d&&jsx(Line,{points:d.points.map((b,g)=>g%2===0?b*e.width+e.x:b*e.height+e.y),stroke:d.tool==="eraser"?"white":d.color,strokeWidth:d.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:d.tool==="eraser"?"destination-out":"source-over",fill:d.isSketch?d.color:void 0,closed:d.isSketch,listening:false},"active")]})});Zd.displayName="ImageWithDrawing";var Ti=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(l=>{let d=o(l);return d?jsx(Zd,{img:l,loadedImage:d,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n},l.id):null})}));Ti.displayName="ImageLayer";var Np=({src:e,x:o,id:t,y:a,width:s,height:r,isSelected:n,rotation:l=0,onTransformEnd:d,onDragEnd:u})=>{let m=xe(),f=useRef(null),i=c=>{m(jo(c));};return jsxs(Group,{draggable:true,x:o,y:a,width:s,height:r,rotation:l,onDragEnd:u,onTransformEnd:d,children:[jsx(Rect,{width:s,height:r,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${s}px`,height:`${r}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:f,src:e,controls:true,autoPlay:true,onClick:()=>i(t),onSeeking:c=>c.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Qd=Np;var Kp=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,nodeRef:n})=>{let[l,d]=useState(null),u=useSelector(y=>y.toolbar.selectedTool),m=u==="pen"||u==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let y=new window.Image;y.src=e.thumbnailDataUrl,y.onload=()=>{d(y);};}},[e.thumbnailDataUrl]),!l)return null;let f=e.width/2,i=e.height/2,c=Math.min(e.width,e.height)*.08,p=Math.max(40,Math.min(c,80));return jsxs(Group,{draggable:!m,listening:!m,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...m?{}:{onDragEnd:a,onTransformEnd:s},ref:y=>{if(n(y),y){let h=y.getStage()?.container();if(h){let x=b=>{let g=y.getStage()?.getPointerPosition();if(g){let L={x:e.x,y:e.y,width:e.width,height:e.height};g.x>=L.x&&g.x<=L.x+L.width&&g.y>=L.y&&g.y<=L.y+L.height&&r(b);}};h.addEventListener("contextmenu",x),y._contextMenuCleanup=()=>{h.removeEventListener("contextmenu",x);};}}},children:[jsx(Image$1,{image:l,width:e.width,height:e.height,listening:!m,...m?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:f,y:i,radius:p,fill:"white",listening:!m,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...m?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:f,y:i,radius:p*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!m,...m?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:f+p*.1,y:i,sides:3,radius:p*.35,fill:"white",rotation:90,listening:!m,...m?{}:{onClick:t,onTap:t}})]})},tu=Kp;var Di=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:s,onTransformEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(l=>jsxs(be__default.Fragment,{children:[jsx(tu,{video:l,isSelected:!l.isPlaying&&o===l.id,onClick:()=>a(l.id),onDragEnd:d=>s(l.id,d),onTransformEnd:d=>r(l.id,d),onContextMenu:d=>n(d,l.id,"video"),nodeRef:d=>{d?t.current.set(l.id,d):t.current.delete(l.id);}}),l.isPlaying&&(()=>{let d=l.x,u=l.y;if(l.isRecorded){let m=typeof window<"u"?window.innerWidth:l.width,f=typeof window<"u"?window.innerHeight:l.height;d=(m-l.width)/2,u=(f-l.height)/2;}return jsx(Qd,{id:l.id,src:l.objectUrl,x:d,y:u,width:l.width,height:l.height,isSelected:false,rotation:l.rotation,onTransformEnd:m=>r(l.id,m),onDragEnd:m=>s(l.id,m)})})()]},l.id))}));Di.displayName="VideoLayer";var Ri=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:s,handleShapeDragStart:r,onContextMenu:n})=>{let l=useSelector(u=>u.toolbar.selectedTool),d=l==="pen"||l==="eraser";return jsx(Fragment,{children:e.map((u,m)=>{let f=u.id||m,i={id:u.id,x:u.x,y:u.y,rotation:u.rotation,draggable:!u.locked&&!d,listening:!d,fill:u.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(u.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},radius:u.radius||u.width/2,width:u.width,height:u.width},f);case "star":return jsx(Star,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},numPoints:5,innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},sides:3,radius:u.radius||u.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},sides:u.sides||6,radius:u.radius||u.width/2},f);case "ellipse":return jsx(Ellipse,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},radiusX:u.radiusX||u.width/2,radiusY:u.radiusY||u.height/2},f);case "ring":return jsx(Ring,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2},f);case "wedge":return jsx(Wedge,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},radius:u.radius||u.width/2,angle:u.angle||60},f);case "arrow":return jsx(Arrow,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,scaleX:u.scaleX||1,scaleY:u.scaleY||1,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},points:u.points||[0,0,u.width,0],pointerLength:u.pointerLength||10,pointerWidth:u.pointerWidth||10,stroke:"#000000",strokeWidth:u.strokeWidth||3,fill:"transparent"},f);case "line":return jsx(Line,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,scaleX:u.scaleX||1,scaleY:u.scaleY||1,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},points:u.points||[0,0,u.width,0],stroke:"#000000",strokeWidth:u.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2,angle:u.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},width:u.width,height:u.height,cornerRadius:u.type==="rounded-rectangle"?10:0},f)}})})});Ri.displayName="ShapeLayer";var ru=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:s,onContextMenu:r,onDoubleClick:n,editingTextId:l})=>{let d=useSelector(m=>m.toolbar.selectedTool),u=d==="pen"||d==="eraser";return jsx(Fragment,{children:e.map(m=>{let f=m.id===l,i=m.fontWeight==="bold",c=i?Math.max(1,m.fontSize/25):0;return jsx(Text,{id:m.id,ref:p=>{p?o.current.set(m.id,p):o.current.delete(m.id);},text:m.text,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:!m.locked&&!f&&!u,listening:!u,fontSize:m.fontSize,fontFamily:m.fontFamily,fontStyle:m.fontStyle,fontWeight:m.fontWeight,textDecoration:m.textDecoration,fill:m.fill,stroke:i?m.fill:void 0,strokeWidth:c,align:m.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...u?{}:{onClick:()=>s(m.id),onTap:()=>s(m.id),onDblClick:()=>n(m.id),onDblTap:()=>n(m.id),onDragEnd:p=>t(p,m.id),onTransformEnd:()=>a(m.id),onContextMenu:p=>{p.evt.preventDefault();let y=p.evt;r(y,m.id,"text");}}},m.id)})})};var gh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onNext:n,onPrevious:l,nodeRef:d})=>{let[u,m]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let h=new window.Image;h.src=e.images[e.currentIndex],h.onload=()=>{m(h);};}},[e.images,e.currentIndex]),!u||e.images.length===0)return null;let f=8,i=2,c=Math.min(e.width,e.height)*.08,p=Math.max(16,Math.min(c,32)),y=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:s,ref:h=>{if(d(h),h){let x=h.getStage()?.container();if(x){let b=g=>{let L=h.getStage()?.getPointerPosition();if(L){let C={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=C.x&&L.x<=C.x+C.width&&L.y>=C.y&&L.y<=C.y+C.height&&r(g);}};x.addEventListener("contextmenu",b),h._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",b);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,stroke:"#E5E7EB",strokeWidth:i,listening:false}),jsx(Image$1,{x:i+4,y:i+4,image:u,width:e.width-(i+4)*2,height:e.height-(i+4)*2,cornerRadius:f-i,onClick:t,onTap:t}),jsx(Rect,{x:i,y:e.height-50,width:e.width-i*2,height:50,cornerRadius:[0,0,f-i,f-i],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:y+p,y:e.height/2,onClick:h=>{h.cancelBubble=true,l();},onTap:h=>{h.cancelBubble=true,l();},children:[jsx(Circle,{radius:p,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-y-p,y:e.height/2,onClick:h=>{h.cancelBubble=true,n();},onTap:h=>{h.cancelBubble=true,n();},children:[jsx(Circle,{radius:p,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},iu=gh;var Bi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onNext:n,onPrevious:l,onContextMenu:d})=>jsx(Fragment,{children:e.map(u=>jsx(iu,{flashcard:u,isSelected:t===u.id,onClick:()=>r(u.id),onDragEnd:a,onTransformEnd:m=>s(u.id,m),onContextMenu:m=>d(m,u.id,"flashcard"),onNext:()=>n(u.id),onPrevious:()=>l(u.id),nodeRef:m=>{m?o.current.set(u.id,m):o.current.delete(u.id);}},u.id))}));Bi.displayName="FlashcardLayer";var du=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null);Q(g=>g.toolbar.selectedTool);let d=Q(g=>g.toolbar.penColor),u=Q(g=>g.toolbar.strokeWidth),m=Q(g=>g.canvas.isSketchMode),f=Q(g=>g.canvas.slides.find(C=>C.id===g.canvas.currentSlideId)?.photoFrames.find(C=>C.id===e)),i=f?.annotations||[],c=f?.isDrawingMode||false,p=f?.width||1,y=f?.height||1,h=useCallback(g=>{if(!c)return;t.current=true,a.current=false,s.current=[{x:g.x,y:g.y}];let L=g.x/p,C=g.y/y;n({tool:"pen",points:[L,C],color:d,strokeWidth:u/p,isSketch:m});},[c,d,u,m,p,y]),x=useCallback(g=>{if(!t.current||!r)return;a.current=true;let L=s.current[s.current.length-1];if(Math.sqrt(Math.pow(g.x-L.x,2)+Math.pow(g.y-L.y,2))<2)return;s.current.push({x:g.x,y:g.y});let S;if(m)S=Ts(s.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((v,M)=>M%2===0?v/p:v/y);else {let k=g.x/p,v=g.y/y;S=[...r.points,k,v];}n(k=>k?{...k,points:S}:null);},[m,u,r,p,y]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(ti({frameId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:i,activeLine:r,isDrawingMode:c,startDrawing:h,draw:x,stopDrawing:b}};var Ih=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onStartCamera:n,onCapture:l,cameraStream:d,nodeRef:u})=>{let[m,f]=useState(null),[i,c]=useState(null),p=useRef(null),y=useRef(null),h=useRef(null),x=useRef(null),b=useRef(0),g=33,L=useSelector(q=>q.toolbar.selectedTool),C=L==="pen"||L==="eraser",{annotations:S,activeLine:k,isDrawingMode:v,startDrawing:M,draw:B,stopDrawing:D}=du(e.id);useEffect(()=>{if(!v)return;let q=()=>{D();},_=()=>{D();};return window.addEventListener("mouseup",q),window.addEventListener("touchend",_),()=>{window.removeEventListener("mouseup",q),window.removeEventListener("touchend",_);}},[D,v]),useEffect(()=>{if(e.capturedImageUrl){let q=new window.Image;q.src=e.capturedImageUrl,q.onload=()=>{f(q);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&d){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),y.current||(y.current=document.createElement("canvas"));let q=p.current,_=y.current;q.srcObject=d;let H=()=>{_.width=q.videoWidth||640,_.height=q.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",_.width,_.height);let K=te=>{if(te-b.current<g){h.current=requestAnimationFrame(K);return}b.current=te;let Z=_.getContext("2d");if(Z&&q.readyState===q.HAVE_ENOUGH_DATA){Z.drawImage(q,0,0,_.width,_.height);let J=_.toDataURL("image/jpeg",.6),le=new window.Image;le.onload=()=>{c(le);},le.src=J;}h.current=requestAnimationFrame(K);};h.current=requestAnimationFrame(K);};return q.onloadedmetadata=H,q.readyState>=q.HAVE_METADATA&&H(),q.play().catch(K=>console.error("Error playing video:",K)),()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null);}}return ()=>{c(null),x.current&&(x.current.src="");}},[e.isCapturing,d]);let O=()=>{p.current&&e.isCapturing&&l(p.current);},W=q=>{if(e.capturedImageUrl){if(!v){t();return}let _=q.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);M(Z);}q.cancelBubble=true;}else t();},T=q=>{if(!v||!e.capturedImageUrl)return;let _=q.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);B(Z);}},U=()=>{!v||!e.capturedImageUrl||D();},R=e.isCapturing?i:m,oe=Math.min(e.width,e.height)*.12,V=Math.max(25,Math.min(oe,50)),se=e.width/2,G=e.height/2;return jsxs(Group,{id:e.id,draggable:!v&&!C,listening:true,x:e.x,y:e.y,...C?{}:{onDragEnd:a,onTransformEnd:s},rotation:e.rotation,width:e.width,height:e.height,ref:q=>{if(u(q),q){let _=q.getStage()?.container();if(_){let H=K=>{let te=q.getStage()?.getPointerPosition();if(te){let Z={x:e.x,y:e.y,width:e.width,height:e.height};te.x>=Z.x&&te.x<=Z.x+Z.width&&te.y>=Z.y&&te.y<=Z.y+Z.height&&r(K);}};_.addEventListener("contextmenu",H),q._contextMenuCleanup=()=>{_.removeEventListener("contextmenu",H);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:R?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),R&&jsx(Image$1,{image:R,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:W,onTap:W,onMouseDown:W,onTouchStart:W,onMouseMove:T,onTouchMove:T,onMouseUp:U,onTouchEnd:U,...C?{}:{onDragEnd:a,onTransformEnd:s}}),S?.map((q,_)=>{let H=q.points.map((te,Z)=>Z%2===0?te*e.width:te*e.height),K=q.strokeWidth*e.width;return jsx(Line,{points:H,stroke:q.tool==="eraser"?"white":q.color,strokeWidth:K,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:q.tool==="eraser"?"destination-out":"source-over",fill:q.isSketch?q.color:void 0,closed:q.isSketch,listening:false},_)}),k&&jsx(Line,{points:k.points.map((q,_)=>_%2===0?q*e.width:q*e.height),stroke:k.tool==="eraser"?"white":k.color,strokeWidth:k.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:k.tool==="eraser"?"destination-out":"source-over",fill:k.isSketch?k.color:void 0,closed:k.isSketch,listening:false},"active"),!R&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:G-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:se-V+6,y:G-60,width:V*1.6,height:V*1.6,radius:V,fill:"white",cornerRadius:8,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?O():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?O():n();}}),jsx(Html,{groupProps:{x:se-12,y:G-40,width:V*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?O():n();}})})]}),jsx(Text,{x:0,y:G,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:G+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:se-24,y:G+104,width:V*1.6,height:V*1.6,radius:V,fill:"#096B76",cornerRadius:V,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?O():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?O():n();}}),jsx(Html,{groupProps:{x:se-8,y:G+120,width:V*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?O():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:se-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:q=>{q.stopPropagation(),O();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},mu=Ih;var Ui=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onStartCamera:n,onCapture:l,cameraStreams:d,onContextMenu:u})=>jsx(Fragment,{children:e.map(m=>jsx(mu,{photoFrame:m,isSelected:t===m.id,onClick:()=>r(m.id),onDragEnd:f=>a(f,m.id),onTransformEnd:f=>s(m.id,f),onContextMenu:f=>u(f,m.id,"photoFrame"),onStartCamera:()=>n(m.id),onCapture:f=>l(m.id,f),cameraStream:d.get(m.id),nodeRef:f=>{f?o.current.set(m.id,f):o.current.delete(m.id);}},m.id))}));Ui.displayName="PhotoFrameLayer";var xu=({x:e,y:o,onAction:t,onClose:a,type:s,elementId:r="",isDrawingMode:n,menuRef:l})=>{useEffect(()=>{let f=c=>{l?.current&&!l.current.contains(c.target)&&a();},i=c=>{c.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",i),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",i);}},[a]);let d=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:n?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(i=>!(i.showForTypes&&!i.showForTypes.includes(s)||i.hideForTypes&&i.hideForTypes.includes(s))),[s,n]),u=(f,i)=>{f==="order"||f==="lock"?t(f,i):(t(f),a());},m=jsx("div",{ref:l,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:d.map((f,i)=>jsxs("button",{onClick:c=>u(f.action,c),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${f.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[f.icon,jsx("span",{className:`font-medium ${f.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:f.label})]}),f.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},i))})});return createPortal(m,document.body)};var bu=({x:e,y:o,items:t,onClose:a})=>{let s=useRef(null);return useEffect(()=>{let r=n=>{s.current&&!s.current.contains(n.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:s,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((r,n)=>jsx("button",{onClick:()=>{r.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:r.label})},n))})})};var yu=createContext(null),Wi=()=>useContext(yu);function Yh({children:e,className:o="",style:t}){let a=useRef(null),[s,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(yu.Provider,{value:s,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function ot(){let e=Wi();return typeof document>"u"?null:e||document.body}var wu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:s,onClose:r})=>{let[n,l]=useState(a),d=useRef(null),u=ot();useEffect(()=>{d.current?.focus();},[]);let m=()=>{s(n),r();},f=c=>{c.key==="Enter"?m():c.key==="Escape"&&r();};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:d,type:"text",value:n,onChange:c=>l(c.target.value),onKeyDown:f,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:r,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:m,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),u):null};var Fs=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,s]=useState(e),r=useRef(null),n=ot();useEffect(()=>{let f=i=>{i.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let l=f=>{f.preventDefault(),o(a);},d=(f,i,c)=>{c/=100;let p=i*Math.min(c,1-c)/100,y=h=>{let x=(h+f/30)%12,b=c-p*Math.max(Math.min(x-3,9-x,1),-1);return Math.round(255*b).toString(16).padStart(2,"0")};return `#${y(0)}${y(8)}${y(4)}`},u=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!n)return null;let m=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:r,className:"max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:l,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:f=>s(f.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:f=>s(f.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:f=>{let i=parseInt(f.target.value),c=d(i,100,50);s(c);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:u.map(f=>jsx("button",{type:"button",onClick:()=>s(f),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===f.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:f},title:f},f))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(m,n)};var hg=({imageSrc:e,onCrop:o})=>{let[t]=Iu(e),a=useRef(null),s=useRef(null),r=useRef(null),n=useMemo(()=>{if(!t)return {width:600,height:400};let p=Math.min(600/t.width,400/t.height);return {width:t.width*p,height:t.height*p}},[t]),l=useMemo(()=>{let i=n.width*.5,c=n.height*.5,p=(n.width-i)/2,y=(n.height-c)/2;return {x:p,y,width:i,height:c}},[n]),[d,u]=useState(l);useEffect(()=>{u(l);},[l]),useEffect(()=>{r.current&&s.current&&(r.current.nodes([s.current]),r.current.getLayer()?.batchDraw());},[d]),useEffect(()=>{o(d.x,d.y,d.width,d.height);},[d,o]);let m=()=>{let i=s.current;if(!i)return;let c=i.scaleX(),p=i.scaleY();i.scaleX(1),i.scaleY(1),u({x:i.x(),y:i.y(),width:Math.max(20,i.width()*c),height:Math.max(20,i.height()*p)});},f=()=>{let i=s.current;i&&u({x:i.x(),y:i.y(),width:i.width(),height:i.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:d.x,y:d.y,width:d.width,height:d.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:s,x:d.x,y:d.y,width:d.width,height:d.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:f,onTransformEnd:m,dragBoundFunc:i=>{let c=Math.max(0,Math.min(i.x,n.width-d.width)),p=Math.max(0,Math.min(i.y,n.height-d.height));return {x:c,y:p}}}),jsx(Transformer,{ref:r,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(i,c)=>c.width<20||c.height<20||c.x<0||c.y<0||c.x+c.width>n.width||c.y+c.height>n.height?i:c})]})})},Cu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[s,r]=useState({x:0,y:0,width:0,height:0}),[n]=Iu(e),l=ot();useEffect(()=>{let f=i=>{i.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let d=(f,i,c,p)=>{r({x:f,y:i,width:c,height:p});},u=()=>{if(!n)return;let c=Math.min(600/n.width,400/n.height),p=s.x/c,y=s.y/c,h=s.width/c,x=s.height/c,b=document.createElement("canvas");b.width=h,b.height=x;let g=b.getContext("2d");if(!g)return;g.drawImage(n,p,y,h,x,0,0,h,x);let L=b.toDataURL("image/png");o(L);};return l?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(hg,{imageSrc:e,onCrop:d})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:u,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),l):null};var dr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[s,r]=useState(false),[n,l]=useState(null),[d,u]=useState(0),[m,f]=useState(true),i=useRef(null),c=useRef([]),p=useRef(null),y=useRef(null),h=useRef(null),x=useRef(null),b=useRef(null),g=useRef(null);useEffect(()=>()=>{h.current&&cancelAnimationFrame(h.current),p.current&&clearInterval(p.current),y.current&&y.current.getTracks().forEach(v=>v.stop());},[]);let L=async()=>{try{let v,M=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let T=o.current.getLayers();console.log("Konva layers:",T.length),T.forEach((_,H)=>{let K=_.getChildren();console.log(`Layer ${H} children count:`,K.length);});let U=document.createElement("canvas");U.width=o.current.width(),U.height=o.current.height();let R=U.getContext("2d",{willReadFrequently:!1});if(!R){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",U.width,"x",U.height),b.current=U;let oe=()=>{if(R.clearRect(0,0,U.width,U.height),T.forEach(_=>{let H=_.getCanvas()._canvas;H&&R.drawImage(H,0,0);}),a?.current){let _=a.current;R.drawImage(_,0,0);}};g.current=oe,o.current.draw(),oe(),await new Promise(_=>setTimeout(_,100)),console.log("Creating captureStream..."),v=U.captureStream(30),console.log("Canvas stream created, tracks:",v.getTracks().length);let se=v.getVideoTracks()[0];se&&console.log("Video track:",se.label,"state:",se.readyState);let G=0,q=()=>{oe(),o?.current&&(o.current.getLayers().forEach(H=>{H.batchDraw();}),G++,G%60===0&&console.log("Drawing frame:",G)),h.current=requestAnimationFrame(q);};q();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(m)try{M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(T){console.warn("Microphone access denied:",T);}let B=[...v.getVideoTracks()];M&&B.push(...M.getAudioTracks());let D=new MediaStream(B);y.current=D;let O="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?O="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?O="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?O="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(O="video/webm;codecs=vp8"),console.log("Using mimeType:",O);let W=new MediaRecorder(D,{mimeType:O,videoBitsPerSecond:25e5});i.current=W,c.current=[],W.ondataavailable=T=>{console.log("Data available, size:",T.data.size),T.data.size>0&&c.current.push(T.data);},W.onstop=()=>{console.log("Recording stopped, chunks:",c.current.length);let T=new Blob(c.current,{type:O});console.log("Final blob size:",T.size),o?.current&&g.current&&b.current&&(o.current.draw(),o.current.getLayers().forEach(R=>{R.batchDraw();}),g.current(),x.current=b.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",x.current.length)),D.getTracks().forEach(U=>U.stop()),p.current&&clearInterval(p.current),h.current&&(cancelAnimationFrame(h.current),h.current=null),l(T);},W.onerror=T=>{console.error("MediaRecorder error:",T);},console.log("Starting recording..."),W.start(1e3),r(!0),u(0),p.current=setInterval(()=>{u(T=>T+1);},1e3);}catch(v){console.error("Error starting screen recording:",v),alert("Failed to start recording. Please ensure you granted permission.");}},C=()=>{i.current&&s&&(console.log("Stopping recording, state:",i.current.state),i.current.state!=="inactive"&&(i.current.requestData(),setTimeout(()=>{i.current&&i.current.state!=="inactive"&&i.current.stop();},100)),r(false));},S=()=>{if(n){let v=URL.createObjectURL(n),M=document.createElement("a");M.href=v,M.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(v);}},k=v=>{let M=Math.floor(v/60),B=v%60;return `${M.toString().padStart(2,"0")}:${B.toString().padStart(2,"0")}`};return s?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:k(d)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:C,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!n&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>f(!m),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${m?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:m?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:L,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),n&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(n),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",k(d)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&n&&x.current&&(t(n,x.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:S,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{l(null),u(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})})};var Tu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:s})=>{let r=ot(),[n,l]=useState(false),[d,u]=useState(null),[m,f]=useState(false),[i,c]=useState(0),p=useRef(null),y=useRef([]),h=useRef(null),x=useRef(null);useEffect(()=>{o&&!d&&fetch(o).then(B=>B.blob()).then(B=>u(B)).catch(B=>console.error("Error loading audio:",B));},[o,d]);let b=async()=>{try{let B=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),D=new MediaRecorder(B);p.current=D,y.current=[],D.ondataavailable=O=>{O.data.size>0&&y.current.push(O.data);},D.onstop=()=>{let O=new Blob(y.current,{type:"audio/webm"});u(O),B.getTracks().forEach(W=>W.stop()),h.current&&clearInterval(h.current);},D.start(),l(!0),c(0),h.current=setInterval(()=>{c(O=>O+1);},1e3);}catch(B){console.error("Error starting audio recording:",B),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{p.current&&n&&(p.current.stop(),l(false));},L=()=>{if(d){let B=URL.createObjectURL(d),D=new Audio(B);x.current=D,D.onended=()=>{f(false),URL.revokeObjectURL(B);},D.play(),f(true);}},C=()=>{x.current&&(x.current.pause(),x.current.currentTime=0,f(false));},S=async()=>{if(d){let B=new FileReader;B.onloadend=()=>{let D=B.result;t(D),s();},B.readAsDataURL(d);}},k=()=>{u(null),a();},v=B=>{let D=Math.floor(B/60),O=B%60;return `${D.toString().padStart(2,"0")}:${O.toString().padStart(2,"0")}`};if(!r)return null;if(n){let B=jsx("div",{className:"pointer-events-none fixed inset-0 z-50",children:jsxs("div",{className:"pointer-events-auto fixed top-[100px] left-1/2 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:v(i)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:g,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]})});return createPortal(B,r)}let M=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!d&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:b,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),d&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:m?C:L,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),m?"Playing...":"Play Audio"]}),jsx("button",{onClick:k,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:S,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:s,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})});return createPortal(M,r)};var kt=({audioData:e,x:o,y:t,width:a,scale:s=1,offsetX:r=0,offsetY:n=0,containerTop:l=90,containerRight:d=320})=>{let[u,m]=useState(false),f=useRef(null),i=y=>{if(y.stopPropagation(),u&&f.current)f.current.pause(),f.current.currentTime=0,m(false);else {let h=new Audio(e);f.current=h,h.onended=()=>{m(false);},h.onerror=()=>{console.error("Error playing audio"),m(false);},h.play(),m(true);}},c=(o+a)*s+r-15,p=t*s+n+l-15;return jsx("button",{onClick:i,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${u?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${c}px`,top:`${p}px`,width:"30px",height:"30px",zIndex:99},title:u?"Stop Audio":"Play Audio",children:u?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var Du=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),s=Q(he),r=useMemo(()=>{if(!s)return [];let h=[];return s.images?.forEach(x=>{h.push({id:x.id,type:"image",name:"Image",timestamp:x.timestamp||0});}),s.videos?.forEach(x=>{h.push({id:x.id,type:"video",name:"Video",timestamp:x.timestamp||0});}),s.shapes?.forEach(x=>{h.push({id:x.id,type:"shape",name:`${x.type} Shape`,timestamp:x.timestamp||0});}),s.texts?.forEach(x=>{h.push({id:x.id,type:"text",name:x.text.substring(0,20)+(x.text.length>20?"...":""),timestamp:x.timestamp||0});}),s.flashcards?.forEach(x=>{h.push({id:x.id,type:"flashcard",name:`Flashcard (${x.images.length} images)`,timestamp:x.timestamp||0});}),s.photoFrames?.forEach(x=>{h.push({id:x.id,type:"photoFrame",name:"Photo Frame",timestamp:x.timestamp||0});}),s.multipleChoices?.forEach(x=>{h.push({id:x.id,type:"mcq",name:"Multiple Choice",timestamp:x.timestamp||0});}),s.trueFalses?.forEach(x=>{h.push({id:x.id,type:"trueFalse",name:"True/False",timestamp:x.timestamp||0});}),s.shortAnswers?.forEach(x=>{h.push({id:x.id,type:"shortAnswer",name:"Short Answer",timestamp:x.timestamp||0});}),s.LongAnswer?.forEach(x=>{h.push({id:x.id,type:"longAnswer",name:"Long Answer",timestamp:x.timestamp||0});}),s.fillInTheBlanks?.forEach(x=>{h.push({id:x.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:x.timestamp||0});}),s.lines?.forEach(x=>{x.id&&h.push({id:x.id,type:"line",name:"Drawn Line",timestamp:x.timestamp||0});}),h.sort((x,b)=>b.timestamp-x.timestamp)},[s]),[n,l]=useState(r),[d,u]=useState(false);useEffect(()=>{d||l(r);},[r]);let m=h=>{let x="h-5 w-5";switch(h){case "image":return jsx(Image$3,{className:x});case "video":return jsx(VideoCamera,{className:x});case "shape":return jsx(Shapes$1,{className:x});case "text":return jsx(TextT,{className:x});case "flashcard":return jsx(Cards$1,{className:x});case "photoFrame":return jsx(FrameCorners,{className:x});case "line":return jsx(Pen,{className:x});default:return jsx(Question,{className:x})}},c=h=>{u(true),l(h);},p=()=>{u(false);let h=Date.now();n.forEach((x,b)=>{let g=h-b;a(Qo({id:x.id,type:x.type,newTimestamp:g}));});},y=jsxs("div",{className:"konva-editor-root",children:[jsx("div",{className:"fixed inset-0 z-9999 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-10000 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$2,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:n.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:n,onReorder:c,className:"space-y-1",children:n.map(h=>{let x=h.id===e;return jsxs(Reorder.Item,{value:h,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${x?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(h.id,h.type),className:`font-medium ${x?"text-[#096B76]":"text-[#00000099]"}`,children:h.name})}),jsx("div",{className:`${x?"text-[#096B76]":"text-[#00000099]"}`,children:m(h.type)})]},h.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[n.length," Layers"]})]})]})]});return createPortal(y,document.body)};var Ru=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>{let n=useSelector(G=>G.toolbar.selectedTool),l=n==="pen"||n==="eraser",[d,u]=useState(new Set),[m,f]=useState(false),[i,c]=useState(null),p=useRef(null);useEffect(()=>{let G=p.current;if(G)return a.current.set(e.id,G),()=>{a.current.delete(e.id);}},[e.id]);let y=new Set(e.data.responseOptions.correctIndex),h=y.size>1,x=G=>{m||u(h?q=>{let _=new Set(q);return _.has(G)?_.delete(G):_.add(G),_}:new Set([G]));},b=()=>{d.size>0&&f(true);},g=()=>{f(false),u(new Set);},L=d.size===y.size&&Array.from(d).every(G=>y.has(G)),C=Array.from(d).filter(G=>y.has(G)),S=h&&C.length>0&&!L,k=()=>L?"\u2713 Correct! Great job! \u{1F389}":S?`\u26A0 Partially correct (${C.length}/${y.size})`:"\u2717 Try again!",v=()=>L?{bg:"#dcfce7",text:"#166534"}:S?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},M=55,B=8,D=24,O=60,W=60,T=h&&!m?25:0,U=e.data.feedbackMode==="practice"?48:0,R=12,oe=O+T+(m?W:0),V=e.data.responseOptions.options.length*(M+B),se=oe+V+R+U+D;return jsxs(Group,{ref:p,name:"mcq-element",draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...l?{}:{onDragEnd:s,onClick:G=>t(e.id),onTap:G=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:se,width:e.width,onTransformEnd:G=>o(e.id,G),onContextMenu:G=>{G.cancelBubble=true,r(G.evt,e.id,"mcq");}}),jsx(Text,{x:D+8,y:D,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-D*2,listening:false}),h&&!m&&e.data.feedbackMode==="practice"?jsx(Text,{x:D,y:D+35,text:`Select ${y.size} answers (${d.size}/${y.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-D*2,listening:false}):null,m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:D+24,y:O+T,width:e.width-D*2-40,height:W-20,fill:v().bg,cornerRadius:8}),jsx(Text,{x:D,y:O+T,width:e.width-D*2,height:W-20,text:k(),fontSize:16,fontStyle:"bold",fill:v().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((G,q)=>{let _=y.has(q),H=d.has(q),K=oe+q*(M+B),te="#e5e7eb",Z="#ffffff",J="#111827";return m&&_?(te="#22c55e",Z="#dcfce7",J="#1B9D2C"):m&&H&&!_?(te="#ef4444",Z="#fee2e2",J="#ef4444"):H&&(te="#096B76",Z="#ECFFF8",J="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:D+12,y:K+(M-20)/2,width:20,height:20,fill:H?"#096B76":"white",stroke:H?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:h?4:10,onClick:le=>{le.cancelBubble=true,x(q);},onTap:le=>{le.cancelBubble=true,x(q);}}),H&&jsx(Text,{x:D+12,y:K+(M-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:D+44,y:K,width:e.width-D*2-60,height:M,fill:Z,stroke:te,strokeWidth:2,cornerRadius:8,onClick:le=>{le.cancelBubble=true,x(q);},onTap:le=>{le.cancelBubble=true,x(q);}}),jsx(Text,{x:D+60,y:K,width:e.width-D*2-80,height:M,text:G,fontSize:16,fill:J,verticalAlign:"middle",listening:false})]},q)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:oe+e.data.responseOptions.options.length*(M+B)+12,children:[jsxs(Group,{onMouseDown:G=>{G.cancelBubble=true,c("check");},onMouseUp:G=>{G.cancelBubble=true,c(null),b();},onMouseLeave:G=>{G.cancelBubble=true,c(null);},onTouchStart:G=>{G.cancelBubble=true,c("check");},onTouchEnd:G=>{G.cancelBubble=true,c(null),b();},scaleX:i==="check"?.95:1,scaleY:i==="check"?.95:1,children:[jsx(Rect,{x:D+14,width:(e.width-D*2-24)/(m?2:1),height:48,fill:d.size===0||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:D+14,width:(e.width-D*2-24)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-D*2)/2+8,onMouseDown:()=>c("reset"),onMouseUp:()=>{c(null),g();},onMouseLeave:()=>c(null),onTouchStart:()=>c("reset"),onTouchEnd:()=>{c(null),g();},scaleX:i==="reset"?.95:1,scaleY:i==="reset"?.95:1,children:[jsx(Rect,{x:D,width:(e.width-D*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:D,width:(e.width-D*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ru.displayName="MultipleChoice";var Eu=Ru;var _i=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:s})=>{let r=useDispatch(),n=useSelector(H=>H.toolbar.selectedTool),l=n==="pen"||n==="eraser",[d,u]=useState(false),[m,f]=useState(new Set),[i,c]=useState(false),[p,y]=useState(false),[h,x]=useState(0),b=340,g=100,L=window.innerWidth*.4,C=window.innerHeight*.5,S=b+20,k=g+60,v=L-40,M=C-300,B=useRef(null);useEffect(()=>{let H=B.current;if(H)return s.current.set(e.id,H),()=>{s.current.delete(e.id);}},[e.id]);let D=H=>{r(ca({id:e.id,x:H.target.x(),y:H.target.y()}));},O=H=>{let K=H.target,te=K.x(),Z=K.y(),J=window.innerWidth*.2,Ie=te+J>S&&te<S+v&&Z+50>k&&Z<k+M;u(Ie);},W=(H,K)=>{let te=K.target,Z=te.x(),J=te.y(),le=window.innerWidth*.2,Y=Z+le>S&&Z<S+v&&J+50>k&&J<k+M;f(Y?Me=>new Set(Me).add(H):Me=>{let Be=new Set(Me);return Be.delete(H),Be}),u(false);},T=()=>{c(true);},U=()=>{c(false),f(new Set),x(H=>H+1);},R=new Set(e.data.responseOptions.correctIndex),oe=m.size===R.size&&Array.from(m).every(H=>R.has(H)),V=Array.from(m).filter(H=>R.has(H)),se=V.length>0&&!oe,G=()=>oe?"\u2713 Correct! Great job!":se?`\u26A0 Partially correct (${V.length}/${R.size})`:"\u2717 Try again!",q=()=>oe?{bg:"#dcfce7",text:"#166534"}:se?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},_=()=>i?oe?"#4CAF50":se?"#f59e0b":"#ef4444":d?"#4CAF50":"#075560";return jsxs(Group,{ref:B,name:"mcq-element",width:L,height:C,draggable:!l,listening:!l,...l?{}:{onClick:H=>a(e.id),onTap:H=>a(e.id),onContextMenu:H=>{H.evt.preventDefault(),o(H.evt,e.id,"mcq");}},children:[jsxs(Group,{x:b,y:g,rotation:e.rotation,onDragEnd:D,children:[jsx(Rect,{fill:"white",stroke:d?"#4CAF50":"#e5e7eb",strokeWidth:d?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?C-100:C-50,width:L,shadowColor:d?"#4CAF50":"transparent",shadowBlur:d?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:v,height:M,fill:"#EBF6F7",stroke:_(),strokeWidth:3,dash:[10,10],cornerRadius:8}),i&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:M+18,width:v-5,height:60,fill:q().bg,cornerRadius:8}),jsx(Text,{x:20,y:M+20,width:v,height:60,text:G(),fontSize:18,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle"})]}),m.size===0&&!i&&jsx(Text,{x:20,y:60,width:v,height:M-60,text:R.size>1?`Drop ${R.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:i?C-200:C-160,children:[jsxs(Group,{onMouseDown:()=>{y(true),T();},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{y(true),T();},onTouchEnd:()=>y(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:v}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:v,height:40,align:"center",verticalAlign:"middle",listening:false})]}),i&&jsxs(Group,{y:50,onMouseDown:U,onTouchStart:U,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:v}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:v,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((H,K)=>{let te=K%2,Z=Math.floor(K/2),J=window.innerWidth*.2,le=50,Ie=10,Y=m.has(K),Me=R.has(K),Be=i&&Y,Et="transparent";return Be?Et=Me?"#4CAF50":"#ef4444":Y&&(Et="#4CAF50"),jsxs(Group,{x:340+te*(J+Ie),y:g+C-80+Z*(le+Ie),draggable:!i,onDragMove:O,onDragEnd:oo=>W(K,oo),opacity:i&&!Y?.5:1,children:[jsx(Rect,{width:J-20,height:le,fill:"white",stroke:Et,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:J-20,height:le,text:H,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${K}-${h}`)})]})};_i.displayName="MultipleChoiceDragAndDrop";var Fu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Eu,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:l=>s(l,n.id),onContextMenu:r},n.id):jsx(_i,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r},n.id))});var Bu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(R=>R.toolbar.selectedTool),l=n==="pen"||n==="eraser",[d,u]=useState(null),[m,f]=useState(false),[i,c]=useState(null),p=useRef(null);useEffect(()=>{let R=p.current;if(R)return a.current.set(e.id,R),()=>{a.current.delete(e.id);}},[e.id]);let y=()=>{d!==null&&f(true);},h=()=>{f(false),u(null);},x=e.data.responseOptions.correctAnswer,b=d===x,g=R=>{m||u(R);},L=()=>b?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},S=70,k=12,v=24,M=60,B=60,D=e.data.feedbackMode==="practice"?48:0,O=12,W=M+(m?B:0),T=2*(S+k),U=W+T+O+D+v;return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...l?{}:{onDragEnd:R=>r(R,e.id),onClick:R=>t(e.id),onTap:R=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:U-20,width:e.width,onTransformEnd:R=>o(e.id,R),onContextMenu:R=>{R.cancelBubble=true,s(R.evt,e.id,"trueFalse");}}),jsx(Text,{x:v,y:v,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-v*2,listening:false}),m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:v,y:M,width:e.width-v*2,height:B-10,fill:C().bg,cornerRadius:8}),jsx(Text,{x:v,y:M,width:e.width-v*2,height:B-10,text:L(),fontSize:16,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((R,oe)=>{let V=x===R.value,se=d===R.value,G=(e.width-v*3)/2,q=v+oe*(G+v),_=W,H=R.value===true,K=H?"#10b981":"#ef4444",te="#ffffff",Z="#ffffff",J="#e5e7eb";return m&&(V?(Z=H?"#f0fdf4":"#fef2f2",J=H?"#86efac":"#fecaca"):se&&!V&&(Z="#fee2e2",J="#ef4444")),se&&!m&&(J="#096B76",Z="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:q,y:_,width:G,height:S+50,fill:Z,stroke:J,strokeWidth:2,cornerRadius:12,onClick:le=>{le.cancelBubble=true,g(R.value);},onTap:le=>{le.cancelBubble=true,g(R.value);}}),jsx(Circle,{x:q+G/2,y:_+40,radius:28,fill:K,listening:false}),H?jsx(Text,{x:q+G/2-14,y:_+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:q+G/2-14,y:_+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:q,y:_+85,width:G,height:30,text:R.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},R.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:W+2*(S+k),children:[jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,c("check");},onMouseUp:R=>{R.cancelBubble=true,c(null),y();},onMouseLeave:R=>{R.cancelBubble=true,c(null);},onTouchStart:R=>{R.cancelBubble=true,c("check");},onTouchEnd:R=>{R.cancelBubble=true,c(null),y();},scaleX:i==="check"?.95:1,scaleY:i==="check"?.95:1,children:[jsx(Rect,{x:v,width:(e.width-v*2-8)/(m?2:1),height:48,fill:d===null||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:v,width:(e.width-v*2-8)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-v*2)/2+8,onMouseDown:()=>c("reset"),onMouseUp:()=>{c(null),h();},onMouseLeave:()=>c(null),onTouchStart:()=>c("reset"),onTouchEnd:()=>{c(null),h();},scaleX:i==="reset"?.95:1,scaleY:i==="reset"?.95:1,children:[jsx(Rect,{x:v,width:(e.width-v*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:v,width:(e.width-v*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Bu.displayName="TrueFalse";var Ou=Bu;var mx="#FFFFFF",$i=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),s=useSelector(K=>K.toolbar.selectedTool),r=s==="pen"||s==="eraser",[n,l]=useState(false),[d,u]=useState(null),[m,f]=useState(false),[i,c]=useState(false),[p,y]=useState(0),[h,x]=useState(false),b=340,g=100,L=window.innerWidth*.4,C=window.innerHeight*.5,S=L-40,k=C-300,v=20,M=60,B=S,D=k,O=L*.2-40,W=50,T=useRef(null),U=K=>{a(fa({id:e.id,x:K.target.x(),y:K.target.y()}));},R=K=>{let te=K.target,Z=te.x(),J=te.y(),le=Math.max(0,Math.min(Z+O,v+B)-Math.max(Z,v)),Ie=Math.max(0,Math.min(J+W,M+D)-Math.max(J,M)),Y=le*Ie,Me=O*W;l(Y/Me>=.5);},oe=(K,te)=>{let Z=te.target,J=Z.x(),le=Z.y(),Ie=Math.max(0,Math.min(J+O,v+B)-Math.max(J,v)),Y=Math.max(0,Math.min(le+W,M+D)-Math.max(le,M)),Me=Ie*Y,Be=O*W;if(Me/Be>=.5)u(K);else return;l(false);},V=()=>{f(true);},se=()=>{f(false),u(null),y(K=>K+1);},G=e.data.responseOptions.correctAnswer,q=d===G,_=()=>q?"\u2713 Correct! Great job!":"\u2717 Try again!",H=()=>q?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:T,name:"trueFalse-element",width:L,height:C,draggable:!r,listening:!r,...r?{}:{onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:g,rotation:e.rotation,onDragEnd:U,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:m?C:e.data.feedbackMode==="practice"?C-50:C-100,width:L,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:S,height:k,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:S,height:60,fill:H().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:S,height:60,text:_(),fontSize:18,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle"})]}),d===null&&!m&&jsx(Text,{x:20,y:60,width:S,height:k-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:C-100,children:[jsxs(Group,{onMouseDown:()=>{d!==null&&(c(true),V());},onMouseUp:()=>c(false),onMouseLeave:()=>c(false),onTouchStart:()=>{d!==null&&(c(true),V());},onTouchEnd:()=>c(false),scaleX:i?.95:1,scaleY:i?.95:1,children:[jsx(Rect,{fill:d===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:se,onTouchStart:se,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((K,te)=>{let Z=window.innerWidth*.2,J=50,le=10,Ie=d===K.value,Y=G===K.value,Me=m&&Ie,Be="transparent";return Me?Be=Y?"#4CAF50":"#ef4444":Ie&&(Be="#4CAF50"),jsxs(Group,{x:16+te*(Z+le),y:g+C-300,draggable:!m,onDragMove:R,onDragEnd:Et=>oe(K.value,Et),opacity:m&&!Ie?.5:1,children:[jsx(Rect,{width:Z-40,height:J,fill:"#075560",stroke:Be,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z-40,height:J,text:K.label,fontSize:18,fontStyle:"bold",fill:mx,align:"center",verticalAlign:"middle",listening:false})]},`${K.value}-${p}`)})]})})};$i.displayName="TrueFalseDragAndDrop";var Nu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Ou,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s},n.id):jsx($i,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r},n.id))});var xa=new WeakMap,ko=new WeakMap,hr={current:[]},Ji=false,pr=0,mr=new Set,Hs=new Map;function Vu(e){let o=Array.from(e).sort((t,a)=>t instanceof qt&&t.options.deps.includes(a)?1:a instanceof qt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(hr.current.includes(t))continue;hr.current.push(t),t.recompute();let a=ko.get(t);if(a)for(let s of a){let r=xa.get(s);r&&Vu(r);}}}function gx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function xx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Us(e){if(pr>0&&!Hs.has(e)&&Hs.set(e,e.prevState),mr.add(e),!(pr>0)&&!Ji)try{for(Ji=!0;mr.size>0;){let o=Array.from(mr);mr.clear();for(let t of o){let a=Hs.get(t)??t.prevState;t.prevState=a,gx(t);}for(let t of o){let a=xa.get(t);a&&(hr.current.push(t),Vu(a));}for(let t of o){let a=xa.get(t);if(a)for(let s of a)xx(s);}}}finally{Ji=false,hr.current=[],Hs.clear();}}function ht(e){pr++;try{e();}finally{if(pr--,pr===0){let o=mr.values().next().value;o&&Us(o);}}}function qu(e){return typeof e=="function"}var jt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var s,r;this.listeners.add(a);let n=(r=(s=this.options)==null?void 0:s.onSubscribe)==null?void 0:r.call(s,a,this);return ()=>{this.listeners.delete(a),n?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,s;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):qu(o)?this.state=o(this.prevState):this.state=o,(s=(a=this.options)==null?void 0:a.onUpdate)==null||s.call(a),Us(this);}};var qt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),s=new Array(t);for(let r=0;r<t;r++){let n=this.options.deps[r];a[r]=n.prevState,s[r]=n.state;}return this.lastSeenDepValues=s,{prevDepVals:a,currDepVals:s,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let s=this.getDepVals();this.state=this.options.fn(s),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let r of this.options.deps)r instanceof e&&r.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:s}=this.getDepVals();for(let r=0;r<s.length;r++)if(s[r]!==a[r]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,s;this.listeners.add(t);let r=(s=(a=this.options).onSubscribe)==null?void 0:s.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof jt){let a=xa.get(t);a||(a=new Set,xa.set(t,a)),a.add(this);let s=ko.get(this);s||(s=new Set,ko.set(this,s)),s.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof jt){let a=xa.get(t);a&&a.delete(this);let s=ko.get(this);s&&s.delete(t);}}};function bx(e){return typeof e=="function"}function Zi(e,...o){return bx(e)?e(...o):e}function Hu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ba,st,et,gr,va,Ha,Zt,Mo,xr,Ws,br,To,Ua=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:s=1e3}){Pe(this,ba,true);Pe(this,st);Pe(this,et);Pe(this,gr);Pe(this,va);Pe(this,Ha);Pe(this,Zt);Pe(this,Mo);Pe(this,xr,0);Pe(this,Ws,5);Pe(this,br,()=>{this.debugLog("Connected to event bus"),Ce(this,Ha,true),this.debugLog("Emitting queued events",j(this,va)),j(this,va).forEach(o=>this.emitEventToBus(o)),Ce(this,va,[]),this.stopConnectLoop(),j(this,et).call(this).removeEventListener("tanstack-connect-success",j(this,br));});Pe(this,To,()=>{if(j(this,et).call(this).addEventListener("tanstack-connect-success",j(this,br)),j(this,xr)<j(this,Ws)){hd(this,xr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}j(this,et).call(this).removeEventListener("tanstack-connect",j(this,To)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Ce(this,st,o),Ce(this,ba,a),Ce(this,et,this.getGlobalTarget),Ce(this,gr,t),this.debugLog(" Initializing event subscription for plugin",j(this,st)),Ce(this,va,[]),Ce(this,Ha,false),Ce(this,Zt,null),Ce(this,Mo,s);}startConnectLoop(){j(this,Zt)!==null||j(this,Ha)||(this.debugLog(`Starting connect loop (every ${j(this,Mo)}ms)`),Ce(this,Zt,setInterval(j(this,To),j(this,Mo))));}stopConnectLoop(){j(this,Zt)!==null&&(clearInterval(j(this,Zt)),Ce(this,Zt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){j(this,gr)&&console.log(`\u{1F334} [tanstack-devtools:${j(this,st)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return j(this,st)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});j(this,et).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{j(this,et).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!j(this,ba)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!j(this,Ha)){this.debugLog("Bus not available, will be pushed as soon as connected"),j(this,va).push({type:`${j(this,st)}:${o}`,payload:t,pluginId:j(this,st)}),typeof CustomEvent<"u"&&(j(this,To).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${j(this,st)}:${o}`,payload:t,pluginId:j(this,st)})}on(o,t){let a=`${j(this,st)}:${o}`;if(!j(this,ba))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let s=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return j(this,et).call(this).addEventListener(a,s),this.debugLog("Registered event to bus",a),()=>{j(this,et).call(this).removeEventListener(a,s);}}onAll(o){if(!j(this,ba))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;o(s);};return j(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!j(this,ba))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;j(this,st)&&s.pluginId!==j(this,st)||o(s);};return j(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}};ba=new WeakMap,st=new WeakMap,et=new WeakMap,gr=new WeakMap,va=new WeakMap,Ha=new WeakMap,Zt=new WeakMap,Mo=new WeakMap,xr=new WeakMap,Ws=new WeakMap,br=new WeakMap,To=new WeakMap;var Qi=class extends Ua{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Uu=(e,o)=>{el.emit(e,o);},el=new Qi;function Wu(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var vx={enabled:true,leading:true,trailing:true,wait:0},ya,gt,Wa,za,Ga,Ao,zs=class{constructor(o,t){Pe(this,ya);Pe(this,gt);Pe(this,Wa);Pe(this,za);Pe(this,Ga);Pe(this,Ao);this.fn=o,this.store=new jt(Wu()),this.setOptions=a=>{this.options={...this.options,...a},j(this,Wa).call(this)||this.cancel();},Ce(this,gt,a=>{this.store.setState(s=>{let r={...s,...a},{isPending:n}=r;return {...r,status:j(this,Wa).call(this)?n?"pending":"idle":"disabled"}}),Uu("Throttler",this);}),Ce(this,Wa,()=>!!Zi(this.options.enabled,this)),Ce(this,za,()=>Zi(this.options.wait,this)),this.maybeExecute=(...a)=>{j(this,gt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let s=Date.now(),r=s-this.store.state.lastExecutionTime,n=j(this,za).call(this);if(this.options.leading&&r>=n)j(this,Ga).call(this,...a);else if(j(this,gt).call(this,{lastArgs:a}),!j(this,ya)&&this.options.trailing){let l=this.store.state.lastExecutionTime?s-this.store.state.lastExecutionTime:0,d=n-l;j(this,gt).call(this,{isPending:true}),Ce(this,ya,setTimeout(()=>{let{lastArgs:u}=this.store.state;u!==void 0&&j(this,Ga).call(this,...u);},d));}},Ce(this,Ga,(...a)=>{if(!j(this,Wa).call(this))return;this.fn(...a);let s=Date.now(),r=s+j(this,za).call(this);j(this,Ao).call(this),j(this,gt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:s,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||j(this,gt).call(this,{nextExecutionTime:void 0});},j(this,za).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&j(this,Ga).call(this,...this.store.state.lastArgs);},Ce(this,Ao,()=>{j(this,ya)&&(clearTimeout(j(this,ya)),Ce(this,ya,void 0));}),this.cancel=()=>{j(this,Ao).call(this),j(this,gt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{j(this,gt).call(this,Wu());},this.key=Hu(t.key),this.options={...vx,...t},j(this,gt).call(this,this.options.initialState??{}),el.on("d-Throttler",a=>{a.payload.key===this.key&&(j(this,gt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};ya=new WeakMap,gt=new WeakMap,Wa=new WeakMap,za=new WeakMap,Ga=new WeakMap,Ao=new WeakMap;function tl(e,o){return new zs(e,o).maybeExecute}function wa(e,o){return typeof e=="function"?e(o):e}function La(e,o){return js(o).reduce((a,s)=>{if(a===null)return null;if(typeof a<"u")return a[s]},e)}function Po(e,o,t){let a=js(o);function s(r){if(!a.length)return wa(t,r);let n=a.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[n]:s(r[n])}):{[n]:s()};if(Array.isArray(r)&&typeof n=="number"){let l=r.slice(0,n);return [...l.length?l:new Array(n),s(r[n]),...r.slice(n+1)]}return [...new Array(n),s()]}return s(e)}function ol(e,o){let t=js(o);function a(s){if(!s)return;if(t.length===1){let n=t[0];if(Array.isArray(s)&&typeof n=="number")return s.filter((u,m)=>m!==n);let{[n]:l,...d}=s;return d}let r=t.shift();if(typeof r=="string"&&typeof s=="object")return {...s,[r]:a(s[r])};if(typeof r=="number"&&Array.isArray(s)){if(r>=s.length)return s;let n=s.slice(0,r);return [...n.length?n:new Array(r),a(s[r]),...s.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var yx=/^(\d+)$/gm,wx=/\.(\d+)(?=\.)/gm,Lx=/^(\d+)\./gm,Sx=/\.(\d+$)/gm,Ix=/\.{2,}/gm,al="__int__",Gs=`${al}$1`;function js(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(yx,Gs).replace(wx,`.${Gs}.`).replace(Lx,`${Gs}.`).replace(Sx,`.${Gs}`).replace(Ix,".").split(".").map(o=>{if(o.startsWith(al)){let t=o.substring(al.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function rl(e){return !(Array.isArray(e)&&e.length===0)}function Do(e,o){let t=a=>a.validators.filter(Boolean).map(s=>({cause:s.cause,validate:s.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Ro(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:s,onDynamicAsyncDebounceMs:r}=o.validators||{},n=t??0,l=d=>d.validators.filter(Boolean).map(u=>{let m=u?.cause||e,f=n;switch(m){case "change":f=s??n;break;case "blur":f=a??n;break;case "dynamic":f=r??n;break;case "submit":f=0;break}return e==="submit"&&(f=0),{cause:m,validate:u.fn,debounceMs:f}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:l})}var vr=e=>!!e&&typeof e=="object"&&"fields"in e;function Sa(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[s,r]of e)if(!o.has(s)||!Object.is(r,o.get(s)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let s of e)if(!o.has(s))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let s of t)if(!a.includes(s)||!Sa(e[s],o[s]))return false;return true}var Xs=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},$s=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function _e(e,o){return e==null?o:{...e,...o}}var Ka=256,_s=[],Ks;for(;Ka--;)_s[Ka]=(Ka+256).toString(16).substring(1);function sl(){let e=0,o,t="";if(!Ks||Ka+16>256){for(Ks=new Array(256),e=256;e--;)Ks[e]=256*Math.random()|0;e=0,Ka=0;}for(;e<16;e++)o=Ks[Ka+e],e===6?t+=_s[o&15|64]:e===8?t+=_s[o&63|128]:t+=_s[o],e&1&&e>1&&e<11&&(t+="-");return Ka++,t}var Ia=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},s={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,s,r,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[s,n],form:e.form});case "change":return e.runValidation({validators:[a,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Cx(e,o){let t=new Map;for(let a of e){let s=a.path??[],r=o,n="";for(let l=0;l<s.length;l++){let d=s[l];if(d===void 0)continue;let u=typeof d=="object"?d.key:d,m=Number(u);Array.isArray(r)&&!Number.isNaN(m)?n+=`[${m}]`:n+=(l>0?".":"")+String(u),typeof r=="object"&&r!==null?r=r[u]:r=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var zu=(e,o)=>{let t=Cx(e,o);return {form:t,fields:t}},Ca={validate({value:e,validationSource:o},t){let a=t["~standard"].validate(e);if(a instanceof Promise)throw new Error("async function passed to sync validator");if(a.issues)return o==="field"?a.issues:zu(a.issues,e)},async validateAsync({value:e,validationSource:o},t){let a=await t["~standard"].validate(e);if(a.issues)return o==="field"?a.issues:zu(a.issues,e)}},Ys=e=>!!e&&"~standard"in e;var Eo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function yr(e){function o(f,i,c,p){let y=a(f,i,c,p);({insert:()=>l(y,f,i),remove:()=>d(y),swap:()=>p!==void 0&&m(y,f,i,p),move:()=>p!==void 0&&u(y,f,i,p)})[c]();}function t(f,i){return `${f}[${i}]`}function a(f,i,c,p){let y=[t(f,i)];if(c==="swap")y.push(t(f,p));else if(c==="move"){let[h,x]=[Math.min(i,p),Math.max(i,p)];for(let b=h;b<=x;b++)y.push(t(f,b));}else {let h=e.getFieldValue(f),x=Array.isArray(h)?h.length:0;for(let b=i+1;b<x;b++)y.push(t(f,b));}return Object.keys(e.fieldInfo).filter(h=>y.some(x=>h.startsWith(x)))}function s(f,i){return f.replace(/\[(\d+)\]/,(c,p)=>{let y=parseInt(p,10);return `[${i==="up"?y+1:Math.max(0,y-1)}]`})}function r(f,i){(i==="up"?f:[...f].reverse()).forEach(p=>{let y=s(p.toString(),i),h=e.getFieldMeta(y);h?e.setFieldMeta(p,h):e.setFieldMeta(p,n());});}let n=()=>Eo,l=(f,i,c)=>{r(f,"down"),f.forEach(p=>{p.toString().startsWith(t(i,c))&&e.setFieldMeta(p,n());});},d=f=>{r(f,"up");},u=(f,i,c,p)=>{let y=new Map(Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(i,c))).map(h=>[h,e.getFieldMeta(h)]));r(f,c<p?"up":"down"),Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(i,p))).forEach(h=>{let x=h.replace(t(i,p),t(i,c)),b=y.get(x);b&&e.setFieldMeta(h,b);});},m=(f,i,c,p)=>{f.forEach(y=>{if(!y.toString().startsWith(t(i,c)))return;let h=y.toString().replace(t(i,c),t(i,p)),[x,b]=[e.getFieldMeta(y),e.getFieldMeta(h)];x&&e.setFieldMeta(h,x),b&&e.setFieldMeta(y,b);});};return {handleArrayFieldMetaShift:o}}var nl=class extends Ua{constructor(){super({pluginId:"form-devtools"});}},xt=new nl;function il(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var Lr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),s=this.store.mount(),r=()=>{a(),s(),xt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return xt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let s=this.options;this.options=a;let r=!!a.transform?.deps?.some((d,u)=>d!==this.prevTransformArray[u]),n=a.defaultValues&&!Sa(a.defaultValues,s.defaultValues)&&!this.state.isTouched,l=!Sa(a.defaultState,s.defaultState)&&!this.state.isTouched;!n&&!l&&!r||(ht(()=>{this.baseStore.setState(()=>il(Object.assign({},this.state,l?a.defaultState:{},n?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),xt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,s)=>{let{fieldMeta:r}=this.state,n=this.resetFieldMeta(r);a&&!s?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>il({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let s=[];return ht(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let l=n.instance;s.push(Promise.resolve().then(()=>l.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(d=>({...d,isTouched:!0}));});}),(await Promise.all(s)).flat()},this.validateArrayFieldsStartingFrom=async(a,s,r)=>{let n=this.getFieldValue(a),l=Array.isArray(n)?Math.max(n.length-1,0):null,d=[`${a}[${s}]`];for(let i=s+1;i<=(l??0);i++)d.push(`${a}[${i}]`);let u=Object.keys(this.fieldInfo).filter(i=>d.some(c=>i.startsWith(c))),m=[];return ht(()=>{u.forEach(i=>{m.push(Promise.resolve().then(()=>this.validateField(i,r)));});}),(await Promise.all(m)).flat()},this.validateField=(a,s)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(n=>({...n,isTouched:true})),r.validate(s)):[]},this.validateSync=a=>{let s=Do(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ia}),r=false,n={};return ht(()=>{for(let u of s){if(!u.validate)continue;let m=this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:f,fieldErrors:i}=Js(m),c=wr(u.cause);for(let p of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[p]===void 0)continue;let y=this.getFieldMeta(p);if(!y)continue;let{errorMap:h,errorSourceMap:x}=y,b=i?.[p],{newErrorValue:g,newSource:L}=Xs({newFormValidatorError:b,isPreviousErrorFromFormValidator:x?.[c]==="form",previousErrorValue:h?.[c]});L==="form"&&(n[p]={...n[p],[c]:b}),h?.[c]!==g&&this.setFieldMeta(p,C=>({...C,errorMap:{...C.errorMap,[c]:g},errorSourceMap:{...C.errorSourceMap,[c]:L}}));}this.state.errorMap?.[c]!==f&&this.baseStore.setState(p=>({...p,errorMap:{...p.errorMap,[c]:f}})),(f||i)&&(r=!0);}let l=wr("submit");this.state.errorMap?.[l]&&a!=="submit"&&!r&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[l]:void 0}}));let d=wr("server");this.state.errorMap?.[d]&&a!=="server"&&!r&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[d]:void 0}}));}),{hasErrored:r,fieldsErrorMap:n}},this.validateAsync=async a=>{let s=Ro(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ia});this.state.isFormValidating||this.baseStore.setState(u=>({...u,isFormValidating:true}));let r=[],n;for(let u of s){if(!u.validate)continue;let m=wr(u.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let i=new AbortController;this.state.validationMetaMap[m]={lastAbortController:i},r.push(new Promise(async c=>{let p;try{p=await new Promise((b,g)=>{setTimeout(async()=>{if(i.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:i.signal},type:"validateAsync"}));}catch(L){g(L);}},u.debounceMs);});}catch(b){p=b;}let{formError:y,fieldErrors:h}=Js(p);h&&(n=n?{...n,...h}:h);let x=wr(u.cause);for(let b of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[b]===void 0)continue;let g=this.getFieldMeta(b);if(!g)continue;let{errorMap:L,errorSourceMap:C}=g,S=n?.[b],{newErrorValue:k,newSource:v}=Xs({newFormValidatorError:S,isPreviousErrorFromFormValidator:C?.[x]==="form",previousErrorValue:L?.[x]});L?.[x]!==k&&this.setFieldMeta(b,M=>({...M,errorMap:{...M.errorMap,[x]:k},errorSourceMap:{...M.errorSourceMap,[x]:v}}));}this.baseStore.setState(b=>({...b,errorMap:{...b.errorMap,[x]:y}})),c(n?{fieldErrors:n,errorMapKey:x}:void 0);}));}let l=[],d={};if(r.length){l=await Promise.all(r);for(let u of l)if(u?.fieldErrors){let{errorMapKey:m}=u;for(let[f,i]of Object.entries(u.fieldErrors)){let p={...d[f]||{},[m]:i};d[f]=p;}}}return this.baseStore.setState(u=>({...u,isFormValidating:false})),d},this.validate=a=>{let{hasErrored:s,fieldsErrorMap:r}=this.validateSync(a);return s&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>La(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var s;return (s=this.fieldInfo)[a]||(s[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,s)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:wa(s,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((s,r)=>{let n=r;return s[n]=Eo,s},{}),this.setFieldValue=(a,s,r)=>{let n=r?.dontUpdateMeta??false,l=r?.dontRunListeners??false,d=r?.dontValidate??false;ht(()=>{n||this.setFieldMeta(a,u=>({...u,isTouched:!0,isDirty:!0,errorMap:{...u?.errorMap,onMount:void 0}})),this.baseStore.setState(u=>({...u,values:Po(u.values,a,s)}));}),l||this.getFieldInfo(a).instance?.triggerOnChangeListener(),d||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(n=>{let l=a.toString();return n!==l&&n.startsWith(l)}),a];this.baseStore.setState(n=>{let l={...n};return r.forEach(d=>{l.values=ol(l.values,d),delete this.fieldInfo[d],delete l.fieldMetaBase[d];}),l});},this.pushFieldValue=(a,s,r)=>{this.setFieldValue(a,n=>[...Array.isArray(n)?n:[],s],r);},this.insertFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,d=>[...d.slice(0,s),r,...d.slice(s)],_e(n,{dontValidate:true}));let l=n?.dontValidate??false;l||await this.validateField(a,"change"),yr(this).handleArrayFieldMetaShift(a,s,"insert"),l||await this.validateArrayFieldsStartingFrom(a,s,"change");},this.replaceFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,d=>d.map((u,m)=>m===s?r:u),_e(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.removeFieldValue=async(a,s,r)=>{let n=this.getFieldValue(a),l=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,u=>u.filter((m,f)=>f!==s),_e(r,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"remove"),l!==null){let u=`${a}[${l}]`;this.deleteField(u);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.swapFieldValues=(a,s,r,n)=>{this.setFieldValue(a,d=>{let u=d[s],m=d[r];return Po(Po(d,`${s}`,m),`${r}`,u)},_e(n,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"swap",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,s,r,n)=>{this.setFieldValue(a,d=>{let u=[...d];return u.splice(r,0,u.splice(s,1)[0]),u},_e(n,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"move",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,s)=>{let r=this.getFieldValue(a),n=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],_e(s,{dontValidate:true})),n!==null)for(let d=0;d<=n;d++){let u=`${a}[${d}]`;this.deleteField(u);}(s?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:Eo},values:this.options.defaultValues?Po(s.values,a,La(this.options.defaultValues,a)):s.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[s,r])=>(Object.keys(r).length&&r.errors.length&&(a[s]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Ca.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ca.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??sl(),this._devtoolsSubmissionOverride=false,this.baseStore=new jt(il({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new qt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,l=a?.[0],d=s[0],u=0,m={};for(let f of Object.keys(d.fieldMetaBase)){let i=d.fieldMetaBase[f],c=l?.fieldMetaBase[f],p=n?.[f],y=La(d.values,f),h=p?.errors;if(!c||i.errorMap!==c.errorMap){h=Object.values(i.errorMap??{}).filter(C=>C!==void 0);let L=this.getFieldInfo(f)?.instance;L&&!L.options.disableErrorFlat&&(h=h?.flat(1));}let x=!rl(h??[]),b=!i.isDirty,g=Sa(y,La(this.options.defaultValues,f))||Sa(y,this.getFieldInfo(f)?.instance?.options.defaultValue);if(p&&p.isPristine===b&&p.isValid===x&&p.isDefaultValue===g&&p.errors===h&&i===c){m[f]=p,u++;continue}m[f]={...i,errors:h,isPristine:b,isValid:x,isDefaultValue:g};}return Object.keys(d.fieldMetaBase).length&&n&&u===Object.keys(d.fieldMetaBase).length?n:m}}),this.store=new qt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,l=a?.[0],d=s[0],u=s[1],m=Object.values(u).filter(Boolean),f=m.some(T=>T.isValidating),i=m.every(T=>T.isValid),c=m.some(T=>T.isTouched),p=m.some(T=>T.isBlurred),y=m.every(T=>T.isDefaultValue),h=c&&d.errorMap?.onMount,x=m.some(T=>T.isDirty),b=!x,g=!!(d.errorMap?.onMount||m.some(T=>T?.errorMap?.onMount)),L=!!f,C=n?.errors??[];(!l||d.errorMap!==l.errorMap)&&(C=Object.values(d.errorMap).reduce((T,U)=>U===void 0?T:U&&vr(U)?(T.push(U.form),T):(T.push(U),T),[]));let S=C.length===0,k=i&&S,v=this.options.canSubmitWhenInvalid??false,M=d.submissionAttempts===0&&!c&&!g||!L&&!d.isSubmitting&&k||v,B=d.errorMap;if(h&&(C=C.filter(T=>T!==d.errorMap.onMount),B=Object.assign(B,{onMount:void 0})),n&&l&&n.errorMap===B&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===C&&n.isFieldsValidating===f&&n.isFieldsValid===i&&n.isFormValid===S&&n.isValid===k&&n.canSubmit===M&&n.isTouched===c&&n.isBlurred===p&&n.isPristine===b&&n.isDefaultValue===y&&n.isDirty===x&&Sa(l,d))return n;let D={...d,errorMap:B,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:f,isFieldsValid:i,isFormValid:S,isValid:k,canSubmit:M,isTouched:c,isBlurred:p,isPristine:b,isDefaultValue:y,isDirty:x},O=this.options.transform?.deps??[];if(O.length!==this.prevTransformArray.length||O.some((T,U)=>T!==this.prevTransformArray[U])){let T=Object.assign({},this,{state:D});this.options.transform?.fn(T),D=T.state,this.prevTransformArray=O;}return D}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=tl(a=>xt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),xt.on("request-form-state",a=>{a.payload.id===this._formId&&xt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),xt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),xt.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return Ys(o.validate)?Ca[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(s=>({...s,isSubmitted:false,submissionAttempts:s.submissionAttempts+1,isSubmitSuccessful:false})),ht(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance&&(s.instance.state.meta.isTouched||s.instance.setMeta(r=>({...r,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(s=>({...s,isSubmitting:true}));let a=()=>{this.baseStore.setState(s=>({...s,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(s=>s.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}ht(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance?.options.listeners?.onSubmit?.({value:s.instance.state.value,fieldApi:s.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),ht(()=>{this.baseStore.setState(s=>({...s,isSubmitted:!0,isSubmitSuccessful:!0})),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(s){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:s}),a(),s}}setErrorMap(o){ht(()=>{Object.entries(o).forEach(([t,a])=>{let s=t;if(vr(a)){let{formError:r,fieldErrors:n}=Js(a);for(let l of Object.keys(this.fieldInfo))this.getFieldMeta(l)&&this.setFieldMeta(l,u=>({...u,errorMap:{...u.errorMap,[s]:n?.[l]},errorSourceMap:{...u.errorSourceMap,[s]:"form"}}));this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[s]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[s]:a}}));});});}};function Js(e){if(e){if(vr(e)){let o=Js(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function wr(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}var Sr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:s}=this.options.validators||{};if(s){let r=this.runValidator({validate:s,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:r},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let s=La(t.form.options.defaultValues,t.name),r=t.defaultValue??s;a?this.setValue(n=>n||r,{dontUpdateMeta:true}):r!==void 0&&this.setValue(r,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,_e(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,_e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,s)=>{this.form.insertFieldValue(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,s)=>{this.form.replaceFieldValue(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,_e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,s)=>{this.form.swapFieldValues(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,s)=>{this.form.moveFieldValues(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,_e(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),s=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:n,onBlurListenTo:l}=r.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&s.push(r.instance),t==="blur"&&l?.includes(this.name)&&s.push(r.instance);}return s},this.validateSync=(t,a)=>{let s=Do(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ia}),n=this.getLinkedFields(t).reduce((u,m)=>{let f=Do(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Ia});return f.forEach(i=>{i.field=m;}),u.concat(f)},[]),l=false;ht(()=>{let u=(m,f)=>{let i=Zs(f.cause),c=f.validate?Gu(m.runValidator({validate:f.validate,value:{value:m.store.state.value,validationSource:"field",fieldApi:m},type:"validate"})):void 0,p=a[i],{newErrorValue:y,newSource:h}=$s({formLevelError:p,fieldLevelError:c});m.state.meta.errorMap?.[i]!==y&&m.setMeta(x=>({...x,errorMap:{...x.errorMap,[i]:y},errorSourceMap:{...x.errorSourceMap,[i]:h}})),y&&(l=!0);};for(let m of s)u(this,m);for(let m of n)m.validate&&u(m.field,m);});let d=Zs("submit");return this.state.meta.errorMap?.[d]&&t!=="submit"&&!l&&this.setMeta(u=>({...u,errorMap:{...u.errorMap,[d]:void 0},errorSourceMap:{...u.errorSourceMap,[d]:void 0}})),{hasErrored:l}},this.validateAsync=async(t,a)=>{let s=Ro(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ia}),r=await a,n=this.getLinkedFields(t),l=n.reduce((i,c)=>{let p=Ro(t,{...c.options,form:c.form,validationLogic:c.form.options.validationLogic||Ia});return p.forEach(y=>{y.field=c;}),i.concat(p)},[]);this.state.meta.isValidating||this.setMeta(i=>({...i,isValidating:true}));for(let i of n)i.setMeta(c=>({...c,isValidating:true}));let d=[],u=[],m=(i,c,p)=>{let y=Zs(c.cause);i.getInfo().validationMetaMap[y]?.lastAbortController.abort();let x=new AbortController;this.getInfo().validationMetaMap[y]={lastAbortController:x},p.push(new Promise(async b=>{let g;try{g=await new Promise((v,M)=>{this.timeoutIds.validations[c.cause]&&clearTimeout(this.timeoutIds.validations[c.cause]),this.timeoutIds.validations[c.cause]=setTimeout(async()=>{if(x.signal.aborted)return v(void 0);try{v(await this.runValidator({validate:c.validate,value:{value:i.store.state.value,fieldApi:i,signal:x.signal,validationSource:"field"},type:"validateAsync"}));}catch(B){M(B);}},c.debounceMs);});}catch(v){g=v;}if(x.signal.aborted)return b(void 0);let L=Gu(g),C=r[this.name]?.[y],{newErrorValue:S,newSource:k}=$s({formLevelError:C,fieldLevelError:L});i.setMeta(v=>({...v,errorMap:{...v?.errorMap,[y]:S},errorSourceMap:{...v.errorSourceMap,[y]:k}})),b(S);}));};for(let i of s)i.validate&&m(this,i,d);for(let i of l)i.validate&&m(i.field,i,u);let f=[];(d.length||u.length)&&(f=await Promise.all(d),await Promise.all(u)),this.setMeta(i=>({...i,isValidating:false}));for(let i of n)i.setMeta(c=>({...c,isValidating:false}));return f.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:s}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,s[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Zs(t)]?.lastAbortController.abort(),this.state.meta.errors;let n=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,n)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Ca.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ca.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new qt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Eo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Ys(o.validate)?Ca[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function Gu(e){if(e)return e}function Zs(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function Qs(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Mx)}function Mx(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,s]of e)if(!o.has(a)||!Object.is(s,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=Ku(e);if(t.length!==Ku(o).length)return false;for(let a=0;a<t.length;a++)if(!Object.prototype.hasOwnProperty.call(o,t[a])||!Object.is(e[t[a]],o[t[a]]))return false;return true}function Ku(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Fo=typeof window<"u"?useLayoutEffect:useEffect;function Fx(e){let[o]=useState(()=>{let a=new Sr({...e,form:e.form,name:e.name});return a.Field=ll,a});return Fo(o.mount,[o]),Fo(()=>{o.update(e);}),Qs(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var ll=(({children:e,...o})=>{let t=Fx(o),a=useMemo(()=>wa(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Nx({form:e,selector:o,children:t}){let a=Qs(e.store,o);return wa(t,a)}function dl(e){let o=useId(),[t]=useState(()=>{let a=new Lr({...e,formId:o}),s=a;return s.Field=function(n){return jsx(ll,{...n,form:a})},s.Subscribe=function(n){return jsx(Nx,{form:a,selector:n.selector,children:n.children})},s});return Fo(t.mount,[]),Fo(()=>{t.update(e);}),t}function ul({field:e}){return jsxs(Fragment,{children:[e.state.meta.isTouched&&!e.state.meta.isValid?jsx("em",{children:e.state.meta.errors.join(", ")}):null,e.state.meta.isValidating?"Validating...":null]})}var jx=({editElement:e})=>{let o=useDispatch(),t=useSelector(he),a=useRef(null),s=ot(),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[l,d]=useState(n),u=dl({defaultValues:{questionType:n,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:i})=>{if(i.questionType==="true-false"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctAnswer:i.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?fa(c):oi(c));}else if(i.questionType==="multiple-choice"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctIndex:i.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?ca(c):ai(c));}else if(i.questionType==="short-answer"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctShortAnswer:i.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?$o(c):ri(c));}else if(i.questionType==="fill-in-the-blank"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctShortAnswer:i.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Jo(c):ni(c));}else if(i.questionType==="long-answer"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctLongAnswer:i.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Yo(c):si(c));}o(ma(false));}}),m=()=>{o(ma(false));};if(!s)return null;let f=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:i=>{i.preventDefault(),i.stopPropagation(),u.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{m();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(u.Field,{name:"questionType",children:i=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:i.name,name:i.name,value:i.state.value,onBlur:i.handleBlur,onChange:c=>{i.handleChange(c.target.value),d(c.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(ul,{field:i})]})}),l&&!["short-answer","fill-in-the-blank","long-answer"].includes(l)&&jsx(u.Field,{name:"responseType",children:i=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:i.name,name:i.name,value:i.state.value,onBlur:i.handleBlur,onChange:c=>i.handleChange(c.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(ul,{field:i})]})})]}),jsx(u.Field,{name:"feedbackMode",children:i=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${l==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:l==="long-answer",onClick:()=>i.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${i.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:l==="long-answer",onClick:()=>i.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${i.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),l==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(ul,{field:i})]})}),jsx(u.Field,{name:"question",validators:{onChange:({value:i})=>i?void 0:"A question is required"},children:i=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:i.state.value,onChange:c=>i.handleChange(c.target.value),onBlur:i.handleBlur,placeholder:"Enter Your Question"})}),i.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:i.state.meta.errors.join(", ")})]})}),l==="true-false"&&jsx(u.Field,{name:"responseOptions.correctAnswer",children:i=>{let c=i.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>i.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${c===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),c===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>i.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${c===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),c===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),l==="multiple-choice"&&jsx(u.Field,{name:"responseOptions",validators:{onChange:({value:i})=>{if(i.options.filter(p=>!p.trim()).length>0)return "All options must have text";if(!i.correctIndex||i.correctIndex.length===0)return "Please select at least one correct answer"}},children:i=>{let c=(x,b)=>{let g=[...i.state.value.options];g[x]=b,i.handleChange({...i.state.value,options:g});},p=()=>{if(i.state.value.options.length>=6){alert("Maximum 6 options allowed");return}i.handleChange({...i.state.value,options:[...i.state.value.options,""]});},y=x=>{if(i.state.value.options.length<=2){alert("Minimum 2 options required");return}let b=i.state.value.options.filter((L,C)=>C!==x),g=i.state.value.correctIndex?.filter(L=>L!==x).map(L=>L>x?L-1:L);i.handleChange({...i.state.value,options:b,correctIndex:g});},h=x=>{let b=i.state.value.correctIndex||[];if(b.includes(x))i.handleChange({...i.state.value,correctIndex:b.filter(L=>L!==x)});else {if(b.length>=6){alert("Maximum 6 correct answers allowed");return}i.handleChange({...i.state.value,correctIndex:[...b,x]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:i.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:i.state.value.options.map((x,b)=>{let g=!x.trim(),L=i.state.value.correctIndex?.includes(b),C=i.state.meta.isTouched&&g;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>h(b),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${L?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:L&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${C?"border-red-500 bg-red-50":L?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${b+1}`,value:x,onChange:S=>c(b,S.target.value),onBlur:i.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),i.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>y(b),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},b)})}),jsx("button",{type:"button",onClick:p,disabled:i.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),i.state.value.correctIndex.length===0||i.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:i.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(l==="short-answer"||l==="fill-in-the-blank")&&jsx(u.Field,{name:"responseOptions.correctShortAnswer",children:i=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:i.state.value,onChange:c=>{i.handleChange(c.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),i.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:i.state.meta.errors.join(", ")})]})}),l==="long-answer"&&jsx(u.Field,{name:"responseOptions.correctLongAnswer",children:i=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:i.state.value,onChange:c=>{i.handleChange(c.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),i.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:i.state.meta.errors.join(", ")})]})}),jsx(u.Subscribe,{selector:i=>[i.canSubmit,i.isSubmitting],children:([i,c])=>jsx("button",{type:"submit",disabled:!i,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:c?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,s)},Xu=jx;var Zu=({text:e,position:o})=>{let t=xe(),a=u=>{t(ce()),t(It({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+u))}));},s=u=>{t(ce()),t(It({id:e.id,fill:u}));},r=()=>{t(ce()),t(It({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ce()),t(It({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},l=()=>{t(ce()),t(It({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},d=u=>{t(ce()),t(It({id:e.id,fontFamily:u}));};return jsxs("div",{className:"fixed z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:"50%",top:`${Math.max(60,o.y-60)}px`,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:u=>u.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:u=>d(u.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:r,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:[jsx(TextB,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextB,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:n,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:l,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:[jsx(TextUnderline,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextUnderline,{size:16,weight:"bold",className:"hidden sm:block"})]})]}),jsx("div",{className:"border-l border-gray-200 pl-1",children:jsx("input",{type:"color",value:e.fill,onChange:u=>s(u.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var ec=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:s,scale:r,textareaRef:n})=>{let l=useRef(null),d=useMemo(()=>({fontSize:`${e.fontSize*r}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,r]),u=useCallback(m=>{m.style.height="auto",m.style.height=`${m.scrollHeight}px`;let f=document.createElement("span");f.style.font=window.getComputedStyle(m).font,f.style.fontSize=m.style.fontSize,f.style.fontFamily=m.style.fontFamily,f.style.fontWeight=m.style.fontWeight,f.style.fontStyle=m.style.fontStyle,f.style.visibility="hidden",f.style.position="absolute",f.style.whiteSpace="pre";let i=m.value.split(`
|
|
4
|
+
`),c=0;document.body.appendChild(f);for(let y of i){f.textContent=y||" ";let h=f.offsetWidth;h>c&&(c=h);}document.body.removeChild(f);let p=10;m.style.width=`${Math.max(200,c+p+20)}px`;},[]);return useEffect(()=>{let m=l.current;m&&(m.style.fontSize=`${e.fontSize*r}px`,m.style.fontFamily=e.fontFamily,m.style.fontStyle=e.fontStyle,m.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",m.style.textDecoration=e.textDecoration,m.style.color=e.fill,u(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,u]),jsx("div",{style:{position:"absolute",top:`${s.top}px`,left:`${s.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(l.current=m,n.current=m,m){m.focus();let f=m.value.length;m.setSelectionRange(f,f),u(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:d},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var tc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(T=>T.toolbar.selectedTool),l=n==="pen"||n==="eraser",d=useRef(null),[u,m]=useState(""),[f,i]=useState(false),[c,p]=useState(null);useEffect(()=>{let T=d.current;if(T)return a.current.set(e.id,T),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=f&&u.trim().toLowerCase()===y,x=()=>{i(false),m("");},b=()=>h?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",g=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,C=60,S=f?40:0,k=f?54:20,v=50,M=12,B=e.data.feedbackMode==="practice"?48:0,D=12,O=30,W=C+S+O+v+M+D+B+L;return jsxs(Group,{ref:d,draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:W,name:"sa-element",...l?{}:{onDragEnd:r,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:W,onTransformEnd:T=>t(e.id,T),onContextMenu:T=>{T.cancelBubble=true,s(T.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+S+O-k,width:e.width-L*2+4,height:v+6,fill:"#ffffff",stroke:h?"#22c55e":f?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:C+S+O-k},divProps:{style:{width:`${e.width-L*2-4}px`,height:`${v}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:T=>m(T.target.value),disabled:f,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:f?"none":"auto"}})}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C+80,width:e.width/2+24,height:S,fill:g().bg,cornerRadius:8}),jsx(Text,{x:36,y:C+80,width:e.width-L*2,height:S,text:b(),fontSize:12,fontStyle:"bold",fill:g().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:C+S+O+v+M+D,children:[jsxs(Group,{onMouseDown:T=>{T.cancelBubble=true,p("check");},onMouseUp:T=>{T.cancelBubble=true,p(null),u.length>0&&i(true);},onMouseLeave:T=>{T.cancelBubble=true,p(null);},onTouchStart:T=>{T.cancelBubble=true,p("check");},onTouchEnd:T=>{T.cancelBubble=true,p(null),u.length>0&&i(true);},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(f?2:1),height:48,fill:u.length===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),x();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),x();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});tc.displayName="ShortAnswer";var ac=tc;var rc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(ac,{shortAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:l=>r(l,n.id)},n.id))});var sc=e=>{let o=useDispatch(),a=useSelector(he)?.fillInTheBlanks||[],s=useRef(new Map),r=useCallback((n,l)=>{let d=n.target;o(Jo({id:l,x:d.x(),y:d.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:s,handleFillInTheBlanksDragEnd:r}};var Tt=24,ml=51,Ar=64,nc=15,an=32,ic=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:s,fibRefs:r})=>{let n=useSelector(v=>v.toolbar.selectedTool),l=n==="pen"||n==="eraser",d=useRef(null),[u,m]=useState(""),[f,i]=useState(false),[c,p]=useState(null);useEffect(()=>{let v=d.current;if(v)return r.current.set(e.id,v),()=>{r.current.delete(e.id);}},[e.id,r]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=f&&u.trim().toLowerCase()===y,x=()=>{i(false),m("");},b=()=>{u.length>0&&i(true);},g=e.width-Tt*2,L=(g-nc)/2,C=e.data.feedbackMode==="practice",S=useMemo(()=>{let v=Tt,M=v;v+=60;let B=v;v+=35;let D=v;v+=ml+16;let O=v;f&&(v+=an+16);let W=v;return C&&(v+=Ar),v+=Tt,{questionY:M,helperTextY:B,inputY:D,feedbackY:O,buttonsY:W,totalHeight:v}},[f,C]),k=()=>f?h?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:d,draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...l?{}:{onDragEnd:v=>a(v,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:S.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,s?.(v.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Tt,y:S.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:g,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Tt,y:S.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:g,listening:false}),jsx(Rect,{x:Tt,y:S.inputY,width:g,height:ml,fill:"#ffffff",stroke:k(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Tt,y:S.inputY},divProps:{style:{width:`${g}px`,height:`${ml}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:v=>m(v.target.value),disabled:f,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),f&&jsxs(Group,{y:S.feedbackY,children:[jsx(Rect,{x:Tt,width:h?206:140,height:an,fill:h?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:h?"\u2713":"\u2717",x:Tt+10,y:0,width:16,height:an,fontSize:14,fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:h?"Right Answer, Great Job!":"Wrong Answer",x:Tt+30,y:0,height:an,fontSize:14,fontStyle:"600",fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),C&&jsxs(Group,{y:S.buttonsY,children:[jsxs(Group,{x:Tt,onMouseDown:v=>{v.cancelBubble=true,p("reset");},onMouseUp:v=>{v.cancelBubble=true,p(null),x();},onMouseLeave:v=>{v.cancelBubble=true,p(null);},onTouchStart:v=>{v.cancelBubble=true,p("reset");},onTouchEnd:v=>{v.cancelBubble=true,p(null),x();},scaleX:c==="reset"?.98:1,scaleY:c==="reset"?.98:1,children:[jsx(Rect,{width:L,height:Ar,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:L,height:Ar,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Tt+L+nc,onMouseDown:v=>{v.cancelBubble=true,p("submit");},onMouseUp:v=>{v.cancelBubble=true,p(null),b();},onMouseLeave:v=>{v.cancelBubble=true,p(null);},onTouchStart:v=>{v.cancelBubble=true,p("submit");},onTouchEnd:v=>{v.cancelBubble=true,p(null),b();},scaleX:c==="submit"?.98:1,scaleY:c==="submit"?.98:1,children:[jsx(Rect,{width:L,height:Ar,fill:u.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:L,height:Ar,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});ic.displayName="FillInTheBlanks";var lc=ic;var uc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r})=>jsx(Fragment,{children:e.map(n=>jsx(lc,{fillInTheBlank:n,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r},n.id))});var xl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(W=>W.toolbar.selectedTool),l=n==="pen"||n==="eraser",d=useRef(null),[u,m]=useState(""),[f,i]=useState(false),[c,p]=useState(null);useEffect(()=>{let W=d.current;if(W)return a.current.set(e.id,W),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=f&&u.trim().toLowerCase()===y,x=()=>{i(false),m("");},b=()=>h?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",g=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,C=60,S=f?60:0,k=120,v=12,M=48,B=12,D=30,O=C+S+D+k+v+B+M+L;return jsxs(Group,{ref:d,draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...l?{}:{onDragEnd:r,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:W=>{let T=d.current?.getStage()?.getPointerPosition();if(!T||!s)return;let U={x:e.x,y:e.y,width:e.width,height:e.height};T.x>=U.x&&T.x<=U.x+U.width&&T.y>=U.y&&T.y<=U.y+U.height&&s(W.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:O,onTransformEnd:W=>t(e.id,W)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C,width:e.width-L*2,height:S,fill:g().bg,cornerRadius:8}),jsx(Text,{x:L,y:C,width:e.width-L*2,height:S,text:b(),fontSize:14,fontStyle:"bold",fill:g().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:C+S+v,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+S+D,width:e.width-L*2,height:k,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:C+S+D},divProps:{style:{width:`${e.width-L*2}px`,height:`${k}px`,pointerEvents:f?"none":"auto"}},children:jsx("textarea",{value:u,onChange:W=>m(W.target.value),disabled:f,placeholder:`Type your extended answer here...\r
|
|
5
5
|
\r
|
|
6
|
-
This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:u?"none":"auto"}})}),jsx(Group,{y:k+C+D+L+y+O,children:u&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),b();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),b();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:S,width:e.width-S*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:U=>U.cancelBubble=true,onTap:U=>U.cancelBubble=true}),jsx(Text,{x:S,width:e.width-S*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});hl.displayName="LongAnswer";var lc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>jsx(Fragment,{children:e.map(n=>jsx(hl,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>s(i,n.id)},n.id))});var _a=1600,ja=900,fc=3200,mc=1800,gb=.4,xb=1.5,bb=e=>{let o=0,t=0,a=_a,r=ja;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:_a,height:ja};let s=(l,d,f,u)=>{o=Math.min(o,l),t=Math.min(t,d),a=Math.max(a,l+f),r=Math.max(r,d+u);};e.lines?.forEach(l=>{if(l.points&&l.points.length>=2){let d=l.x||0,f=l.y||0,u=l.scaleX||1,c=l.scaleY||1;for(let m=0;m<l.points.length;m+=2){let p=d+l.points[m]*u,v=f+l.points[m+1]*c;o=Math.min(o,p),t=Math.min(t,v),a=Math.max(a,p),r=Math.max(r,v);}}}),e.images?.forEach(l=>s(l.x,l.y,l.width,l.height)),e.videos?.forEach(l=>s(l.x,l.y,l.width,l.height)),e.shapes?.forEach(l=>s(l.x,l.y,l.width,l.height)),e.texts?.forEach(l=>s(l.x,l.y,l.width||200,l.height||l.fontSize||24)),e.flashcards?.forEach(l=>s(l.x,l.y,l.width,l.height)),e.photoFrames?.forEach(l=>s(l.x,l.y,l.width,l.height)),e.multipleChoices?.forEach(l=>s(l.x,l.y,l.width,l.height)),e.trueFalses?.forEach(l=>s(l.x,l.y,l.width,l.height)),e.shortAnswers?.forEach(l=>s(l.x,l.y,l.width,l.height)),e.LongAnswer?.forEach(l=>s(l.x,l.y,l.width,l.height)),e.fillInTheBlanks?.forEach(l=>s(l.x,l.y,l.width,l.height));let n=Math.min(a-o,fc),i=Math.min(r-t,mc);return o=Math.max(o,a-fc),t=Math.max(t,r-mc),{minX:o,minY:t,maxX:a,maxY:r,width:n,height:i}},vb=(e,o,t={minX:0,minY:0,maxX:_a,maxY:ja,width:_a,height:ja})=>{let a=Math.max(t.width,_a),r=Math.max(t.height,ja),s=e/o,n=a/r,i,l,d,u=0;if(s>n){l=r,i=Math.round(l*s),d=o/l;}else {i=a,l=Math.round(i/s),d=e/i;let c=r*d;u=(o-c)/2;}return d=Math.max(gb,Math.min(xb,d)),{scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:u,baseWidth:i,baseHeight:l,contentOffsetX:t.minX,contentOffsetY:t.minY}},pc=(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}},yb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r={enabled:true}}={})=>{let s=at(),n=Q(w=>w.toolbar.selectedTool),i=Q(he),l=Q(co),d=i?.editingActivity,f=i?.showMcqForm,u=i?.lines||[],c=useRef(null),m=useRef(null),[p,v]=useState(null),[h,b]=useState(""),x=useRef(null),[g,S]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:_a,stageHeight:ja,offsetX:0,offsetY:0,baseWidth:_a,baseHeight:ja,contentOffsetX:0,contentOffsetY:0}),k=useMemo(()=>bb(i||null),[l]),[C,L]=useState(null),[y,M]=useState(null),[O,D]=useState(null),[q,U]=useState(null),[A,W]=useState(null),[E,ne]=useState(null),[N,re]=useState(null),[G,V]=useState(false),[_,H]=useState(null),[K,te]=useState(false),Z=useRef(null),J=useRef(null),le=useRef(null),{debouncedGenerateThumbnail:Ie}=Kd(l,c);useEffect(()=>{let w=()=>{if(m.current){let P=m.current.getBoundingClientRect(),F=vb(P.width,P.height,k);S(F);}};w();let I=new ResizeObserver(w);return m.current&&I.observe(m.current),window.addEventListener("resize",w),()=>{I.disconnect(),window.removeEventListener("resize",w);}},[k]),useEffect(()=>{if(c.current){let w=c.current.container();w&&(w.style.cursor="");}},[n]);let Y=useCallback(()=>{c.current&&requestAnimationFrame(()=>{if(!c.current)return;c.current.getLayers().forEach(F=>F.batchDraw());let I=1/6,P=c.current.toDataURL({pixelRatio:I});b(P),Ie();});},[Ie]),Me=useRef(l);useEffect(()=>{Me.current!==l&&(Me.current=l,Y());},[l,Y]);let Be=useRef(null),Rt=useRef(true);useEffect(()=>{if(!i)return;let w=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),I=Be.current?.count!==w;!Rt.current&&I&&setTimeout(()=>{Y();},100),Be.current={slideId:l,count:w},Rt.current=false;},[i,l,Y]),useEffect(()=>{c.current&&e&&e(c);},[e]),useEffect(()=>{le.current&&a&&a(le);},[a]);let{startDrawing:ao,draw:qr,stopDrawing:Hr,setCanvasRef:Ln,tool:oo,color:In,strokeWidth:Cn,isSketchMode:kn}=bd(Y),ia=useRef(new Map),{images:Mn,getLoadedImage:Tn,imageRefs:ro,handleDragEnd:Ur,handleImageTransformEnd:An}=Cd(Y),{videos:R,videoRefs:oe,handleVideoClick:ye,handleVideoDragEnd:ge,handleVideoTransformEnd:se}=Td(Y),{multipleChoice:ue,handleMcqTransform:we,mcqRefs:Ne,handleDragEnd:Et}=kd(Y),{trueFalse:dt,handleTrueFalseTransform:Te,trueFalseRefs:Ue,handleTrueFalseDragEnd:Yt}=Md(Y),{shortAnswers:la,saRefs:Ra,handleShortAnswerDragEnd:Pn}=Fd(Y),{longAnswers:Wr,handleLongAnswerDragEnd:Ft}=Bd(Y),{fillInTheBlanks:da,handleFillInTheBlanksDragEnd:Ea,fibRefs:zr}=tc(Y),{transformerRef:fe,boundBoxFunc:vt}=Ud(),{shapes:nm,shapeRefs:Gr,isDragging:td,handleShapeDragEnd:im,handleShapeResizeEnd:lm}=Dd(Y),{texts:Ko,textRefs:ua,handleDragEnd:dm,handleTransformEnd:um,handleDoubleClick:cm,startEditing:Kr,editingTextId:pe,editingValue:ad,handleEditingChange:od,finishEditing:Dn}=Ed(Y,Z);useEffect(()=>{t&&t(Kr);},[t,Kr]);let _r=Q(w=>w.canvas.editingTextId);useEffect(()=>{_r&&_r!==pe&&Kr(_r);},[_r,pe,Kr]);let{flashcards:fm,flashcardRefs:jr,handleDragEnd:mm,handleFlashcardTransformEnd:pm,handleNext:hm,handlePrevious:gm}=Nd(Y),{photoFrames:rd,photoFrameRefs:Xr,handleDragEnd:xm,handlePhotoFrameTransformEnd:bm,startCamera:vm,capturePhoto:ym,cameraStreams:wm}=Hd(Y);useEffect(()=>{if(fe.current){if(pe){fe.current.nodes([]),fe.current.getLayer()?.batchDraw();return}if(p&&!R.find(P=>P.id===p)?.isPlaying){let P=ia.current.get(p)||ro.current.get(p)||oe.current.get(p)||Gr.current.get(p)||ua.current.get(p)||Ne.current.get(p)||jr.current.get(p)||Xr.current.get(p)||Ra.current.get(p)||Ue.current.get(p)||zr.current.get(p);if(P){let F=P.attrs?.locked;if(P.visible()&&F!==true){fe.current.nodes([P]),fe.current.getLayer()?.batchDraw();return}}}fe.current.nodes([]),fe.current.getLayer()?.batchDraw();}},[p,pe,R,ia,ro,oe,Gr,ua,jr,Xr,rd,Ne,Ue,zr,fe]);let Ke=useCallback(w=>{v(w),o?.(w);},[o]),so=useCallback(()=>{v(null),o?.(null),fe.current&&(fe.current.nodes([]),fe.current.getLayer()?.batchDraw());},[fe,o]),sd=useCallback(w=>i?i.lines?.some(I=>I.id===w)?"line":i.images?.some(I=>I.id===w)?"image":i.videos?.some(I=>I.id===w)?"video":i.shapes?.some(I=>I.id===w)?"shape":i.texts?.some(I=>I.id===w)?"text":i.flashcards?.some(I=>I.id===w)?"flashcard":i.photoFrames?.some(I=>I.id===w)?"photoFrame":i.multipleChoices?.some(I=>I.id===w)?"mcq":i.trueFalses?.some(I=>I.id===w)?"trueFalse":i.shortAnswers?.some(I=>I.id===w)?"shortAnswer":i.LongAnswer?.some(I=>I.id===w)?"longAnswer":i.fillInTheBlanks?.some(I=>I.id===w)?"fillInTheBlanks":null:null,[i]),nd=useCallback((w,I)=>{switch(s(ce()),I){case "line":s(Is(w));break;case "image":s(Yr(w));break;case "video":s(es(w));break;case "shape":s(os(w));break;case "text":s(rs(w));break;case "flashcard":s(ns(w));break;case "photoFrame":s(ls(w));break;case "mcq":s(us(w));break;case "trueFalse":s(fs(w));break;case "shortAnswer":s(ps(w));break;case "longAnswer":s(gs(w));break;case "fillInTheBlanks":s(bs(w));break}so(),Y();},[s,so,Y]);useEffect(()=>{let w=I=>{if(I.key!=="Delete"||!p||pe)return;let P=document.activeElement;if(P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P?.getAttribute("contenteditable")==="true")return;I.preventDefault();let Ae=sd(p);Ae&&nd(p,Ae);};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[p,pe,sd,nd]),useEffect(()=>{let w=fe.current;return ()=>{w&&w.nodes([]);}},[l]),useEffect(()=>{let w=I=>{pe&&I.target.tagName!=="TEXTAREA"&&Dn();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[pe,Dn]),useEffect(()=>{let w=pe||p;if(!w||p&&pe){M(null);return}let I=ua.current.get(w),P=c.current;if(!I||!P){M(null);return}let F=P.container().getBoundingClientRect(),Ae=I.absolutePosition(),Se=P.scaleX();M({x:F.left+(Ae.x+I.width()*Se/2)*Se,y:F.top+Ae.y*Se});},[p,pe,Ko,ua]),useEffect(()=>{if(!pe){D(null);return}let w=ua.current.get(pe),I=c.current;if(!w||!I){D(null);return}let P=I.container().getBoundingClientRect(),F=w.absolutePosition(),Ae=I.scaleX();D({top:P.top+F.y*Ae,left:P.left+F.x*Ae,scale:Ae});},[pe,Ko,ua]);let id=useCallback(w=>{let I=w.target.getClassName(),P=w.target===w.target.getStage(),F=I==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",Ae=I==="Image",Se=I==="Text",ae=I==="Group"||w.target.getParent()?.getClassName()==="Group",Bt=I==="Circle"||I==="Star"||I==="RegularPolygon"||I==="Ellipse"||I==="Ring"||I==="Wedge"||I==="Arrow"||I==="Line"||I==="Arc"||I==="Rect"&&w.target.attrs.id,wt=I==="Group";if(P&&!F&&!Ae&&!Se&&!ae&&!Bt&&!wt&&so(),!(n==="pen"||n==="eraser")&&(Ae||Se||F||ae||Bt||wt))return;let Ye=w.target.getStage()?.getPointerPosition();if(!Ye)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let B=pc(Ye,g);ao(B);}},[n,ao,so,g]),ld=useCallback(w=>{if(td)return;let I=w.target.getStage()?.getPointerPosition();if(!I)return;let P=pc(I,g);qr(P);},[qr,td,g]),dd=useCallback(()=>{Hr();},[Hr]),Sm=useCallback(w=>{Ur(w,Y);},[Ur,Y]),Lm=useCallback(w=>{ye(w),Ke(w);},[ye,Ke]),yt=useCallback((w,I,P)=>{if(w.preventDefault(),!r.enabled)return;let F=w.clientX,Ae=w.clientY,Se=x.current?.offsetHeight||450,ae=x.current?.offsetWidth||450,Bt=window.innerHeight,wt=window.innerWidth,tt=F,Ye=Ae;Ae+Se>Bt&&(Ye=Ae-Se),F+ae>wt&&(tt=F-ae),L({x:tt,y:Ye,elementId:I,elementType:P}),Ke(I);},[Ke,r.enabled]),ud=useCallback(w=>{s(Jo(w)),s(ma(true));},[s]),Im=useCallback(w=>{s(jo(w)),s(Ba(true));},[s]),Cm=useCallback((w,I)=>{if(!C)return;let{elementId:P,elementType:F}=C;switch(w){case "order":if(I){let T=I.target.getBoundingClientRect();U({x:T.right+5,y:T.top,type:"order"});}break;case "lock":if(I){let T=I.target.getBoundingClientRect();U({x:T.right+5,y:T.top,type:"lock"});}break;case "link":if(L(null),F==="line")break;let Ae=i?F==="image"?i.images.find(T=>T.id===P):i.videos.find(T=>T.id===P):null;W({type:"link",defaultValue:Ae?.link||""});break;case "voice":if(L(null),F==="line")break;let Se=i?F==="image"?i.images.find(T=>T.id===P):F==="video"?i.videos.find(T=>T.id===P):F==="text"?i.texts.find(T=>T.id===P):F==="flashcard"?i.flashcards.find(T=>T.id===P):F==="photoFrame"?i.photoFrames.find(T=>T.id===P):F==="mcq"?i.multipleChoices.find(T=>T.id===P):F==="fillInTheBlanks"?i.fillInTheBlanks.find(T=>T.id===P):F==="longAnswer"?i.LongAnswer.find(T=>T.id===P):F==="shortAnswer"?i.shortAnswers.find(T=>T.id===P):F==="trueFalse"?i.trueFalses.find(T=>T.id===P):F==="shape"?i.shapes.find(T=>T.id===P):null:null;H({elementId:P,elementType:F,existingAudio:Se?.audioData});break;case "edit":L(null);let ae=null;F==="mcq"?ae=i?.multipleChoices.find(T=>T.id===P):F==="trueFalse"?ae=i?.trueFalses.find(T=>T.id===P):F==="shortAnswer"?ae=i?.shortAnswers.find(T=>T.id===P):F==="longAnswer"?ae=i?.LongAnswer.find(T=>T.id===P):F==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(T=>T.id===P)),ae&&ud(ae);break;case "editFlashcard":L(null);let Bt=i?.flashcards.find(T=>T.id===P);Bt&&Im(Bt);break;case "color":L(null);let wt=i?.shapes.find(T=>T.id===P);ne({elementId:P,elementType:"shape",defaultColor:wt?.color||"#096B76"});break;case "crop":if(L(null),F==="image"){let T=i?.images.find(Rm=>Rm.id===P);T&&re({elementId:P,imageSrc:T.src});}break;case "draw":L(null),F==="image"?s(Jn(P)):F==="photoFrame"&&s(Qn(P));break;case "duplicate":s(ce()),F==="line"?s(ci(P)):F==="image"?s(Jr(P)):F==="video"?s(ts(P)):F==="shape"?s(as(P)):F==="text"?s(ss(P)):F==="flashcard"?s(is(P)):F==="photoFrame"?s(ds(P)):F==="mcq"?s(cs(P)):F==="trueFalse"?s(ms(P)):F==="shortAnswer"?s(hs(P)):F==="fillInTheBlanks"?s(vs(P)):F==="longAnswer"&&s(xs(P)),Y();break;case "infinite-clone":s(ce());let tt=5;for(let T=0;T<tt;T++)F==="image"?s(Jr(P)):F==="video"?s(ts(P)):F==="shape"?s(as(P)):F==="text"?s(ss(P)):F==="flashcard"?s(is(P)):F==="photoFrame"?s(ds(P)):F==="mcq"?s(cs(P)):F==="trueFalse"?s(ms(P)):F==="shortAnswer"?s(hs(P)):F==="fillInTheBlanks"?s(vs(P)):F==="longAnswer"&&s(xs(P));Y();break;case "make-response":if(L(null),F==="line")break;let Ye=`#response-${P}`;s(ce()),s(ys({id:P,type:F,link:Ye})),(i?F==="image"?i.images.find(T=>T.id===P):F==="video"?i.videos.find(T=>T.id===P):F==="shape"?i.shapes.find(T=>T.id===P):F==="flashcard"?i.flashcards.find(T=>T.id===P):F==="photoFrame"?i.photoFrames.find(T=>T.id===P):i.multipleChoices.find(T=>T.id===P):null)?.altText||s(ws({id:P,type:F,altText:"Interactive response area"})),Y(),console.log(`Element ${P} marked as interactive response area`);break;case "accessibility":if(L(null),F==="line")break;let B=i?F==="image"?i.images.find(T=>T.id===P):F==="video"?i.videos.find(T=>T.id===P):F==="shape"?i.shapes.find(T=>T.id===P):null:null;W({type:"altText",defaultValue:B?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),L(null),te(true),console.log("showLayersPanel state set to:",true);break;case "delete":s(ce()),F==="line"?s(Is(P)):F==="image"?s(Yr(P)):F==="video"?s(es(P)):F==="shape"?s(os(P)):F==="text"?s(rs(P)):F==="flashcard"?s(ns(P)):F==="photoFrame"?s(ls(P)):F==="mcq"?s(us(P)):F==="trueFalse"?s(fs(P)):F==="shortAnswer"?s(ps(P)):F==="longAnswer"?s(gs(P)):F==="fillInTheBlanks"&&s(bs(P)),so(),Y();break}},[C,s,Y,so,i,ud]),km=useCallback(()=>{L(null),U(null);},[]),Rn=useCallback(w=>{if(!C)return;let{elementId:I,elementType:P}=C;switch(s(ce()),w){case "bring-to-front":P!=="line"&&s(ii({id:I,type:P}));break;case "send-to-back":P!=="line"&&s(li({id:I,type:P}));break;case "lock":case "unlock":P!=="line"&&s(di({id:I,type:P}));break}Y(),L(null),U(null);},[C,s,Y]),Mm=useCallback(w=>{if(!C||!A)return;let{elementId:I,elementType:P}=C;s(ce()),A.type==="link"&&P!=="line"?s(ys({id:I,type:P,link:w})):A.type==="altText"&&P!=="line"&&s(ws({id:I,type:P,altText:w})),Y(),W(null);},[C,A,s,Y]),Tm=useCallback(w=>{if(!_)return;let{elementId:I,elementType:P}=_;s(ce()),s(Ss({id:I,type:P,audioData:w})),Y(),H(null);},[_,s,Y]),Am=useCallback(()=>{if(!_)return;let{elementId:w,elementType:I}=_;s(ce()),s(Ss({id:w,type:I,audioData:""})),Y();},[_,s,Y]),Pm=useCallback(w=>{if(!E)return;let{elementId:I}=E;s(ce()),s(lo({id:I,color:w})),Y(),ne(null);},[E,s,Y]),Dm=useCallback(w=>{if(!N)return;let{elementId:I}=N;s(ce()),s(io({id:I,src:w})),Y(),re(null);},[N,s,Y]);return jsxs("div",{ref:m,className:"fixed inset-0",style:{cursor:n==="pen"?"crosshair":n==="eraser"?"":"default"},children:[n==="pen"&&jsx(Ld,{ref:w=>{if(J.current=w,Ln(w),w){let I=w.getCanvasElement();I&&(le.current=I,a&&a(le));}},width:g.baseWidth,height:g.baseHeight,tool:oo,color:In,strokeWidth:Cn/g.scale,isSketchMode:kn,xOffset:g.contentOffsetX,yOffset:g.contentOffsetY-g.offsetY/g.scale,style:{width:g.stageWidth,height:g.stageHeight}}),jsxs(Stage,{ref:c,width:g.stageWidth,height:g.stageHeight,scaleX:g.scaleX,scaleY:g.scaleY,x:g.offsetX,y:0,onMouseDown:id,onMouseMove:ld,onMouseUp:dd,onTouchStart:id,onTouchMove:ld,onTouchEnd:dd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:g.baseWidth,height:g.stageHeight/g.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-g.contentOffsetX,y:g.offsetY/g.scale-g.contentOffsetY,children:(()=>{let w=[];return u.forEach((I,P)=>{w.push({type:"line",timestamp:I.timestamp||P,element:{...I,id:I.id??`line-${P}`},index:P});}),nm.forEach(I=>{w.push({type:"shape",timestamp:I.timestamp||0,element:I});}),Mn.forEach(I=>{w.push({type:"image",timestamp:I.timestamp||0,element:I});}),R.forEach(I=>{w.push({type:"video",timestamp:I.timestamp||0,element:I});}),Ko.forEach(I=>{w.push({type:"text",timestamp:I.timestamp||0,element:I});}),fm.forEach(I=>{w.push({type:"flashcard",timestamp:I.timestamp||0,element:I});}),rd.forEach(I=>{w.push({type:"photoFrame",timestamp:I.timestamp||0,element:I});}),ue.forEach(I=>{w.push({type:"mcq",timestamp:I.timestamp||0,element:I});}),dt.forEach(I=>{w.push({type:"trueFalse",timestamp:I.timestamp||0,element:I});}),la.forEach(I=>{w.push({type:"shortAnswer",timestamp:I.timestamp||0,element:I});}),Wr.forEach(I=>{w.push({type:"longAnswer",timestamp:I.timestamp||0,element:I});}),da.forEach(I=>{w.push({type:"fillInTheBlanks",timestamp:I.timestamp||0,element:I});}),w.sort((I,P)=>I.timestamp-P.timestamp),w.map((I,P)=>{let F=`${I.type}-${"id"in I.element&&I.element.id||I.index||P}`,Ae="id"in I.element?I.element.id:void 0,Se=Ae&&p===Ae;switch(I.type){case "line":let ae=I.element,Bt=I.index||0,wt=ae.tool==="eraser",tt=ae.isSketch&&ae.tool==="pen",Ye=ae.isSketch&&wt,St=ae.id||`line-${Bt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),n==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:tt||Ye?void 0:ae.color,strokeWidth:tt||Ye?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Ye?wt?"black":ae.color:void 0,closed:tt||Ye,tension:0,globalCompositeOperation:wt?"destination-out":"source-over",listening:true,onClick:()=>{s(ce()),s($r(Bt));},onTap:()=>{s(ce()),s($r(Bt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:B=>{let T=B.target.getStage();T&&(T.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:B=>{let T=B.target.getStage();T&&(T.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},F):jsxs(be__default.Fragment,{children:[jsx(Group,{id:St,ref:B=>{B?ia.current.set(St,B):ia.current.delete(St);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:n==="select",listening:n==="select",onClick:()=>{n==="select"&&(console.log("Line clicked:",St),Ke(St));},onTap:()=>{n==="select"&&(console.log("Line tapped:",St),Ke(St));},onDragEnd:B=>{s(ce()),s(Ls({id:St,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onTransformEnd:B=>{s(ce()),s(Ls({id:St,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onMouseEnter:B=>{if(n==="select"){let T=B.target.getStage();T&&(T.container().style.cursor="move");}},onMouseLeave:B=>{if(n==="select"){let T=B.target.getStage();T&&(T.container().style.cursor="default");}},onContextMenu:B=>{let T=B.evt;T.preventDefault(),yt(T,St,"line");},children:jsx(Line,{points:ae.points||[],stroke:tt||Ye?void 0:ae.color,strokeWidth:tt||Ye?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Ye?wt?"black":ae.color:void 0,closed:tt||Ye,tension:0,globalCompositeOperation:wt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=ia.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!T),T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "shape":return jsxs(be__default.Fragment,{children:[jsx(Di,{onSelect:Ke,shapes:[I.element],shapeRefs:Gr,handleShapeDragEnd:im,handleShapeResizeEnd:lm,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=Gr.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "image":return jsxs(be__default.Fragment,{children:[jsx(Mi,{images:[I.element],getLoadedImage:Tn,imageRefs:ro,onDragEnd:Sm,onTransform:An,onSelect:Ke,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=ro.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "video":return jsxs(be__default.Fragment,{children:[jsx(Pi,{videos:[I.element],selectedId:p,videoRefs:oe,onVideoClick:Lm,onDragEnd:ge,onTransformEnd:se,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=oe.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "text":return jsxs(be__default.Fragment,{children:[jsx(au,{texts:[I.element],textRefs:ua,onDragEnd:dm,onTransformEnd:um,onSelect:Ke,onContextMenu:yt,onDoubleClick:cm,editingTextId:pe,editingValue:ad,onEditingChange:od}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=ua.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Fi,{flashcards:[I.element],flashcardRefs:jr,selectedId:p,onDragEnd:mm,onTransform:pm,onSelect:Ke,onNext:hm,onPrevious:gm,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=jr.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Hi,{photoFrames:[I.element],photoFrameRefs:Xr,selectedId:p,onDragEnd:xm,onTransform:bm,onSelect:Ke,onStartCamera:vm,onCapture:ym,cameraStreams:wm,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=Xr.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(Pu,{handleMcqTransform:we,multipleChoice:[I.element],handleSelect:Ke,mcqRefs:Ne,handleDragEnd:Et,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=Ne.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Eu,{trueFalses:[I.element],handleTrueFalseTransform:Te,handleSelect:Ke,trueFalseRefs:Ue,onContextMenu:yt,handleDragEnd:Yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=Ue.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(ec,{shortAnswers:[I.element],handleSelect:Ke,handleTransform:we,saRefs:Ra,onContextMenu:yt,handleDragEnd:Pn}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=Ra.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(lc,{longAnswer:[I.element],handleSelect:Ke,handleTransform:we,saRefs:Ra,onContextMenu:yt,handleDragEnd:Ft}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=Ra.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(nc,{fillInTheBlanks:[I.element],handleSelect:Ke,handleTransform:we,onContextMenu:yt,handleDragEnd:Ea,fibRefs:zr}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let T=zr.current.get(p);T&&T.visible()&&(B.nodes([T]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);default:return null}})})()})]}),C&&jsx(hu,{menuRef:x,x:C.x,y:C.y,type:C.elementType,onAction:Cm,onClose:km,isDrawingMode:C.elementType==="image"?i?.images.find(w=>w.id===C.elementId)?.isDrawingMode:C.elementType==="photoFrame"?i?.photoFrames.find(w=>w.id===C.elementId)?.isDrawingMode:false}),q&&C&&jsx(gu,{x:q.x,y:q.y,items:q.type==="order"?[{label:"Bring to Front",onClick:()=>Rn("bring-to-front")},{label:"Send to Back",onClick:()=>Rn("send-to-back")}]:[{label:i&&(C.elementType==="image"?i.images.find(w=>w.id===C.elementId)?.locked:i.videos.find(w=>w.id===C.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Rn(i&&(C.elementType==="image"?i.images.find(w=>w.id===C.elementId)?.locked:i.videos.find(w=>w.id===C.elementId)?.locked)?"unlock":"lock")}],onClose:()=>U(null)}),A&&jsx(xu,{title:A.type==="link"?"Add Link":"Add Alt Text",label:A.type==="link"?"URL":"Alternative Text",placeholder:A.type==="link"?"https://example.com":"Describe this image/video",defaultValue:A.defaultValue,onSave:Mm,onClose:()=>W(null)}),E&&jsx(Es,{defaultColor:E.defaultColor,onConfirm:Pm,onCancel:()=>ne(null)}),N&&jsx(wu,{imageSrc:N.imageSrc,onConfirm:Dm,onCancel:()=>re(null)}),G&&jsx(lr,{onClose:()=>V(false),stageRef:c}),_&&jsx(Iu,{elementId:_.elementId,elementType:_.elementType,existingAudio:_.existingAudio,onSave:Tm,onDelete:Am,onClose:()=>H(null)}),K&&jsx(Mu,{selectedElementId:p||void 0,onClose:()=>te(false),onSelectElement:w=>{Ke(w),te(false);}}),i?.images.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.videos.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.shapes?.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.texts?.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.flashcards?.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(Ct,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),f&&jsx(Gu,{editElement:d}),y&&(()=>{let w=pe||p;if(!w)return null;let I=Ko.find(P=>P.id===w);return I?jsx(Xu,{text:I,position:y}):null})(),O&&pe&&(()=>{let w=Ko.find(I=>I.id===pe);return w?jsx(Yu,{text:w,editingValue:ad,onEditingChange:od,onFinish:Dn,position:{top:O.top,left:O.left},scale:O.scale,textareaRef:Z},pe):null})()]})},wb=yb;function gl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Ze(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function hc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Pr(...e){return o=>{let t=false,a=e.map(r=>{let s=hc(r,o);return !t&&typeof s=="function"&&(t=true),s});if(t)return ()=>{for(let r=0;r<a.length;r++){let s=a[r];typeof s=="function"?s():hc(e[r],null);}}}}function Pt(...e){return be.useCallback(Pr(...e),e)}function Ca(e,o=[]){let t=[];function a(s,n){let i=be.createContext(n),l=t.length;t=[...t,n];let d=u=>{let{scope:c,children:m,...p}=u,v=c?.[e]?.[l]||i,h=be.useMemo(()=>p,Object.values(p));return jsx(v.Provider,{value:h,children:m})};d.displayName=s+"Provider";function f(u,c){let m=c?.[e]?.[l]||i,p=be.useContext(m);if(p)return p;if(n!==void 0)return n;throw new Error(`\`${u}\` must be used within \`${s}\``)}return [d,f]}let r=()=>{let s=t.map(n=>be.createContext(n));return function(i){let l=i?.[e]||s;return be.useMemo(()=>({[`__scope${e}`]:{...i,[e]:l}}),[i,l])}};return r.scopeName=e,[a,Lb(r,...o)]}function Lb(...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(s){let n=a.reduce((i,{useScope:l,scopeName:d})=>{let u=l(s)[`__scope${d}`];return {...i,...u}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var Bo=globalThis?.document?be.useLayoutEffect:()=>{};var Ib=be[" useInsertionEffect ".trim().toString()]||Bo;function ea({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,s,n]=Cb({defaultProp:o,onChange:t}),i=e!==void 0,l=i?e:r;{let f=be.useRef(e!==void 0);be.useEffect(()=>{let u=f.current;u!==i&&console.warn(`${a} is changing from ${u?"controlled":"uncontrolled"} to ${i?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=i;},[i,a]);}let d=be.useCallback(f=>{if(i){let u=kb(f)?f(e):f;u!==e&&n.current?.(u);}else s(f);},[i,e,s,n]);return [l,d]}function Cb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),s=be.useRef(o);return Ib(()=>{s.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(s.current?.(t),r.current=t);},[t,r]),[t,a,s]}function kb(e){return typeof e=="function"}var Mb=be.createContext(void 0);function Oo(e){let o=be.useContext(Mb);return e||o||"ltr"}function bc(e){let o=be.useRef({value:e,previous:e});return be.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function yc(e){let[o,t]=be.useState(void 0);return Bo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let s=r[0],n,i;if("borderBoxSize"in s){let l=s.borderBoxSize,d=Array.isArray(l)?l[0]:l;n=d.inlineSize,i=d.blockSize;}else n=e.offsetWidth,i=e.offsetHeight;t({width:n,height:i});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function Sc(e){let o=Tb(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),l=i.find(Pb);if(l){let d=l.props.children,f=i.map(u=>u===l?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...n,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...n,ref:r,children:s})});return t.displayName=`${e}.Slot`,t}function Tb(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=Rb(r),i=Db(s,r.props);return r.type!==be.Fragment&&(i.ref=a?Pr(a,n):n),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Ab=Symbol("radix.slottable");function Pb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ab}function Db(e,o){let t={...o};for(let a in o){let r=e[a],s=o[a];/^on[A-Z]/.test(a)?r&&s?t[a]=(...i)=>{let l=s(...i);return r(...i),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...s}:a==="className"&&(t[a]=[r,s].filter(Boolean).join(" "));}return {...e,...t}}function Rb(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 Bb=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],it=Bb.reduce((e,o)=>{let t=Sc(`Primitive.${o}`),a=be.forwardRef((r,s)=>{let{asChild:n,...i}=r,l=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(l,{...i,ref:s})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function xl(e){let o=Ob(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),l=i.find(Vb);if(l){let d=l.props.children,f=i.map(u=>u===l?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...n,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...n,ref:r,children:s})});return t.displayName=`${e}.Slot`,t}function Ob(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=Hb(r),i=qb(s,r.props);return r.type!==be.Fragment&&(i.ref=a?Pr(a,n):n),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Nb=Symbol("radix.slottable");function Vb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Nb}function qb(e,o){let t={...o};for(let a in o){let r=e[a],s=o[a];/^on[A-Z]/.test(a)?r&&s?t[a]=(...i)=>{let l=s(...i);return r(...i),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...s}:a==="className"&&(t[a]=[r,s].filter(Boolean).join(" "));}return {...e,...t}}function Hb(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function ln(e){let o=e+"CollectionProvider",[t,a]=Ca(o),[r,s]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=v=>{let{scope:h,children:b}=v,x=be__default.useRef(null),g=be__default.useRef(new Map).current;return jsx(r,{scope:h,itemMap:g,collectionRef:x,children:b})};n.displayName=o;let i=e+"CollectionSlot",l=xl(i),d=be__default.forwardRef((v,h)=>{let{scope:b,children:x}=v,g=s(i,b),S=Pt(h,g.collectionRef);return jsx(l,{ref:S,children:x})});d.displayName=i;let f=e+"CollectionItemSlot",u="data-radix-collection-item",c=xl(f),m=be__default.forwardRef((v,h)=>{let{scope:b,children:x,...g}=v,S=be__default.useRef(null),k=Pt(h,S),C=s(f,b);return be__default.useEffect(()=>(C.itemMap.set(S,{ref:S,...g}),()=>void C.itemMap.delete(S))),jsx(c,{[u]:"",ref:k,children:x})});m.displayName=f;function p(v){let h=s(e+"CollectionConsumer",v);return be__default.useCallback(()=>{let x=h.collectionRef.current;if(!x)return [];let g=Array.from(x.querySelectorAll(`[${u}]`));return Array.from(h.itemMap.values()).sort((C,L)=>g.indexOf(C.ref.current)-g.indexOf(L.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:n,Slot:d,ItemSlot:m},p,a]}var Cc=["PageUp","PageDown"],kc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Mc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},No="Slider",[vl,Wb,zb]=ln(No),[Tc]=Ca(No,[zb]),[Gb,dn]=Tc(No),Ac=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:s=1,orientation:n="horizontal",disabled:i=false,minStepsBetweenThumbs:l=0,defaultValue:d=[a],value:f,onValueChange:u=()=>{},onValueCommit:c=()=>{},inverted:m=false,form:p,...v}=e,h=be.useRef(new Set),b=be.useRef(0),g=n==="horizontal"?Kb:_b,[S=[],k]=ea({prop:f,defaultProp:d,onChange:D=>{[...h.current][b.current]?.focus(),u(D);}}),C=be.useRef(S);function L(D){let q=Jb(S,D);O(D,q);}function y(D){O(D,b.current);}function M(){let D=C.current[b.current];S[b.current]!==D&&c(S);}function O(D,q,{commit:U}={commit:false}){let A=tv(s),W=av(Math.round((D-a)/s)*s+a,A),E=gl(W,[a,r]);k((ne=[])=>{let N=$b(ne,E,q);if(ev(N,l*s)){b.current=N.indexOf(E);let re=String(N)!==String(ne);return re&&U&&c(N),re?N:ne}else return ne});}return jsx(Gb,{scope:e.__scopeSlider,name:t,disabled:i,min:a,max:r,valueIndexToChangeRef:b,thumbs:h.current,values:S,orientation:n,form:p,children:jsx(vl.Provider,{scope:e.__scopeSlider,children:jsx(vl.Slot,{scope:e.__scopeSlider,children:jsx(g,{"aria-disabled":i,"data-disabled":i?"":void 0,...v,ref:o,onPointerDown:Ze(v.onPointerDown,()=>{i||(C.current=S);}),min:a,max:r,inverted:m,onSlideStart:i?void 0:L,onSlideMove:i?void 0:y,onSlideEnd:i?void 0:M,onHomeKeyDown:()=>!i&&O(a,0,{commit:true}),onEndKeyDown:()=>!i&&O(r,S.length-1,{commit:true}),onStepKeyDown:({event:D,direction:q})=>{if(!i){let W=Cc.includes(D.key)||D.shiftKey&&kc.includes(D.key)?10:1,E=b.current,ne=S[E],N=s*W*q;O(ne+N,E,{commit:true});}}})})})})});Ac.displayName=No;var[Pc,Dc]=Tc(No,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Kb=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:s,onSlideStart:n,onSlideMove:i,onSlideEnd:l,onStepKeyDown:d,...f}=e,[u,c]=be.useState(null),m=Pt(o,g=>c(g)),p=be.useRef(void 0),v=Oo(r),h=v==="ltr",b=h&&!s||!h&&s;function x(g){let S=p.current||u.getBoundingClientRect(),k=[0,S.width],L=Sl(k,b?[t,a]:[a,t]);return p.current=S,L(g-S.left)}return jsx(Pc,{scope:e.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:jsx(Rc,{dir:v,"data-orientation":"horizontal",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:g=>{let S=x(g.clientX);n?.(S);},onSlideMove:g=>{let S=x(g.clientX);i?.(S);},onSlideEnd:()=>{p.current=void 0,l?.();},onStepKeyDown:g=>{let k=Mc[b?"from-left":"from-right"].includes(g.key);d?.({event:g,direction:k?-1:1});}})})}),_b=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:s,onSlideMove:n,onSlideEnd:i,onStepKeyDown:l,...d}=e,f=be.useRef(null),u=Pt(o,f),c=be.useRef(void 0),m=!r;function p(v){let h=c.current||f.current.getBoundingClientRect(),b=[0,h.height],g=Sl(b,m?[a,t]:[t,a]);return c.current=h,g(v-h.top)}return jsx(Pc,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:jsx(Rc,{"data-orientation":"vertical",...d,ref:u,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:v=>{let h=p(v.clientY);s?.(h);},onSlideMove:v=>{let h=p(v.clientY);n?.(h);},onSlideEnd:()=>{c.current=void 0,i?.();},onStepKeyDown:v=>{let b=Mc[m?"from-bottom":"from-top"].includes(v.key);l?.({event:v,direction:b?-1:1});}})})}),Rc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:s,onHomeKeyDown:n,onEndKeyDown:i,onStepKeyDown:l,...d}=e,f=dn(No,t);return jsx(it.span,{...d,ref:o,onKeyDown:Ze(e.onKeyDown,u=>{u.key==="Home"?(n(u),u.preventDefault()):u.key==="End"?(i(u),u.preventDefault()):Cc.concat(kc).includes(u.key)&&(l(u),u.preventDefault());}),onPointerDown:Ze(e.onPointerDown,u=>{let c=u.target;c.setPointerCapture(u.pointerId),u.preventDefault(),f.thumbs.has(c)?c.focus():a(u);}),onPointerMove:Ze(e.onPointerMove,u=>{u.target.hasPointerCapture(u.pointerId)&&r(u);}),onPointerUp:Ze(e.onPointerUp,u=>{let c=u.target;c.hasPointerCapture(u.pointerId)&&(c.releasePointerCapture(u.pointerId),s(u));})})}),Ec="SliderTrack",Fc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=dn(Ec,t);return jsx(it.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});Fc.displayName=Ec;var yl="SliderRange",Bc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=dn(yl,t),s=Dc(yl,t),n=be.useRef(null),i=Pt(o,n),l=r.values.length,d=r.values.map(c=>Vc(c,r.min,r.max)),f=l>1?Math.min(...d):0,u=100-Math.max(...d);return jsx(it.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:i,style:{...e.style,[s.startEdge]:f+"%",[s.endEdge]:u+"%"}})});Bc.displayName=yl;var wl="SliderThumb",Oc=be.forwardRef((e,o)=>{let t=Wb(e.__scopeSlider),[a,r]=be.useState(null),s=Pt(o,i=>r(i)),n=be.useMemo(()=>a?t().findIndex(i=>i.ref.current===a):-1,[t,a]);return jsx(jb,{...e,ref:s,index:n})}),jb=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...s}=e,n=dn(wl,t),i=Dc(wl,t),[l,d]=be.useState(null),f=Pt(o,x=>d(x)),u=l?n.form||!!l.closest("form"):true,c=yc(l),m=n.values[a],p=m===void 0?0:Vc(m,n.min,n.max),v=Yb(a,n.values.length),h=c?.[i.size],b=h?Zb(h,p,i.direction):0;return be.useEffect(()=>{if(l)return n.thumbs.add(l),()=>{n.thumbs.delete(l);}},[l,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[i.startEdge]:`calc(${p}% + ${b}px)`},children:[jsx(vl.ItemSlot,{scope:e.__scopeSlider,children:jsx(it.span,{role:"slider","aria-label":e["aria-label"]||v,"aria-valuemin":n.min,"aria-valuenow":m,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...s,ref:f,style:m===void 0?{display:"none"}:e.style,onFocus:Ze(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),u&&jsx(Nc,{name:r??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:m},a)]})});Oc.displayName=wl;var Xb="RadioBubbleInput",Nc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),s=Pt(r,a),n=bc(o);return be.useEffect(()=>{let i=r.current;if(!i)return;let l=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(l,"value").set;if(n!==o&&f){let u=new Event("input",{bubbles:true});f.call(i,o),i.dispatchEvent(u);}},[n,o]),jsx(it.input,{style:{display:"none"},...t,ref:s,defaultValue:o})});Nc.displayName=Xb;function $b(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,s)=>r-s)}function Vc(e,o,t){let s=100/(t-o)*(e-o);return gl(s,[0,100])}function Yb(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Jb(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 Zb(e,o,t){let a=e/2,s=Sl([0,50],[0,a]);return (a-s(o)*t)*t}function Qb(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function ev(e,o){if(o>0){let t=Qb(e);return Math.min(...t)>=o}return true}function Sl(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 tv(e){return (String(e).split(".")[1]||"").length}function av(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var qc=Ac,Hc=Fc,Uc=Bc,Wc=Oc;function zc(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=zc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function un(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=zc(e))&&(a&&(a+=" "),a+=o);return a}var rv=(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},sv=(e,o)=>({classGroupId:e,validator:o}),Xc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Gc=[],nv="arbitrary..",iv=e=>{let o=dv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return lv(n);let i=n.split("-"),l=i[0]===""&&i.length>1?1:0;return $c(i,l,o)},getConflictingClassGroupIds:(n,i)=>{if(i){let l=a[n],d=t[n];return l?d?rv(d,l):l:d||Gc}return t[n]||Gc}}},$c=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],s=t.nextPart.get(r);if(s){let d=$c(e,o+1,s);if(d)return d}let n=t.validators;if(n===null)return;let i=o===0?e.join("-"):e.slice(o).join("-"),l=n.length;for(let d=0;d<l;d++){let f=n[d];if(f.validator(i))return f.classGroupId}},lv=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?nv+a:void 0})(),dv=e=>{let{theme:o,classGroups:t}=e;return uv(t,o)},uv=(e,o)=>{let t=Xc();for(let a in e){let r=e[a];Cl(r,t,a,o);}return t},Cl=(e,o,t,a)=>{let r=e.length;for(let s=0;s<r;s++){let n=e[s];cv(n,o,t,a);}},cv=(e,o,t,a)=>{if(typeof e=="string"){fv(e,o,t);return}if(typeof e=="function"){mv(e,o,t,a);return}pv(e,o,t,a);},fv=(e,o,t)=>{let a=e===""?o:Yc(o,e);a.classGroupId=t;},mv=(e,o,t,a)=>{if(hv(e)){Cl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(sv(t,e));},pv=(e,o,t,a)=>{let r=Object.entries(e),s=r.length;for(let n=0;n<s;n++){let[i,l]=r[n];Cl(l,Yc(o,i),t,a);}},Yc=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let s=0;s<r;s++){let n=a[s],i=t.nextPart.get(n);i||(i=Xc(),t.nextPart.set(n,i)),t=i;}return t},hv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,gv=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(s,n)=>{t[s]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(s){let n=t[s];if(n!==void 0)return n;if((n=a[s])!==void 0)return r(s,n),n},set(s,n){s in t?t[s]=n:r(s,n);}}};var xv=[],Kc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),bv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let s=[],n=0,i=0,l=0,d,f=r.length;for(let v=0;v<f;v++){let h=r[v];if(n===0&&i===0){if(h===":"){s.push(r.slice(l,v)),l=v+1;continue}if(h==="/"){d=v;continue}}h==="["?n++:h==="]"?n--:h==="("?i++:h===")"&&i--;}let u=s.length===0?r:r.slice(l),c=u,m=false;u.endsWith("!")?(c=u.slice(0,-1),m=true):u.startsWith("!")&&(c=u.slice(1),m=true);let p=d&&d>l?d-l:void 0;return Kc(s,m,c,p)};if(o){let r=o+":",s=a;a=n=>n.startsWith(r)?s(n.slice(r.length)):Kc(xv,false,n,void 0,true);}if(t){let r=a;a=s=>t({className:s,parseClassName:r});}return a},vv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],i=n[0]==="[",l=o.has(n);i||l?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(n)):r.push(n);}return r.length>0&&(r.sort(),a.push(...r)),a}},yv=e=>({cache:gv(e.cacheSize),parseClassName:bv(e),sortModifiers:vv(e),...iv(e)}),wv=/\s+/,Sv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:s}=o,n=[],i=e.trim().split(wv),l="";for(let d=i.length-1;d>=0;d-=1){let f=i[d],{isExternal:u,modifiers:c,hasImportantModifier:m,baseClassName:p,maybePostfixModifierPosition:v}=t(f);if(u){l=f+(l.length>0?" "+l:l);continue}let h=!!v,b=a(h?p.substring(0,v):p);if(!b){if(!h){l=f+(l.length>0?" "+l:l);continue}if(b=a(p),!b){l=f+(l.length>0?" "+l:l);continue}h=false;}let x=c.length===0?"":c.length===1?c[0]:s(c).join(":"),g=m?x+"!":x,S=g+b;if(n.indexOf(S)>-1)continue;n.push(S);let k=r(b,h);for(let C=0;C<k.length;++C){let L=k[C];n.push(g+L);}l=f+(l.length>0?" "+l:l);}return l},Lv=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=Jc(t))&&(r&&(r+=" "),r+=a);return r},Jc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Jc(e[a]))&&(t&&(t+=" "),t+=o);return t},Iv=(e,...o)=>{let t,a,r,s,n=l=>{let d=o.reduce((f,u)=>u(f),e());return t=yv(d),a=t.cache.get,r=t.cache.set,s=i,i(l)},i=l=>{let d=a(l);if(d)return d;let f=Sv(l,t);return r(l,f),f};return s=n,(...l)=>s(Lv(...l))},Cv=[],He=e=>{let o=t=>t[e]||Cv;return o.isThemeGetter=true,o},Zc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Qc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,kv=/^\d+\/\d+$/,Mv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Tv=/\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$/,Av=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Pv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Dv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Vo=e=>kv.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),ka=e=>!!e&&Number.isInteger(Number(e)),Ll=e=>e.endsWith("%")&&de(e.slice(0,-1)),ta=e=>Mv.test(e),Rv=()=>true,Ev=e=>Tv.test(e)&&!Av.test(e),ef=()=>false,Fv=e=>Pv.test(e),Bv=e=>Dv.test(e),Ov=e=>!X(e)&&!$(e),Nv=e=>qo(e,of,ef),X=e=>Zc.test(e),$a=e=>qo(e,rf,Ev),Il=e=>qo(e,Wv,de),_c=e=>qo(e,tf,ef),Vv=e=>qo(e,af,Bv),cn=e=>qo(e,sf,Fv),$=e=>Qc.test(e),Dr=e=>Ho(e,rf),qv=e=>Ho(e,zv),jc=e=>Ho(e,tf),Hv=e=>Ho(e,of),Uv=e=>Ho(e,af),fn=e=>Ho(e,sf,true),qo=(e,o,t)=>{let a=Zc.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Ho=(e,o,t=false)=>{let a=Qc.exec(e);return a?a[1]?o(a[1]):t:false},tf=e=>e==="position"||e==="percentage",af=e=>e==="image"||e==="url",of=e=>e==="length"||e==="size"||e==="bg-size",rf=e=>e==="length",Wv=e=>e==="number",zv=e=>e==="family-name",sf=e=>e==="shadow";var Gv=()=>{let e=He("color"),o=He("font"),t=He("text"),a=He("font-weight"),r=He("tracking"),s=He("leading"),n=He("breakpoint"),i=He("container"),l=He("spacing"),d=He("radius"),f=He("shadow"),u=He("inset-shadow"),c=He("text-shadow"),m=He("drop-shadow"),p=He("blur"),v=He("perspective"),h=He("aspect"),b=He("ease"),x=He("animate"),g=()=>["auto","avoid","all","avoid-page","page","left","right","column"],S=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],k=()=>[...S(),$,X],C=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],y=()=>[$,X,l],M=()=>[Vo,"full","auto",...y()],O=()=>[ka,"none","subgrid",$,X],D=()=>["auto",{span:["full",ka,$,X]},ka,$,X],q=()=>[ka,"auto",$,X],U=()=>["auto","min","max","fr",$,X],A=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],W=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...y()],ne=()=>[Vo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...y()],N=()=>[e,$,X],re=()=>[...S(),jc,_c,{position:[$,X]}],G=()=>["no-repeat",{repeat:["","x","y","space","round"]}],V=()=>["auto","cover","contain",Hv,Nv,{size:[$,X]}],_=()=>[Ll,Dr,$a],H=()=>["","none","full",d,$,X],K=()=>["",de,Dr,$a],te=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[de,Ll,jc,_c],le=()=>["","none",p,$,X],Ie=()=>["none",de,$,X],Y=()=>["none",de,$,X],Me=()=>[de,$,X],Be=()=>[Vo,"full",...y()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ta],breakpoint:[ta],color:[Rv],container:[ta],"drop-shadow":[ta],ease:["in","out","in-out"],font:[Ov],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ta],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ta],shadow:[ta],spacing:["px",de],text:[ta],"text-shadow":[ta],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Vo,X,$,h]}],container:["container"],columns:[{columns:[de,X,$,i]}],"break-after":[{"break-after":g()}],"break-before":[{"break-before":g()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:k()}],overflow:[{overflow:C()}],"overflow-x":[{"overflow-x":C()}],"overflow-y":[{"overflow-y":C()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:M()}],"inset-x":[{"inset-x":M()}],"inset-y":[{"inset-y":M()}],start:[{start:M()}],end:[{end:M()}],top:[{top:M()}],right:[{right:M()}],bottom:[{bottom:M()}],left:[{left:M()}],visibility:["visible","invisible","collapse"],z:[{z:[ka,"auto",$,X]}],basis:[{basis:[Vo,"full","auto",i,...y()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Vo,"auto","initial","none",X]}],grow:[{grow:["",de,$,X]}],shrink:[{shrink:["",de,$,X]}],order:[{order:[ka,"first","last","none",$,X]}],"grid-cols":[{"grid-cols":O()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":O()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":U()}],"auto-rows":[{"auto-rows":U()}],gap:[{gap:y()}],"gap-x":[{"gap-x":y()}],"gap-y":[{"gap-y":y()}],"justify-content":[{justify:[...A(),"normal"]}],"justify-items":[{"justify-items":[...W(),"normal"]}],"justify-self":[{"justify-self":["auto",...W()]}],"align-content":[{content:["normal",...A()]}],"align-items":[{items:[...W(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...W(),{baseline:["","last"]}]}],"place-content":[{"place-content":A()}],"place-items":[{"place-items":[...W(),"baseline"]}],"place-self":[{"place-self":["auto",...W()]}],p:[{p:y()}],px:[{px:y()}],py:[{py:y()}],ps:[{ps:y()}],pe:[{pe:y()}],pt:[{pt:y()}],pr:[{pr:y()}],pb:[{pb:y()}],pl:[{pl:y()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":y()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":y()}],"space-y-reverse":["space-y-reverse"],size:[{size:ne()}],w:[{w:[i,"screen",...ne()]}],"min-w":[{"min-w":[i,"screen","none",...ne()]}],"max-w":[{"max-w":[i,"screen","none","prose",{screen:[n]},...ne()]}],h:[{h:["screen","lh",...ne()]}],"min-h":[{"min-h":["screen","lh","none",...ne()]}],"max-h":[{"max-h":["screen","lh",...ne()]}],"font-size":[{text:["base",t,Dr,$a]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,Il]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ll,X]}],"font-family":[{font:[qv,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":[de,"none",$,Il]}],leading:[{leading:[s,...y()]}],"list-image":[{"list-image":["none",$,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...te(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",$,$a]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[de,"auto",$,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:y()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:re()}],"bg-repeat":[{bg:G()}],"bg-size":[{bg:V()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ka,$,X],radial:["",$,X],conic:[ka,$,X]},Uv,Vv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:_()}],"gradient-via-pos":[{via:_()}],"gradient-to-pos":[{to:_()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:H()}],"rounded-s":[{"rounded-s":H()}],"rounded-e":[{"rounded-e":H()}],"rounded-t":[{"rounded-t":H()}],"rounded-r":[{"rounded-r":H()}],"rounded-b":[{"rounded-b":H()}],"rounded-l":[{"rounded-l":H()}],"rounded-ss":[{"rounded-ss":H()}],"rounded-se":[{"rounded-se":H()}],"rounded-ee":[{"rounded-ee":H()}],"rounded-es":[{"rounded-es":H()}],"rounded-tl":[{"rounded-tl":H()}],"rounded-tr":[{"rounded-tr":H()}],"rounded-br":[{"rounded-br":H()}],"rounded-bl":[{"rounded-bl":H()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...te(),"hidden","none"]}],"divide-style":[{divide:[...te(),"hidden","none"]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...te(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,$,X]}],"outline-w":[{outline:["",de,Dr,$a]}],"outline-color":[{outline:N()}],shadow:[{shadow:["","none",f,fn,cn]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":["none",u,fn,cn]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[de,$a]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":["none",c,fn,cn]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[de,$,X]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,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":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":S()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:re()}],"mask-repeat":[{mask:G()}],"mask-size":[{mask:V()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,X]}],filter:[{filter:["","none",$,X]}],blur:[{blur:le()}],brightness:[{brightness:[de,$,X]}],contrast:[{contrast:[de,$,X]}],"drop-shadow":[{"drop-shadow":["","none",m,fn,cn]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:["",de,$,X]}],"hue-rotate":[{"hue-rotate":[de,$,X]}],invert:[{invert:["",de,$,X]}],saturate:[{saturate:[de,$,X]}],sepia:[{sepia:["",de,$,X]}],"backdrop-filter":[{"backdrop-filter":["","none",$,X]}],"backdrop-blur":[{"backdrop-blur":le()}],"backdrop-brightness":[{"backdrop-brightness":[de,$,X]}],"backdrop-contrast":[{"backdrop-contrast":[de,$,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,$,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,$,X]}],"backdrop-invert":[{"backdrop-invert":["",de,$,X]}],"backdrop-opacity":[{"backdrop-opacity":[de,$,X]}],"backdrop-saturate":[{"backdrop-saturate":[de,$,X]}],"backdrop-sepia":[{"backdrop-sepia":["",de,$,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":y()}],"border-spacing-x":[{"border-spacing-x":y()}],"border-spacing-y":[{"border-spacing-y":y()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",$,X]}],ease:[{ease:["linear","initial",b,$,X]}],delay:[{delay:[de,$,X]}],animate:[{animate:["none",x,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[v,$,X]}],"perspective-origin":[{"perspective-origin":k()}],rotate:[{rotate:Ie()}],"rotate-x":[{"rotate-x":Ie()}],"rotate-y":[{"rotate-y":Ie()}],"rotate-z":[{"rotate-z":Ie()}],scale:[{scale:Y()}],"scale-x":[{"scale-x":Y()}],"scale-y":[{"scale-y":Y()}],"scale-z":[{"scale-z":Y()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[$,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:k()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Be()}],"translate-x":[{"translate-x":Be()}],"translate-y":[{"translate-y":Be()}],"translate-z":[{"translate-z":Be()}],"translate-none":["translate-none"],accent:[{accent:N()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":y()}],"scroll-mx":[{"scroll-mx":y()}],"scroll-my":[{"scroll-my":y()}],"scroll-ms":[{"scroll-ms":y()}],"scroll-me":[{"scroll-me":y()}],"scroll-mt":[{"scroll-mt":y()}],"scroll-mr":[{"scroll-mr":y()}],"scroll-mb":[{"scroll-mb":y()}],"scroll-ml":[{"scroll-ml":y()}],"scroll-p":[{"scroll-p":y()}],"scroll-px":[{"scroll-px":y()}],"scroll-py":[{"scroll-py":y()}],"scroll-ps":[{"scroll-ps":y()}],"scroll-pe":[{"scroll-pe":y()}],"scroll-pt":[{"scroll-pt":y()}],"scroll-pr":[{"scroll-pr":y()}],"scroll-pb":[{"scroll-pb":y()}],"scroll-pl":[{"scroll-pl":y()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,X]}],fill:[{fill:["none",...N()]}],"stroke-w":[{stroke:[de,Dr,$a,Il]}],stroke:[{stroke:["none",...N()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var nf=Iv(Gv);function Ma(...e){return nf(un(e))}function mn({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:s,trackClassName:n,thumbClassName:i,...l}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(qc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Ma("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...l,children:[jsx(Hc,{"data-slot":"slider-track",className:Ma("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(Uc,{"data-slot":"slider-range",className:Ma("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",s)})}),Array.from({length:d.length},(f,u)=>jsx(Wc,{"data-slot":"slider-thumb",className:Ma("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",i)},u))]})}var _v="SchooplaVideoStorage";var Xt="videos",pn=()=>new Promise((e,o)=>{let t=indexedDB.open(_v,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Xt)||r.createObjectStore(Xt,{keyPath:"id"});};}),Ya=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await pn(),s=a.transaction([Xt],"readwrite").objectStore(Xt),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((i,l)=>{let d=s.put(n);d.onsuccess=()=>i(!0),d.onerror=()=>l(d.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var df=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await pn(),t=e.transaction([Xt],"readonly").objectStore(Xt);return new Promise((a,r)=>{let s=t.getAll();s.onsuccess=()=>{e.close();let n=s.result,i=new Map;n.forEach(l=>{i.set(l.id,{blob:l.blob,thumbnailDataUrl:l.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${i.size} video blobs from IndexedDB`),a(i);},s.onerror=()=>{e.close(),r(s.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Ml=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await pn(),a=o.transaction([Xt],"readwrite").objectStore(Xt);await new Promise((r,s)=>{let n=a.delete(e);n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},uf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await pn(),t=e.transaction([Xt],"readwrite").objectStore(Xt);await new Promise((a,r)=>{let s=t.clear();s.onsuccess=()=>a(!0),s.onerror=()=>r(s.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},cf=e=>URL.createObjectURL(e);var jv=be[" useId ".trim().toString()]||(()=>{}),Xv=0;function ff(e){let[o,t]=be.useState(jv());return Bo(()=>{t(a=>a??String(Xv++));},[e]),(o?`radix-${o}`:"")}function mf(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var Al="rovingFocusGroup.onEntryFocus",$v={bubbles:false,cancelable:true},Rr="RovingFocusGroup",[Pl,pf,Yv]=ln(Rr),[Jv,Dl]=Ca(Rr,[Yv]),[Zv,Qv]=Jv(Rr),hf=be.forwardRef((e,o)=>jsx(Pl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Pl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(ey,{...e,ref:o})})}));hf.displayName=Rr;var ey=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:s,currentTabStopId:n,defaultCurrentTabStopId:i,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:f=false,...u}=e,c=be.useRef(null),m=Pt(o,c),p=Oo(s),[v,h]=ea({prop:n,defaultProp:i??null,onChange:l,caller:Rr}),[b,x]=be.useState(false),g=mf(d),S=pf(t),k=be.useRef(false),[C,L]=be.useState(0);return be.useEffect(()=>{let y=c.current;if(y)return y.addEventListener(Al,g),()=>y.removeEventListener(Al,g)},[g]),jsx(Zv,{scope:t,orientation:a,dir:p,loop:r,currentTabStopId:v,onItemFocus:be.useCallback(y=>h(y),[h]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>L(y=>y+1),[]),onFocusableItemRemove:be.useCallback(()=>L(y=>y-1),[]),children:jsx(it.div,{tabIndex:b||C===0?-1:0,"data-orientation":a,...u,ref:m,style:{outline:"none",...e.style},onMouseDown:Ze(e.onMouseDown,()=>{k.current=true;}),onFocus:Ze(e.onFocus,y=>{let M=!k.current;if(y.target===y.currentTarget&&M&&!b){let O=new CustomEvent(Al,$v);if(y.currentTarget.dispatchEvent(O),!O.defaultPrevented){let D=S().filter(E=>E.focusable),q=D.find(E=>E.active),U=D.find(E=>E.id===v),W=[q,U,...D].filter(Boolean).map(E=>E.ref.current);bf(W,f);}}k.current=false;}),onBlur:Ze(e.onBlur,()=>x(false))})})}),gf="RovingFocusGroupItem",xf=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:s,children:n,...i}=e,l=ff(),d=s||l,f=Qv(gf,t),u=f.currentTabStopId===d,c=pf(t),{onFocusableItemAdd:m,onFocusableItemRemove:p,currentTabStopId:v}=f;return be.useEffect(()=>{if(a)return m(),()=>p()},[a,m,p]),jsx(Pl.ItemSlot,{scope:t,id:d,focusable:a,active:r,children:jsx(it.span,{tabIndex:u?0:-1,"data-orientation":f.orientation,...i,ref:o,onMouseDown:Ze(e.onMouseDown,h=>{a?f.onItemFocus(d):h.preventDefault();}),onFocus:Ze(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:Ze(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){f.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let b=oy(h,f.orientation,f.dir);if(b!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let g=c().filter(S=>S.focusable).map(S=>S.ref.current);if(b==="last")g.reverse();else if(b==="prev"||b==="next"){b==="prev"&&g.reverse();let S=g.indexOf(h.currentTarget);g=f.loop?ry(g,S+1):g.slice(S+1);}setTimeout(()=>bf(g));}}),children:typeof n=="function"?n({isCurrentTabStop:u,hasTabStop:v!=null}):n})})});xf.displayName=gf;var ty={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ay(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function oy(e,o,t){let a=ay(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return ty[a]}function bf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function ry(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var vf=hf,yf=xf;var Sf="Toggle",Rl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...s}=e,[n,i]=ea({prop:t,onChange:r,defaultProp:a??false,caller:Sf});return jsx(it.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...s,ref:o,onClick:Ze(e.onClick,()=>{e.disabled||i(!n);})})});Rl.displayName=Sf;var Ta="ToggleGroup",[If]=Ca(Ta,[Dl]),Cf=Dl(),El=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(iy,{...a,ref:o});if(t==="multiple")return jsx(ly,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Ta}\``)});El.displayName=Ta;var[kf,Mf]=If(Ta),iy=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=ea({prop:t,defaultProp:a??"",onChange:r,caller:Ta});return jsx(kf,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:i,onItemDeactivate:be__default.useCallback(()=>i(""),[i]),children:jsx(Tf,{...s,ref:o})})}),ly=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=ea({prop:t,defaultProp:a??[],onChange:r,caller:Ta}),l=be__default.useCallback(f=>i((u=[])=>[...u,f]),[i]),d=be__default.useCallback(f=>i((u=[])=>u.filter(c=>c!==f)),[i]);return jsx(kf,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:l,onItemDeactivate:d,children:jsx(Tf,{...s,ref:o})})});El.displayName=Ta;var[dy,uy]=If(Ta),Tf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:s,dir:n,loop:i=true,...l}=e,d=Cf(t),f=Oo(n),u={role:"group",dir:f,...l};return jsx(dy,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(vf,{asChild:true,...d,orientation:s,dir:f,loop:i,children:jsx(it.div,{...u,ref:o})}):jsx(it.div,{...u,ref:o})})}),hn="ToggleGroupItem",cy=be__default.forwardRef((e,o)=>{let t=Mf(hn,e.__scopeToggleGroup),a=uy(hn,e.__scopeToggleGroup),r=Cf(e.__scopeToggleGroup),s=t.value.includes(e.value),n=a.disabled||e.disabled,i={...e,pressed:s,disabled:n},l=be__default.useRef(null);return a.rovingFocus?jsx(yf,{asChild:true,...r,focusable:!n,active:s,ref:l,children:jsx(Lf,{...i,ref:o})}):jsx(Lf,{...i,ref:o})});cy.displayName=hn;var Lf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,s=Mf(hn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=s.type==="single"?n:void 0;return jsx(Rl,{...i,...r,ref:o,onPressedChange:l=>{l?s.onItemActivate(a):s.onItemDeactivate(a);}})}),Af=El;var py=be.createContext({size:"default",variant:"default",spacing:0});function Aa({className:e,variant:o,size:t,spacing:a=1,children:r,...s}){return jsx(Af,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Ma("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...s,children:jsx(py.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var gy={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Ff=createSlice({name:"toolbar",initialState:gy,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:Wt,setPenColor:Wo,setStrokeWidth:Er,setFontSize:HP,setFontFamily:UP,setFontStyle:WP,setFontWeight:zP,setTextDecoration:GP,setTextColor:KP}=Ff.actions,Bf=Ff.reducer;var Of=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,s]=useState(null),[n,i]=useState(0),[l,d]=useState(null),[f,u]=useState(false),c=useRef(null),m=useRef([]),p=useRef(null),v=useRef(null),h=useRef(null);useEffect(()=>((async()=>{try{let y=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});d(y),u(!0),h.current&&(h.current.srcObject=y);}catch(y){console.error("Error accessing camera:",y),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),l&&l.getTracks().forEach(y=>y.stop());}),[]);let b=()=>{l&&(l.getTracks().forEach(L=>L.stop()),d(null),u(false));},x=async()=>{try{let L=null,y=null;try{L=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(U){console.error("Error accessing camera for recording:",U),alert("Failed to access camera for recording.");return}try{y=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let M=[...L.getVideoTracks()];y&&M.push(...y.getAudioTracks());let O=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 q=new MediaRecorder(O,{mimeType:D,videoBitsPerSecond:25e5});c.current=q,m.current=[],q.ondataavailable=U=>{U.data.size>0&&m.current.push(U.data);},q.onstop=()=>{let U=new Blob(m.current,{type:D}),A=document.createElement("video");A.src=URL.createObjectURL(U),A.muted=!0,A.currentTime=.1,A.onseeked=()=>{let W=document.createElement("canvas");W.width=A.videoWidth,W.height=A.videoHeight;let E=W.getContext("2d");E&&(E.drawImage(A,0,0),v.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(A.src);},O.getTracks().forEach(W=>W.stop()),L&&L.getTracks().forEach(W=>W.stop()),y&&y.getTracks().forEach(W=>W.stop()),p.current&&clearInterval(p.current),s(U),b();},q.onerror=U=>{console.error("MediaRecorder error:",U);},q.start(1e3),a(!0),i(0),p.current=setInterval(()=>{i(U=>U+1);},1e3);}catch(L){console.error("Error starting camera recording:",L),alert("Failed to start recording. Please check permissions.");}},g=()=>{c.current&&t&&(c.current.state!=="inactive"&&(c.current.requestData(),setTimeout(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop();},100)),a(false));},S=()=>{if(r){let L=URL.createObjectURL(r),y=document.createElement("a");y.href=L,y.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(L);}},k=L=>{let y=Math.floor(L/60),M=L%60;return `${y.toString().padStart(2,"0")}:${M.toString().padStart(2,"0")}`},C=jsx("div",{className:"konva-editor-root",children:jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black/50 p-6",onMouseDown:L=>{L.target===L.currentTarget&&e(),L.stopPropagation();},onMouseUp:L=>L.stopPropagation(),onMouseMove:L=>L.stopPropagation(),onTouchStart:L=>L.stopPropagation(),onTouchMove:L=>L.stopPropagation(),onTouchEnd:L=>L.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:L=>L.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:h,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!t&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:x,disabled:!f,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!f&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),t&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:g,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(n)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",k(n)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{s(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick: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&&v.current&&(o(r,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(C,document.body)};var aa=40,Vf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[s,n]=useState(t?.order||"sequential"),[i,l]=useState(false),d=useRef(null),f=useRef(null);useEffect(()=>{let x=g=>{g.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let u=x=>{let g=x.target.files;if(!g||g.length===0)return;let S=aa-a.length;if(S<=0){alert(`You can only upload a maximum of ${aa} images`);return}let k=Array.from(g).slice(0,S);k.length<g.length&&alert(`Only ${S} more images can be added (max ${aa} total)`);let C=k.map(L=>new Promise((y,M)=>{let O=new FileReader;O.onload=D=>{D.target?.result?y(D.target.result):M(new Error("Failed to read file"));},O.onerror=M,O.readAsDataURL(L);}));Promise.all(C).then(L=>{r(y=>[...y,...L]),f.current&&(f.current.value="");});},c=x=>{x.preventDefault(),l(false);let g=Array.from(x.dataTransfer.files).filter(L=>L.type.startsWith("image/"));if(g.length===0)return;let S=aa-a.length;if(S<=0){alert(`You can only upload a maximum of ${aa} images`);return}let k=g.slice(0,S);k.length<g.length&&alert(`Only ${S} more images can be added (max ${aa} total)`);let C=k.map(L=>new Promise((y,M)=>{let O=new FileReader;O.onload=D=>{D.target?.result?y(D.target.result):M(new Error("Failed to read file"));},O.onerror=M,O.readAsDataURL(L);}));Promise.all(C).then(L=>{r(y=>[...y,...L]);});},m=x=>{x.preventDefault(),l(true);},p=()=>{l(false);},v=x=>{r(g=>g.filter((S,k)=>k!==x));},b=jsx("div",{className:"konva-editor-root",children:jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:d,className:"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:x=>{if(x.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,s,t?.id);},className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=aa?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",aa," images"]}):jsxs("span",{children:[a.length,"/",aa," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:u,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:c,onDragOver:m,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 ${i?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:i?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${s==="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 ${s==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${s==="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 ${s==="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,g)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${g+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(g),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:g+1})]},g))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})})});return createPortal(b,document.body)};var gn={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},Ry={enabled:true};function Nl(e){return e?{tools:{...gn.tools,...e.tools},actions:{...gn.actions,...e.actions}}:gn}var Ey={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Fy={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var lw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:r}={})=>{let s=xe(),n=Q(R=>R.canvas.slides.find(oe=>oe.id===R.canvas.currentSlideId)),i=n?.videos||[],l=n?.editingFlashcard,d=Q(R=>R.toolbar.selectedTool),f=Q(R=>R.toolbar.penColor),u=Q(R=>R.toolbar.strokeWidth),c=n?.showMcqForm,m=n?.showFlashcardForm,p=useRef(null),v=useMemo(()=>Nl(r),[r]),{tools:h,actions:b}=v,x=i.some(R=>R.isRecorded&&R.isPlaying),g=Q(R=>R.toolbar.fontSize),S=Q(R=>R.toolbar.fontFamily),k=Q(R=>R.toolbar.fontStyle),C=Q(R=>R.toolbar.fontWeight),L=Q(R=>R.toolbar.textDecoration),y=Q(R=>R.toolbar.textColor),[M,O]=useState(false),[D,q]=useState(false),[U,A]=useState(false),[W,E]=useState(false),[ne,N]=useState(false),[re,G]=useState(false),[V,_]=useState(false),H=useRef(null),K=useRef(null),te=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),Z=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),J=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],[]),le=useMemo(()=>te.filter(R=>{let oe=h[R.configKey];return typeof oe=="boolean"?oe:Array.isArray(oe)?oe.length>0:true}),[h,te]),Ie=useMemo(()=>{let R=h.shapes;return R===false?[]:R===true?Z:Array.isArray(R)?Z.filter(oe=>R.includes(oe.name)):Z},[h.shapes,Z]),Y=useMemo(()=>{let R=h.activities;return R===false?[]:R===true?J:Array.isArray(R)?J.filter(oe=>R.includes(oe.name)):J},[h.activities,J]),Me=useMemo(()=>{let R=h.media;return R===false?{photoFrame:false,image:false,video:false}:R===true?{photoFrame:true,image:true,video:true}:Array.isArray(R)?{photoFrame:R.includes("photo-frame"),image:R.includes("image"),video:R.includes("video")}:{photoFrame:true,image:true,video:true}},[h.media]),Be=useMemo(()=>{let R=h.activities;return R===false?false:R===true?true:Array.isArray(R)?R.includes("flashcard"):true},[h.activities]),Rt=R=>{let oe=R.target.files;!oe||oe.length===0||(s(Wt("select")),s(ct(false)),E(false),Array.from(oe).forEach(ye=>{let ge=new FileReader;ge.onload=se=>{let ue=new window.Image;ue.src=se.target?.result,ue.onload=()=>{let we=ue.width/ue.height,Ne=300,Et=300,dt=ue.width,Te=ue.height;dt>Ne&&(dt=Ne,Te=dt/we),Te>Et&&(Te=Et,dt=Te*we),s(ce());let Ue=960-dt/2,Yt=540-Te/2;s(Gn({id:v4(),src:ue.src,x:Ue,y:Yt,width:dt,height:Te,draggable:true,rotation:0}));};},ge.readAsDataURL(ye);}),R.target.value="");},ao=async R=>{let oe=R.target.files;if(!(!oe||oe.length===0)){console.log("files",R),s(Wt("select")),s(ct(false)),E(false);for(let ye of Array.from(oe))try{let ge=URL.createObjectURL(ye),se=document.createElement("video");console.log("video",se),se.src=ge,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((Ft,da)=>{let Ea=setTimeout(()=>da(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ea),Ft();},se.onerror=()=>{clearTimeout(Ea),da(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Ft,da)=>{let Ea=setTimeout(()=>da(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ea),Ft()):se.onloadeddata=()=>{clearTimeout(Ea),Ft();};});let ue=Math.min(.8,se.duration/2);console.log("Seeking to:",ue),se.currentTime=ue,await new Promise(Ft=>{let da=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ft();},5e3);se.onseeked=()=>{clearTimeout(da),console.log("Seek completed"),Ft();};});let we=document.createElement("canvas"),Ne=se.videoWidth/se.videoHeight,Et=400,dt=400,Te=se.videoWidth,Ue=se.videoHeight;Te>Et&&(Te=Et,Ue=Te/Ne),Ue>dt&&(Ue=dt,Te=Ue*Ne),we.width=Te,we.height=Ue;let Yt=we.getContext("2d",{willReadFrequently:!1});if(!Yt)throw new Error("Failed to get canvas context");if(await new Promise(Ft=>setTimeout(Ft,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Te,height:Ue}),Yt.drawImage(se,0,0,Te,Ue);let la=we.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",la.length),s(ce());let Ra=960-Te/2,Pn=540-Ue/2,Wr=v4();await Ya(Wr,ye,la),s(Zr({id:Wr,objectUrl:ge,thumbnailDataUrl:la,videoBlob:ye,x:Ra,y:Pn,width:Te,height:Ue,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${ye.name}`);}catch(ge){console.error("Error processing video:",ge),alert(`Failed to process video: ${ye.name}`);}R.target.value="";}},qr=(R,oe,ye)=>{s(ce()),s(Wt("select")),s(ct(false));let ge=300,se=300,ue=960-ge/2,we=540-se/2;s(ye?uo({id:ye,images:R,order:oe,x:ue,y:we,width:ge,height:se,rotation:0,draggable:true}):jn({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:R,currentIndex:0,order:oe,x:ue,y:we,width:ge,height:se,rotation:0,draggable:true})),s(Ba(false));},Hr=()=>{s(ce()),s(Wt("select")),s(ct(false));let R=400,oe=300,ye=800-R/2,ge=450-oe/2;if(t?.current){let se=t.current,ue=se.scaleX()||1,we=se.scaleY()||1,Ne=se.width()/ue,Et=se.height()/we;ye=Ne/2-R/2,ge=Et/2-oe/2;}s(Yn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ye,y:ge,width:R,height:oe,rotation:0,draggable:true,isCapturing:false})),N(false);},Ln=R=>{let ue={};switch(R.name){case "circle":case "ring":case "wedge":case "arc":ue.radius=50,(R.name==="ring"||R.name==="arc")&&(ue.innerRadius=25,ue.outerRadius=50),(R.name==="wedge"||R.name==="arc")&&(ue.angle=R.name==="wedge"?60:90);break;case "ellipse":ue.radiusX=60,ue.radiusY=40;break;case "triangle":ue.radius=50,ue.sides=3;break;case "polygon":ue.radius=50,ue.sides=6;break;case "star":ue.innerRadius=25,ue.outerRadius=50,ue.numPoints=5;break;case "arrow":case "line":ue.points=[0,0,100,0],R.name==="arrow"&&(ue.pointerLength=10,ue.pointerWidth=10);break}let we={id:`shape-${Date.now()}`,type:R.name,x:910,y:490,width:100,height:100,rotation:0,color:f,...ue};s(ce()),s(ct(false)),s(Wt(R.name)),s(Kn(we));},oo=R=>{if(s(Wt(R)),R==="select")s(ct(false));else if(R==="text"){s(ct(false)),s(ce());let oe=200,ye=50,ge=960-oe/2,se=540-ye/2,we=window.innerWidth<768?Math.max(g,32):g,Ne=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;s(_n({id:Ne,text:"",x:ge,y:se,width:oe,height:ye,rotation:0,draggable:true,fontSize:we,fontFamily:S,fontStyle:k,fontWeight:C,textDecoration:L,fill:y,align:"left"})),setTimeout(()=>{s(Qo(Ne));},100),a&&a(Ne);}else s(ct(true));},In=()=>{s(fi()),s(Wt("select")),s(ct(false));},Cn=()=>{o?o():t?O(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},kn=()=>{q(true);},ia=async(R,oe)=>{try{s(Wt("select")),s(ct(!1));let ye=URL.createObjectURL(R),ge=document.createElement("video");ge.src=ye,ge.muted=!0,ge.playsInline=!0,ge.preload="auto",await new Promise((Ue,Yt)=>{let la=setTimeout(()=>Yt(new Error("Metadata load timeout")),1e4);ge.onloadedmetadata=()=>{clearTimeout(la),Ue();},ge.onerror=()=>{clearTimeout(la),Yt(new Error("Failed to load video"));};});let se=640,ue=ge.videoWidth/ge.videoHeight,we=se,Ne=we/ue;s(ce());let Et=960-we/2,dt=540-Ne/2,Te=v4();await Ya(Te,R,oe),s(Zr({id:Te,objectUrl:ye,thumbnailDataUrl:oe,videoBlob:R,x:Et,y:dt,width:we,height:Ne,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),O(!1),q(!1);}catch(ye){console.error("Error adding recorded video to canvas:",ye),alert("Failed to add video to canvas. Please try again.");}},Mn=R=>{s(Wt("select")),s(ct(false)),s(Jo(null)),R&&s(ni(R)),s(ma(!c));},Tn=()=>{s(jo(null)),s(Ba(true)),N(false);},ro=()=>{A(!U);},Ur=()=>{E(!W);},An=()=>{N(!ne);};return useEffect(()=>{if(!V)return;let R=oe=>{p.current&&!p.current.contains(oe.target)&&_(false);};return document.addEventListener("mousedown",R),()=>{document.removeEventListener("mousedown",R);}},[V]),x?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Aa,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:le.map((R,oe)=>jsx("div",{title:R.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 ${R.name===d?"bg-primary/10":""}`,onClick:()=>{if(R.name==="image"){Ur(),A(false),N(false),oo(R.name);return}else if(R.name==="shapes"){ro(),E(false),N(false),oo(R.name);return}else if(R.name==="activities"){oo(R.name),An(),A(false),E(false);return}oo(R.name),A(false),E(false),N(false);},children:jsx(R.icon,{weight:"fill",className:"text-primary text-xl"})},oe))}),U&&jsx(Aa,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:Ie.map((R,oe)=>jsx("div",{title:R.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Ln(R),children:jsx(R.icon,{weight:"fill",className:"text-primary text-xl"})},oe))}),W&&jsxs(Aa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Me.photoFrame&&jsx("div",{title:"Photo frame",onClick:Hr,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Me.image&&jsx("div",{title:"Image",onClick:()=>H.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Me.video&&jsx("div",{title:"Video",onClick:()=>K.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),ne&&jsxs(Aa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Be&&jsx("div",{title:"Flashcard",onClick:()=>Tn(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),Y.map((R,oe)=>jsx("div",{title:R.label,onClick:()=>Mn(R.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(R.icon,{weight:"fill",className:"text-primary text-xl"})},oe))]})]}),(b.undo||b.redo||b.screenRecord||b.cameraRecord||b.clear)&&jsxs(Aa,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[b.undo&&jsx("button",{value:"undo",onClick:()=>s(mi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl"})}),b.redo&&jsx("button",{value:"redo",onClick:()=>s(pi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl"})}),b.screenRecord&&jsx("button",{value:"screen-record",onClick:Cn,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6279F8] md:block",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl"})}),jsx("button",{title:"Pen Color",onClick:()=>G(true),className:"relative mx-4 my-2 flex cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-white text-xl md:hidden",style:{borderColor:f},children:jsx("div",{className:"h-5 w-5 rounded-full border-2 border-white shadow-sm",style:{backgroundColor:f}})}),jsxs("div",{ref:p,className:"relative md:hidden",children:[jsx("button",{title:"Pen Size",onClick:()=>_(!V),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${V?"bg-primary/10":""}`,children:jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border-2 border-[#FFFFFF80] bg-[#000000CC]",children:jsx("span",{className:"text-xs font-semibold text-white",children:u})})}),V&&jsxs("div",{className:"absolute top-1/2 left-full z-50 ml-2 w-48 -translate-y-1/2 rounded-lg border bg-white p-4 shadow-xl",children:[jsx("p",{className:"mb-3 text-xs font-semibold text-black/40",children:"PEN SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 shrink-0 rounded-full bg-black"}),jsx(mn,{defaultValue:[12],max:28,min:6,step:1,className:"w-full",value:[u],rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:R=>s(Er(R[0]))}),jsx("div",{className:"h-5 w-5 shrink-0 rounded-full bg-black"})]})]})]}),b.cameraRecord&&jsx("button",{value:"camera-record",onClick:kn,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6BBB93] md:block",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl"})}),b.clear&&jsx("button",{value:"clear",onClick:()=>In(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl"})})]})]}),jsx("input",{ref:H,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:Rt}),jsx("input",{ref:K,type:"file",accept:"video/*",className:"hidden",onChange:ao}),!o&&M&&t&&jsx(lr,{onClose:()=>O(false),stageRef:t,onRecordingComplete:ia}),D&&jsx(Of,{onClose:()=>q(false),onRecordingComplete:ia}),m&&jsx(Vf,{editingFlashcard:l,onConfirm:qr,onCancel:()=>s(Ba(false))}),re&&jsx(Es,{defaultColor:f,onConfirm:R=>{s(Wo(R)),G(false);},onCancel:()=>G(false)})]})},dw=lw;var Wl=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let r=ut(fo),s=ut(bi),n=a?s:r,i=ut(er),f=(ut(x=>x.canvas.slides.find(g=>g.id===x.canvas.currentSlideId))?.videos||[]).some(x=>x.isRecorded&&x.isPlaying),[u,c]=useState(false),[m,p]=useState(null),[v,h]=useState(null),b=async()=>{if(r.length===0){h({type:"error",message:"No slides to publish"});return}if(!e){h({type:"error",message:"No publish handler provided"});return}c(true),h(null);try{let x=await e(n,i,g=>{p(g);});x.success?h({type:"success",message:x.message}):h({type:"error",message:x.message});}catch(x){h({type:"error",message:x instanceof Error?x.message:"An unexpected error occurred"});}finally{c(false),setTimeout(()=>{p(null),h(null);},3e3);}};return f?null:jsxs("button",{onClick:b,disabled:u||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 pw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:r,onDescriptionChange:s,showPublishButton:n=true,showBackButton:i=true,editableTitle:l=true,editableDescription:d=true,className:f="",rightContent:u,leftContent:c,includeInactiveSlides:m=false})=>{let p=at(),v=ut(er),h=ut(yi),b=e??(h?v.title:"")??"Untitled",x=o??(h?v.description:"")??"Add a description...",[g,S]=useState(false),[k,C]=useState(false),[L,y]=useState(b),[M,O]=useState(x),D=useRef(null),q=useRef(null);useEffect(()=>{y(b);},[b]),useEffect(()=>{O(x);},[x]),useEffect(()=>{g&&D.current&&(D.current.focus(),D.current.select());},[g]),useEffect(()=>{k&&q.current&&(q.current.focus(),q.current.select());},[k]);let U=()=>{l&&S(true);},A=()=>{d&&C(true);},W=()=>{S(false),L.trim()&&L!==b?r?r(L.trim()):p(hi(L.trim())):L.trim()||y(b);},E=()=>{C(false),M.trim()&&M!==x?s?s(M.trim()):p(gi(M.trim())):M.trim()||O(x);},ne=re=>{re.key==="Enter"?W():re.key==="Escape"&&(y(b),S(false));},N=re=>{re.key==="Enter"?E():re.key==="Escape"&&(O(x),C(false));};return jsxs("div",{className:`fixed top-0 left-0 z-100 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${f}`,children:[c||jsxs("div",{className:"flex items-center gap-6",children:[i&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[g?jsx("input",{ref:D,type:"text",value:L,onChange:re=>y(re.target.value),onBlur:W,onKeyDown:ne,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:U,title:L,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${l?"hover:border-primary cursor-text":""}`,children:L}),k?jsx("input",{ref:q,type:"text",value:M,onChange:re=>O(re.target.value),onBlur:E,onKeyDown:N,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:A,title:M,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${d?"hover:border-primary cursor-text":""}`,children:M})]})]}),u||n&&a&&jsx(Wl,{onPublish:a,includeInactiveSlides:m})]})};var yw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],ww=({colors:e=yw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let[s,n]=useState(true),i=Q(he),l=Q(c=>c.toolbar.penColor),d=Q(c=>c.toolbar.strokeWidth),f=i?.backgroundColor,u=xe();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:s?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:`absolute bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:px-8 2xl:py-6 ${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-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(mn,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[d],onValueChange:c=>u(Er(c[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"COLOR"}),jsxs(Aa,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(c=>jsx("button",{value:c.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${l===c.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:c.value},onClick:()=>u(Wo(c.value))},c.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>u(Wo(c.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-xs font-semibold whitespace-nowrap text-[#00000066] 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] lg:h-12 lg:w-12",style:{backgroundColor:f},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>u(Wn(c.target.value))})})]})}),jsx("div",{className:"absolute -top-4 left-1/2 flex flex-col items-center justify-between px-2",children:jsx("button",{onClick:()=>n(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{size:20,weight:"bold",className:"text-gray-600"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>n(true),className:"absolute bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};function Sw({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var Wf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Iw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),Gl=e=>{let o=Iw(e);return o.charAt(0).toUpperCase()+o.slice(1)},yn=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),zf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Gf={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var _f=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:s,iconNode:n,...i},l)=>createElement("svg",{ref:l,...Gf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:yn("lucide",r),...!s&&!zf(i)&&{"aria-hidden":"true"},...i},[...n.map(([d,f])=>createElement(d,f)),...Array.isArray(s)?s:[s]]));var wn=(e,o)=>{let t=forwardRef(({className:a,...r},s)=>createElement(_f,{ref:s,iconNode:o,className:yn(`lucide-${Wf(Gl(e))}`,`lucide-${e}`,a),...r}));return t.displayName=Gl(e),t};var Tw=[["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"}]],Or=wn("copy",Tw);var Aw=[["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"}]],Nr=wn("trash-2",Aw);var Xf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:s,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick: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:i=>{i.stopPropagation(),s();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Or,{size:14})}),!a&&jsx("button",{onClick:i=>{i.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Nr,{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 Ew=({softDelete:e=false})=>{let o=at(),t=ut(fo),a=ut(co),r=ut(vi),[s,n]=useState(true),d=(ut(p=>p.canvas.slides.find(v=>v.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),f=()=>{r&&o(Nn());},u=p=>{o(Hn(p));},c=p=>{o(qn(p));},m=p=>{t.length>1&&o(Vn({id:p,softDelete:e}));};return d?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-100 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:s?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((p,v)=>jsx(Xf,{slide:p,index:v,isSelected:p.id===a,isSingleSlide:t.length===1,onSelect:()=>u(p.id),onDuplicate:()=>c(p.id),onDelete:()=>m(p.id)},p.id))}),jsxs("button",{onClick:f,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:!s&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var Fw="SchooplaEditorDB",Bw=1,Pa="slides",Da="metadata",Kl="schoopla_current_slide_id",Jf="presentation_metadata",Vr=()=>new Promise((e,o)=>{let t=indexedDB.open(Fw,Bw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Pa)||r.createObjectStore(Pa,{keyPath:"id"}),r.objectStoreNames.contains(Da)||r.createObjectStore(Da,{keyPath:"id"});};}),_l=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Vr(),a=o.transaction([Pa],"readwrite").objectStore(Pa);await new Promise((r,s)=>{let n=a.clear();n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);});for(let r of e)await new Promise((s,n)=>{let i=a.add(r);i.onsuccess=()=>s(!0),i.onerror=()=>n(i.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},jl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Vr(),t=e.transaction([Pa],"readonly").objectStore(Pa);return new Promise((a,r)=>{let s=t.getAll();s.onsuccess=()=>{e.close();let n=s.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(i=>({id:i.id,width:i.width,height:i.height,x:i.x,y:i.y}))),a(n.length>0?n:null);},s.onerror=()=>{e.close(),r(s.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Sn=async()=>{try{let e=await Vr(),o=e.transaction([Pa,Da],"readwrite"),t=o.objectStore(Pa),a=o.objectStore(Da);await new Promise((r,s)=>{let n=t.clear();n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);}),await new Promise((r,s)=>{let n=a.clear();n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(Kl),localStorage.removeItem("schoopla_presentation_metadata"),await uf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Xl=e=>{try{localStorage.setItem(Kl,e);}catch(o){console.error("Error saving current slide ID:",o);}},$l=()=>{try{return localStorage.getItem(Kl)}catch(e){return console.error("Error loading current slide ID:",e),null}},Yl=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Jl=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await Vr(),a=o.transaction([Da],"readwrite").objectStore(Da);await new Promise((r,s)=>{let n=a.put({id:Jf,...e});n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Zl=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await Vr(),t=e.transaction([Da],"readonly").objectStore(Da);return new Promise((a,r)=>{let s=t.get(Jf);s.onsuccess=()=>{e.close();let n=s.result;if(n){let{id:i,...l}=n;console.log("\u2705 Loaded presentation metadata:",l),a(l);}else console.log("No presentation metadata found"),a(null);},s.onerror=()=>{e.close(),r(s.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 Ow=["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"],Nw=["canvas/clearCanvas"],Vw=["canvas/setPresentationTitle","canvas/setPresentationDescription"],qw=Yl((e,o)=>{_l(e),Xl(o);},500),Hw=Yl(e=>{Jl(e);},500),Uw=(e,o)=>{_l(e),Xl(o);},Ql=false,Zf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Ml(r).catch(s=>{console.error("Error deleting video blob:",s);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,n=e.getState().canvas.slides.find(i=>i.id===r);n&&n.videos&&n.videos.length>0&&n.videos.forEach(i=>{Ml(i.id).catch(l=>{console.error("Error deleting video blob:",l);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,s=e.getState(),i=s.canvas.slides.find(l=>l.id===s.canvas.currentSlideId)?.videos.find(l=>l.id===r);i&&i.videoBlob&&setTimeout(()=>{let l=e.getState(),f=l.canvas.slides.find(u=>u.id===l.canvas.currentSlideId)?.videos.find(u=>u.id!==r&&u.x===i.x+20&&u.y===i.y+20);f&&i.videoBlob&&Ya(f.id,i.videoBlob,f.thumbnailDataUrl).catch(u=>{console.error("Error saving duplicated video blob:",u);});},0);}let a=o(t);if(t.type&&Nw.includes(t.type)){if(!Ql){Ql=true;try{let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;Uw(s,n);}finally{setTimeout(()=>{Ql=false;},0);}}}else if(t.type&&Ow.includes(t.type)){let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;qw(s,n);}else if(t.type&&Vw.includes(t.type)){let r=e.getState(),{presentationMetadata:s}=r.canvas;Hw(s);}return a});new QueryClient;var Gw=configureStore({reducer:{toolbar:Bf,canvas:gd},middleware:e=>e({serializableCheck:false}).concat(Zf)});var Kw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:s=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:n,quality:a,pixelRatio:r}),l=document.createElement("a");l.download=`${s}.${t}`,l.href=i,document.body.appendChild(l),l.click(),document.body.removeChild(l);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},_w=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((s,n)=>{try{let i=t==="png"?"image/png":"image/jpeg",l=e.toDataURL({mimeType:i,quality:a,pixelRatio:r});fetch(l).then(d=>d.blob()).then(d=>s(d)).catch(d=>n(d));}catch(i){n(i);}})},jw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,s=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:s,quality:a,pixelRatio:r})};var Xw=(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 s=a*a+r*r,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/s)),i=o.x+n*a,l=o.y+n*r;return Math.sqrt(Math.pow(e.x-i,2)+Math.pow(e.y-l,2))},ed=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],s=e[e.length-1];for(let n=1;n<e.length-1;n++){let i=Xw(e[n],r,s);i>t&&(t=i,a=n);}if(t>o){let n=ed(e.slice(0,a+1),o),i=ed(e.slice(a),o);return [...n.slice(0,-1),...i]}return [r,s]},$w=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},Yw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Qf=(e,o=1.5)=>{if(e.length<=4)return e;let t=$w(e),a=ed(t,o);return Yw(a)},em=(e,o=1.5)=>({...e,points:Qf(e.points,o)}),Jw=(e,o=1.5)=>e.map(t=>em(t,o)),Zw=(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 Qw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var tm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((s,n)=>{let i=new Image;i.onload=()=>{let{width:l,height:d}=i;if(l>t||d>a){let p=l/d;l>d?(l=Math.min(l,t),d=l/p):(d=Math.min(d,a),l=d*p);}let f=document.createElement("canvas");f.width=l,f.height=d;let u=f.getContext("2d");if(!u){n(new Error("Failed to get canvas context"));return}u.drawImage(i,0,0,l,d);let c=Qw(e),m=f.toDataURL(c,r);s(m);},i.onerror=n,i.src=e;})};var to=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},zo=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Go=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",eS=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:s=.85}=o,n=[],i=0;for(let l of e){let d=[],f=[],u=[];for(let c of l.images){let m=c.src;if(t&&m.startsWith("data:"))try{m=await tm(m,{maxWidth:a,maxHeight:r,quality:s});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(m.startsWith("data:")){let p=to(m),v=zo(m);i+=p.byteLength;let h={id:c.id,x:c.x,y:c.y,width:c.width,height:c.height,draggable:c.draggable,rotation:c.rotation,locked:c.locked,link:c.link,altText:c.altText,zIndex:c.zIndex,buffer:p,mimeType:v};if(c.audioData&&c.audioData.startsWith("data:")){let b=to(c.audioData),x=zo(c.audioData);i+=b.byteLength,h.audioBuffer=b,h.audioMimeType=x;}d.push(h);}}for(let c of l.videos){let m,p;if(c.videoBlob)m=await c.videoBlob.arrayBuffer(),p=c.videoBlob.type;else if(c.videoData&&c.videoData.startsWith("data:"))m=to(c.videoData),p=zo(c.videoData);else {console.warn(`Video ${c.id} has no blob or videoData, skipping`);continue}i+=m.byteLength;let v={id:c.id,thumbnailDataUrl:c.thumbnailDataUrl,x:c.x,y:c.y,width:c.width,height:c.height,draggable:c.draggable,isPlaying:c.isPlaying,rotation:c.rotation,locked:c.locked,link:c.link,altText:c.altText,zIndex:c.zIndex,isRecorded:c.isRecorded,buffer:m,mimeType:p};if(c.audioData&&c.audioData.startsWith("data:")){let h=to(c.audioData),b=zo(c.audioData);i+=h.byteLength,v.audioBuffer=h,v.audioMimeType=b;}f.push(v);}for(let c of l.photoFrames){let m={id:c.id,x:c.x,y:c.y,width:c.width,height:c.height,rotation:c.rotation,draggable:c.draggable,locked:c.locked,link:c.link,altText:c.altText,zIndex:c.zIndex,isCapturing:c.isCapturing};if(c.capturedImageUrl&&c.capturedImageUrl.startsWith("data:")){let p=to(c.capturedImageUrl),v=zo(c.capturedImageUrl);i+=p.byteLength,m.buffer=p,m.mimeType=v;}if(c.audioData&&c.audioData.startsWith("data:")){let p=to(c.audioData),v=zo(c.audioData);i+=p.byteLength,m.audioBuffer=p,m.audioMimeType=v;}u.push(m);}n.push({...l,images:d,videos:f,photoFrames:u});}return {slides:n,totalSize:i}},tS=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},aS=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((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,draggable:s.draggable,rotation:s.rotation,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,mimeType:s.mimeType,fileKey:`slide_${r}_image_${n}`,audioFileKey:s.audioBuffer?`slide_${r}_image_${n}_audio`:void 0,audioMimeType:s.audioMimeType})),videos:a.videos.map((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,draggable:s.draggable,isPlaying:s.isPlaying,rotation:s.rotation,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,isRecorded:s.isRecorded,mimeType:s.mimeType,fileKey:`slide_${r}_video_${n}`,thumbnailFileKey:`slide_${r}_video_${n}_thumbnail`,audioFileKey:s.audioBuffer?`slide_${r}_video_${n}_audio`:void 0,audioMimeType:s.audioMimeType})),photoFrames:a.photoFrames.map((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,rotation:s.rotation,draggable:s.draggable,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,isCapturing:s.isCapturing,mimeType:s.mimeType,fileKey:s.buffer?`slide_${r}_photoframe_${n}`:void 0,audioFileKey:s.audioBuffer?`slide_${r}_photoframe_${n}_audio`:void 0,audioMimeType:s.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((s,n)=>{let i=new Blob([s.buffer],{type:s.mimeType}),l=`${s.id}.${Go(s.mimeType)}`;if(o.append(`slide_${r}_image_${n}`,i,l),s.audioBuffer&&s.audioMimeType){let d=new Blob([s.audioBuffer],{type:s.audioMimeType}),f=`${s.id}_audio.${Go(s.audioMimeType)}`;o.append(`slide_${r}_image_${n}_audio`,d,f);}}),a.videos.forEach((s,n)=>{let i=new Blob([s.buffer],{type:s.mimeType}),l=`${s.id}.${Go(s.mimeType)}`;if(o.append(`slide_${r}_video_${n}`,i,l),s.thumbnailDataUrl&&s.thumbnailDataUrl.startsWith("data:")){let d=to(s.thumbnailDataUrl),f=new Blob([d],{type:"image/jpeg"}),u=`${s.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${n}_thumbnail`,f,u);}if(s.audioBuffer&&s.audioMimeType){let d=new Blob([s.audioBuffer],{type:s.audioMimeType}),f=`${s.id}_audio.${Go(s.audioMimeType)}`;o.append(`slide_${r}_video_${n}_audio`,d,f);}}),a.photoFrames.forEach((s,n)=>{if(s.buffer&&s.mimeType){let i=new Blob([s.buffer],{type:s.mimeType}),l=`${s.id}.${Go(s.mimeType)}`;o.append(`slide_${r}_photoframe_${n}`,i,l);}if(s.audioBuffer&&s.audioMimeType){let i=new Blob([s.audioBuffer],{type:s.audioMimeType}),l=`${s.id}_audio.${Go(s.audioMimeType)}`;o.append(`slide_${r}_photoframe_${n}_audio`,i,l);}});}),o};var sS=()=>{let e=at(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let r=await jl(),s=$l(),n=await Zl();if(r&&r.length>0){let i=await df(),l=r.map(f=>{if(f.videos&&f.videos.length>0){let u=f.videos.map(c=>{let m=i.get(c.id);if(m){let p=cf(m.blob);return {...c,objectUrl:p,thumbnailDataUrl:m.thumbnailDataUrl,videoBlob:m.blob}}else return c});return {...f,videos:u}}return f}),d=s&&l.find(f=>f.id===s)?s:l[0].id;e(no({slides:l,currentSlideId:d}));}e(n?xi({title:n.title,description:n.description}):Cs(!0));}catch(r){console.error("Error loading persisted slides:",r),e(Cs(true));}finally{t(false);}})();},[e]),{isLoading:o}};var om=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||""})),rm=new WeakSet,sm=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 Ya(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},nS=()=>{let e=at(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||rm.has(a))return;rm.add(a);let{slides:r,currentSlideId:s,skipLocalPersistence:n=true}=a;if(n)try{await Sn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let i=s&&r.find(d=>d.id===s)?s:r[0].id,l=om(r);e(no({slides:l,currentSlideId:i})),await sm(l);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:s,skipLocalPersistence:n=true}=a;if(n)try{await Sn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let i=s&&r.find(d=>d.id===s)?s:r[0].id,l=om(r);e(no({slides:l,currentSlideId:i})),await sm(l);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
|
|
6
|
+
This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:f?"none":"auto"}})}),jsx(Group,{y:C+S+D+k+v+B,children:f&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),x();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),x();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});xl.displayName="LongAnswer";var fc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(xl,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:l=>r(l,n.id)},n.id))});var ja=1600,Xa=900,gc=3200,xc=1800,Mb=.4,Tb=1.5,Ab=e=>{let o=0,t=0,a=ja,s=Xa;if(!e)return {minX:o,minY:t,maxX:a,maxY:s,width:ja,height:Xa};let r=(d,u,m,f)=>{o=Math.min(o,d),t=Math.min(t,u),a=Math.max(a,d+m),s=Math.max(s,u+f);};e.lines?.forEach(d=>{if(d.points&&d.points.length>=2){let u=d.x||0,m=d.y||0,f=d.scaleX||1,i=d.scaleY||1;for(let c=0;c<d.points.length;c+=2){let p=u+d.points[c]*f,y=m+d.points[c+1]*i;o=Math.min(o,p),t=Math.min(t,y),a=Math.max(a,p),s=Math.max(s,y);}}}),e.images?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.videos?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.shapes?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.texts?.forEach(d=>r(d.x,d.y,d.width||200,d.height||d.fontSize||24)),e.flashcards?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.photoFrames?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.multipleChoices?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.trueFalses?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.shortAnswers?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.LongAnswer?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.fillInTheBlanks?.forEach(d=>r(d.x,d.y,d.width,d.height));let n=Math.min(a-o,gc),l=Math.min(s-t,xc);return o=Math.max(o,a-gc),t=Math.max(t,s-xc),{minX:o,minY:t,maxX:a,maxY:s,width:n,height:l}},Pb=(e,o,t={minX:0,minY:0,maxX:ja,maxY:Xa,width:ja,height:Xa})=>{let a=Math.max(t.width,ja),s=Math.max(t.height,Xa),r=e/o,n=a/s,l,d,u,f=0;if(r>n){d=s,l=Math.round(d*r),u=o/d;}else {l=a,d=Math.round(l/r),u=e/l;let i=s*u;f=(o-i)/2;}return u=Math.max(Mb,Math.min(Tb,u)),{scale:u,scaleX:u,scaleY:u,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:l,baseHeight:d,contentOffsetX:t.minX,contentOffsetY:t.minY}},bc=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},Db=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:s={enabled:true}}={})=>{let r=at(),n=Q(w=>w.toolbar.selectedTool),l=Q(he),d=Q(fo),u=l?.editingActivity,m=l?.showMcqForm,f=l?.lines||[],i=useRef(null),c=useRef(null),[p,y]=useState(null),[h,x]=useState(""),b=useRef(null),[g,L]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:ja,stageHeight:Xa,offsetX:0,offsetY:0,baseWidth:ja,baseHeight:Xa,contentOffsetX:0,contentOffsetY:0}),C=useMemo(()=>Ab(l||null),[d]),[S,k]=useState(null),[v,M]=useState(null),[B,D]=useState(null),[O,W]=useState(null),[T,U]=useState(null),[R,oe]=useState(null),[V,se]=useState(null),[G,q]=useState(false),[_,H]=useState(null),[K,te]=useState(false),Z=useRef(null),J=useRef(null),le=useRef(null),{debouncedGenerateThumbnail:Ie}=jd(d,i);useEffect(()=>{let w=()=>{if(c.current){let P=c.current.getBoundingClientRect(),F=Pb(P.width,P.height,C);L(F);}};w();let I=new ResizeObserver(w);return c.current&&I.observe(c.current),window.addEventListener("resize",w),()=>{I.disconnect(),window.removeEventListener("resize",w);}},[C]),useEffect(()=>{if(i.current){let w=i.current.container();w&&(w.style.cursor="");}},[n]);let Y=useCallback(()=>{i.current&&requestAnimationFrame(()=>{if(!i.current)return;i.current.getLayers().forEach(F=>F.batchDraw());let I=1/6,P=i.current.toDataURL({pixelRatio:I});x(P),Ie();});},[Ie]),Me=useRef(d);useEffect(()=>{Me.current!==d&&(Me.current=d,Y());},[d,Y]);let Be=useRef(null),Et=useRef(true);useEffect(()=>{if(!l)return;let w=(l.lines?.length||0)+(l.images?.length||0)+(l.videos?.length||0)+(l.shapes?.length||0)+(l.texts?.length||0)+(l.flashcards?.length||0)+(l.photoFrames?.length||0)+(l.multipleChoices?.length||0)+(l.trueFalses?.length||0)+(l.shortAnswers?.length||0)+(l.LongAnswer?.length||0)+(l.fillInTheBlanks?.length||0),I=Be.current?.count!==w;!Et.current&&I&&setTimeout(()=>{Y();},100),Be.current={slideId:d,count:w},Et.current=false;},[l,d,Y]),useEffect(()=>{i.current&&e&&e(i);},[e]),useEffect(()=>{le.current&&a&&a(le);},[a]);let{startDrawing:oo,draw:Hr,stopDrawing:Ur,setCanvasRef:In,tool:ro,color:Cn,strokeWidth:kn,isSketchMode:Mn}=yd(Y),ia=useRef(new Map),{images:Tn,getLoadedImage:An,imageRefs:so,handleDragEnd:Wr,handleImageTransformEnd:Pn}=Md(Y),{videos:E,videoRefs:re,handleVideoClick:ye,handleVideoDragEnd:ge,handleVideoTransformEnd:ne}=Pd(Y),{multipleChoice:ue,handleMcqTransform:we,mcqRefs:Ne,handleDragEnd:Ft}=Td(Y),{trueFalse:ut,handleTrueFalseTransform:Te,trueFalseRefs:Ue,handleTrueFalseDragEnd:Jt}=Ad(Y),{shortAnswers:la,saRefs:Ea,handleShortAnswerDragEnd:Dn}=Od(Y),{longAnswers:zr,handleLongAnswerDragEnd:Bt}=Nd(Y),{fillInTheBlanks:da,handleFillInTheBlanksDragEnd:Fa,fibRefs:Gr}=sc(Y),{transformerRef:fe,boundBoxFunc:yt}=zd(),{shapes:um,shapeRefs:Kr,isDragging:od,handleShapeDragEnd:cm,handleShapeResizeEnd:fm}=Ed(Y),{texts:_o,textRefs:ua,handleDragEnd:mm,handleTransformEnd:pm,handleDoubleClick:hm,startEditing:_r,editingTextId:pe,editingValue:rd,handleEditingChange:sd,finishEditing:Rn}=Bd(Y,Z);useEffect(()=>{t&&t(_r);},[t,_r]);let jr=Q(w=>w.canvas.editingTextId);useEffect(()=>{jr&&jr!==pe&&_r(jr);},[jr,pe,_r]);let{flashcards:gm,flashcardRefs:Xr,handleDragEnd:xm,handleFlashcardTransformEnd:bm,handleNext:vm,handlePrevious:ym}=qd(Y),{photoFrames:nd,photoFrameRefs:$r,handleDragEnd:wm,handlePhotoFrameTransformEnd:Lm,startCamera:Sm,capturePhoto:Im,cameraStreams:Cm}=Wd(Y);useEffect(()=>{if(fe.current){if(pe){fe.current.nodes([]),fe.current.getLayer()?.batchDraw();return}if(p&&!E.find(P=>P.id===p)?.isPlaying){let P=ia.current.get(p)||so.current.get(p)||re.current.get(p)||Kr.current.get(p)||ua.current.get(p)||Ne.current.get(p)||Xr.current.get(p)||$r.current.get(p)||Ea.current.get(p)||Ue.current.get(p)||Gr.current.get(p);if(P){let F=P.attrs?.locked;if(P.visible()&&F!==true){fe.current.nodes([P]),fe.current.getLayer()?.batchDraw();return}}}fe.current.nodes([]),fe.current.getLayer()?.batchDraw();}},[p,pe,E,ia,so,re,Kr,ua,Xr,$r,nd,Ne,Ue,Gr,fe]);let Ge=useCallback(w=>{y(w),o?.(w);},[o]),no=useCallback(()=>{y(null),o?.(null),fe.current&&(fe.current.nodes([]),fe.current.getLayer()?.batchDraw());},[fe,o]),id=useCallback(w=>l?l.lines?.some(I=>I.id===w)?"line":l.images?.some(I=>I.id===w)?"image":l.videos?.some(I=>I.id===w)?"video":l.shapes?.some(I=>I.id===w)?"shape":l.texts?.some(I=>I.id===w)?"text":l.flashcards?.some(I=>I.id===w)?"flashcard":l.photoFrames?.some(I=>I.id===w)?"photoFrame":l.multipleChoices?.some(I=>I.id===w)?"mcq":l.trueFalses?.some(I=>I.id===w)?"trueFalse":l.shortAnswers?.some(I=>I.id===w)?"shortAnswer":l.LongAnswer?.some(I=>I.id===w)?"longAnswer":l.fillInTheBlanks?.some(I=>I.id===w)?"fillInTheBlanks":null:null,[l]),ld=useCallback((w,I)=>{switch(r(ce()),I){case "line":r(Cs(w));break;case "image":r(Jr(w));break;case "video":r(ts(w));break;case "shape":r(rs(w));break;case "text":r(ss(w));break;case "flashcard":r(is(w));break;case "photoFrame":r(ds(w));break;case "mcq":r(cs(w));break;case "trueFalse":r(ms(w));break;case "shortAnswer":r(hs(w));break;case "longAnswer":r(xs(w));break;case "fillInTheBlanks":r(vs(w));break}no(),Y();},[r,no,Y]);useEffect(()=>{let w=I=>{if(I.key!=="Delete"||!p||pe)return;let P=document.activeElement;if(P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P?.getAttribute("contenteditable")==="true")return;I.preventDefault();let Ae=id(p);Ae&&ld(p,Ae);};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[p,pe,id,ld]),useEffect(()=>{let w=fe.current;return ()=>{w&&w.nodes([]);}},[d]),useEffect(()=>{let w=I=>{pe&&I.target.tagName!=="TEXTAREA"&&Rn();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[pe,Rn]),useEffect(()=>{let w=pe||p;if(!w||p&&pe){M(null);return}let I=ua.current.get(w),P=i.current;if(!I||!P){M(null);return}let F=P.container().getBoundingClientRect(),Ae=I.absolutePosition(),Le=P.scaleX();M({x:F.left+(Ae.x+I.width()*Le/2)*Le,y:F.top+Ae.y*Le});},[p,pe,_o,ua]),useEffect(()=>{if(!pe){D(null);return}let w=ua.current.get(pe),I=i.current;if(!w||!I){D(null);return}let P=I.container().getBoundingClientRect(),F=w.absolutePosition(),Ae=I.scaleX();D({top:P.top+F.y*Ae,left:P.left+F.x*Ae,scale:Ae});},[pe,_o,ua]);let dd=useCallback(w=>{let I=w.target.getClassName(),P=w.target===w.target.getStage(),F=I==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",Ae=I==="Image",Le=I==="Text",ae=I==="Group"||w.target.getParent()?.getClassName()==="Group",Ot=I==="Circle"||I==="Star"||I==="RegularPolygon"||I==="Ellipse"||I==="Ring"||I==="Wedge"||I==="Arrow"||I==="Line"||I==="Arc"||I==="Rect"&&w.target.attrs.id,Lt=I==="Group";if(P&&!F&&!Ae&&!Le&&!ae&&!Ot&&!Lt&&no(),!(n==="pen"||n==="eraser")&&(Ae||Le||F||ae||Ot||Lt))return;let Xe=w.target.getStage()?.getPointerPosition();if(!Xe)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let N=bc(Xe,g);oo(N);}},[n,oo,no,g]),ud=useCallback(w=>{if(od)return;let I=w.target.getStage()?.getPointerPosition();if(!I)return;let P=bc(I,g);Hr(P);},[Hr,od,g]),cd=useCallback(()=>{Ur();},[Ur]),km=useCallback(w=>{Wr(w,Y);},[Wr,Y]),Mm=useCallback(w=>{ye(w),Ge(w);},[ye,Ge]),wt=useCallback((w,I,P)=>{if(w.preventDefault(),!s.enabled)return;let F=w.clientX,Ae=w.clientY,Le=b.current?.offsetHeight||450,ae=b.current?.offsetWidth||450,Ot=window.innerHeight,Lt=window.innerWidth,tt=F,Xe=Ae;Ae+Le>Ot&&(Xe=Ae-Le),F+ae>Lt&&(tt=F-ae),k({x:tt,y:Xe,elementId:I,elementType:P}),Ge(I);},[Ge,s.enabled]),fd=useCallback(w=>{r(Zo(w)),r(ma(true));},[r]),Tm=useCallback(w=>{r(Xo(w)),r(Oa(true));},[r]),Am=useCallback((w,I)=>{if(!S)return;let{elementId:P,elementType:F}=S;switch(w){case "order":if(I){let A=I.target.getBoundingClientRect();W({x:A.right+5,y:A.top,type:"order"});}break;case "lock":if(I){let A=I.target.getBoundingClientRect();W({x:A.right+5,y:A.top,type:"lock"});}break;case "link":if(k(null),F==="line")break;let Ae=l?F==="image"?l.images.find(A=>A.id===P):l.videos.find(A=>A.id===P):null;U({type:"link",defaultValue:Ae?.link||""});break;case "voice":if(k(null),F==="line")break;let Le=l?F==="image"?l.images.find(A=>A.id===P):F==="video"?l.videos.find(A=>A.id===P):F==="text"?l.texts.find(A=>A.id===P):F==="flashcard"?l.flashcards.find(A=>A.id===P):F==="photoFrame"?l.photoFrames.find(A=>A.id===P):F==="mcq"?l.multipleChoices.find(A=>A.id===P):F==="fillInTheBlanks"?l.fillInTheBlanks.find(A=>A.id===P):F==="longAnswer"?l.LongAnswer.find(A=>A.id===P):F==="shortAnswer"?l.shortAnswers.find(A=>A.id===P):F==="trueFalse"?l.trueFalses.find(A=>A.id===P):F==="shape"?l.shapes.find(A=>A.id===P):null:null;H({elementId:P,elementType:F,existingAudio:Le?.audioData});break;case "edit":k(null);let ae=null;F==="mcq"?ae=l?.multipleChoices.find(A=>A.id===P):F==="trueFalse"?ae=l?.trueFalses.find(A=>A.id===P):F==="shortAnswer"?ae=l?.shortAnswers.find(A=>A.id===P):F==="longAnswer"?ae=l?.LongAnswer.find(A=>A.id===P):F==="fillInTheBlanks"&&(ae=l?.fillInTheBlanks.find(A=>A.id===P)),ae&&fd(ae);break;case "editFlashcard":k(null);let Ot=l?.flashcards.find(A=>A.id===P);Ot&&Tm(Ot);break;case "color":k(null);let Lt=l?.shapes.find(A=>A.id===P);oe({elementId:P,elementType:"shape",defaultColor:Lt?.color||"#096B76"});break;case "crop":if(k(null),F==="image"){let A=l?.images.find(Om=>Om.id===P);A&&se({elementId:P,imageSrc:A.src});}break;case "draw":k(null),F==="image"?r(Zn(P)):F==="photoFrame"&&r(ei(P));break;case "duplicate":r(ce()),F==="line"?r(fi(P)):F==="image"?r(Zr(P)):F==="video"?r(as(P)):F==="shape"?r(os(P)):F==="text"?r(ns(P)):F==="flashcard"?r(ls(P)):F==="photoFrame"?r(us(P)):F==="mcq"?r(fs(P)):F==="trueFalse"?r(ps(P)):F==="shortAnswer"?r(gs(P)):F==="fillInTheBlanks"?r(ys(P)):F==="longAnswer"&&r(bs(P)),Y();break;case "infinite-clone":r(ce());let tt=5;for(let A=0;A<tt;A++)F==="image"?r(Zr(P)):F==="video"?r(as(P)):F==="shape"?r(os(P)):F==="text"?r(ns(P)):F==="flashcard"?r(ls(P)):F==="photoFrame"?r(us(P)):F==="mcq"?r(fs(P)):F==="trueFalse"?r(ps(P)):F==="shortAnswer"?r(gs(P)):F==="fillInTheBlanks"?r(ys(P)):F==="longAnswer"&&r(bs(P));Y();break;case "make-response":if(k(null),F==="line")break;let Xe=`#response-${P}`;r(ce()),r(ws({id:P,type:F,link:Xe})),(l?F==="image"?l.images.find(A=>A.id===P):F==="video"?l.videos.find(A=>A.id===P):F==="shape"?l.shapes.find(A=>A.id===P):F==="flashcard"?l.flashcards.find(A=>A.id===P):F==="photoFrame"?l.photoFrames.find(A=>A.id===P):l.multipleChoices.find(A=>A.id===P):null)?.altText||r(Ls({id:P,type:F,altText:"Interactive response area"})),Y(),console.log(`Element ${P} marked as interactive response area`);break;case "accessibility":if(k(null),F==="line")break;let N=l?F==="image"?l.images.find(A=>A.id===P):F==="video"?l.videos.find(A=>A.id===P):F==="shape"?l.shapes.find(A=>A.id===P):null:null;U({type:"altText",defaultValue:N?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),k(null),te(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ce()),F==="line"?r(Cs(P)):F==="image"?r(Jr(P)):F==="video"?r(ts(P)):F==="shape"?r(rs(P)):F==="text"?r(ss(P)):F==="flashcard"?r(is(P)):F==="photoFrame"?r(ds(P)):F==="mcq"?r(cs(P)):F==="trueFalse"?r(ms(P)):F==="shortAnswer"?r(hs(P)):F==="longAnswer"?r(xs(P)):F==="fillInTheBlanks"&&r(vs(P)),no(),Y();break}},[S,r,Y,no,l,fd]),Pm=useCallback(()=>{k(null),W(null);},[]),En=useCallback(w=>{if(!S)return;let{elementId:I,elementType:P}=S;switch(r(ce()),w){case "bring-to-front":P!=="line"&&r(li({id:I,type:P}));break;case "send-to-back":P!=="line"&&r(di({id:I,type:P}));break;case "lock":case "unlock":P!=="line"&&r(ui({id:I,type:P}));break}Y(),k(null),W(null);},[S,r,Y]),Dm=useCallback(w=>{if(!S||!T)return;let{elementId:I,elementType:P}=S;r(ce()),T.type==="link"&&P!=="line"?r(ws({id:I,type:P,link:w})):T.type==="altText"&&P!=="line"&&r(Ls({id:I,type:P,altText:w})),Y(),U(null);},[S,T,r,Y]),Rm=useCallback(w=>{if(!_)return;let{elementId:I,elementType:P}=_;r(ce()),r(Ss({id:I,type:P,audioData:w})),Y(),H(null);},[_,r,Y]),Em=useCallback(()=>{if(!_)return;let{elementId:w,elementType:I}=_;r(ce()),r(Ss({id:w,type:I,audioData:""})),Y();},[_,r,Y]),Fm=useCallback(w=>{if(!R)return;let{elementId:I}=R;r(ce()),r(uo({id:I,color:w})),Y(),oe(null);},[R,r,Y]),Bm=useCallback(w=>{if(!V)return;let{elementId:I}=V;r(ce()),r(lo({id:I,src:w})),Y(),se(null);},[V,r,Y]);return jsxs("div",{ref:c,className:"fixed inset-0",style:{cursor:n==="pen"?"crosshair":n==="eraser"?"":"default"},children:[n==="pen"&&jsx(Cd,{ref:w=>{if(J.current=w,In(w),w){let I=w.getCanvasElement();I&&(le.current=I,a&&a(le));}},width:g.baseWidth,height:g.baseHeight,tool:ro,color:Cn,strokeWidth:kn/g.scale,isSketchMode:Mn,xOffset:g.contentOffsetX,yOffset:g.contentOffsetY-g.offsetY/g.scale,style:{width:g.stageWidth,height:g.stageHeight}}),jsxs(Stage,{ref:i,width:g.stageWidth,height:g.stageHeight,scaleX:g.scaleX,scaleY:g.scaleY,x:g.offsetX,y:0,onMouseDown:dd,onMouseMove:ud,onMouseUp:cd,onTouchStart:dd,onTouchMove:ud,onTouchEnd:cd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:g.baseWidth,height:g.stageHeight/g.scale,fill:l?.backgroundColor||"white"})}),jsx(Layer,{x:-g.contentOffsetX,y:g.offsetY/g.scale-g.contentOffsetY,children:(()=>{let w=[];return f.forEach((I,P)=>{w.push({type:"line",timestamp:I.timestamp||P,element:{...I,id:I.id??`line-${P}`},index:P});}),um.forEach(I=>{w.push({type:"shape",timestamp:I.timestamp||0,element:I});}),Tn.forEach(I=>{w.push({type:"image",timestamp:I.timestamp||0,element:I});}),E.forEach(I=>{w.push({type:"video",timestamp:I.timestamp||0,element:I});}),_o.forEach(I=>{w.push({type:"text",timestamp:I.timestamp||0,element:I});}),gm.forEach(I=>{w.push({type:"flashcard",timestamp:I.timestamp||0,element:I});}),nd.forEach(I=>{w.push({type:"photoFrame",timestamp:I.timestamp||0,element:I});}),ue.forEach(I=>{w.push({type:"mcq",timestamp:I.timestamp||0,element:I});}),ut.forEach(I=>{w.push({type:"trueFalse",timestamp:I.timestamp||0,element:I});}),la.forEach(I=>{w.push({type:"shortAnswer",timestamp:I.timestamp||0,element:I});}),zr.forEach(I=>{w.push({type:"longAnswer",timestamp:I.timestamp||0,element:I});}),da.forEach(I=>{w.push({type:"fillInTheBlanks",timestamp:I.timestamp||0,element:I});}),w.sort((I,P)=>I.timestamp-P.timestamp),w.map((I,P)=>{let F=`${I.type}-${"id"in I.element&&I.element.id||I.index||P}`,Ae="id"in I.element?I.element.id:void 0,Le=Ae&&p===Ae;switch(I.type){case "line":let ae=I.element,Ot=I.index||0,Lt=ae.tool==="eraser",tt=ae.isSketch&&ae.tool==="pen",Xe=ae.isSketch&&Lt,St=ae.id||`line-${Ot}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),n==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:tt||Xe?void 0:ae.color,strokeWidth:tt||Xe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Xe?Lt?"black":ae.color:void 0,closed:tt||Xe,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,onClick:()=>{r(ce()),r(Yr(Ot));},onTap:()=>{r(ce()),r(Yr(Ot));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:N=>{let A=N.target.getStage();A&&(A.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:N=>{let A=N.target.getStage();A&&(A.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},F):jsxs(be__default.Fragment,{children:[jsx(Group,{id:St,ref:N=>{N?ia.current.set(St,N):ia.current.delete(St);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:n==="select",listening:n==="select",onClick:()=>{n==="select"&&(console.log("Line clicked:",St),Ge(St));},onTap:()=>{n==="select"&&(console.log("Line tapped:",St),Ge(St));},onDragEnd:N=>{r(ce()),r(Is({id:St,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),Y();},onTransformEnd:N=>{r(ce()),r(Is({id:St,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),Y();},onMouseEnter:N=>{if(n==="select"){let A=N.target.getStage();A&&(A.container().style.cursor="move");}},onMouseLeave:N=>{if(n==="select"){let A=N.target.getStage();A&&(A.container().style.cursor="default");}},onContextMenu:N=>{let A=N.evt;A.preventDefault(),wt(A,St,"line");},children:jsx(Line,{points:ae.points||[],stroke:tt||Xe?void 0:ae.color,strokeWidth:tt||Xe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Xe?Lt?"black":ae.color:void 0,closed:tt||Xe,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=ia.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!A),A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "shape":return jsxs(be__default.Fragment,{children:[jsx(Ri,{onSelect:Ge,shapes:[I.element],shapeRefs:Kr,handleShapeDragEnd:cm,handleShapeResizeEnd:fm,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Kr.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "image":return jsxs(be__default.Fragment,{children:[jsx(Ti,{images:[I.element],getLoadedImage:An,imageRefs:so,onDragEnd:km,onTransform:Pn,onSelect:Ge,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=so.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "video":return jsxs(be__default.Fragment,{children:[jsx(Di,{videos:[I.element],selectedId:p,videoRefs:re,onVideoClick:Mm,onDragEnd:ge,onTransformEnd:ne,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=re.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "text":return jsxs(be__default.Fragment,{children:[jsx(ru,{texts:[I.element],textRefs:ua,onDragEnd:mm,onTransformEnd:pm,onSelect:Ge,onContextMenu:wt,onDoubleClick:hm,editingTextId:pe,editingValue:rd,onEditingChange:sd}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=ua.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Bi,{flashcards:[I.element],flashcardRefs:Xr,selectedId:p,onDragEnd:xm,onTransform:bm,onSelect:Ge,onNext:vm,onPrevious:ym,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Xr.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Ui,{photoFrames:[I.element],photoFrameRefs:$r,selectedId:p,onDragEnd:wm,onTransform:Lm,onSelect:Ge,onStartCamera:Sm,onCapture:Im,cameraStreams:Cm,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=$r.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(Fu,{handleMcqTransform:we,multipleChoice:[I.element],handleSelect:Ge,mcqRefs:Ne,handleDragEnd:Ft,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Ne.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Nu,{trueFalses:[I.element],handleTrueFalseTransform:Te,handleSelect:Ge,trueFalseRefs:Ue,onContextMenu:wt,handleDragEnd:Jt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Ue.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(rc,{shortAnswers:[I.element],handleSelect:Ge,handleTransform:we,saRefs:Ea,onContextMenu:wt,handleDragEnd:Dn}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Ea.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(fc,{longAnswer:[I.element],handleSelect:Ge,handleTransform:we,saRefs:Ea,onContextMenu:wt,handleDragEnd:Bt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Ea.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(uc,{fillInTheBlanks:[I.element],handleSelect:Ge,handleTransform:we,onContextMenu:wt,handleDragEnd:Fa,fibRefs:Gr}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Gr.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);default:return null}})})()})]}),S&&jsx(xu,{menuRef:b,x:S.x,y:S.y,type:S.elementType,onAction:Am,onClose:Pm,isDrawingMode:S.elementType==="image"?l?.images.find(w=>w.id===S.elementId)?.isDrawingMode:S.elementType==="photoFrame"?l?.photoFrames.find(w=>w.id===S.elementId)?.isDrawingMode:false}),O&&S&&jsx(bu,{x:O.x,y:O.y,items:O.type==="order"?[{label:"Bring to Front",onClick:()=>En("bring-to-front")},{label:"Send to Back",onClick:()=>En("send-to-back")}]:[{label:l&&(S.elementType==="image"?l.images.find(w=>w.id===S.elementId)?.locked:l.videos.find(w=>w.id===S.elementId)?.locked)?"Unlock":"Lock",onClick:()=>En(l&&(S.elementType==="image"?l.images.find(w=>w.id===S.elementId)?.locked:l.videos.find(w=>w.id===S.elementId)?.locked)?"unlock":"lock")}],onClose:()=>W(null)}),T&&jsx(wu,{title:T.type==="link"?"Add Link":"Add Alt Text",label:T.type==="link"?"URL":"Alternative Text",placeholder:T.type==="link"?"https://example.com":"Describe this image/video",defaultValue:T.defaultValue,onSave:Dm,onClose:()=>U(null)}),R&&jsx(Fs,{defaultColor:R.defaultColor,onConfirm:Fm,onCancel:()=>oe(null)}),V&&jsx(Cu,{imageSrc:V.imageSrc,onConfirm:Bm,onCancel:()=>se(null)}),G&&jsx(dr,{onClose:()=>q(false),stageRef:i}),_&&jsx(Tu,{elementId:_.elementId,elementType:_.elementType,existingAudio:_.existingAudio,onSave:Rm,onDelete:Em,onClose:()=>H(null)}),K&&jsx(Du,{selectedElementId:p||void 0,onClose:()=>te(false),onSelectElement:w=>{Ge(w),te(false);}}),l?.images.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.videos.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.shapes?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.texts?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.flashcards?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),m&&jsx(Xu,{editElement:u}),v&&(()=>{let w=pe||p;if(!w)return null;let I=_o.find(P=>P.id===w);return I?jsx(Zu,{text:I,position:v}):null})(),B&&pe&&(()=>{let w=_o.find(I=>I.id===pe);return w?jsx(ec,{text:w,editingValue:rd,onEditingChange:sd,onFinish:Rn,position:{top:B.top,left:B.left},scale:B.scale,textareaRef:Z},pe):null})()]})},Rb=Db;function bl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Ye(e,o,{checkForDefaultPrevented:t=true}={}){return function(s){if(e?.(s),t===false||!s.defaultPrevented)return o?.(s)}}function vc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Dr(...e){return o=>{let t=false,a=e.map(s=>{let r=vc(s,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let s=0;s<a.length;s++){let r=a[s];typeof r=="function"?r():vc(e[s],null);}}}}function Dt(...e){return be.useCallback(Dr(...e),e)}function ka(e,o=[]){let t=[];function a(r,n){let l=be.createContext(n),d=t.length;t=[...t,n];let u=f=>{let{scope:i,children:c,...p}=f,y=i?.[e]?.[d]||l,h=be.useMemo(()=>p,Object.values(p));return jsx(y.Provider,{value:h,children:c})};u.displayName=r+"Provider";function m(f,i){let c=i?.[e]?.[d]||l,p=be.useContext(c);if(p)return p;if(n!==void 0)return n;throw new Error(`\`${f}\` must be used within \`${r}\``)}return [u,m]}let s=()=>{let r=t.map(n=>be.createContext(n));return function(l){let d=l?.[e]||r;return be.useMemo(()=>({[`__scope${e}`]:{...l,[e]:d}}),[l,d])}};return s.scopeName=e,[a,Fb(s,...o)]}function Fb(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(r){let n=a.reduce((l,{useScope:d,scopeName:u})=>{let f=d(r)[`__scope${u}`];return {...l,...f}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var Oo=globalThis?.document?be.useLayoutEffect:()=>{};var Bb=be[" useInsertionEffect ".trim().toString()]||Oo;function ea({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[s,r,n]=Ob({defaultProp:o,onChange:t}),l=e!==void 0,d=l?e:s;{let m=be.useRef(e!==void 0);be.useEffect(()=>{let f=m.current;f!==l&&console.warn(`${a} is changing from ${f?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=l;},[l,a]);}let u=be.useCallback(m=>{if(l){let f=Nb(m)?m(e):m;f!==e&&n.current?.(f);}else r(m);},[l,e,r,n]);return [d,u]}function Ob({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),s=be.useRef(t),r=be.useRef(o);return Bb(()=>{r.current=o;},[o]),be.useEffect(()=>{s.current!==t&&(r.current?.(t),s.current=t);},[t,s]),[t,a,r]}function Nb(e){return typeof e=="function"}var Vb=be.createContext(void 0);function No(e){let o=be.useContext(Vb);return e||o||"ltr"}function Lc(e){let o=be.useRef({value:e,previous:e});return be.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Ic(e){let[o,t]=be.useState(void 0);return Oo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;let r=s[0],n,l;if("borderBoxSize"in r){let d=r.borderBoxSize,u=Array.isArray(d)?d[0]:d;n=u.inlineSize,l=u.blockSize;}else n=e.offsetWidth,l=e.offsetHeight;t({width:n,height:l});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function kc(e){let o=qb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,l=be.Children.toArray(r),d=l.find(Ub);if(d){let u=d.props.children,m=l.map(f=>f===d?be.Children.count(u)>1?be.Children.only(null):be.isValidElement(u)?u.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(u)?be.cloneElement(u,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function qb(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=zb(s),l=Wb(r,s.props);return s.type!==be.Fragment&&(l.ref=a?Dr(a,n):n),be.cloneElement(s,l)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Hb=Symbol("radix.slottable");function Ub(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Hb}function Wb(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...l)=>{let d=r(...l);return s(...l),d}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function zb(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var _b=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],lt=_b.reduce((e,o)=>{let t=kc(`Primitive.${o}`),a=be.forwardRef((s,r)=>{let{asChild:n,...l}=s,d=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(d,{...l,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function vl(e){let o=jb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,l=be.Children.toArray(r),d=l.find($b);if(d){let u=d.props.children,m=l.map(f=>f===d?be.Children.count(u)>1?be.Children.only(null):be.isValidElement(u)?u.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(u)?be.cloneElement(u,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function jb(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=Jb(s),l=Yb(r,s.props);return s.type!==be.Fragment&&(l.ref=a?Dr(a,n):n),be.cloneElement(s,l)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Xb=Symbol("radix.slottable");function $b(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Xb}function Yb(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...l)=>{let d=r(...l);return s(...l),d}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function Jb(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function dn(e){let o=e+"CollectionProvider",[t,a]=ka(o),[s,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=y=>{let{scope:h,children:x}=y,b=be__default.useRef(null),g=be__default.useRef(new Map).current;return jsx(s,{scope:h,itemMap:g,collectionRef:b,children:x})};n.displayName=o;let l=e+"CollectionSlot",d=vl(l),u=be__default.forwardRef((y,h)=>{let{scope:x,children:b}=y,g=r(l,x),L=Dt(h,g.collectionRef);return jsx(d,{ref:L,children:b})});u.displayName=l;let m=e+"CollectionItemSlot",f="data-radix-collection-item",i=vl(m),c=be__default.forwardRef((y,h)=>{let{scope:x,children:b,...g}=y,L=be__default.useRef(null),C=Dt(h,L),S=r(m,x);return be__default.useEffect(()=>(S.itemMap.set(L,{ref:L,...g}),()=>void S.itemMap.delete(L))),jsx(i,{[f]:"",ref:C,children:b})});c.displayName=m;function p(y){let h=r(e+"CollectionConsumer",y);return be__default.useCallback(()=>{let b=h.collectionRef.current;if(!b)return [];let g=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(h.itemMap.values()).sort((S,k)=>g.indexOf(S.ref.current)-g.indexOf(k.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:n,Slot:u,ItemSlot:c},p,a]}var Ac=["PageUp","PageDown"],Pc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Dc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Vo="Slider",[wl,Qb,ev]=dn(Vo),[Rc]=ka(Vo,[ev]),[tv,un]=Rc(Vo),Ec=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:s=100,step:r=1,orientation:n="horizontal",disabled:l=false,minStepsBetweenThumbs:d=0,defaultValue:u=[a],value:m,onValueChange:f=()=>{},onValueCommit:i=()=>{},inverted:c=false,form:p,...y}=e,h=be.useRef(new Set),x=be.useRef(0),g=n==="horizontal"?av:ov,[L=[],C]=ea({prop:m,defaultProp:u,onChange:D=>{[...h.current][x.current]?.focus(),f(D);}}),S=be.useRef(L);function k(D){let O=lv(L,D);B(D,O);}function v(D){B(D,x.current);}function M(){let D=S.current[x.current];L[x.current]!==D&&i(L);}function B(D,O,{commit:W}={commit:false}){let T=fv(r),U=mv(Math.round((D-a)/r)*r+a,T),R=bl(U,[a,s]);C((oe=[])=>{let V=nv(oe,R,O);if(cv(V,d*r)){x.current=V.indexOf(R);let se=String(V)!==String(oe);return se&&W&&i(V),se?V:oe}else return oe});}return jsx(tv,{scope:e.__scopeSlider,name:t,disabled:l,min:a,max:s,valueIndexToChangeRef:x,thumbs:h.current,values:L,orientation:n,form:p,children:jsx(wl.Provider,{scope:e.__scopeSlider,children:jsx(wl.Slot,{scope:e.__scopeSlider,children:jsx(g,{"aria-disabled":l,"data-disabled":l?"":void 0,...y,ref:o,onPointerDown:Ye(y.onPointerDown,()=>{l||(S.current=L);}),min:a,max:s,inverted:c,onSlideStart:l?void 0:k,onSlideMove:l?void 0:v,onSlideEnd:l?void 0:M,onHomeKeyDown:()=>!l&&B(a,0,{commit:true}),onEndKeyDown:()=>!l&&B(s,L.length-1,{commit:true}),onStepKeyDown:({event:D,direction:O})=>{if(!l){let U=Ac.includes(D.key)||D.shiftKey&&Pc.includes(D.key)?10:1,R=x.current,oe=L[R],V=r*U*O;B(oe+V,R,{commit:true});}}})})})})});Ec.displayName=Vo;var[Fc,Bc]=Rc(Vo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),av=be.forwardRef((e,o)=>{let{min:t,max:a,dir:s,inverted:r,onSlideStart:n,onSlideMove:l,onSlideEnd:d,onStepKeyDown:u,...m}=e,[f,i]=be.useState(null),c=Dt(o,g=>i(g)),p=be.useRef(void 0),y=No(s),h=y==="ltr",x=h&&!r||!h&&r;function b(g){let L=p.current||f.getBoundingClientRect(),C=[0,L.width],k=Il(C,x?[t,a]:[a,t]);return p.current=L,k(g-L.left)}return jsx(Fc,{scope:e.__scopeSlider,startEdge:x?"left":"right",endEdge:x?"right":"left",direction:x?1:-1,size:"width",children:jsx(Oc,{dir:y,"data-orientation":"horizontal",...m,ref:c,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:g=>{let L=b(g.clientX);n?.(L);},onSlideMove:g=>{let L=b(g.clientX);l?.(L);},onSlideEnd:()=>{p.current=void 0,d?.();},onStepKeyDown:g=>{let C=Dc[x?"from-left":"from-right"].includes(g.key);u?.({event:g,direction:C?-1:1});}})})}),ov=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:s,onSlideStart:r,onSlideMove:n,onSlideEnd:l,onStepKeyDown:d,...u}=e,m=be.useRef(null),f=Dt(o,m),i=be.useRef(void 0),c=!s;function p(y){let h=i.current||m.current.getBoundingClientRect(),x=[0,h.height],g=Il(x,c?[a,t]:[t,a]);return i.current=h,g(y-h.top)}return jsx(Fc,{scope:e.__scopeSlider,startEdge:c?"bottom":"top",endEdge:c?"top":"bottom",size:"height",direction:c?1:-1,children:jsx(Oc,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{let h=p(y.clientY);r?.(h);},onSlideMove:y=>{let h=p(y.clientY);n?.(h);},onSlideEnd:()=>{i.current=void 0,l?.();},onStepKeyDown:y=>{let x=Dc[c?"from-bottom":"from-top"].includes(y.key);d?.({event:y,direction:x?-1:1});}})})}),Oc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:s,onSlideEnd:r,onHomeKeyDown:n,onEndKeyDown:l,onStepKeyDown:d,...u}=e,m=un(Vo,t);return jsx(lt.span,{...u,ref:o,onKeyDown:Ye(e.onKeyDown,f=>{f.key==="Home"?(n(f),f.preventDefault()):f.key==="End"?(l(f),f.preventDefault()):Ac.concat(Pc).includes(f.key)&&(d(f),f.preventDefault());}),onPointerDown:Ye(e.onPointerDown,f=>{let i=f.target;i.setPointerCapture(f.pointerId),f.preventDefault(),m.thumbs.has(i)?i.focus():a(f);}),onPointerMove:Ye(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f);}),onPointerUp:Ye(e.onPointerUp,f=>{let i=f.target;i.hasPointerCapture(f.pointerId)&&(i.releasePointerCapture(f.pointerId),r(f));})})}),Nc="SliderTrack",Vc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=un(Nc,t);return jsx(lt.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...a,ref:o})});Vc.displayName=Nc;var Ll="SliderRange",qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=un(Ll,t),r=Bc(Ll,t),n=be.useRef(null),l=Dt(o,n),d=s.values.length,u=s.values.map(i=>Wc(i,s.min,s.max)),m=d>1?Math.min(...u):0,f=100-Math.max(...u);return jsx(lt.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...a,ref:l,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:f+"%"}})});qc.displayName=Ll;var Sl="SliderThumb",Hc=be.forwardRef((e,o)=>{let t=Qb(e.__scopeSlider),[a,s]=be.useState(null),r=Dt(o,l=>s(l)),n=be.useMemo(()=>a?t().findIndex(l=>l.ref.current===a):-1,[t,a]);return jsx(rv,{...e,ref:r,index:n})}),rv=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:s,...r}=e,n=un(Sl,t),l=Bc(Sl,t),[d,u]=be.useState(null),m=Dt(o,b=>u(b)),f=d?n.form||!!d.closest("form"):true,i=Ic(d),c=n.values[a],p=c===void 0?0:Wc(c,n.min,n.max),y=iv(a,n.values.length),h=i?.[l.size],x=h?dv(h,p,l.direction):0;return be.useEffect(()=>{if(d)return n.thumbs.add(d),()=>{n.thumbs.delete(d);}},[d,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[l.startEdge]:`calc(${p}% + ${x}px)`},children:[jsx(wl.ItemSlot,{scope:e.__scopeSlider,children:jsx(lt.span,{role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":n.min,"aria-valuenow":c,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...r,ref:m,style:c===void 0?{display:"none"}:e.style,onFocus:Ye(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),f&&jsx(Uc,{name:s??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:c},a)]})});Hc.displayName=Sl;var sv="RadioBubbleInput",Uc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let s=be.useRef(null),r=Dt(s,a),n=Lc(o);return be.useEffect(()=>{let l=s.current;if(!l)return;let d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"value").set;if(n!==o&&m){let f=new Event("input",{bubbles:true});m.call(l,o),l.dispatchEvent(f);}},[n,o]),jsx(lt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});Uc.displayName=sv;function nv(e=[],o,t){let a=[...e];return a[t]=o,a.sort((s,r)=>s-r)}function Wc(e,o,t){let r=100/(t-o)*(e-o);return bl(r,[0,100])}function iv(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function lv(e,o){if(e.length===1)return 0;let t=e.map(s=>Math.abs(s-o)),a=Math.min(...t);return t.indexOf(a)}function dv(e,o,t){let a=e/2,r=Il([0,50],[0,a]);return (a-r(o)*t)*t}function uv(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function cv(e,o){if(o>0){let t=uv(e);return Math.min(...t)>=o}return true}function Il(e,o){return t=>{if(e[0]===e[1]||o[0]===o[1])return o[0];let a=(o[1]-o[0])/(e[1]-e[0]);return o[0]+a*(t-e[0])}}function fv(e){return (String(e).split(".")[1]||"").length}function mv(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var zc=Ec,Gc=Vc,Kc=qc,_c=Hc;function jc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(o=0;o<s;o++)e[o]&&(t=jc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function cn(){for(var e,o,t=0,a="",s=arguments.length;t<s;t++)(e=arguments[t])&&(o=jc(e))&&(a&&(a+=" "),a+=o);return a}var hv=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},gv=(e,o)=>({classGroupId:e,validator:o}),Zc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Xc=[],xv="arbitrary..",bv=e=>{let o=yv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return vv(n);let l=n.split("-"),d=l[0]===""&&l.length>1?1:0;return Qc(l,d,o)},getConflictingClassGroupIds:(n,l)=>{if(l){let d=a[n],u=t[n];return d?u?hv(u,d):d:u||Xc}return t[n]||Xc}}},Qc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let s=e[o],r=t.nextPart.get(s);if(r){let u=Qc(e,o+1,r);if(u)return u}let n=t.validators;if(n===null)return;let l=o===0?e.join("-"):e.slice(o).join("-"),d=n.length;for(let u=0;u<d;u++){let m=n[u];if(m.validator(l))return m.classGroupId}},vv=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?xv+a:void 0})(),yv=e=>{let{theme:o,classGroups:t}=e;return wv(t,o)},wv=(e,o)=>{let t=Zc();for(let a in e){let s=e[a];Ml(s,t,a,o);}return t},Ml=(e,o,t,a)=>{let s=e.length;for(let r=0;r<s;r++){let n=e[r];Lv(n,o,t,a);}},Lv=(e,o,t,a)=>{if(typeof e=="string"){Sv(e,o,t);return}if(typeof e=="function"){Iv(e,o,t,a);return}Cv(e,o,t,a);},Sv=(e,o,t)=>{let a=e===""?o:ef(o,e);a.classGroupId=t;},Iv=(e,o,t,a)=>{if(kv(e)){Ml(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(gv(t,e));},Cv=(e,o,t,a)=>{let s=Object.entries(e),r=s.length;for(let n=0;n<r;n++){let[l,d]=s[n];Ml(d,ef(o,l),t,a);}},ef=(e,o)=>{let t=e,a=o.split("-"),s=a.length;for(let r=0;r<s;r++){let n=a[r],l=t.nextPart.get(n);l||(l=Zc(),t.nextPart.set(n,l)),t=l;}return t},kv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Mv=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),s=(r,n)=>{t[r]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let n=t[r];if(n!==void 0)return n;if((n=a[r])!==void 0)return s(r,n),n},set(r,n){r in t?t[r]=n:s(r,n);}}};var Tv=[],$c=(e,o,t,a,s)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:s}),Av=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=s=>{let r=[],n=0,l=0,d=0,u,m=s.length;for(let y=0;y<m;y++){let h=s[y];if(n===0&&l===0){if(h===":"){r.push(s.slice(d,y)),d=y+1;continue}if(h==="/"){u=y;continue}}h==="["?n++:h==="]"?n--:h==="("?l++:h===")"&&l--;}let f=r.length===0?s:s.slice(d),i=f,c=false;f.endsWith("!")?(i=f.slice(0,-1),c=true):f.startsWith("!")&&(i=f.slice(1),c=true);let p=u&&u>d?u-d:void 0;return $c(r,c,i,p)};if(o){let s=o+":",r=a;a=n=>n.startsWith(s)?r(n.slice(s.length)):$c(Tv,false,n,void 0,true);}if(t){let s=a;a=r=>t({className:r,parseClassName:s});}return a},Pv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],s=[];for(let r=0;r<t.length;r++){let n=t[r],l=n[0]==="[",d=o.has(n);l||d?(s.length>0&&(s.sort(),a.push(...s),s=[]),a.push(n)):s.push(n);}return s.length>0&&(s.sort(),a.push(...s)),a}},Dv=e=>({cache:Mv(e.cacheSize),parseClassName:Av(e),sortModifiers:Pv(e),...bv(e)}),Rv=/\s+/,Ev=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:s,sortModifiers:r}=o,n=[],l=e.trim().split(Rv),d="";for(let u=l.length-1;u>=0;u-=1){let m=l[u],{isExternal:f,modifiers:i,hasImportantModifier:c,baseClassName:p,maybePostfixModifierPosition:y}=t(m);if(f){d=m+(d.length>0?" "+d:d);continue}let h=!!y,x=a(h?p.substring(0,y):p);if(!x){if(!h){d=m+(d.length>0?" "+d:d);continue}if(x=a(p),!x){d=m+(d.length>0?" "+d:d);continue}h=false;}let b=i.length===0?"":i.length===1?i[0]:r(i).join(":"),g=c?b+"!":b,L=g+x;if(n.indexOf(L)>-1)continue;n.push(L);let C=s(x,h);for(let S=0;S<C.length;++S){let k=C[S];n.push(g+k);}d=m+(d.length>0?" "+d:d);}return d},Fv=(...e)=>{let o=0,t,a,s="";for(;o<e.length;)(t=e[o++])&&(a=tf(t))&&(s&&(s+=" "),s+=a);return s},tf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=tf(e[a]))&&(t&&(t+=" "),t+=o);return t},Bv=(e,...o)=>{let t,a,s,r,n=d=>{let u=o.reduce((m,f)=>f(m),e());return t=Dv(u),a=t.cache.get,s=t.cache.set,r=l,l(d)},l=d=>{let u=a(d);if(u)return u;let m=Ev(d,t);return s(d,m),m};return r=n,(...d)=>r(Fv(...d))},Ov=[],He=e=>{let o=t=>t[e]||Ov;return o.isThemeGetter=true,o},af=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,of=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Nv=/^\d+\/\d+$/,Vv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,qv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Hv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Uv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Wv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,qo=e=>Nv.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ma=e=>!!e&&Number.isInteger(Number(e)),Cl=e=>e.endsWith("%")&&de(e.slice(0,-1)),ta=e=>Vv.test(e),zv=()=>true,Gv=e=>qv.test(e)&&!Hv.test(e),rf=()=>false,Kv=e=>Uv.test(e),_v=e=>Wv.test(e),jv=e=>!X(e)&&!$(e),Xv=e=>Ho(e,lf,rf),X=e=>af.test(e),Ya=e=>Ho(e,df,Gv),kl=e=>Ho(e,Qv,de),Yc=e=>Ho(e,sf,rf),$v=e=>Ho(e,nf,_v),fn=e=>Ho(e,uf,Kv),$=e=>of.test(e),Rr=e=>Uo(e,df),Yv=e=>Uo(e,ey),Jc=e=>Uo(e,sf),Jv=e=>Uo(e,lf),Zv=e=>Uo(e,nf),mn=e=>Uo(e,uf,true),Ho=(e,o,t)=>{let a=af.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Uo=(e,o,t=false)=>{let a=of.exec(e);return a?a[1]?o(a[1]):t:false},sf=e=>e==="position"||e==="percentage",nf=e=>e==="image"||e==="url",lf=e=>e==="length"||e==="size"||e==="bg-size",df=e=>e==="length",Qv=e=>e==="number",ey=e=>e==="family-name",uf=e=>e==="shadow";var ty=()=>{let e=He("color"),o=He("font"),t=He("text"),a=He("font-weight"),s=He("tracking"),r=He("leading"),n=He("breakpoint"),l=He("container"),d=He("spacing"),u=He("radius"),m=He("shadow"),f=He("inset-shadow"),i=He("text-shadow"),c=He("drop-shadow"),p=He("blur"),y=He("perspective"),h=He("aspect"),x=He("ease"),b=He("animate"),g=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],C=()=>[...L(),$,X],S=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],v=()=>[$,X,d],M=()=>[qo,"full","auto",...v()],B=()=>[Ma,"none","subgrid",$,X],D=()=>["auto",{span:["full",Ma,$,X]},Ma,$,X],O=()=>[Ma,"auto",$,X],W=()=>["auto","min","max","fr",$,X],T=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],R=()=>["auto",...v()],oe=()=>[qo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],V=()=>[e,$,X],se=()=>[...L(),Jc,Yc,{position:[$,X]}],G=()=>["no-repeat",{repeat:["","x","y","space","round"]}],q=()=>["auto","cover","contain",Jv,Xv,{size:[$,X]}],_=()=>[Cl,Rr,Ya],H=()=>["","none","full",u,$,X],K=()=>["",de,Rr,Ya],te=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[de,Cl,Jc,Yc],le=()=>["","none",p,$,X],Ie=()=>["none",de,$,X],Y=()=>["none",de,$,X],Me=()=>[de,$,X],Be=()=>[qo,"full",...v()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ta],breakpoint:[ta],color:[zv],container:[ta],"drop-shadow":[ta],ease:["in","out","in-out"],font:[jv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ta],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ta],shadow:[ta],spacing:["px",de],text:[ta],"text-shadow":[ta],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",qo,X,$,h]}],container:["container"],columns:[{columns:[de,X,$,l]}],"break-after":[{"break-after":g()}],"break-before":[{"break-before":g()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:C()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:M()}],"inset-x":[{"inset-x":M()}],"inset-y":[{"inset-y":M()}],start:[{start:M()}],end:[{end:M()}],top:[{top:M()}],right:[{right:M()}],bottom:[{bottom:M()}],left:[{left:M()}],visibility:["visible","invisible","collapse"],z:[{z:[Ma,"auto",$,X]}],basis:[{basis:[qo,"full","auto",l,...v()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,qo,"auto","initial","none",X]}],grow:[{grow:["",de,$,X]}],shrink:[{shrink:["",de,$,X]}],order:[{order:[Ma,"first","last","none",$,X]}],"grid-cols":[{"grid-cols":B()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":B()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":W()}],"auto-rows":[{"auto-rows":W()}],gap:[{gap:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"justify-content":[{justify:[...T(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...T()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":T()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:v()}],px:[{px:v()}],py:[{py:v()}],ps:[{ps:v()}],pe:[{pe:v()}],pt:[{pt:v()}],pr:[{pr:v()}],pb:[{pb:v()}],pl:[{pl:v()}],m:[{m:R()}],mx:[{mx:R()}],my:[{my:R()}],ms:[{ms:R()}],me:[{me:R()}],mt:[{mt:R()}],mr:[{mr:R()}],mb:[{mb:R()}],ml:[{ml:R()}],"space-x":[{"space-x":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"space-y-reverse":["space-y-reverse"],size:[{size:oe()}],w:[{w:[l,"screen",...oe()]}],"min-w":[{"min-w":[l,"screen","none",...oe()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[n]},...oe()]}],h:[{h:["screen","lh",...oe()]}],"min-h":[{"min-h":["screen","lh","none",...oe()]}],"max-h":[{"max-h":["screen","lh",...oe()]}],"font-size":[{text:["base",t,Rr,Ya]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,kl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Cl,X]}],"font-family":[{font:[Yv,X,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,$,X]}],"line-clamp":[{"line-clamp":[de,"none",$,kl]}],leading:[{leading:[r,...v()]}],"list-image":[{"list-image":["none",$,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:V()}],"text-color":[{text:V()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...te(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",$,Ya]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[de,"auto",$,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:v()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:se()}],"bg-repeat":[{bg:G()}],"bg-size":[{bg:q()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ma,$,X],radial:["",$,X],conic:[Ma,$,X]},Zv,$v]}],"bg-color":[{bg:V()}],"gradient-from-pos":[{from:_()}],"gradient-via-pos":[{via:_()}],"gradient-to-pos":[{to:_()}],"gradient-from":[{from:V()}],"gradient-via":[{via:V()}],"gradient-to":[{to:V()}],rounded:[{rounded:H()}],"rounded-s":[{"rounded-s":H()}],"rounded-e":[{"rounded-e":H()}],"rounded-t":[{"rounded-t":H()}],"rounded-r":[{"rounded-r":H()}],"rounded-b":[{"rounded-b":H()}],"rounded-l":[{"rounded-l":H()}],"rounded-ss":[{"rounded-ss":H()}],"rounded-se":[{"rounded-se":H()}],"rounded-ee":[{"rounded-ee":H()}],"rounded-es":[{"rounded-es":H()}],"rounded-tl":[{"rounded-tl":H()}],"rounded-tr":[{"rounded-tr":H()}],"rounded-br":[{"rounded-br":H()}],"rounded-bl":[{"rounded-bl":H()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...te(),"hidden","none"]}],"divide-style":[{divide:[...te(),"hidden","none"]}],"border-color":[{border:V()}],"border-color-x":[{"border-x":V()}],"border-color-y":[{"border-y":V()}],"border-color-s":[{"border-s":V()}],"border-color-e":[{"border-e":V()}],"border-color-t":[{"border-t":V()}],"border-color-r":[{"border-r":V()}],"border-color-b":[{"border-b":V()}],"border-color-l":[{"border-l":V()}],"divide-color":[{divide:V()}],"outline-style":[{outline:[...te(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,$,X]}],"outline-w":[{outline:["",de,Rr,Ya]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",m,mn,fn]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",f,mn,fn]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[de,Ya]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",i,mn,fn]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[de,$,X]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"mask-image-linear-from-color":[{"mask-linear-from":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"mask-image-t-from-pos":[{"mask-t-from":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"mask-image-t-from-color":[{"mask-t-from":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"mask-image-r-from-pos":[{"mask-r-from":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"mask-image-r-from-color":[{"mask-r-from":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"mask-image-b-from-pos":[{"mask-b-from":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"mask-image-b-from-color":[{"mask-b-from":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"mask-image-l-from-pos":[{"mask-l-from":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"mask-image-l-from-color":[{"mask-l-from":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"mask-image-x-from-pos":[{"mask-x-from":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"mask-image-x-from-color":[{"mask-x-from":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"mask-image-y-from-pos":[{"mask-y-from":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[$,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":J()}],"mask-image-radial-to-pos":[{"mask-radial-to":J()}],"mask-image-radial-from-color":[{"mask-radial-from":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:se()}],"mask-repeat":[{mask:G()}],"mask-size":[{mask:q()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,X]}],filter:[{filter:["","none",$,X]}],blur:[{blur:le()}],brightness:[{brightness:[de,$,X]}],contrast:[{contrast:[de,$,X]}],"drop-shadow":[{"drop-shadow":["","none",c,mn,fn]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",de,$,X]}],"hue-rotate":[{"hue-rotate":[de,$,X]}],invert:[{invert:["",de,$,X]}],saturate:[{saturate:[de,$,X]}],sepia:[{sepia:["",de,$,X]}],"backdrop-filter":[{"backdrop-filter":["","none",$,X]}],"backdrop-blur":[{"backdrop-blur":le()}],"backdrop-brightness":[{"backdrop-brightness":[de,$,X]}],"backdrop-contrast":[{"backdrop-contrast":[de,$,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,$,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,$,X]}],"backdrop-invert":[{"backdrop-invert":["",de,$,X]}],"backdrop-opacity":[{"backdrop-opacity":[de,$,X]}],"backdrop-saturate":[{"backdrop-saturate":[de,$,X]}],"backdrop-sepia":[{"backdrop-sepia":["",de,$,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":v()}],"border-spacing-x":[{"border-spacing-x":v()}],"border-spacing-y":[{"border-spacing-y":v()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",$,X]}],ease:[{ease:["linear","initial",x,$,X]}],delay:[{delay:[de,$,X]}],animate:[{animate:["none",b,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,$,X]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:Ie()}],"rotate-x":[{"rotate-x":Ie()}],"rotate-y":[{"rotate-y":Ie()}],"rotate-z":[{"rotate-z":Ie()}],scale:[{scale:Y()}],"scale-x":[{"scale-x":Y()}],"scale-y":[{"scale-y":Y()}],"scale-z":[{"scale-z":Y()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[$,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Be()}],"translate-x":[{"translate-x":Be()}],"translate-y":[{"translate-y":Be()}],"translate-z":[{"translate-z":Be()}],"translate-none":["translate-none"],accent:[{accent:V()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:V()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":v()}],"scroll-mx":[{"scroll-mx":v()}],"scroll-my":[{"scroll-my":v()}],"scroll-ms":[{"scroll-ms":v()}],"scroll-me":[{"scroll-me":v()}],"scroll-mt":[{"scroll-mt":v()}],"scroll-mr":[{"scroll-mr":v()}],"scroll-mb":[{"scroll-mb":v()}],"scroll-ml":[{"scroll-ml":v()}],"scroll-p":[{"scroll-p":v()}],"scroll-px":[{"scroll-px":v()}],"scroll-py":[{"scroll-py":v()}],"scroll-ps":[{"scroll-ps":v()}],"scroll-pe":[{"scroll-pe":v()}],"scroll-pt":[{"scroll-pt":v()}],"scroll-pr":[{"scroll-pr":v()}],"scroll-pb":[{"scroll-pb":v()}],"scroll-pl":[{"scroll-pl":v()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,X]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[de,Rr,Ya,kl]}],stroke:[{stroke:["none",...V()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var cf=Bv(ty);function Ta(...e){return cf(cn(e))}function pn({className:e,defaultValue:o,value:t,min:a=0,max:s=100,rangeClassName:r,trackClassName:n,thumbClassName:l,...d}){let u=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,s],[t,o,a,s]);return jsxs(zc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:s,className:Ta("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...d,children:[jsx(Gc,{"data-slot":"slider-track",className:Ta("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(Kc,{"data-slot":"slider-range",className:Ta("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:u.length},(m,f)=>jsx(_c,{"data-slot":"slider-thumb",className:Ta("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",l)},f))]})}var oy="SchooplaVideoStorage";var $t="videos",hn=()=>new Promise((e,o)=>{let t=indexedDB.open(oy,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains($t)||s.createObjectStore($t,{keyPath:"id"});};}),Ja=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await hn(),r=a.transaction([$t],"readwrite").objectStore($t),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((l,d)=>{let u=r.put(n);u.onsuccess=()=>l(!0),u.onerror=()=>d(u.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var mf=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await hn(),t=e.transaction([$t],"readonly").objectStore($t);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result,l=new Map;n.forEach(d=>{l.set(d.id,{blob:d.blob,thumbnailDataUrl:d.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${l.size} video blobs from IndexedDB`),a(l);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Al=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await hn(),a=o.transaction([$t],"readwrite").objectStore($t);await new Promise((s,r)=>{let n=a.delete(e);n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},pf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await hn(),t=e.transaction([$t],"readwrite").objectStore($t);await new Promise((a,s)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>s(r.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},hf=e=>URL.createObjectURL(e);var ry=be[" useId ".trim().toString()]||(()=>{}),sy=0;function gf(e){let[o,t]=be.useState(ry());return Oo(()=>{t(a=>a??String(sy++));},[e]),(o?`radix-${o}`:"")}function xf(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var Dl="rovingFocusGroup.onEntryFocus",ny={bubbles:false,cancelable:true},Er="RovingFocusGroup",[Rl,bf,iy]=dn(Er),[ly,El]=ka(Er,[iy]),[dy,uy]=ly(Er),vf=be.forwardRef((e,o)=>jsx(Rl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Rl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(cy,{...e,ref:o})})}));vf.displayName=Er;var cy=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:s=false,dir:r,currentTabStopId:n,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:m=false,...f}=e,i=be.useRef(null),c=Dt(o,i),p=No(r),[y,h]=ea({prop:n,defaultProp:l??null,onChange:d,caller:Er}),[x,b]=be.useState(false),g=xf(u),L=bf(t),C=be.useRef(false),[S,k]=be.useState(0);return be.useEffect(()=>{let v=i.current;if(v)return v.addEventListener(Dl,g),()=>v.removeEventListener(Dl,g)},[g]),jsx(dy,{scope:t,orientation:a,dir:p,loop:s,currentTabStopId:y,onItemFocus:be.useCallback(v=>h(v),[h]),onItemShiftTab:be.useCallback(()=>b(true),[]),onFocusableItemAdd:be.useCallback(()=>k(v=>v+1),[]),onFocusableItemRemove:be.useCallback(()=>k(v=>v-1),[]),children:jsx(lt.div,{tabIndex:x||S===0?-1:0,"data-orientation":a,...f,ref:c,style:{outline:"none",...e.style},onMouseDown:Ye(e.onMouseDown,()=>{C.current=true;}),onFocus:Ye(e.onFocus,v=>{let M=!C.current;if(v.target===v.currentTarget&&M&&!x){let B=new CustomEvent(Dl,ny);if(v.currentTarget.dispatchEvent(B),!B.defaultPrevented){let D=L().filter(R=>R.focusable),O=D.find(R=>R.active),W=D.find(R=>R.id===y),U=[O,W,...D].filter(Boolean).map(R=>R.ref.current);Lf(U,m);}}C.current=false;}),onBlur:Ye(e.onBlur,()=>b(false))})})}),yf="RovingFocusGroupItem",wf=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:s=false,tabStopId:r,children:n,...l}=e,d=gf(),u=r||d,m=uy(yf,t),f=m.currentTabStopId===u,i=bf(t),{onFocusableItemAdd:c,onFocusableItemRemove:p,currentTabStopId:y}=m;return be.useEffect(()=>{if(a)return c(),()=>p()},[a,c,p]),jsx(Rl.ItemSlot,{scope:t,id:u,focusable:a,active:s,children:jsx(lt.span,{tabIndex:f?0:-1,"data-orientation":m.orientation,...l,ref:o,onMouseDown:Ye(e.onMouseDown,h=>{a?m.onItemFocus(u):h.preventDefault();}),onFocus:Ye(e.onFocus,()=>m.onItemFocus(u)),onKeyDown:Ye(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){m.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let x=py(h,m.orientation,m.dir);if(x!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let g=i().filter(L=>L.focusable).map(L=>L.ref.current);if(x==="last")g.reverse();else if(x==="prev"||x==="next"){x==="prev"&&g.reverse();let L=g.indexOf(h.currentTarget);g=m.loop?hy(g,L+1):g.slice(L+1);}setTimeout(()=>Lf(g));}}),children:typeof n=="function"?n({isCurrentTabStop:f,hasTabStop:y!=null}):n})})});wf.displayName=yf;var fy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function my(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function py(e,o,t){let a=my(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return fy[a]}function Lf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function hy(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Sf=vf,If=wf;var kf="Toggle",Fl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:s,...r}=e,[n,l]=ea({prop:t,onChange:s,defaultProp:a??false,caller:kf});return jsx(lt.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:Ye(e.onClick,()=>{e.disabled||l(!n);})})});Fl.displayName=kf;var Aa="ToggleGroup",[Tf]=ka(Aa,[El]),Af=El(),Bl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(by,{...a,ref:o});if(t==="multiple")return jsx(vy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Aa}\``)});Bl.displayName=Aa;var[Pf,Df]=Tf(Aa),by=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,l]=ea({prop:t,defaultProp:a??"",onChange:s,caller:Aa});return jsx(Pf,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:l,onItemDeactivate:be__default.useCallback(()=>l(""),[l]),children:jsx(Rf,{...r,ref:o})})}),vy=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,l]=ea({prop:t,defaultProp:a??[],onChange:s,caller:Aa}),d=be__default.useCallback(m=>l((f=[])=>[...f,m]),[l]),u=be__default.useCallback(m=>l((f=[])=>f.filter(i=>i!==m)),[l]);return jsx(Pf,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:d,onItemDeactivate:u,children:jsx(Rf,{...r,ref:o})})});Bl.displayName=Aa;var[yy,wy]=Tf(Aa),Rf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:s=true,orientation:r,dir:n,loop:l=true,...d}=e,u=Af(t),m=No(n),f={role:"group",dir:m,...d};return jsx(yy,{scope:t,rovingFocus:s,disabled:a,children:s?jsx(Sf,{asChild:true,...u,orientation:r,dir:m,loop:l,children:jsx(lt.div,{...f,ref:o})}):jsx(lt.div,{...f,ref:o})})}),gn="ToggleGroupItem",Ly=be__default.forwardRef((e,o)=>{let t=Df(gn,e.__scopeToggleGroup),a=wy(gn,e.__scopeToggleGroup),s=Af(e.__scopeToggleGroup),r=t.value.includes(e.value),n=a.disabled||e.disabled,l={...e,pressed:r,disabled:n},d=be__default.useRef(null);return a.rovingFocus?jsx(If,{asChild:true,...s,focusable:!n,active:r,ref:d,children:jsx(Mf,{...l,ref:o})}):jsx(Mf,{...l,ref:o})});Ly.displayName=gn;var Mf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...s}=e,r=Df(gn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},l=r.type==="single"?n:void 0;return jsx(Fl,{...l,...s,ref:o,onPressedChange:d=>{d?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Ef=Bl;var Cy=be.createContext({size:"default",variant:"default",spacing:0});function Pa({className:e,variant:o,size:t,spacing:a=1,children:s,...r}){return jsx(Ef,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Ta("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Cy.Provider,{value:{variant:o,size:t,spacing:a},children:s})})}var My={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Vf=createSlice({name:"toolbar",initialState:My,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:zt,setPenColor:zo,setStrokeWidth:Fr,setFontSize:nD,setFontFamily:iD,setFontStyle:lD,setFontWeight:dD,setTextDecoration:uD,setTextColor:cD}=Vf.actions,qf=Vf.reducer;var Hf=({onClose:e,onRecordingComplete:o})=>{let t=ot(),[a,s]=useState(false),[r,n]=useState(null),[l,d]=useState(0),[u,m]=useState(null),[f,i]=useState(false),c=useRef(null),p=useRef([]),y=useRef(null),h=useRef(null),x=useRef(null);useEffect(()=>((async()=>{try{let M=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(M),i(!0),x.current&&(x.current.srcObject=M);}catch(M){console.error("Error accessing camera:",M),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{y.current&&clearInterval(y.current),u&&u.getTracks().forEach(M=>M.stop());}),[]);let b=()=>{u&&(u.getTracks().forEach(v=>v.stop()),m(null),i(false));},g=async()=>{try{let v=null,M=null;try{v=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(T){console.error("Error accessing camera for recording:",T),alert("Failed to access camera for recording.");return}try{M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(T){console.warn("Microphone access denied:",T);}let B=[...v.getVideoTracks()];M&&B.push(...M.getAudioTracks());let D=new MediaStream(B),O="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?O="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?O="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?O="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(O="video/webm;codecs=vp8");let W=new MediaRecorder(D,{mimeType:O,videoBitsPerSecond:25e5});c.current=W,p.current=[],W.ondataavailable=T=>{T.data.size>0&&p.current.push(T.data);},W.onstop=()=>{let T=new Blob(p.current,{type:O}),U=document.createElement("video");U.src=URL.createObjectURL(T),U.muted=!0,U.currentTime=.1,U.onseeked=()=>{let R=document.createElement("canvas");R.width=U.videoWidth,R.height=U.videoHeight;let oe=R.getContext("2d");oe&&(oe.drawImage(U,0,0),h.current=R.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(U.src);},D.getTracks().forEach(R=>R.stop()),v&&v.getTracks().forEach(R=>R.stop()),M&&M.getTracks().forEach(R=>R.stop()),y.current&&clearInterval(y.current),n(T),b();},W.onerror=T=>{console.error("MediaRecorder error:",T);},W.start(1e3),s(!0),d(0),y.current=setInterval(()=>{d(T=>T+1);},1e3);}catch(v){console.error("Error starting camera recording:",v),alert("Failed to start recording. Please check permissions.");}},L=()=>{c.current&&a&&(c.current.state!=="inactive"&&(c.current.requestData(),setTimeout(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop();},100)),s(false));},C=()=>{if(r){let v=URL.createObjectURL(r),M=document.createElement("a");M.href=v,M.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(v);}},S=v=>{let M=Math.floor(v/60),B=v%60;return `${M.toString().padStart(2,"0")}:${B.toString().padStart(2,"0")}`};if(!t)return null;let k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:v=>{v.target===v.currentTarget&&e(),v.stopPropagation();},onMouseUp:v=>v.stopPropagation(),onMouseMove:v=>v.stopPropagation(),onTouchStart:v=>v.stopPropagation(),onTouchMove:v=>v.stopPropagation(),onTouchEnd:v=>v.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:v=>v.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:x,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:g,disabled:!f,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!f&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:L,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:S(l)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",S(l)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),d(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:C,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&h.current&&(o(r,h.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(k,t)};var aa=40,Wf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,s]=useState(t?.images||[]),[r,n]=useState(t?.order||"sequential"),[l,d]=useState(false),u=useRef(null),m=ot(),f=useRef(null);useEffect(()=>{let g=L=>{L.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let i=g=>{let L=g.target.files;if(!L||L.length===0)return;let C=aa-a.length;if(C<=0){alert(`You can only upload a maximum of ${aa} images`);return}let S=Array.from(L).slice(0,C);S.length<L.length&&alert(`Only ${C} more images can be added (max ${aa} total)`);let k=S.map(v=>new Promise((M,B)=>{let D=new FileReader;D.onload=O=>{O.target?.result?M(O.target.result):B(new Error("Failed to read file"));},D.onerror=B,D.readAsDataURL(v);}));Promise.all(k).then(v=>{s(M=>[...M,...v]),f.current&&(f.current.value="");});},c=g=>{g.preventDefault(),d(false);let L=Array.from(g.dataTransfer.files).filter(v=>v.type.startsWith("image/"));if(L.length===0)return;let C=aa-a.length;if(C<=0){alert(`You can only upload a maximum of ${aa} images`);return}let S=L.slice(0,C);S.length<L.length&&alert(`Only ${C} more images can be added (max ${aa} total)`);let k=S.map(v=>new Promise((M,B)=>{let D=new FileReader;D.onload=O=>{O.target?.result?M(O.target.result):B(new Error("Failed to read file"));},D.onerror=B,D.readAsDataURL(v);}));Promise.all(k).then(v=>{s(M=>[...M,...v]);});},p=g=>{g.preventDefault(),d(true);},y=()=>{d(false);},h=g=>{s(L=>L.filter((C,S)=>S!==g));},x=g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!m)return null;let b=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:u,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:x,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=aa?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",aa," images"]}):jsxs("span",{children:[a.length,"/",aa," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:i,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:c,onDragOver:p,onDragLeave:y,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${l?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:l?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,L)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${L+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>h(L),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:L+1})]},L))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(b,m)};var xn={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},zy={enabled:true};function ql(e){return e?{tools:{...xn.tools,...e.tools},actions:{...xn.actions,...e.actions}}:xn}var Gy={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Ky={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var vw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:s}={})=>{let r=xe(),n=Q(E=>E.canvas.slides.find(re=>re.id===E.canvas.currentSlideId)),l=n?.videos||[],d=n?.editingFlashcard,u=Q(E=>E.toolbar.selectedTool),m=Q(E=>E.toolbar.penColor),f=Q(E=>E.toolbar.strokeWidth),i=n?.showMcqForm,c=n?.showFlashcardForm,p=useRef(null),y=useMemo(()=>ql(s),[s]),{tools:h,actions:x}=y,b=l.some(E=>E.isRecorded&&E.isPlaying),g=Q(E=>E.toolbar.fontSize),L=Q(E=>E.toolbar.fontFamily),C=Q(E=>E.toolbar.fontStyle),S=Q(E=>E.toolbar.fontWeight),k=Q(E=>E.toolbar.textDecoration),v=Q(E=>E.toolbar.textColor),[M,B]=useState(false),[D,O]=useState(false),[W,T]=useState(false),[U,R]=useState(false),[oe,V]=useState(false),[se,G]=useState(false),[q,_]=useState(false),H=useRef(null),K=useRef(null),te=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),Z=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),J=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],[]),le=useMemo(()=>te.filter(E=>{let re=h[E.configKey];return typeof re=="boolean"?re:Array.isArray(re)?re.length>0:true}),[h,te]),Ie=useMemo(()=>{let E=h.shapes;return E===false?[]:E===true?Z:Array.isArray(E)?Z.filter(re=>E.includes(re.name)):Z},[h.shapes,Z]),Y=useMemo(()=>{let E=h.activities;return E===false?[]:E===true?J:Array.isArray(E)?J.filter(re=>E.includes(re.name)):J},[h.activities,J]),Me=useMemo(()=>{let E=h.media;return E===false?{photoFrame:false,image:false,video:false}:E===true?{photoFrame:true,image:true,video:true}:Array.isArray(E)?{photoFrame:E.includes("photo-frame"),image:E.includes("image"),video:E.includes("video")}:{photoFrame:true,image:true,video:true}},[h.media]),Be=useMemo(()=>{let E=h.activities;return E===false?false:E===true?true:Array.isArray(E)?E.includes("flashcard"):true},[h.activities]),Et=E=>{let re=E.target.files;!re||re.length===0||(r(zt("select")),r(ft(false)),R(false),Array.from(re).forEach(ye=>{let ge=new FileReader;ge.onload=ne=>{let ue=new window.Image;ue.src=ne.target?.result,ue.onload=()=>{let we=ue.width/ue.height,Ne=300,Ft=300,ut=ue.width,Te=ue.height;ut>Ne&&(ut=Ne,Te=ut/we),Te>Ft&&(Te=Ft,ut=Te*we),r(ce());let Ue=960-ut/2,Jt=540-Te/2;r(Kn({id:v4(),src:ue.src,x:Ue,y:Jt,width:ut,height:Te,draggable:true,rotation:0}));};},ge.readAsDataURL(ye);}),E.target.value="");},oo=async E=>{let re=E.target.files;if(!(!re||re.length===0)){console.log("files",E),r(zt("select")),r(ft(false)),R(false);for(let ye of Array.from(re))try{let ge=URL.createObjectURL(ye),ne=document.createElement("video");console.log("video",ne),ne.src=ge,ne.muted=!0,ne.playsInline=!0,ne.preload="auto",ne.load(),await new Promise((Bt,da)=>{let Fa=setTimeout(()=>da(new Error("Metadata load timeout")),1e4);ne.onloadedmetadata=()=>{clearTimeout(Fa),Bt();},ne.onerror=()=>{clearTimeout(Fa),da(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ne.duration,width:ne.videoWidth,height:ne.videoHeight}),await new Promise((Bt,da)=>{let Fa=setTimeout(()=>da(new Error("Video load timeout")),1e4);ne.readyState>=2?(clearTimeout(Fa),Bt()):ne.onloadeddata=()=>{clearTimeout(Fa),Bt();};});let ue=Math.min(.8,ne.duration/2);console.log("Seeking to:",ue),ne.currentTime=ue,await new Promise(Bt=>{let da=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Bt();},5e3);ne.onseeked=()=>{clearTimeout(da),console.log("Seek completed"),Bt();};});let we=document.createElement("canvas"),Ne=ne.videoWidth/ne.videoHeight,Ft=400,ut=400,Te=ne.videoWidth,Ue=ne.videoHeight;Te>Ft&&(Te=Ft,Ue=Te/Ne),Ue>ut&&(Ue=ut,Te=Ue*Ne),we.width=Te,we.height=Ue;let Jt=we.getContext("2d",{willReadFrequently:!1});if(!Jt)throw new Error("Failed to get canvas context");if(await new Promise(Bt=>setTimeout(Bt,100)),ne.videoWidth===0||ne.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Te,height:Ue}),Jt.drawImage(ne,0,0,Te,Ue);let la=we.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",la.length),r(ce());let Ea=960-Te/2,Dn=540-Ue/2,zr=v4();await Ja(zr,ye,la),r(Qr({id:zr,objectUrl:ge,thumbnailDataUrl:la,videoBlob:ye,x:Ea,y:Dn,width:Te,height:Ue,draggable:!0,isPlaying:!1,rotation:0})),ne.src="",ne.load(),console.log(`Video uploaded: ${ye.name}`);}catch(ge){console.error("Error processing video:",ge),alert(`Failed to process video: ${ye.name}`);}E.target.value="";}},Hr=(E,re,ye)=>{r(ce()),r(zt("select")),r(ft(false));let ge=300,ne=300,ue=960-ge/2,we=540-ne/2;r(ye?co({id:ye,images:E,order:re,x:ue,y:we,width:ge,height:ne,rotation:0,draggable:true}):Xn({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:E,currentIndex:0,order:re,x:ue,y:we,width:ge,height:ne,rotation:0,draggable:true})),r(Oa(false));},Ur=()=>{r(ce()),r(zt("select")),r(ft(false));let E=400,re=300,ye=800-E/2,ge=450-re/2;if(t?.current){let ne=t.current,ue=ne.scaleX()||1,we=ne.scaleY()||1,Ne=ne.width()/ue,Ft=ne.height()/we;ye=Ne/2-E/2,ge=Ft/2-re/2;}r(Jn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ye,y:ge,width:E,height:re,rotation:0,draggable:true,isCapturing:false})),V(false);},In=E=>{let ue={};switch(E.name){case "circle":case "ring":case "wedge":case "arc":ue.radius=50,(E.name==="ring"||E.name==="arc")&&(ue.innerRadius=25,ue.outerRadius=50),(E.name==="wedge"||E.name==="arc")&&(ue.angle=E.name==="wedge"?60:90);break;case "ellipse":ue.radiusX=60,ue.radiusY=40;break;case "triangle":ue.radius=50,ue.sides=3;break;case "polygon":ue.radius=50,ue.sides=6;break;case "star":ue.innerRadius=25,ue.outerRadius=50,ue.numPoints=5;break;case "arrow":case "line":ue.points=[0,0,100,0],E.name==="arrow"&&(ue.pointerLength=10,ue.pointerWidth=10);break}let we={id:`shape-${Date.now()}`,type:E.name,x:910,y:490,width:100,height:100,rotation:0,color:m,...ue};r(ce()),r(ft(false)),r(zt(E.name)),r(_n(we));},ro=E=>{if(r(zt(E)),E==="select")r(ft(false));else if(E==="text"){r(ft(false)),r(ce());let re=200,ye=50,ge=960-re/2,ne=540-ye/2,we=window.innerWidth<768?Math.max(g,32):g,Ne=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(jn({id:Ne,text:"",x:ge,y:ne,width:re,height:ye,rotation:0,draggable:true,fontSize:we,fontFamily:L,fontStyle:C,fontWeight:S,textDecoration:k,fill:v,align:"left"})),setTimeout(()=>{r(er(Ne));},100),a&&a(Ne);}else r(ft(true));},Cn=()=>{r(mi()),r(zt("select")),r(ft(false));},kn=()=>{o?o():t?B(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Mn=()=>{O(true);},ia=async(E,re)=>{try{r(zt("select")),r(ft(!1));let ye=URL.createObjectURL(E),ge=document.createElement("video");ge.src=ye,ge.muted=!0,ge.playsInline=!0,ge.preload="auto",await new Promise((Ue,Jt)=>{let la=setTimeout(()=>Jt(new Error("Metadata load timeout")),1e4);ge.onloadedmetadata=()=>{clearTimeout(la),Ue();},ge.onerror=()=>{clearTimeout(la),Jt(new Error("Failed to load video"));};});let ne=640,ue=ge.videoWidth/ge.videoHeight,we=ne,Ne=we/ue;r(ce());let Ft=960-we/2,ut=540-Ne/2,Te=v4();await Ja(Te,E,re),r(Qr({id:Te,objectUrl:ye,thumbnailDataUrl:re,videoBlob:E,x:Ft,y:ut,width:we,height:Ne,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),B(!1),O(!1);}catch(ye){console.error("Error adding recorded video to canvas:",ye),alert("Failed to add video to canvas. Please try again.");}},Tn=E=>{r(zt("select")),r(ft(false)),r(Zo(null)),E&&r(ii(E)),r(ma(!i));},An=()=>{r(Xo(null)),r(Oa(true)),V(false);},so=()=>{T(!W);},Wr=()=>{R(!U);},Pn=()=>{V(!oe);};return useEffect(()=>{if(!q)return;let E=re=>{p.current&&!p.current.contains(re.target)&&_(false);};return document.addEventListener("mousedown",E),()=>{document.removeEventListener("mousedown",E);}},[q]),b?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Pa,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:le.map((E,re)=>jsx("div",{title:E.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 ${E.name===u?"bg-primary/10":""}`,onClick:()=>{if(E.name==="image"){Wr(),T(false),V(false),ro(E.name);return}else if(E.name==="shapes"){so(),R(false),V(false),ro(E.name);return}else if(E.name==="activities"){ro(E.name),Pn(),T(false),R(false);return}ro(E.name),T(false),R(false),V(false);},children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl"})},re))}),W&&jsx(Pa,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:Ie.map((E,re)=>jsx("div",{title:E.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>In(E),children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl"})},re))}),U&&jsxs(Pa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Me.photoFrame&&jsx("div",{title:"Photo frame",onClick:Ur,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Me.image&&jsx("div",{title:"Image",onClick:()=>H.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Me.video&&jsx("div",{title:"Video",onClick:()=>K.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),oe&&jsxs(Pa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Be&&jsx("div",{title:"Flashcard",onClick:()=>An(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),Y.map((E,re)=>jsx("div",{title:E.label,onClick:()=>Tn(E.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl"})},re))]})]}),(x.undo||x.redo||x.screenRecord||x.cameraRecord||x.clear)&&jsxs(Pa,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[x.undo&&jsx("button",{value:"undo",onClick:()=>r(pi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.redo&&jsx("button",{value:"redo",onClick:()=>r(hi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.screenRecord&&jsx("button",{value:"screen-record",onClick:kn,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6279F8] md:block",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl"})}),jsx("button",{title:"Pen Color",onClick:()=>G(true),className:"relative mx-4 my-2 flex cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-white text-xl md:hidden",style:{borderColor:m},children:jsx("div",{className:"h-5 w-5 rounded-full border-2 border-white shadow-sm",style:{backgroundColor:m}})}),jsxs("div",{ref:p,className:"relative md:hidden",children:[jsx("button",{title:"Pen Size",onClick:()=>_(!q),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${q?"bg-primary/10":""}`,children:jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border-2 border-[#FFFFFF80] bg-[#000000CC]",children:jsx("span",{className:"text-xs font-semibold text-white",children:f})})}),q&&jsxs("div",{className:"absolute top-1/2 left-full z-50 ml-2 w-48 -translate-y-1/2 rounded-lg border bg-white p-4 shadow-xl",children:[jsx("p",{className:"mb-3 text-xs font-semibold text-black/40",children:"PEN SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 shrink-0 rounded-full bg-black"}),jsx(pn,{defaultValue:[12],max:28,min:6,step:1,className:"w-full",value:[f],rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:E=>r(Fr(E[0]))}),jsx("div",{className:"h-5 w-5 shrink-0 rounded-full bg-black"})]})]})]}),x.cameraRecord&&jsx("button",{value:"camera-record",onClick:Mn,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6BBB93] md:block",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl"})}),x.clear&&jsx("button",{value:"clear",onClick:()=>Cn(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl"})})]})]}),jsx("input",{ref:H,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:Et}),jsx("input",{ref:K,type:"file",accept:"video/*",className:"hidden",onChange:oo}),!o&&M&&t&&jsx(dr,{onClose:()=>B(false),stageRef:t,onRecordingComplete:ia}),D&&jsx(Hf,{onClose:()=>O(false),onRecordingComplete:ia}),c&&jsx(Wf,{editingFlashcard:d,onConfirm:Hr,onCancel:()=>r(Oa(false))}),se&&jsx(Fs,{defaultColor:m,onConfirm:E=>{r(zo(E)),G(false);},onCancel:()=>G(false)})]})},yw=vw;var Gl=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let s=ct(mo),r=ct(vi),n=a?r:s,l=ct(tr),m=(ct(b=>b.canvas.slides.find(g=>g.id===b.canvas.currentSlideId))?.videos||[]).some(b=>b.isRecorded&&b.isPlaying),[f,i]=useState(false),[c,p]=useState(null),[y,h]=useState(null),x=async()=>{if(s.length===0){h({type:"error",message:"No slides to publish"});return}if(!e){h({type:"error",message:"No publish handler provided"});return}i(true),h(null);try{let b=await e(n,l,g=>{p(g);});b.success?h({type:"success",message:b.message}):h({type:"error",message:b.message});}catch(b){h({type:"error",message:b instanceof Error?b.message:"An unexpected error occurred"});}finally{i(false),setTimeout(()=>{p(null),h(null);},3e3);}};return m?null:jsxs("button",{onClick:x,disabled:f||s.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var Cw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:s,onDescriptionChange:r,showPublishButton:n=true,showBackButton:l=true,editableTitle:d=true,editableDescription:u=true,className:m="",rightContent:f,leftContent:i,includeInactiveSlides:c=false})=>{let p=at(),y=ct(tr),h=ct(wi),x=e??(h?y.title:"")??"Untitled",b=o??(h?y.description:"")??"Add a description...",[g,L]=useState(false),[C,S]=useState(false),[k,v]=useState(x),[M,B]=useState(b),D=useRef(null),O=useRef(null);useEffect(()=>{v(x);},[x]),useEffect(()=>{B(b);},[b]),useEffect(()=>{g&&D.current&&(D.current.focus(),D.current.select());},[g]),useEffect(()=>{C&&O.current&&(O.current.focus(),O.current.select());},[C]);let W=()=>{d&&L(true);},T=()=>{u&&S(true);},U=()=>{L(false),k.trim()&&k!==x?s?s(k.trim()):p(gi(k.trim())):k.trim()||v(x);},R=()=>{S(false),M.trim()&&M!==b?r?r(M.trim()):p(xi(M.trim())):M.trim()||B(b);},oe=se=>{se.key==="Enter"?U():se.key==="Escape"&&(v(x),L(false));},V=se=>{se.key==="Enter"?R():se.key==="Escape"&&(B(b),S(false));};return jsxs("div",{className:`fixed top-0 left-0 z-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:[i||jsxs("div",{className:"flex items-center gap-6",children:[l&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[g?jsx("input",{ref:D,type:"text",value:k,onChange:se=>v(se.target.value),onBlur:U,onKeyDown:oe,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:W,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${d?"hover:border-primary cursor-text":""}`,children:k}),C?jsx("input",{ref:O,type:"text",value:M,onChange:se=>B(se.target.value),onBlur:R,onKeyDown:V,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:T,title:M,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${u?"hover:border-primary cursor-text":""}`,children:M})]})]}),f||n&&a&&jsx(Gl,{onPublish:a,includeInactiveSlides:c})]})};var Dw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Rw=({colors:e=Dw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:s=""})=>{let[r,n]=useState(true),l=Q(he),d=Q(i=>i.toolbar.penColor),u=Q(i=>i.toolbar.strokeWidth),m=l?.backgroundColor,f=xe();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:r?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:px-8 2xl:py-6 ${s}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(pn,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[u],onValueChange:i=>f(Fr(i[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"COLOR"}),jsxs(Pa,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(i=>jsx("button",{value:i.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${d===i.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:i.value},onClick:()=>f(zo(i.value))},i.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>f(zo(i.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-xs font-semibold whitespace-nowrap text-[#00000066] 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] lg:h-12 lg:w-12",style:{backgroundColor:m},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>f(zn(i.target.value))})})]})}),jsx("div",{className:"absolute -top-4 left-1/2 flex flex-col items-center justify-between px-2",children:jsx("button",{onClick:()=>n(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{size:20,weight:"bold",className:"text-gray-600"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>n(true),className:"fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var _f=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ew=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),_l=e=>{let o=Ew(e);return o.charAt(0).toUpperCase()+o.slice(1)},wn=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),jf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Xf={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var Yf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:n,...l},d)=>createElement("svg",{ref:d,...Xf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:wn("lucide",s),...!r&&!jf(l)&&{"aria-hidden":"true"},...l},[...n.map(([u,m])=>createElement(u,m)),...Array.isArray(r)?r:[r]]));var Ln=(e,o)=>{let t=forwardRef(({className:a,...s},r)=>createElement(Yf,{ref:r,iconNode:o,className:wn(`lucide-${_f(_l(e))}`,`lucide-${e}`,a),...s}));return t.displayName=_l(e),t};var Nw=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Nr=Ln("copy",Nw);var Vw=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Vr=Ln("trash-2",Vw);var Zf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:s,onDuplicate:r,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:s,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:l=>{l.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Nr,{size:14})}),!a&&jsx("button",{onClick:l=>{l.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Vr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var Ww=({softDelete:e=false})=>{let o=at(),t=ct(mo),a=ct(fo),s=ct(yi),[r,n]=useState(true),u=(ct(p=>p.canvas.slides.find(y=>y.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),m=()=>{s&&o(Vn());},f=p=>{o(Un(p));},i=p=>{o(Hn(p));},c=p=>{t.length>1&&o(qn({id:p,softDelete:e}));};return u?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((p,y)=>jsx(Zf,{slide:p,index:y,isSelected:p.id===a,isSingleSlide:t.length===1,onSelect:()=>f(p.id),onDuplicate:()=>i(p.id),onDelete:()=>c(p.id)},p.id))}),jsxs("button",{onClick:m,disabled:!s,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${s?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var zw="SchooplaEditorDB",Gw=1,Da="slides",Ra="metadata",jl="schoopla_current_slide_id",tm="presentation_metadata",qr=()=>new Promise((e,o)=>{let t=indexedDB.open(zw,Gw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Da)||s.createObjectStore(Da,{keyPath:"id"}),s.objectStoreNames.contains(Ra)||s.createObjectStore(Ra,{keyPath:"id"});};}),Xl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await qr(),a=o.transaction([Da],"readwrite").objectStore(Da);await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);});for(let s of e)await new Promise((r,n)=>{let l=a.add(s);l.onsuccess=()=>r(!0),l.onerror=()=>n(l.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},$l=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await qr(),t=e.transaction([Da],"readonly").objectStore(Da);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(l=>({id:l.id,width:l.width,height:l.height,x:l.x,y:l.y}))),a(n.length>0?n:null);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Sn=async()=>{try{let e=await qr(),o=e.transaction([Da,Ra],"readwrite"),t=o.objectStore(Da),a=o.objectStore(Ra);await new Promise((s,r)=>{let n=t.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(jl),localStorage.removeItem("schoopla_presentation_metadata"),await pf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Yl=e=>{try{localStorage.setItem(jl,e);}catch(o){console.error("Error saving current slide ID:",o);}},Jl=()=>{try{return localStorage.getItem(jl)}catch(e){return console.error("Error loading current slide ID:",e),null}},Zl=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Ql=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await qr(),a=o.transaction([Ra],"readwrite").objectStore(Ra);await new Promise((s,r)=>{let n=a.put({id:tm,...e});n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},ed=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await qr(),t=e.transaction([Ra],"readonly").objectStore(Ra);return new Promise((a,s)=>{let r=t.get(tm);r.onsuccess=()=>{e.close();let n=r.result;if(n){let{id:l,...d}=n;console.log("\u2705 Loaded presentation metadata:",d),a(d);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var Kw=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides","canvas/updateSlideThumbnail"],_w=["canvas/clearCanvas"],jw=["canvas/setPresentationTitle","canvas/setPresentationDescription"],Xw=Zl((e,o)=>{Xl(e),Yl(o);},500),$w=Zl(e=>{Ql(e);},500),Yw=(e,o)=>{Xl(e),Yl(o);},td=false,am=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let s=t.payload;Al(s).catch(r=>{console.error("Error deleting video blob:",r);});}if(t.type==="canvas/deleteSlide"&&t.payload){let s=t.payload,n=e.getState().canvas.slides.find(l=>l.id===s);n&&n.videos&&n.videos.length>0&&n.videos.forEach(l=>{Al(l.id).catch(d=>{console.error("Error deleting video blob:",d);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let s=t.payload,r=e.getState(),l=r.canvas.slides.find(d=>d.id===r.canvas.currentSlideId)?.videos.find(d=>d.id===s);l&&l.videoBlob&&setTimeout(()=>{let d=e.getState(),m=d.canvas.slides.find(f=>f.id===d.canvas.currentSlideId)?.videos.find(f=>f.id!==s&&f.x===l.x+20&&f.y===l.y+20);m&&l.videoBlob&&Ja(m.id,l.videoBlob,m.thumbnailDataUrl).catch(f=>{console.error("Error saving duplicated video blob:",f);});},0);}let a=o(t);if(t.type&&_w.includes(t.type)){if(!td){td=true;try{let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;Yw(r,n);}finally{setTimeout(()=>{td=false;},0);}}}else if(t.type&&Kw.includes(t.type)){let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;Xw(r,n);}else if(t.type&&jw.includes(t.type)){let s=e.getState(),{presentationMetadata:r}=s.canvas;$w(r);}return a});new QueryClient;var Qw=configureStore({reducer:{toolbar:qf,canvas:bd},middleware:e=>e({serializableCheck:false}).concat(am)});var eL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2,fileName:r=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",l=e.toDataURL({mimeType:n,quality:a,pixelRatio:s}),d=document.createElement("a");d.download=`${r}.${t}`,d.href=l,document.body.appendChild(d),d.click(),document.body.removeChild(d);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},tL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o;return new Promise((r,n)=>{try{let l=t==="png"?"image/png":"image/jpeg",d=e.toDataURL({mimeType:l,quality:a,pixelRatio:s});fetch(d).then(u=>u.blob()).then(u=>r(u)).catch(u=>n(u));}catch(l){n(l);}})},aL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:s})};var oL=(e,o,t)=>{let a=t.x-o.x,s=t.y-o.y;if(a===0&&s===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+s*s,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*s)/r)),l=o.x+n*a,d=o.y+n*s;return Math.sqrt(Math.pow(e.x-l,2)+Math.pow(e.y-d,2))},ad=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,s=e[0],r=e[e.length-1];for(let n=1;n<e.length-1;n++){let l=oL(e[n],s,r);l>t&&(t=l,a=n);}if(t>o){let n=ad(e.slice(0,a+1),o),l=ad(e.slice(a),o);return [...n.slice(0,-1),...l]}return [s,r]},rL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},sL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},om=(e,o=1.5)=>{if(e.length<=4)return e;let t=rL(e),a=ad(t,o);return sL(a)},rm=(e,o=1.5)=>({...e,points:om(e.points,o)}),nL=(e,o=1.5)=>e.map(t=>rm(t,o)),iL=(e,o)=>{let t=e.length/2,a=o.length/2,s=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${s}%`}};var lL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var sm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:s=.85}=o;return new Promise((r,n)=>{let l=new Image;l.onload=()=>{let{width:d,height:u}=l;if(d>t||u>a){let p=d/u;d>u?(d=Math.min(d,t),u=d/p):(u=Math.min(u,a),d=u*p);}let m=document.createElement("canvas");m.width=d,m.height=u;let f=m.getContext("2d");if(!f){n(new Error("Failed to get canvas context"));return}f.drawImage(l,0,0,d,u);let i=lL(e),c=m.toDataURL(i,s);r(c);},l.onerror=n,l.src=e;})};var ao=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return a.buffer},Go=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Ko=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",dL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:s=1080,imageQuality:r=.85}=o,n=[],l=0;for(let d of e){let u=[],m=[],f=[];for(let i of d.images){let c=i.src;if(t&&c.startsWith("data:"))try{c=await sm(c,{maxWidth:a,maxHeight:s,quality:r});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(c.startsWith("data:")){let p=ao(c),y=Go(c);l+=p.byteLength;let h={id:i.id,x:i.x,y:i.y,width:i.width,height:i.height,draggable:i.draggable,rotation:i.rotation,locked:i.locked,link:i.link,altText:i.altText,zIndex:i.zIndex,buffer:p,mimeType:y};if(i.audioData&&i.audioData.startsWith("data:")){let x=ao(i.audioData),b=Go(i.audioData);l+=x.byteLength,h.audioBuffer=x,h.audioMimeType=b;}u.push(h);}}for(let i of d.videos){let c,p;if(i.videoBlob)c=await i.videoBlob.arrayBuffer(),p=i.videoBlob.type;else if(i.videoData&&i.videoData.startsWith("data:"))c=ao(i.videoData),p=Go(i.videoData);else {console.warn(`Video ${i.id} has no blob or videoData, skipping`);continue}l+=c.byteLength;let y={id:i.id,thumbnailDataUrl:i.thumbnailDataUrl,x:i.x,y:i.y,width:i.width,height:i.height,draggable:i.draggable,isPlaying:i.isPlaying,rotation:i.rotation,locked:i.locked,link:i.link,altText:i.altText,zIndex:i.zIndex,isRecorded:i.isRecorded,buffer:c,mimeType:p};if(i.audioData&&i.audioData.startsWith("data:")){let h=ao(i.audioData),x=Go(i.audioData);l+=h.byteLength,y.audioBuffer=h,y.audioMimeType=x;}m.push(y);}for(let i of d.photoFrames){let c={id:i.id,x:i.x,y:i.y,width:i.width,height:i.height,rotation:i.rotation,draggable:i.draggable,locked:i.locked,link:i.link,altText:i.altText,zIndex:i.zIndex,isCapturing:i.isCapturing};if(i.capturedImageUrl&&i.capturedImageUrl.startsWith("data:")){let p=ao(i.capturedImageUrl),y=Go(i.capturedImageUrl);l+=p.byteLength,c.buffer=p,c.mimeType=y;}if(i.audioData&&i.audioData.startsWith("data:")){let p=ao(i.audioData),y=Go(i.audioData);l+=p.byteLength,c.audioBuffer=p,c.audioMimeType=y;}f.push(c);}n.push({...d,images:u,videos:m,photoFrames:f});}return {slides:n,totalSize:l}},uL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},cL=e=>{let o=new FormData,t=e.slides.map((a,s)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,mimeType:r.mimeType,fileKey:`slide_${s}_image_${n}`,audioFileKey:r.audioBuffer?`slide_${s}_image_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,isPlaying:r.isPlaying,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isRecorded:r.isRecorded,mimeType:r.mimeType,fileKey:`slide_${s}_video_${n}`,thumbnailFileKey:`slide_${s}_video_${n}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${s}_video_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,rotation:r.rotation,draggable:r.draggable,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isCapturing:r.isCapturing,mimeType:r.mimeType,fileKey:r.buffer?`slide_${s}_photoframe_${n}`:void 0,audioFileKey:r.audioBuffer?`slide_${s}_photoframe_${n}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,s)=>{a.images.forEach((r,n)=>{let l=new Blob([r.buffer],{type:r.mimeType}),d=`${r.id}.${Ko(r.mimeType)}`;if(o.append(`slide_${s}_image_${n}`,l,d),r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Ko(r.audioMimeType)}`;o.append(`slide_${s}_image_${n}_audio`,u,m);}}),a.videos.forEach((r,n)=>{let l=new Blob([r.buffer],{type:r.mimeType}),d=`${r.id}.${Ko(r.mimeType)}`;if(o.append(`slide_${s}_video_${n}`,l,d),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let u=ao(r.thumbnailDataUrl),m=new Blob([u],{type:"image/jpeg"}),f=`${r.id}_thumbnail.jpg`;o.append(`slide_${s}_video_${n}_thumbnail`,m,f);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Ko(r.audioMimeType)}`;o.append(`slide_${s}_video_${n}_audio`,u,m);}}),a.photoFrames.forEach((r,n)=>{if(r.buffer&&r.mimeType){let l=new Blob([r.buffer],{type:r.mimeType}),d=`${r.id}.${Ko(r.mimeType)}`;o.append(`slide_${s}_photoframe_${n}`,l,d);}if(r.audioBuffer&&r.audioMimeType){let l=new Blob([r.audioBuffer],{type:r.audioMimeType}),d=`${r.id}_audio.${Ko(r.audioMimeType)}`;o.append(`slide_${s}_photoframe_${n}_audio`,l,d);}});}),o};var pL=()=>{let e=at(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let s=await $l(),r=Jl(),n=await ed();if(s&&s.length>0){let l=await mf(),d=s.map(m=>{if(m.videos&&m.videos.length>0){let f=m.videos.map(i=>{let c=l.get(i.id);if(c){let p=hf(c.blob);return {...i,objectUrl:p,thumbnailDataUrl:c.thumbnailDataUrl,videoBlob:c.blob}}else return i});return {...m,videos:f}}return m}),u=r&&d.find(m=>m.id===r)?r:d[0].id;e(io({slides:d,currentSlideId:u}));}e(n?bi({title:n.title,description:n.description}):ks(!0));}catch(s){console.error("Error loading persisted slides:",s),e(ks(true));}finally{t(false);}})();},[e]),{isLoading:o}};var im=e=>e.map(o=>({...o,lines:o.lines||[],shapes:o.shapes||[],images:o.images||[],videos:o.videos||[],flashcards:o.flashcards||[],photoFrames:o.photoFrames||[],texts:o.texts||[],multipleChoices:o.multipleChoices||[],trueFalses:o.trueFalses||[],shortAnswers:o.shortAnswers||[],LongAnswer:o.LongAnswer||[],fillInTheBlanks:o.fillInTheBlanks||[],createdAt:o.createdAt||Date.now(),updatedAt:o.updatedAt||Date.now(),showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,activityType:o.activityType||""})),lm=new WeakSet,dm=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await Ja(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},hL=()=>{let e=at(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||lm.has(a))return;lm.add(a);let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Sn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(u){console.error("Error clearing local data:",u);}let l=r&&s.find(u=>u.id===r)?r:s[0].id,d=im(s);e(io({slides:d,currentSlideId:l})),await dm(d);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Sn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(u){console.error("Error clearing local data:",u);}let l=r&&s.find(u=>u.id===r)?r:s[0].id,d=im(s);e(io({slides:d,currentSlideId:l})),await dm(d);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
|
|
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{Ky as BASIC_EDITOR_TOOLBAR_CONFIG,Rw as BottomToolbar,Rb as Canvas,zy as DEFAULT_CONTEXT_MENU_CONFIG,xn as DEFAULT_TOOLBAR_CONFIG,Yh as EditorRoot,Gl as PublishButton,dr as ScreenRecorder,Ww as SlideNavigation,yw as Toolbar,Cw as TopNavBar,Gy as VIEWER_TOOLBAR_CONFIG,ni as addFillInTheBlanks,Xn as addFlashcard,Kn as addImage,Qn as addImageAnnotation,Gn as addLine,si as addLongAnswer,ai as addMultipleChoice,Jn as addPhotoFrame,ti as addPhotoFrameAnnotation,_n as addShape,ri as addShortAnswer,Vn as addSlide,jn as addText,oi as addTrueFalse,Qr as addVideo,uL as arrayBufferToBase64,li as bringToFront,mi as clearCanvas,zm as clearImageAnnotations,Sn as clearLocalData,Km as clearPhotoFrameAnnotations,Nn as createEmptySlide,vs as deleteFillInTheBlanks,is as deleteFlashcard,Jr as deleteImage,Cs as deleteLineById,xs as deleteLongAnswer,cs as deleteMultipleChoice,ds as deletePhotoFrame,rs as deleteShape,hs as deleteShortAnswer,qn as deleteSlide,ss as deleteText,ms as deleteTrueFalse,ts as deleteVideo,ys as duplicateFillInTheBlanks,ls as duplicateFlashcard,Zr as duplicateImage,fi as duplicateLine,bs as duplicateLongAnswer,fs as duplicateMultipleChoice,us as duplicatePhotoFrame,os as duplicateShape,gs as duplicateShortAnswer,Hn as duplicateSlide,ns as duplicateText,ps as duplicateTrueFalse,as as duplicateVideo,Xo as editFlashcard,_m as editMultipleChoice,tL as exportSlideAsBlob,eL as exportSlideAsImage,ci as finalizeDrawing,iL as getCompressionStats,aL as getSlideDataURL,Jl as loadCurrentSlideId,$l as loadFromIndexedDB,bi as loadPresentationMetadata,ed as loadPresentationMetadataFromDB,io as loadSlides,ql as mergeToolbarConfig,$n as nextFlashcard,cL as prepareFormData,dL as prepareSlidesForPublishing,Yn as previousFlashcard,hi as redo,Yr as removeLine,Um as reorderSlides,Ql as savePresentationMetadata,ce as saveToHistory,mo as selectAllSlides,vi as selectAllSlidesIncludingInactive,yi as selectCanAddSlide,he as selectCurrentSlide,fo as selectCurrentSlideId,wi as selectMetadataLoaded,tr as selectPresentationMetadata,Jm as selectSlideById,di as sendToBack,ii as setActivityType,Ls as setAltText,Ss as setAudioData,zn as setBackgroundColor,Un as setCurrentSlide,Zo as setEditingActivity,er as setEditingTextId,Xm as setLines,ws as setLink,ks as setMetadataLoaded,zo as setPenColor,xi as setPresentationDescription,gi as setPresentationTitle,Oa as setShowFlashcardForm,ma as setShowMcqForm,ft as setSketchMode,Fr as setStrokeWidth,zt as setTool,om as simplifyFlatPoints,rm as simplifyLine,nL as simplifyLines,Qw as store,Zn as toggleImageDrawingMode,ui as toggleLock,ei as togglePhotoFrameDrawingMode,Ym as toggleSketchMode,jo as toggleVideoPlaying,pi as undo,Qo as updateElementOrder,Jo as updateFillInTheBlanks,co as updateFlashcard,lo as updateImage,Wm as updateImageAnnotation,jm as updateLastLine,$m as updateLinePosition,Is as updateLineTransform,Yo as updateLongAnswer,ca as updateMultipleChoice,Ba as updatePhotoFrame,Gm as updatePhotoFrameAnnotation,uo as updateShape,$o as updateShortAnswer,Wn as updateSlideThumbnail,It as updateText,fa as updateTrueFalse,es as updateVideo,xe as useDispatch,hL as useInitialSlides,Wi as useModalPortal,Q as useSelector,pL as useSlidesPersistence};//# sourceMappingURL=index.js.map
|
|
22
22
|
//# sourceMappingURL=index.js.map
|