@turnix-co/konva-editor 3.0.13 → 3.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- export{default as Konva}from'konva';import*as be from'react';import be__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,useState,useMemo,createElement,useId,useLayoutEffect}from'react';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,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),tt=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 y=t.LongAnswer.find(x=>x.id===a);y&&(y.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:ua,editMultipleChoice:Wm,deleteMultipleChoice:us,duplicateMultipleChoice:cs,addTrueFalse:ai,updateTrueFalse:ca,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:fa,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(y=>y.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),y=useRef(t),h=useRef(a),b=useRef(r),x=useRef(s),g=useRef(i),S=useRef(l);useEffect(()=>{y.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 v=L.getContext("2d");v&&v.clearRect(0,0,L.width,L.height);},[]),C=useCallback(()=>{let L=f.current,v=m.current;if(!L||v.length<1)return;let T=L.getContext("2d");if(!T)return;if(T.clearRect(0,0,L.width,L.height),y.current==="eraser"?(T.globalCompositeOperation="destination-out",T.fillStyle="rgba(0,0,0,1)"):(T.globalCompositeOperation="source-over",T.fillStyle=h.current),v.length===1){T.beginPath(),T.arc(v[0].x,v[0].y,b.current/2,0,Math.PI*2),T.fill();return}let D=wd(v,{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)){T.beginPath(),T.moveTo(D[0][0],D[0][1]);for(let q=1;q<D.length;q++)T.lineTo(D[q][0],D[q][1]);T.closePath(),T.fill();}},[]);return useImperativeHandle(d,()=>({startDrawing:L=>{u.current=true;let v={x:L.x-g.current,y:L.y-S.current};c.current=[{x:L.x,y:L.y}],m.current=[v],p.current=L,C();},draw:L=>{if(!u.current||!p.current)return;let v=L.x-p.current.x,T=L.y-p.current.y;if(Math.sqrt(v*v+T*T)<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 v=wd(c.current,{size:b.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:V=>V,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(V=>[V[0],V[1]]),T={tool:y.current,points:v,color:h.current,strokeWidth:b.current,isSketch:true};return c.current=[],m.current=[],p.current=null,k(),T},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(y=>y.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(),y=c.scaleY(),h=c.rotation(),b=m.width(),x=m.height(),g=Math.max(5,b*p),S=Math.max(5,x*y);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(ua({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(ua({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(ca({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(ca({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),y=Math.max(5,f.height()*c);f.scaleX(1),f.scaleY(1),f.width(p),f.height(y),o(Qr({id:l,width:p,height:y,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(),y=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()*y),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()*y/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=y,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=tt(),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,v=(S-L)/C,T=(k-L)/C,V=l.split(`
3
- `).length,q=r.find(W=>W.id===n)?.fontSize||24,A=V*q*1.2+10;x.width=Math.max(200,v),x.height=Math.max(50,T,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(),y=m.scaleY(),h=m.rotation(),b=Math.max(50,m.width()*p),x=Math.max(50,m.height()*y);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 y=p.target,h=y.scaleX(),b=y.scaleY(),x=y.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);y.scaleX(1),y.scaleY(1),o(Fa({id:m,width:S,height:k,x:y.x(),y:y.y(),rotation:x})),y.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(y=>{let h=new Map(y);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(y=>y.stop()),n(y=>{let h=new Map(y);return h.delete(m),h}),o(Fa({id:m,isCapturing:false})),e?.());},[s,o,e]),u=useCallback((m,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 b=y.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(y=>y.id===s)?.isPlaying){let y=n.get(s)||i.get(s)||l.get(s)||d.get(s)||f.get(s)||(u?u.get(s):null);if(y){e.current.boundBoxFunc(t),e.current.nodes([y]),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=tt(),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,y=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/y;n({tool:i,points:[S,k],color:l,strokeWidth:d/p,isSketch:f});},[i,l,d,f,p,y]),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((v,T)=>T%2===0?v/p:v/y);else {let L=g.x/p,v=g.y/y;C=[...s.points,L,v];}n(L=>L?{...L,points:C}:null);},[f,d,s,p,y]),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 y=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:y,onTap:y,onMouseDown:y,onTouchStart:y,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(y=>y.toolbar.selectedTool),f=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let y=new window.Image;y.src=e.thumbnailDataUrl,y.onload=()=>{l(y);};}},[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:y=>{if(n(y),y){let h=y.getStage()?.container();if(h){let b=x=>{let g=y.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),y._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 y=p.evt;s(y,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)),y=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:r,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:y+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-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"})]})},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,y=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/y;n({tool:"pen",points:[S,k],color:l,strokeWidth:d/p,isSketch:f});},[m,l,d,f,p,y]),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((v,T)=>T%2===0?v/p:v/y);else {let L=g.x/p,v=g.y/y;C=[...s.points,L,v];}n(L=>L?{...L,points:C}:null);},[f,d,s,p,y]),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),y=useRef(null),h=useRef(null),b=useRef(null),x=useRef(0),g=33,S=useSelector(N=>N.toolbar.selectedTool),k=S==="pen"||S==="eraser",{annotations:C,activeLine:L,isDrawingMode:v,startDrawing:T,draw:V,stopDrawing:D}=iu(e.id);useEffect(()=>{if(!v)return;let N=()=>{D();},_=()=>{D();};return window.addEventListener("mouseup",N),window.addEventListener("touchend",_),()=>{window.removeEventListener("mouseup",N),window.removeEventListener("touchend",_);}},[D,v]),useEffect(()=>{if(e.capturedImageUrl){let N=new window.Image;N.src=e.capturedImageUrl,N.onload=()=>{u(N);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&l){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),y.current||(y.current=document.createElement("canvas"));let N=p.current,_=y.current;N.srcObject=l;let H=()=>{_.width=N.videoWidth||640,_.height=N.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&&N.readyState===N.HAVE_ENOUGH_DATA){Z.drawImage(N,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 N.onloadedmetadata=H,N.readyState>=N.HAVE_METADATA&&H(),N.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=N=>{if(e.capturedImageUrl){if(!v){t();return}let _=N.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);T(Z);}N.cancelBubble=true;}else t();},A=N=>{if(!v||!e.capturedImageUrl)return;let _=N.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);V(Z);}},W=()=>{!v||!e.capturedImageUrl||D();},E=e.isCapturing?c:f,ne=Math.min(e.width,e.height)*.12,O=Math.max(25,Math.min(ne,50)),re=e.width/2,G=e.height/2;return jsxs(Group,{id:e.id,draggable:!v&&!k,listening:true,x:e.x,y:e.y,...k?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:N=>{if(d(N),N){let _=N.getStage()?.container();if(_){let H=K=>{let te=N.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),N._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((N,_)=>{let H=N.points.map((te,Z)=>Z%2===0?te*e.width:te*e.height),K=N.strokeWidth*e.width;return jsx(Line,{points:H,stroke:N.tool==="eraser"?"white":N.color,strokeWidth:K,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:N.tool==="eraser"?"destination-out":"source-over",fill:N.isSketch?N.color:void 0,closed:N.isSketch,listening:false},_)}),L&&jsx(Line,{points:L.points.map((N,_)=>_%2===0?N*e.width:N*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-O+6,y:G-60,width:O*1.6,height:O*1.6,radius:O,fill:"white",cornerRadius:8,listening:true,onClick:N=>{N.cancelBubble=true,e.isCapturing?q():n();},onTap:N=>{N.cancelBubble=true,e.isCapturing?q():n();}}),jsx(Html,{groupProps:{x:re-12,y:G-40,width:O*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:N=>{N.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:O*1.6,height:O*1.6,radius:O,fill:"#096B76",cornerRadius:O,listening:true,onClick:N=>{N.cancelBubble=true,e.isCapturing?q():n();},onTap:N=>{N.cancelBubble=true,e.isCapturing?q():n();}}),jsx(Html,{groupProps:{x:re-8,y:G+120,width:O*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:N=>{N.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:N=>{N.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:"fixed inset-0 z-102 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=y=>{let h=(y+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:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:s,className:"pointer-events-auto max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change 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,y=(n.height-m)/2;return {x:p,y,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:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:a,className:"pointer-events-auto max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$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,y=r.width/c,h=r.height/c,b=document.createElement("canvas");b.width=y,b.height=h;let x=b.getContext("2d");if(!x)return;x.drawImage(n,m,p,y,h,0,0,y,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),y=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),y.current&&y.current.getTracks().forEach(v=>v.stop());},[]);let S=async()=>{try{let v,T=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..."),v=W.captureStream(30),console.log("Canvas stream created, tracks:",v.getTracks().length);let re=v.getVideoTracks()[0];re&&console.log("Video track:",re.label,"state:",re.readyState);let G=0,N=()=>{ne(),o?.current&&(o.current.getLayers().forEach(H=>{H.batchDraw();}),G++,G%60===0&&console.log("Drawing frame:",G)),h.current=requestAnimationFrame(N);};N();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{T=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(A){console.warn("Microphone access denied:",A);}let V=[...v.getVideoTracks()];T&&V.push(...T.getAudioTracks());let D=new MediaStream(V);y.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(v){console.error("Error starting screen recording:",v),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 v=URL.createObjectURL(n),T=document.createElement("a");T.href=v,T.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(v);}},L=v=>{let T=Math.floor(v/60),V=v%60;return `${T.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return r?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children: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([]),y=useRef(null),h=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(v=>v.blob()).then(v=>l(v)).catch(v=>console.error("Error loading audio:",v));},[o,i]);let b=async()=>{try{let v=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),T=new MediaRecorder(v);m.current=T,p.current=[],T.ondataavailable=V=>{V.data.size>0&&p.current.push(V.data);},T.onstop=()=>{let V=new Blob(p.current,{type:"audio/webm"});l(V),v.getTracks().forEach(D=>D.stop()),y.current&&clearInterval(y.current);},T.start(),n(!0),c(0),y.current=setInterval(()=>{c(V=>V+1);},1e3);}catch(v){console.error("Error starting audio recording:",v),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{m.current&&s&&(m.current.stop(),n(false));},g=()=>{if(i){let v=URL.createObjectURL(i),T=new Audio(v);h.current=T,T.onended=()=>{f(false),URL.revokeObjectURL(v);},T.play(),f(true);}},S=()=>{h.current&&(h.current.pause(),h.current.currentTime=0,f(false));},k=async()=>{if(i){let v=new FileReader;v.onloadend=()=>{let T=v.result;t(T),r();},v.readAsDataURL(i);}},C=()=>{l(null),a();},L=v=>{let T=Math.floor(v/60),V=v%60;return `${T.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return s?createPortal(jsxs("div",{className:"fixed top-[100px] left-1/2 z-103 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children: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"]})]}),document.body):createPortal(jsx("div",{className:"fixed inset-0 z-103 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!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"})]})]})}),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=y=>{if(y.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}));});},y=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9998 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-9999 w-96 -translate-x-1/2 -translate-y-1/2 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(y,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 y=new Set(e.data.responseOptions.correctIndex),h=y.size>1,b=G=>{f||d(h?N=>{let _=new Set(N);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===y.size&&Array.from(l).every(G=>y.has(G)),k=Array.from(l).filter(G=>y.has(G)),C=h&&k.length>0&&!S,L=()=>S?"\u2713 Correct! Great job! \u{1F389}":C?`\u26A0 Partially correct (${k.length}/${y.size})`:"\u2717 Try again!",v=()=>S?{bg:"#dcfce7",text:"#166534"}:C?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},T=55,V=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),O=e.data.responseOptions.options.length*(T+V),re=ne+O+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 ${y.size} answers (${l.size}/${y.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:v().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:v().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((G,N)=>{let _=y.has(N),H=l.has(N),K=ne+N*(T+V),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+(T-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(N);},onTap:le=>{le.cancelBubble=true,b(N);}}),H&&jsx(Text,{x:D+12,y:K+(T-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:T,fill:Z,stroke:te,strokeWidth:2,cornerRadius:8,onClick:le=>{le.cancelBubble=true,b(N);},onTap:le=>{le.cancelBubble=true,b(N);}}),jsx(Text,{x:D+60,y:K,width:e.width-D*2-80,height:T,text:G,fontSize:16,fill:J,verticalAlign:"middle",listening:false})]},N)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:ne+e.data.responseOptions.options.length*(T+V)+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,y]=useState(false),[h,b]=useState(0),x=340,g=100,S=window.innerWidth*.4,k=window.innerHeight*.5,C=x+20,L=g+60,v=S-40,T=k-300,V=useRef(null);useEffect(()=>{let H=V.current;if(H)return r.current.set(e.id,H),()=>{r.current.delete(e.id);}},[e.id]);let D=H=>{s(ua({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+v&&Z+50>L&&Z<L+T;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+v&&J+50>L&&J<L+T;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)),O=Array.from(f).filter(H=>E.has(H)),re=O.length>0&&!ne,G=()=>ne?"\u2713 Correct! Great job!":re?`\u26A0 Partially correct (${O.length}/${E.size})`:"\u2717 Try again!",N=()=>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:V,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:v,height:T,fill:"#EBF6F7",stroke:_(),strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:T+18,width:v-5,height:60,fill:N().bg,cornerRadius:8}),jsx(Text,{x:20,y:T+20,width:v,height:60,text:G(),fontSize:18,fontStyle:"bold",fill:N().text,align:"center",verticalAlign:"middle"})]}),f.size===0&&!c&&jsx(Text,{x:20,y:60,width:v,height:T-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:()=>{y(true),A();},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{y(true),A();},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})]}),c&&jsxs(Group,{y:50,onMouseDown:W,onTouchStart:W,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=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 y=()=>{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,v=24,T=60,V=60,D=e.data.feedbackMode==="practice"?48:0,q=12,U=T+(f?V:0),A=2*(C+L),W=U+A+q+D+v;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:v,y:v,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-v*2,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:v,y:T,width:e.width-v*2,height:V-10,fill:k().bg,cornerRadius:8}),jsx(Text,{x:v,y:T,width:e.width-v*2,height:V-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 O=b===E.value,re=l===E.value,G=(e.width-v*3)/2,N=v+ne*(G+v),_=U,H=E.value===true,K=H?"#10b981":"#ef4444",te="#ffffff",Z="#ffffff",J="#e5e7eb";return f&&(O?(Z=H?"#f0fdf4":"#fef2f2",J=H?"#86efac":"#fecaca"):re&&!O&&(Z="#fee2e2",J="#ef4444")),re&&!f&&(J="#096B76",Z="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:N,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:N+G/2,y:_+40,radius:28,fill:K,listening:false}),H?jsx(Text,{x:N+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:N+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:N,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),y();},onMouseLeave:E=>{E.cancelBubble=true,m(null);},onTouchStart:E=>{E.cancelBubble=true,m("check");},onTouchEnd:E=>{E.cancelBubble=true,m(null),y();},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:v,width:(e.width-v*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:v,width:(e.width-v*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-v*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:v,width:(e.width-v*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.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})]})]})]})});Du.displayName="TrueFalse";var Ru=Du;var ox="#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,y]=useState(0),[h,b]=useState(false),x=340,g=100,S=window.innerWidth*.4,k=window.innerHeight*.5,C=S-40,L=k-300,v=20,T=60,V=C,D=L,q=S*.2-40,U=50,A=useRef(null),W=K=>{a(ca({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,v+V)-Math.max(Z,v)),Ie=Math.max(0,Math.min(J+U,T+D)-Math.max(J,T)),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,v+V)-Math.max(J,v)),Y=Math.max(0,Math.min(le+U,T+D)-Math.max(le,T)),Me=Ie*Y,Be=q*U;if(Me/Be>=.5)d(K);else return;i(false);},O=()=>{u(true);},re=()=>{u(false),d(null),y(K=>K+1);},G=e.data.responseOptions.correctAnswer,N=l===G,_=()=>N?"\u2713 Correct! Great job!":"\u2717 Try again!",H=()=>N?{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),O());},onMouseUp:()=>m(false),onMouseLeave:()=>m(false),onTouchStart:()=>{l!==null&&(m(true),O());},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:ox,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 nx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function ix(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,nx(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)ix(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 lx(e){return typeof e=="function"}function Yi(e,...o){return lx(e)?e(...o):e}function Ou(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var xa,rt,Qe,hr,ba,qa,Jt,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,Qe);Pe(this,hr);Pe(this,ba);Pe(this,qa);Pe(this,Jt);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,Qe).call(this).removeEventListener("tanstack-connect-success",j(this,xr));});Pe(this,Mo,()=>{if(j(this,Qe).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,Qe).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,Qe,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,Jt,null),Ce(this,ko,r);}startConnectLoop(){j(this,Jt)!==null||j(this,qa)||(this.debugLog(`Starting connect loop (every ${j(this,ko)}ms)`),Ce(this,Jt,setInterval(j(this,Mo),j(this,ko))));}stopConnectLoop(){j(this,Jt)!==null&&(clearInterval(j(this,Jt)),Ce(this,Jt,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,Qe).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{j(this,Qe).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,Qe).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{j(this,Qe).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,Qe).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,Qe).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,Qe).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,Qe).call(this).removeEventListener("tanstack-devtools-global",t)}};xa=new WeakMap,rt=new WeakMap,Qe=new WeakMap,hr=new WeakMap,ba=new WeakMap,qa=new WeakMap,Jt=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 dx={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={...dx,...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 ux=/^(\d+)$/gm,cx=/\.(\d+)(?=\.)/gm,fx=/^(\d+)\./gm,mx=/\.(\d+$)/gm,px=/\.{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(ux,zs).replace(cx,`.${zs}.`).replace(fx,`${zs}.`).replace(mx,`.${zs}`).replace(px,".").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 hx(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=hx(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 y=a(u,c,m,p);({insert:()=>i(y,u,c),remove:()=>l(y),swap:()=>p!==void 0&&f(y,u,c,p),move:()=>p!==void 0&&d(y,u,c,p)})[m]();}function t(u,c){return `${u}[${c}]`}function a(u,c,m,p){let y=[t(u,c)];if(m==="swap")y.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++)y.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++)y.push(t(u,x));}return Object.keys(e.fieldInfo).filter(h=>y.some(b=>h.startsWith(b)))}function r(u,c){return u.replace(/\[(\d+)\]/,(m,p)=>{let y=parseInt(p,10);return `[${c==="up"?y+1:Math.max(0,y-1)}]`})}function s(u,c){(c==="up"?u:[...u].reverse()).forEach(p=>{let y=r(p.toString(),c),h=e.getFieldMeta(y);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 y=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=y.get(b);x&&e.setFieldMeta(h,x);});},f=(u,c,m,p)=>{u.forEach(y=>{if(!y.toString().startsWith(t(c,m)))return;let h=y.toString().replace(t(c,m),t(c,p)),[b,x]=[e.getFieldMeta(y),e.getFieldMeta(h)];b&&e.setFieldMeta(h,b),x&&e.setFieldMeta(y,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 y=this.getFieldMeta(p);if(!y)continue;let{errorMap:h,errorSourceMap:b}=y,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:y,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:v}=js({newFormValidatorError:C,isPreviousErrorFromFormValidator:k?.[b]==="form",previousErrorValue:S?.[b]});S?.[b]!==L&&this.setFieldMeta(x,T=>({...T,errorMap:{...T.errorMap,[b]:L},errorSourceMap:{...T.errorSourceMap,[b]:v}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.errorMap,[b]:y}})),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],y=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(y,wa(this.options.defaultValues,u))||Sa(y,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),y=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,v=this.options.canSubmitWhenInvalid??false,T=l.submissionAttempts===0&&!m&&!g||!S&&!l.isSubmitting&&L||v,V=l.errorMap;if(h&&(k=k.filter(A=>A!==l.errorMap.onMount),V=Object.assign(V,{onMount:void 0})),n&&i&&n.errorMap===V&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===k&&n.isFieldsValidating===u&&n.isFieldsValid===c&&n.isFormValid===C&&n.isValid===L&&n.canSubmit===T&&n.isTouched===m&&n.isBlurred===p&&n.isPristine===x&&n.isDefaultValue===y&&n.isDirty===b&&Sa(i,l))return n;let D={...l,errorMap:V,fieldMeta:this.fieldMetaDerived.state,errors:k,isFieldsValidating:u,isFieldsValid:c,isFormValid:C,isValid:L,canSubmit:T,isTouched:m,isBlurred:p,isPristine:x,isDefaultValue:y,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&&gt.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:y,newSource:h}=Xs({formLevelError:p,fieldLevelError:m});f.state.meta.errorMap?.[c]!==y&&f.setMeta(b=>({...b,errorMap:{...b.errorMap,[c]:y},errorSourceMap:{...b.errorSourceMap,[c]:h}})),y&&(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(y=>{y.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 y=Js(m.cause);c.getInfo().validationMetaMap[y]?.lastAbortController.abort();let b=new AbortController;this.getInfo().validationMetaMap[y]={lastAbortController:b},p.push(new Promise(async x=>{let g;try{g=await new Promise((v,T)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(b.signal.aborted)return v(void 0);try{v(await this.runValidator({validate:m.validate,value:{value:c.store.state.value,fieldApi:c,signal:b.signal,validationSource:"field"},type:"validateAsync"}));}catch(V){T(V);}},m.debounceMs);});}catch(v){g=v;}if(b.signal.aborted)return x(void 0);let S=Hu(g),k=s[this.name]?.[y],{newErrorValue:C,newSource:L}=Xs({formLevelError:k,fieldLevelError:S});c.setMeta(v=>({...v,errorMap:{...v?.errorMap,[y]:C},errorSourceMap:{...v.errorSourceMap,[y]: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,xx)}function xx(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 Ix(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=Ix(o),a=useMemo(()=>ya(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Mx({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(Mx,{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 Nx=({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?ca(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?ua(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(fa(false));}}),d=()=>{o(fa(false));},f=jsx("div",{className:"fixed inset-0 z-106 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-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});},y=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:()=>y(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=Nx;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 y of c){u.textContent=y||" ";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 y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===y,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,v=50,T=12,V=e.data.feedbackMode==="practice"?48:0,D=12,q=30,U=k+C+q+v+T+D+V+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:v+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:`${v}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+v+T+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(v=>v.toolbar.selectedTool),i=n==="pen"||n==="eraser",l=useRef(null),[d,f]=useState(""),[u,c]=useState(false),[m,p]=useState(null);useEffect(()=>{let v=l.current;if(v)return s.current.set(e.id,v),()=>{s.current.delete(e.id);}},[e.id,s]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===y,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 v=Mt,T=v;v+=60;let V=v;v+=35;let D=v;v+=cl+16;let q=v;u&&(v+=tn+16);let U=v;return k&&(v+=Tr),v+=Mt,{questionY:T,helperTextY:V,inputY:D,feedbackY:q,buttonsY:U,totalHeight:v}},[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:v=>a(v,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:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,r?.(v.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:v=>f(v.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:v=>{v.cancelBubble=true,p("reset");},onMouseUp:v=>{v.cancelBubble=true,p(null),b();},onMouseLeave:v=>{v.cancelBubble=true,p(null);},onTouchStart:v=>{v.cancelBubble=true,p("reset");},onTouchEnd:v=>{v.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:v=>{v.cancelBubble=true,p("submit");},onMouseUp:v=>{v.cancelBubble=true,p(null),x();},onMouseLeave:v=>{v.cancelBubble=true,p(null);},onTouchStart:v=>{v.cancelBubble=true,p("submit");},onTouchEnd:v=>{v.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 y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===y,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,v=12,T=48,V=12,D=30,q=k+C+D+L+v+V+T+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+v,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,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"),Bm={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:Bm,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 y=t.LongAnswer.find(x=>x.id===a);y&&(y.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:Om,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:Nm,clearImageAnnotations:Vm,togglePhotoFrameDrawingMode:Qn,addPhotoFrameAnnotation:ei,updatePhotoFrameAnnotation:qm,clearPhotoFrameAnnotations:Hm,addMultipleChoice:ti,updateMultipleChoice:ua,editMultipleChoice:Um,deleteMultipleChoice:us,duplicateMultipleChoice:cs,addTrueFalse:ai,updateTrueFalse:ca,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:fa,setShowFlashcardForm:Ba,setActivityType:ni,setEditingActivity:Jo,bringToFront:ii,sendToBack:li,toggleLock:di,setLink:ys,setAltText:ws,setAudioData:Ss,updateLastLine:Wm,finalizeDrawing:ui,setLines:zm,updateLinePosition:Gm,updateLineTransform:Ls,deleteLineById:Is,duplicateLine:ci,updateElementOrder:Zo,clearCanvas:fi,undo:mi,redo:pi,saveToHistory:ce,toggleSketchMode:Km,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),_m=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(y=>y.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),y=useRef(t),h=useRef(a),b=useRef(r),x=useRef(s),g=useRef(i),S=useRef(l);useEffect(()=>{y.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 v=L.getContext("2d");v&&v.clearRect(0,0,L.width,L.height);},[]),C=useCallback(()=>{let L=f.current,v=m.current;if(!L||v.length<1)return;let T=L.getContext("2d");if(!T)return;if(T.clearRect(0,0,L.width,L.height),y.current==="eraser"?(T.globalCompositeOperation="destination-out",T.fillStyle="rgba(0,0,0,1)"):(T.globalCompositeOperation="source-over",T.fillStyle=h.current),v.length===1){T.beginPath(),T.arc(v[0].x,v[0].y,b.current/2,0,Math.PI*2),T.fill();return}let D=wd(v,{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)){T.beginPath(),T.moveTo(D[0][0],D[0][1]);for(let q=1;q<D.length;q++)T.lineTo(D[q][0],D[q][1]);T.closePath(),T.fill();}},[]);return useImperativeHandle(d,()=>({startDrawing:L=>{u.current=true;let v={x:L.x-g.current,y:L.y-S.current};c.current=[{x:L.x,y:L.y}],m.current=[v],p.current=L,C();},draw:L=>{if(!u.current||!p.current)return;let v=L.x-p.current.x,T=L.y-p.current.y;if(Math.sqrt(v*v+T*T)<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 v=wd(c.current,{size:b.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:V=>V,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(V=>[V[0],V[1]]),T={tool:y.current,points:v,color:h.current,strokeWidth:b.current,isSketch:true};return c.current=[],m.current=[],p.current=null,k(),T},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(y=>y.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(),y=c.scaleY(),h=c.rotation(),b=m.width(),x=m.height(),g=Math.max(5,b*p),S=Math.max(5,x*y);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(ua({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(ua({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(ca({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(ca({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),y=Math.max(5,f.height()*c);f.scaleX(1),f.scaleY(1),f.width(p),f.height(y),o(Qr({id:l,width:p,height:y,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(),y=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()*y),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()*y/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=y,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,v=(S-L)/C,T=(k-L)/C,V=l.split(`
3
+ `).length,q=r.find(W=>W.id===n)?.fontSize||24,A=V*q*1.2+10;x.width=Math.max(200,v),x.height=Math.max(50,T,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(),y=m.scaleY(),h=m.rotation(),b=Math.max(50,m.width()*p),x=Math.max(50,m.height()*y);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 y=p.target,h=y.scaleX(),b=y.scaleY(),x=y.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);y.scaleX(1),y.scaleY(1),o(Fa({id:m,width:S,height:k,x:y.x(),y:y.y(),rotation:x})),y.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(y=>{let h=new Map(y);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(y=>y.stop()),n(y=>{let h=new Map(y);return h.delete(m),h}),o(Fa({id:m,isCapturing:false})),e?.());},[s,o,e]),u=useCallback((m,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 b=y.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(y=>y.id===s)?.isPlaying){let y=n.get(s)||i.get(s)||l.get(s)||d.get(s)||f.get(s)||(u?u.get(s):null);if(y){e.current.boundBoxFunc(t),e.current.nodes([y]),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 yp=(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=yp(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var Sp=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 Sp(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,y=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/y;n({tool:i,points:[S,k],color:l,strokeWidth:d/p,isSketch:f});},[i,l,d,f,p,y]),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((v,T)=>T%2===0?v/p:v/y);else {let L=g.x/p,v=g.y/y;C=[...s.points,L,v];}n(L=>L?{...L,points:C}:null);},[f,d,s,p,y]),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 y=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:y,onTap:y,onMouseDown:y,onTouchStart:y,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 Rp=({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=Rp;var Hp=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,nodeRef:n})=>{let[i,l]=useState(null),d=useSelector(y=>y.toolbar.selectedTool),f=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let y=new window.Image;y.src=e.thumbnailDataUrl,y.onload=()=>{l(y);};}},[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:y=>{if(n(y),y){let h=y.getStage()?.container();if(h){let b=x=>{let g=y.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),y._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=Hp;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 y=p.evt;s(y,f.id,"text");}}},f.id)})})};var ch=({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)),y=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:r,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:y+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-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"})]})},su=ch;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,y=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/y;n({tool:"pen",points:[S,k],color:l,strokeWidth:d/p,isSketch:f});},[m,l,d,f,p,y]),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((v,T)=>T%2===0?v/p:v/y);else {let L=g.x/p,v=g.y/y;C=[...s.points,L,v];}n(L=>L?{...L,points:C}:null);},[f,d,s,p,y]),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 vh=({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),y=useRef(null),h=useRef(null),b=useRef(null),x=useRef(0),g=33,S=useSelector(N=>N.toolbar.selectedTool),k=S==="pen"||S==="eraser",{annotations:C,activeLine:L,isDrawingMode:v,startDrawing:T,draw:V,stopDrawing:D}=iu(e.id);useEffect(()=>{if(!v)return;let N=()=>{D();},_=()=>{D();};return window.addEventListener("mouseup",N),window.addEventListener("touchend",_),()=>{window.removeEventListener("mouseup",N),window.removeEventListener("touchend",_);}},[D,v]),useEffect(()=>{if(e.capturedImageUrl){let N=new window.Image;N.src=e.capturedImageUrl,N.onload=()=>{u(N);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&l){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),y.current||(y.current=document.createElement("canvas"));let N=p.current,_=y.current;N.srcObject=l;let H=()=>{_.width=N.videoWidth||640,_.height=N.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&&N.readyState===N.HAVE_ENOUGH_DATA){Z.drawImage(N,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 N.onloadedmetadata=H,N.readyState>=N.HAVE_METADATA&&H(),N.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=N=>{if(e.capturedImageUrl){if(!v){t();return}let _=N.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);T(Z);}N.cancelBubble=true;}else t();},A=N=>{if(!v||!e.capturedImageUrl)return;let _=N.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);V(Z);}},W=()=>{!v||!e.capturedImageUrl||D();},E=e.isCapturing?c:f,ne=Math.min(e.width,e.height)*.12,O=Math.max(25,Math.min(ne,50)),re=e.width/2,G=e.height/2;return jsxs(Group,{id:e.id,draggable:!v&&!k,listening:true,x:e.x,y:e.y,...k?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:N=>{if(d(N),N){let _=N.getStage()?.container();if(_){let H=K=>{let te=N.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),N._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((N,_)=>{let H=N.points.map((te,Z)=>Z%2===0?te*e.width:te*e.height),K=N.strokeWidth*e.width;return jsx(Line,{points:H,stroke:N.tool==="eraser"?"white":N.color,strokeWidth:K,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:N.tool==="eraser"?"destination-out":"source-over",fill:N.isSketch?N.color:void 0,closed:N.isSketch,listening:false},_)}),L&&jsx(Line,{points:L.points.map((N,_)=>_%2===0?N*e.width:N*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-O+6,y:G-60,width:O*1.6,height:O*1.6,radius:O,fill:"white",cornerRadius:8,listening:true,onClick:N=>{N.cancelBubble=true,e.isCapturing?q():n();},onTap:N=>{N.cancelBubble=true,e.isCapturing?q():n();}}),jsx(Html,{groupProps:{x:re-12,y:G-40,width:O*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:N=>{N.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:O*1.6,height:O*1.6,radius:O,fill:"#096B76",cornerRadius:O,listening:true,onClick:N=>{N.cancelBubble=true,e.isCapturing?q():n();},onTap:N=>{N.cancelBubble=true,e.isCapturing?q():n();}}),jsx(Html,{groupProps:{x:re-8,y:G+120,width:O*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:N=>{N.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:N=>{N.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=vh;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:"fixed inset-0 z-102 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=y=>{let h=(y+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:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:s,className:"pointer-events-auto max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change 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 og=({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,y=(n.height-m)/2;return {x:p,y,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:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:a,className:"pointer-events-auto max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(og,{imageSrc:e,onCrop:(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,y=r.width/c,h=r.height/c,b=document.createElement("canvas");b.width=y,b.height=h;let x=b.getContext("2d");if(!x)return;x.drawImage(n,m,p,y,h,0,0,y,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),y=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),y.current&&y.current.getTracks().forEach(v=>v.stop());},[]);let S=async()=>{try{let v,T=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..."),v=W.captureStream(30),console.log("Canvas stream created, tracks:",v.getTracks().length);let re=v.getVideoTracks()[0];re&&console.log("Video track:",re.label,"state:",re.readyState);let G=0,N=()=>{ne(),o?.current&&(o.current.getLayers().forEach(H=>{H.batchDraw();}),G++,G%60===0&&console.log("Drawing frame:",G)),h.current=requestAnimationFrame(N);};N();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{T=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(A){console.warn("Microphone access denied:",A);}let V=[...v.getVideoTracks()];T&&V.push(...T.getAudioTracks());let D=new MediaStream(V);y.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(v){console.error("Error starting screen recording:",v),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 v=URL.createObjectURL(n),T=document.createElement("a");T.href=v,T.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(v);}},L=v=>{let T=Math.floor(v/60),V=v%60;return `${T.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return r?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children: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 Lu=({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([]),y=useRef(null),h=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(v=>v.blob()).then(v=>l(v)).catch(v=>console.error("Error loading audio:",v));},[o,i]);let b=async()=>{try{let v=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),T=new MediaRecorder(v);m.current=T,p.current=[],T.ondataavailable=V=>{V.data.size>0&&p.current.push(V.data);},T.onstop=()=>{let V=new Blob(p.current,{type:"audio/webm"});l(V),v.getTracks().forEach(D=>D.stop()),y.current&&clearInterval(y.current);},T.start(),n(!0),c(0),y.current=setInterval(()=>{c(V=>V+1);},1e3);}catch(v){console.error("Error starting audio recording:",v),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{m.current&&s&&(m.current.stop(),n(false));},g=()=>{if(i){let v=URL.createObjectURL(i),T=new Audio(v);h.current=T,T.onended=()=>{f(false),URL.revokeObjectURL(v);},T.play(),f(true);}},S=()=>{h.current&&(h.current.pause(),h.current.currentTime=0,f(false));},k=async()=>{if(i){let v=new FileReader;v.onloadend=()=>{let T=v.result;t(T),r();},v.readAsDataURL(i);}},C=()=>{l(null),a();},L=v=>{let T=Math.floor(v/60),V=v%60;return `${T.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return s?jsx("div",{className:"pointer-events-none fixed inset-0 z-106",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"]})]})}):jsx("div",{className:"fixed inset-0 z-106 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"})]})]})})};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=y=>{if(y.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 ku=({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}));});},y=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9998 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-9999 w-96 -translate-x-1/2 -translate-y-1/2 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(y,document.body)};var Mu=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 y=new Set(e.data.responseOptions.correctIndex),h=y.size>1,b=G=>{f||d(h?N=>{let _=new Set(N);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===y.size&&Array.from(l).every(G=>y.has(G)),k=Array.from(l).filter(G=>y.has(G)),C=h&&k.length>0&&!S,L=()=>S?"\u2713 Correct! Great job! \u{1F389}":C?`\u26A0 Partially correct (${k.length}/${y.size})`:"\u2717 Try again!",v=()=>S?{bg:"#dcfce7",text:"#166534"}:C?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},T=55,V=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),O=e.data.responseOptions.options.length*(T+V),re=ne+O+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 ${y.size} answers (${l.size}/${y.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:v().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:v().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((G,N)=>{let _=y.has(N),H=l.has(N),K=ne+N*(T+V),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+(T-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(N);},onTap:le=>{le.cancelBubble=true,b(N);}}),H&&jsx(Text,{x:D+12,y:K+(T-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:T,fill:Z,stroke:te,strokeWidth:2,cornerRadius:8,onClick:le=>{le.cancelBubble=true,b(N);},onTap:le=>{le.cancelBubble=true,b(N);}}),jsx(Text,{x:D+60,y:K,width:e.width-D*2-80,height:T,text:G,fontSize:16,fill:J,verticalAlign:"middle",listening:false})]},N)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:ne+e.data.responseOptions.options.length*(T+V)+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})]})]})]})});Mu.displayName="MultipleChoice";var Tu=Mu;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,y]=useState(false),[h,b]=useState(0),x=340,g=100,S=window.innerWidth*.4,k=window.innerHeight*.5,C=x+20,L=g+60,v=S-40,T=k-300,V=useRef(null);useEffect(()=>{let H=V.current;if(H)return r.current.set(e.id,H),()=>{r.current.delete(e.id);}},[e.id]);let D=H=>{s(ua({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+v&&Z+50>L&&Z<L+T;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+v&&J+50>L&&J<L+T;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)),O=Array.from(f).filter(H=>E.has(H)),re=O.length>0&&!ne,G=()=>ne?"\u2713 Correct! Great job!":re?`\u26A0 Partially correct (${O.length}/${E.size})`:"\u2717 Try again!",N=()=>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:V,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:v,height:T,fill:"#EBF6F7",stroke:_(),strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:T+18,width:v-5,height:60,fill:N().bg,cornerRadius:8}),jsx(Text,{x:20,y:T+20,width:v,height:60,text:G(),fontSize:18,fontStyle:"bold",fill:N().text,align:"center",verticalAlign:"middle"})]}),f.size===0&&!c&&jsx(Text,{x:20,y:60,width:v,height:T-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:()=>{y(true),A();},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{y(true),A();},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})]}),c&&jsxs(Group,{y:50,onMouseDown:W,onTouchStart:W,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=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 Au=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Tu,{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 Pu=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 y=()=>{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,v=24,T=60,V=60,D=e.data.feedbackMode==="practice"?48:0,q=12,U=T+(f?V:0),A=2*(C+L),W=U+A+q+D+v;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:v,y:v,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-v*2,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:v,y:T,width:e.width-v*2,height:V-10,fill:k().bg,cornerRadius:8}),jsx(Text,{x:v,y:T,width:e.width-v*2,height:V-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 O=b===E.value,re=l===E.value,G=(e.width-v*3)/2,N=v+ne*(G+v),_=U,H=E.value===true,K=H?"#10b981":"#ef4444",te="#ffffff",Z="#ffffff",J="#e5e7eb";return f&&(O?(Z=H?"#f0fdf4":"#fef2f2",J=H?"#86efac":"#fecaca"):re&&!O&&(Z="#fee2e2",J="#ef4444")),re&&!f&&(J="#096B76",Z="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:N,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:N+G/2,y:_+40,radius:28,fill:K,listening:false}),H?jsx(Text,{x:N+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:N+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:N,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),y();},onMouseLeave:E=>{E.cancelBubble=true,m(null);},onTouchStart:E=>{E.cancelBubble=true,m("check");},onTouchEnd:E=>{E.cancelBubble=true,m(null),y();},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:v,width:(e.width-v*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:v,width:(e.width-v*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-v*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:v,width:(e.width-v*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.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})]})]})]})});Pu.displayName="TrueFalse";var Du=Pu;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,y]=useState(0),[h,b]=useState(false),x=340,g=100,S=window.innerWidth*.4,k=window.innerHeight*.5,C=S-40,L=k-300,v=20,T=60,V=C,D=L,q=S*.2-40,U=50,A=useRef(null),W=K=>{a(ca({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,v+V)-Math.max(Z,v)),Ie=Math.max(0,Math.min(J+U,T+D)-Math.max(J,T)),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,v+V)-Math.max(J,v)),Y=Math.max(0,Math.min(le+U,T+D)-Math.max(le,T)),Me=Ie*Y,Be=q*U;if(Me/Be>=.5)d(K);else return;i(false);},O=()=>{u(true);},re=()=>{u(false),d(null),y(K=>K+1);},G=e.data.responseOptions.correctAnswer,N=l===G,_=()=>N?"\u2713 Correct! Great job!":"\u2717 Try again!",H=()=>N?{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),O());},onMouseUp:()=>m(false),onMouseLeave:()=>m(false),onTouchStart:()=>{l!==null&&(m(true),O());},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 Ru=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Du,{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 Eu(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&&Eu(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),Eu(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 Fu(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):Fu(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 Bu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var xa,rt,et,hr,ba,qa,Jt,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,Jt);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,Jt,null),Ce(this,ko,r);}startConnectLoop(){j(this,Jt)!==null||j(this,qa)||(this.debugLog(`Starting connect loop (every ${j(this,ko)}ms)`),Ce(this,Jt,setInterval(j(this,Mo),j(this,ko))));}stopConnectLoop(){j(this,Jt)!==null&&(clearInterval(j(this,Jt)),Ce(this,Jt,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,Jt=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});}},Ou=(e,o)=>{Zi.emit(e,o);},Zi=new Ji;function Nu(){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(Nu()),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"}}),Ou("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,Nu());},this.key=Bu(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 je(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 Vu=(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:Vu(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:Vu(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 y=a(u,c,m,p);({insert:()=>i(y,u,c),remove:()=>l(y),swap:()=>p!==void 0&&f(y,u,c,p),move:()=>p!==void 0&&d(y,u,c,p)})[m]();}function t(u,c){return `${u}[${c}]`}function a(u,c,m,p){let y=[t(u,c)];if(m==="swap")y.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++)y.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++)y.push(t(u,x));}return Object.keys(e.fieldInfo).filter(h=>y.some(b=>h.startsWith(b)))}function r(u,c){return u.replace(/\[(\d+)\]/,(m,p)=>{let y=parseInt(p,10);return `[${c==="up"?y+1:Math.max(0,y-1)}]`})}function s(u,c){(c==="up"?u:[...u].reverse()).forEach(p=>{let y=r(p.toString(),c),h=e.getFieldMeta(y);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 y=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=y.get(b);x&&e.setFieldMeta(h,x);});},f=(u,c,m,p)=>{u.forEach(y=>{if(!y.toString().startsWith(t(c,m)))return;let h=y.toString().replace(t(c,m),t(c,p)),[b,x]=[e.getFieldMeta(y),e.getFieldMeta(h)];b&&e.setFieldMeta(h,b),x&&e.setFieldMeta(y,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 y=this.getFieldMeta(p);if(!y)continue;let{errorMap:h,errorSourceMap:b}=y,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:y,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:v}=js({newFormValidatorError:C,isPreviousErrorFromFormValidator:k?.[b]==="form",previousErrorValue:S?.[b]});S?.[b]!==L&&this.setFieldMeta(x,T=>({...T,errorMap:{...T.errorMap,[b]:L},errorSourceMap:{...T.errorSourceMap,[b]:v}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.errorMap,[b]:y}})),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)],je(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),je(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),je(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)},je(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},je(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,[],je(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],y=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(y,wa(this.options.defaultValues,u))||Sa(y,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),y=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,v=this.options.canSubmitWhenInvalid??false,T=l.submissionAttempts===0&&!m&&!g||!S&&!l.isSubmitting&&L||v,V=l.errorMap;if(h&&(k=k.filter(A=>A!==l.errorMap.onMount),V=Object.assign(V,{onMount:void 0})),n&&i&&n.errorMap===V&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===k&&n.isFieldsValidating===u&&n.isFieldsValid===c&&n.isFormValid===C&&n.isValid===L&&n.canSubmit===T&&n.isTouched===m&&n.isBlurred===p&&n.isPristine===x&&n.isDefaultValue===y&&n.isDirty===b&&Sa(i,l))return n;let D={...l,errorMap:V,fieldMeta:this.fieldMetaDerived.state,errors:k,isFieldsValidating:u,isFieldsValid:c,isFormValid:C,isValid:L,canSubmit:T,isTouched:m,isBlurred:p,isPristine:x,isDefaultValue:y,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&&gt.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,je(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,je(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,je(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,je(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,je(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,je(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),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?qu(f.runValidator({validate:u.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,p=a[c],{newErrorValue:y,newSource:h}=Xs({formLevelError:p,fieldLevelError:m});f.state.meta.errorMap?.[c]!==y&&f.setMeta(b=>({...b,errorMap:{...b.errorMap,[c]:y},errorSourceMap:{...b.errorSourceMap,[c]:h}})),y&&(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(y=>{y.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 y=Js(m.cause);c.getInfo().validationMetaMap[y]?.lastAbortController.abort();let b=new AbortController;this.getInfo().validationMetaMap[y]={lastAbortController:b},p.push(new Promise(async x=>{let g;try{g=await new Promise((v,T)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(b.signal.aborted)return v(void 0);try{v(await this.runValidator({validate:m.validate,value:{value:c.store.state.value,fieldApi:c,signal:b.signal,validationSource:"field"},type:"validateAsync"}));}catch(V){T(V);}},m.debounceMs);});}catch(v){g=v;}if(b.signal.aborted)return x(void 0);let S=qu(g),k=s[this.name]?.[y],{newErrorValue:C,newSource:L}=Xs({formLevelError:k,fieldLevelError:S});c.setMeta(v=>({...v,errorMap:{...v?.errorMap,[y]:C},errorSourceMap:{...v.errorSourceMap,[y]: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 qu(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=Hu(e);if(t.length!==Hu(o).length)return false;for(let a=0;a<t.length;a++)if(!Object.prototype.hasOwnProperty.call(o,t[a])||!Object.is(e[t[a]],o[t[a]]))return false;return true}function Hu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var 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?ca(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?ua(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(fa(false));}}),d=()=>{o(fa(false));},f=jsx("div",{className:"fixed inset-0 z-106 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-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});},y=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:()=>y(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)},zu=Ox;var ju=({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 $u=({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 y of c){u.textContent=y||" ";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 Yu=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 y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===y,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,v=50,T=12,V=e.data.feedbackMode==="practice"?48:0,D=12,q=30,U=k+C+q+v+T+D+V+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:v+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:`${v}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+v+T+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})]})]})]})});Yu.displayName="ShortAnswer";var Ju=Yu;var Qu=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>jsx(Fragment,{children:e.map(n=>jsx(Ju,{shortAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>s(i,n.id)},n.id))});var ec=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,tc=15,tn=32,ac=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:s})=>{let n=useSelector(v=>v.toolbar.selectedTool),i=n==="pen"||n==="eraser",l=useRef(null),[d,f]=useState(""),[u,c]=useState(false),[m,p]=useState(null);useEffect(()=>{let v=l.current;if(v)return s.current.set(e.id,v),()=>{s.current.delete(e.id);}},[e.id,s]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===y,b=()=>{c(false),f("");},x=()=>{d.length>0&&c(true);},g=e.width-Mt*2,S=(g-tc)/2,k=e.data.feedbackMode==="practice",C=useMemo(()=>{let v=Mt,T=v;v+=60;let V=v;v+=35;let D=v;v+=cl+16;let q=v;u&&(v+=tn+16);let U=v;return k&&(v+=Tr),v+=Mt,{questionY:T,helperTextY:V,inputY:D,feedbackY:q,buttonsY:U,totalHeight:v}},[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:v=>a(v,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:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,r?.(v.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:v=>f(v.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:v=>{v.cancelBubble=true,p("reset");},onMouseUp:v=>{v.cancelBubble=true,p(null),b();},onMouseLeave:v=>{v.cancelBubble=true,p(null);},onTouchStart:v=>{v.cancelBubble=true,p("reset");},onTouchEnd:v=>{v.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+tc,onMouseDown:v=>{v.cancelBubble=true,p("submit");},onMouseUp:v=>{v.cancelBubble=true,p(null),x();},onMouseLeave:v=>{v.cancelBubble=true,p(null);},onTouchStart:v=>{v.cancelBubble=true,p("submit");},onTouchEnd:v=>{v.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})]})]})]})});ac.displayName="FillInTheBlanks";var oc=ac;var sc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:s})=>jsx(Fragment,{children:e.map(n=>jsx(oc,{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 y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===y,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,v=12,T=48,V=12,D=30,q=k+C+D+L+v+V+T+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+v,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
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+v+V,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,xb=.4,bb=1.5,vb=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,y=f+l.points[m+1]*c;o=Math.min(o,p),t=Math.min(t,y),a=Math.max(a,p),r=Math.max(r,y);}}}),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}},yb=(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(xb,Math.min(bb,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}},wb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r={enabled:true}}={})=>{let s=tt(),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,y]=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(()=>vb(i||null),[l]),[C,L]=useState(null),[v,T]=useState(null),[V,D]=useState(null),[q,U]=useState(null),[A,W]=useState(null),[E,ne]=useState(null),[O,re]=useState(null),[G,N]=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=yb(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),na=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:ia,saRefs:Ra,handleShortAnswerDragEnd:Pn}=Fd(Y),{longAnswers:Wr,handleLongAnswerDragEnd:Ft}=Bd(Y),{fillInTheBlanks:la,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:da,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=na.current.get(p)||ro.current.get(p)||oe.current.get(p)||Gr.current.get(p)||da.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,na,ro,oe,Gr,da,jr,Xr,rd,Ne,Ue,zr,fe]);let Ge=useCallback(w=>{y(w),o?.(w);},[o]),so=useCallback(()=>{y(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){T(null);return}let I=da.current.get(w),P=c.current;if(!I||!P){T(null);return}let F=P.container().getBoundingClientRect(),Ae=I.absolutePosition(),Se=P.scaleX();T({x:F.left+(Ae.x+I.width()*Se/2)*Se,y:F.top+Ae.y*Se});},[p,pe,Ko,da]),useEffect(()=>{if(!pe){D(null);return}let w=da.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,da]);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 Xe=w.target.getStage()?.getPointerPosition();if(!Xe)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let B=pc(Xe,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),Ge(w);},[ye,Ge]),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,et=F,Xe=Ae;Ae+Se>Bt&&(Xe=Ae-Se),F+ae>wt&&(et=F-ae),L({x:et,y:Xe,elementId:I,elementType:P}),Ge(I);},[Ge,r.enabled]),ud=useCallback(w=>{s(Jo(w)),s(fa(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 M=I.target.getBoundingClientRect();U({x:M.right+5,y:M.top,type:"order"});}break;case "lock":if(I){let M=I.target.getBoundingClientRect();U({x:M.right+5,y:M.top,type:"lock"});}break;case "link":if(L(null),F==="line")break;let Ae=i?F==="image"?i.images.find(M=>M.id===P):i.videos.find(M=>M.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(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="text"?i.texts.find(M=>M.id===P):F==="flashcard"?i.flashcards.find(M=>M.id===P):F==="photoFrame"?i.photoFrames.find(M=>M.id===P):F==="mcq"?i.multipleChoices.find(M=>M.id===P):F==="fillInTheBlanks"?i.fillInTheBlanks.find(M=>M.id===P):F==="longAnswer"?i.LongAnswer.find(M=>M.id===P):F==="shortAnswer"?i.shortAnswers.find(M=>M.id===P):F==="trueFalse"?i.trueFalses.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.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(M=>M.id===P):F==="trueFalse"?ae=i?.trueFalses.find(M=>M.id===P):F==="shortAnswer"?ae=i?.shortAnswers.find(M=>M.id===P):F==="longAnswer"?ae=i?.LongAnswer.find(M=>M.id===P):F==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(M=>M.id===P)),ae&&ud(ae);break;case "editFlashcard":L(null);let Bt=i?.flashcards.find(M=>M.id===P);Bt&&Im(Bt);break;case "color":L(null);let wt=i?.shapes.find(M=>M.id===P);ne({elementId:P,elementType:"shape",defaultColor:wt?.color||"#096B76"});break;case "crop":if(L(null),F==="image"){let M=i?.images.find(Rm=>Rm.id===P);M&&re({elementId:P,imageSrc:M.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 et=5;for(let M=0;M<et;M++)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 Xe=`#response-${P}`;s(ce()),s(ys({id:P,type:F,link:Xe})),(i?F==="image"?i.images.find(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.id===P):F==="flashcard"?i.flashcards.find(M=>M.id===P):F==="photoFrame"?i.photoFrames.find(M=>M.id===P):i.multipleChoices.find(M=>M.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(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.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(!O)return;let{elementId:I}=O;s(ce()),s(io({id:I,src:w})),Y(),re(null);},[O,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});}),ia.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});}),la.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",et=ae.isSketch&&ae.tool==="pen",Xe=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:et||Xe?void 0:ae.color,strokeWidth:et||Xe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:et||Xe?wt?"black":ae.color:void 0,closed:et||Xe,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 M=B.target.getStage();M&&(M.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:B=>{let M=B.target.getStage();M&&(M.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},F):jsxs(be__default.Fragment,{children:[jsx(Group,{id:St,ref:B=>{B?na.current.set(St,B):na.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: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 M=B.target.getStage();M&&(M.container().style.cursor="move");}},onMouseLeave:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="default");}},onContextMenu:B=>{let M=B.evt;M.preventDefault(),yt(M,St,"line");},children:jsx(Line,{points:ae.points||[],stroke:et||Xe?void 0:ae.color,strokeWidth:et||Xe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:et||Xe?wt?"black":ae.color:void 0,closed:et||Xe,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 M=na.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!M),M&&M.visible()&&(B.nodes([M]),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:Ge,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 M=Gr.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Ge,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=ro.current.get(p);M&&M.visible()&&(B.nodes([M]),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 M=oe.current.get(p);M&&M.visible()&&(B.nodes([M]),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:da,onDragEnd:dm,onTransformEnd:um,onSelect:Ge,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 M=da.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Ge,onNext:hm,onPrevious:gm,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=jr.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Ge,onStartCamera:vm,onCapture:ym,cameraStreams:wm,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=Xr.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Ge,mcqRefs:Ne,handleDragEnd:Et,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=Ne.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Ge,trueFalseRefs:Ue,onContextMenu:yt,handleDragEnd:Yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=Ue.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Ge,handleTransform:we,saRefs:Ra,onContextMenu:yt,handleDragEnd:Pn}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=Ra.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Ge,handleTransform:we,saRefs:Ra,onContextMenu:yt,handleDragEnd:Ft}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=Ra.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Ge,handleTransform:we,onContextMenu:yt,handleDragEnd:Ea,fibRefs:zr}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=zr.current.get(p);M&&M.visible()&&(B.nodes([M]),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)}),O&&jsx(wu,{imageSrc:O.imageSrc,onConfirm:Dm,onCancel:()=>re(null)}),G&&jsx(lr,{onClose:()=>N(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=>{Ge(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}),v&&(()=>{let w=pe||p;if(!w)return null;let I=Ko.find(P=>P.id===w);return I?jsx(Xu,{text:I,position:v}):null})(),V&&pe&&(()=>{let w=Ko.find(I=>I.id===pe);return w?jsx(Yu,{text:w,editingValue:ad,onEditingChange:od,onFinish:Dn,position:{top:V.top,left:V.left},scale:V.scale,textareaRef:Z},pe):null})()]})},Sb=wb;function gl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Ye(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,y=c?.[e]?.[l]||i,h=be.useMemo(()=>p,Object.values(p));return jsx(y.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,Ib(r,...o)]}function Ib(...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 Cb=be[" useInsertionEffect ".trim().toString()]||Bo;function Qt({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,s,n]=kb({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=Mb(f)?f(e):f;u!==e&&n.current?.(u);}else s(f);},[i,e,s,n]);return [l,d]}function kb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),s=be.useRef(o);return Cb(()=>{s.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(s.current?.(t),r.current=t);},[t,r]),[t,a,s]}function Mb(e){return typeof e=="function"}var Tb=be.createContext(void 0);function Oo(e){let o=be.useContext(Tb);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=Ab(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),l=i.find(Db);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 Ab(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=Eb(r),i=Rb(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 Pb=Symbol("radix.slottable");function Db(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Pb}function Rb(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 Eb(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 Ob=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],it=Ob.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=Nb(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),l=i.find(qb);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 Nb(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=Ub(r),i=Hb(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 Vb=Symbol("radix.slottable");function qb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Vb}function Hb(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 Ub(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=y=>{let{scope:h,children:b}=y,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((y,h)=>{let{scope:b,children:x}=y,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((y,h)=>{let{scope:b,children:x,...g}=y,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(y){let h=s(e+"CollectionConsumer",y);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,zb,Gb]=ln(No),[Tc]=Ca(No,[Gb]),[Kb,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,...y}=e,h=be.useRef(new Set),b=be.useRef(0),g=n==="horizontal"?_b:jb,[S=[],k]=Qt({prop:f,defaultProp:d,onChange:D=>{[...h.current][b.current]?.focus(),u(D);}}),C=be.useRef(S);function L(D){let q=Zb(S,D);V(D,q);}function v(D){V(D,b.current);}function T(){let D=C.current[b.current];S[b.current]!==D&&c(S);}function V(D,q,{commit:U}={commit:false}){let A=av(s),W=ov(Math.round((D-a)/s)*s+a,A),E=gl(W,[a,r]);k((ne=[])=>{let O=Yb(ne,E,q);if(tv(O,l*s)){b.current=O.indexOf(E);let re=String(O)!==String(ne);return re&&U&&c(O),re?O:ne}else return ne});}return jsx(Kb,{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,...y,ref:o,onPointerDown:Ye(y.onPointerDown,()=>{i||(C.current=S);}),min:a,max:r,inverted:m,onSlideStart:i?void 0:L,onSlideMove:i?void 0:v,onSlideEnd:i?void 0:T,onHomeKeyDown:()=>!i&&V(a,0,{commit:true}),onEndKeyDown:()=>!i&&V(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],O=s*W*q;V(ne+O,E,{commit:true});}}})})})})});Ac.displayName=No;var[Pc,Dc]=Tc(No,{startEdge:"left",endEdge:"right",size:"width",direction:1}),_b=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),y=Oo(r),h=y==="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:y,"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});}})})}),jb=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(y){let h=c.current||f.current.getBoundingClientRect(),b=[0,h.height],g=Sl(b,m?[a,t]:[t,a]);return c.current=h,g(y-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:y=>{let h=p(y.clientY);s?.(h);},onSlideMove:y=>{let h=p(y.clientY);n?.(h);},onSlideEnd:()=>{c.current=void 0,i?.();},onStepKeyDown:y=>{let b=Mc[m?"from-bottom":"from-top"].includes(y.key);l?.({event:y,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:Ye(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:Ye(e.onPointerDown,u=>{let c=u.target;c.setPointerCapture(u.pointerId),u.preventDefault(),f.thumbs.has(c)?c.focus():a(u);}),onPointerMove:Ye(e.onPointerMove,u=>{u.target.hasPointerCapture(u.pointerId)&&r(u);}),onPointerUp:Ye(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=zb(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(Xb,{...e,ref:s,index:n})}),Xb=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),y=Jb(a,n.values.length),h=c?.[i.size],b=h?Qb(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"]||y,"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:Ye(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 $b="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=$b;function Yb(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 Jb(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Zb(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 Qb(e,o,t){let a=e/2,s=Sl([0,50],[0,a]);return (a-s(o)*t)*t}function ev(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function tv(e,o){if(o>0){let t=ev(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 av(e){return (String(e).split(".")[1]||"").length}function ov(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 sv=(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},nv=(e,o)=>({classGroupId:e,validator:o}),Xc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Gc=[],iv="arbitrary..",lv=e=>{let o=uv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return dv(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?sv(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}},dv=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?iv+a:void 0})(),uv=e=>{let{theme:o,classGroups:t}=e;return cv(t,o)},cv=(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];fv(n,o,t,a);}},fv=(e,o,t,a)=>{if(typeof e=="string"){mv(e,o,t);return}if(typeof e=="function"){pv(e,o,t,a);return}hv(e,o,t,a);},mv=(e,o,t)=>{let a=e===""?o:Yc(o,e);a.classGroupId=t;},pv=(e,o,t,a)=>{if(gv(e)){Cl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(nv(t,e));},hv=(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},gv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,xv=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 bv=[],Kc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),vv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let s=[],n=0,i=0,l=0,d,f=r.length;for(let y=0;y<f;y++){let h=r[y];if(n===0&&i===0){if(h===":"){s.push(r.slice(l,y)),l=y+1;continue}if(h==="/"){d=y;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(bv,false,n,void 0,true);}if(t){let r=a;a=s=>t({className:s,parseClassName:r});}return a},yv=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}},wv=e=>({cache:xv(e.cacheSize),parseClassName:vv(e),sortModifiers:yv(e),...lv(e)}),Sv=/\s+/,Lv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:s}=o,n=[],i=e.trim().split(Sv),l="";for(let d=i.length-1;d>=0;d-=1){let f=i[d],{isExternal:u,modifiers:c,hasImportantModifier:m,baseClassName:p,maybePostfixModifierPosition:y}=t(f);if(u){l=f+(l.length>0?" "+l:l);continue}let h=!!y,b=a(h?p.substring(0,y):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},Iv=(...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},Cv=(e,...o)=>{let t,a,r,s,n=l=>{let d=o.reduce((f,u)=>u(f),e());return t=wv(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=Lv(l,t);return r(l,f),f};return s=n,(...l)=>s(Iv(...l))},kv=[],He=e=>{let o=t=>t[e]||kv;return o.isThemeGetter=true,o},Zc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Qc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Mv=/^\d+\/\d+$/,Tv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Av=/\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$/,Pv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Dv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Rv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Vo=e=>Mv.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)),ea=e=>Tv.test(e),Ev=()=>true,Fv=e=>Av.test(e)&&!Pv.test(e),ef=()=>false,Bv=e=>Dv.test(e),Ov=e=>Rv.test(e),Nv=e=>!X(e)&&!$(e),Vv=e=>qo(e,of,ef),X=e=>Zc.test(e),$a=e=>qo(e,rf,Fv),Il=e=>qo(e,zv,de),_c=e=>qo(e,tf,ef),qv=e=>qo(e,af,Ov),cn=e=>qo(e,sf,Bv),$=e=>Qc.test(e),Dr=e=>Ho(e,rf),Hv=e=>Ho(e,Gv),jc=e=>Ho(e,tf),Uv=e=>Ho(e,of),Wv=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",zv=e=>e==="number",Gv=e=>e==="family-name",sf=e=>e==="shadow";var Kv=()=>{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"),y=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"],v=()=>[$,X,l],T=()=>[Vo,"full","auto",...v()],V=()=>[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",...v()],ne=()=>[Vo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],O=()=>[e,$,X],re=()=>[...S(),jc,_c,{position:[$,X]}],G=()=>["no-repeat",{repeat:["","x","y","space","round"]}],N=()=>["auto","cover","contain",Uv,Vv,{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",...v()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ea],breakpoint:[ea],color:[Ev],container:[ea],"drop-shadow":[ea],ease:["in","out","in-out"],font:[Nv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ea],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ea],shadow:[ea],spacing:["px",de],text:[ea],"text-shadow":[ea],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:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{start:T()}],end:[{end:T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[ka,"auto",$,X]}],basis:[{basis:[Vo,"full","auto",i,...v()]}],"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":V()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":V()}],"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:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"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: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: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":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"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:[Hv,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,...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:O()}],"text-color":[{text:O()}],"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:O()}],"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:re()}],"bg-repeat":[{bg:G()}],"bg-size":[{bg:N()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ka,$,X],radial:["",$,X],conic:[ka,$,X]},Wv,qv]}],"bg-color":[{bg:O()}],"gradient-from-pos":[{from:_()}],"gradient-via-pos":[{via:_()}],"gradient-to-pos":[{to:_()}],"gradient-from":[{from:O()}],"gradient-via":[{via:O()}],"gradient-to":[{to:O()}],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:O()}],"border-color-x":[{"border-x":O()}],"border-color-y":[{"border-y":O()}],"border-color-s":[{"border-s":O()}],"border-color-e":[{"border-e":O()}],"border-color-t":[{"border-t":O()}],"border-color-r":[{"border-r":O()}],"border-color-b":[{"border-b":O()}],"border-color-l":[{"border-l":O()}],"divide-color":[{divide:O()}],"outline-style":[{outline:[...te(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,$,X]}],"outline-w":[{outline:["",de,Dr,$a]}],"outline-color":[{outline:O()}],shadow:[{shadow:["","none",f,fn,cn]}],"shadow-color":[{shadow:O()}],"inset-shadow":[{"inset-shadow":["none",u,fn,cn]}],"inset-shadow-color":[{"inset-shadow":O()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:O()}],"ring-offset-w":[{"ring-offset":[de,$a]}],"ring-offset-color":[{"ring-offset":O()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":O()}],"text-shadow":[{"text-shadow":["none",c,fn,cn]}],"text-shadow-color":[{"text-shadow":O()}],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":O()}],"mask-image-linear-to-color":[{"mask-linear-to":O()}],"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":O()}],"mask-image-t-to-color":[{"mask-t-to":O()}],"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":O()}],"mask-image-r-to-color":[{"mask-r-to":O()}],"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":O()}],"mask-image-b-to-color":[{"mask-b-to":O()}],"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":O()}],"mask-image-l-to-color":[{"mask-l-to":O()}],"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":O()}],"mask-image-x-to-color":[{"mask-x-to":O()}],"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":O()}],"mask-image-y-to-color":[{"mask-y-to":O()}],"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":O()}],"mask-image-radial-to-color":[{"mask-radial-to":O()}],"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":O()}],"mask-image-conic-to-color":[{"mask-conic-to":O()}],"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:N()}],"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":O()}],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",b,$,X]}],delay:[{delay:[de,$,X]}],animate:[{animate:["none",x,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,$,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:O()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:O()}],"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",...O()]}],"stroke-w":[{stroke:[de,Dr,$a,Il]}],stroke:[{stroke:["none",...O()]}],"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=Cv(Kv);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 jv="SchooplaVideoStorage";var Xt="videos",pn=()=>new Promise((e,o)=>{let t=indexedDB.open(jv,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 Xv=be[" useId ".trim().toString()]||(()=>{}),$v=0;function ff(e){let[o,t]=be.useState(Xv());return Bo(()=>{t(a=>a??String($v++));},[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",Yv={bubbles:false,cancelable:true},Rr="RovingFocusGroup",[Pl,pf,Jv]=ln(Rr),[Zv,Dl]=Ca(Rr,[Jv]),[Qv,ey]=Zv(Rr),hf=be.forwardRef((e,o)=>jsx(Pl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Pl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(ty,{...e,ref:o})})}));hf.displayName=Rr;var ty=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),[y,h]=Qt({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 v=c.current;if(v)return v.addEventListener(Al,g),()=>v.removeEventListener(Al,g)},[g]),jsx(Qv,{scope:t,orientation:a,dir:p,loop:r,currentTabStopId:y,onItemFocus:be.useCallback(v=>h(v),[h]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>L(v=>v+1),[]),onFocusableItemRemove:be.useCallback(()=>L(v=>v-1),[]),children:jsx(it.div,{tabIndex:b||C===0?-1:0,"data-orientation":a,...u,ref:m,style:{outline:"none",...e.style},onMouseDown:Ye(e.onMouseDown,()=>{k.current=true;}),onFocus:Ye(e.onFocus,v=>{let T=!k.current;if(v.target===v.currentTarget&&T&&!b){let V=new CustomEvent(Al,Yv);if(v.currentTarget.dispatchEvent(V),!V.defaultPrevented){let D=S().filter(E=>E.focusable),q=D.find(E=>E.active),U=D.find(E=>E.id===y),W=[q,U,...D].filter(Boolean).map(E=>E.ref.current);bf(W,f);}}k.current=false;}),onBlur:Ye(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=ey(gf,t),u=f.currentTabStopId===d,c=pf(t),{onFocusableItemAdd:m,onFocusableItemRemove:p,currentTabStopId:y}=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:Ye(e.onMouseDown,h=>{a?f.onItemFocus(d):h.preventDefault();}),onFocus:Ye(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:Ye(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){f.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let b=ry(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?sy(g,S+1):g.slice(S+1);}setTimeout(()=>bf(g));}}),children:typeof n=="function"?n({isCurrentTabStop:u,hasTabStop:y!=null}):n})})});xf.displayName=gf;var ay={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function oy(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ry(e,o,t){let a=oy(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return ay[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 sy(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]=Qt({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:Ye(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(ly,{...a,ref:o});if(t==="multiple")return jsx(dy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Ta}\``)});El.displayName=Ta;var[kf,Mf]=If(Ta),ly=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Qt({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})})}),dy=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Qt({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[uy,cy]=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(uy,{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",fy=be__default.forwardRef((e,o)=>{let t=Mf(hn,e.__scopeToggleGroup),a=cy(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})});fy.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 hy=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(hy.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var xy={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Ff=createSlice({name:"toolbar",initialState:xy,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:UP,setFontFamily:WP,setFontStyle:zP,setFontWeight:GP,setTextDecoration:KP,setTextColor:_P}=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),y=useRef(null),h=useRef(null);useEffect(()=>((async()=>{try{let v=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});d(v),u(!0),h.current&&(h.current.srcObject=v);}catch(v){console.error("Error accessing camera:",v),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),l&&l.getTracks().forEach(v=>v.stop());}),[]);let b=()=>{l&&(l.getTracks().forEach(L=>L.stop()),d(null),u(false));},x=async()=>{try{let L=null,v=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{v=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let T=[...L.getVideoTracks()];v&&T.push(...v.getAudioTracks());let V=new MediaStream(T),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(V,{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),y.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(A.src);},V.getTracks().forEach(W=>W.stop()),L&&L.getTracks().forEach(W=>W.stop()),v&&v.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),v=document.createElement("a");v.href=L,v.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(v),v.click(),document.body.removeChild(v),URL.revokeObjectURL(L);}},k=L=>{let v=Math.floor(L/60),T=L%60;return `${v.toString().padStart(2,"0")}:${T.toString().padStart(2,"0")}`},C=jsx("div",{className:"fixed inset-0 z-100 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&&y.current&&(o(r,y.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(C,document.body)};var ta=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=ta-a.length;if(S<=0){alert(`You can only upload a maximum of ${ta} images`);return}let k=Array.from(g).slice(0,S);k.length<g.length&&alert(`Only ${S} more images can be added (max ${ta} total)`);let C=k.map(L=>new Promise((v,T)=>{let V=new FileReader;V.onload=D=>{D.target?.result?v(D.target.result):T(new Error("Failed to read file"));},V.onerror=T,V.readAsDataURL(L);}));Promise.all(C).then(L=>{r(v=>[...v,...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=ta-a.length;if(S<=0){alert(`You can only upload a maximum of ${ta} images`);return}let k=g.slice(0,S);k.length<g.length&&alert(`Only ${S} more images can be added (max ${ta} total)`);let C=k.map(L=>new Promise((v,T)=>{let V=new FileReader;V.onload=D=>{D.target?.result?v(D.target.result):T(new Error("Failed to read file"));},V.onerror=T,V.readAsDataURL(L);}));Promise.all(C).then(L=>{r(v=>[...v,...L]);});},m=x=>{x.preventDefault(),l(true);},p=()=>{l(false);},y=x=>{r(g=>g.filter((S,k)=>k!==x));},b=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:d,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$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>=ta?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ta," images"]}):jsxs("span",{children:[a.length,"/",ta," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:u,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop: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:()=>y(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}},Ey={enabled:true};function Nl(e){return e?{tools:{...gn.tools,...e.tools},actions:{...gn.actions,...e.actions}}:gn}var Fy={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}},By={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var dw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config: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),y=useMemo(()=>Nl(r),[r]),{tools:h,actions:b}=y,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),v=Q(R=>R.toolbar.textColor),[T,V]=useState(false),[D,q]=useState(false),[U,A]=useState(false),[W,E]=useState(false),[ne,O]=useState(false),[re,G]=useState(false),[N,_]=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,la)=>{let Ea=setTimeout(()=>la(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ea),Ft();},se.onerror=()=>{clearTimeout(Ea),la(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Ft,la)=>{let Ea=setTimeout(()=>la(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 la=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ft();},5e3);se.onseeked=()=>{clearTimeout(la),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 ia=we.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",ia.length),s(ce());let Ra=960-Te/2,Pn=540-Ue/2,Wr=v4();await Ya(Wr,ye,ia),s(Zr({id:Wr,objectUrl:ge,thumbnailDataUrl:ia,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})),O(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:v,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?V(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},kn=()=>{q(true);},na=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 ia=setTimeout(()=>Yt(new Error("Metadata load timeout")),1e4);ge.onloadedmetadata=()=>{clearTimeout(ia),Ue();},ge.onerror=()=>{clearTimeout(ia),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})),V(!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(fa(!c));},Tn=()=>{s(jo(null)),s(Ba(true)),O(false);},ro=()=>{A(!U);},Ur=()=>{E(!W);},An=()=>{O(!ne);};return useEffect(()=>{if(!N)return;let R=oe=>{p.current&&!p.current.contains(oe.target)&&_(false);};return document.addEventListener("mousedown",R),()=>{document.removeEventListener("mousedown",R);}},[N]),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),O(false),oo(R.name);return}else if(R.name==="shapes"){ro(),E(false),O(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),O(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:()=>_(!N),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${N?"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})})}),N&&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&&T&&t&&jsx(lr,{onClose:()=>V(false),stageRef:t,onRecordingComplete:na}),D&&jsx(Of,{onClose:()=>q(false),onRecordingComplete:na}),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)})]})},uw=dw;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),[y,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 hw=({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=tt(),y=ut(er),h=ut(yi),b=e??(h?y.title:"")??"Untitled",x=o??(h?y.description:"")??"Add a description...",[g,S]=useState(false),[k,C]=useState(false),[L,v]=useState(b),[T,V]=useState(x),D=useRef(null),q=useRef(null);useEffect(()=>{v(b);},[b]),useEffect(()=>{V(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()||v(b);},E=()=>{C(false),T.trim()&&T!==x?s?s(T.trim()):p(gi(T.trim())):T.trim()||V(x);},ne=re=>{re.key==="Enter"?W():re.key==="Escape"&&(v(b),S(false));},O=re=>{re.key==="Enter"?E():re.key==="Escape"&&(V(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=>v(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:T,onChange:re=>V(re.target.value),onBlur:E,onKeyDown:O,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:T,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:T})]})]}),u||n&&a&&jsx(Wl,{onPublish:a,includeInactiveSlides:m})]})};var ww=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Sw=({colors:e=ww,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 Lw({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(),Cw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),Gl=e=>{let o=Cw(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 Aw=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Or=wn("copy",Aw);var Pw=[["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",Pw);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 Fw=({softDelete:e=false})=>{let o=tt(),t=ut(fo),a=ut(co),r=ut(vi),[s,n]=useState(true),d=(ut(p=>p.canvas.slides.find(y=>y.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,y)=>jsx(Xf,{slide:p,index:y,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 Bw="SchooplaEditorDB",Ow=1,Pa="slides",Da="metadata",Kl="schoopla_current_slide_id",Jf="presentation_metadata",Vr=()=>new Promise((e,o)=>{let t=indexedDB.open(Bw,Ow);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 Nw=["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"],Vw=["canvas/clearCanvas"],qw=["canvas/setPresentationTitle","canvas/setPresentationDescription"],Hw=Yl((e,o)=>{_l(e),Xl(o);},500),Uw=Yl(e=>{Jl(e);},500),Ww=(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&&Vw.includes(t.type)){if(!Ql){Ql=true;try{let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;Ww(s,n);}finally{setTimeout(()=>{Ql=false;},0);}}}else if(t.type&&Nw.includes(t.type)){let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;Hw(s,n);}else if(t.type&&qw.includes(t.type)){let r=e.getState(),{presentationMetadata:s}=r.canvas;Uw(s);}return a});new QueryClient;var Kw=configureStore({reducer:{toolbar:Bf,canvas:gd},middleware:e=>e({serializableCheck:false}).concat(Zf)});var _w=(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")}},jw=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);}})},Xw=(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 $w=(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=$w(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]},Yw=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},Jw=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=Yw(e),a=ed(t,o);return Jw(a)},em=(e,o=1.5)=>({...e,points:Qf(e.points,o)}),Zw=(e,o=1.5)=>e.map(t=>em(t,o)),Qw=(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 eS=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=eS(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",tS=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),y=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:y};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 y={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,y.audioBuffer=h,y.audioMimeType=b;}f.push(y);}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),y=zo(c.capturedImageUrl);i+=p.byteLength,m.buffer=p,m.mimeType=y;}if(c.audioData&&c.audioData.startsWith("data:")){let p=to(c.audioData),y=zo(c.audioData);i+=p.byteLength,m.audioBuffer=p,m.audioMimeType=y;}u.push(m);}n.push({...l,images:d,videos:f,photoFrames:u});}return {slides:n,totalSize:i}},aS=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},oS=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 nS=()=>{let e=tt(),[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);}}},iS=()=>{let e=tt(),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:u?"none":"auto"}})}),jsx(Group,{y:k+C+D+L+v+V,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 ic=({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,cc=3200,fc=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,y=f+l.points[m+1]*c;o=Math.min(o,p),t=Math.min(t,y),a=Math.max(a,p),r=Math.max(r,y);}}}),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,cc),i=Math.min(r-t,fc);return o=Math.max(o,a-cc),t=Math.max(t,r-fc),{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}},mc=(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,y]=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),[v,T]=useState(null),[V,D]=useState(null),[q,U]=useState(null),[A,W]=useState(null),[E,ne]=useState(null),[O,re]=useState(null),[G,N]=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),na=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:ia,saRefs:Ra,handleShortAnswerDragEnd:Pn}=Fd(Y),{longAnswers:Wr,handleLongAnswerDragEnd:Ft}=Bd(Y),{fillInTheBlanks:la,handleFillInTheBlanksDragEnd:Ea,fibRefs:zr}=ec(Y),{transformerRef:fe,boundBoxFunc:vt}=Ud(),{shapes:sm,shapeRefs:Gr,isDragging:td,handleShapeDragEnd:nm,handleShapeResizeEnd:im}=Dd(Y),{texts:Ko,textRefs:da,handleDragEnd:lm,handleTransformEnd:dm,handleDoubleClick:um,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:cm,flashcardRefs:jr,handleDragEnd:fm,handleFlashcardTransformEnd:mm,handleNext:pm,handlePrevious:hm}=Nd(Y),{photoFrames:rd,photoFrameRefs:Xr,handleDragEnd:gm,handlePhotoFrameTransformEnd:xm,startCamera:bm,capturePhoto:vm,cameraStreams:ym}=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=na.current.get(p)||ro.current.get(p)||oe.current.get(p)||Gr.current.get(p)||da.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,na,ro,oe,Gr,da,jr,Xr,rd,Ne,Ue,zr,fe]);let Ke=useCallback(w=>{y(w),o?.(w);},[o]),so=useCallback(()=>{y(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){T(null);return}let I=da.current.get(w),P=c.current;if(!I||!P){T(null);return}let F=P.container().getBoundingClientRect(),Ae=I.absolutePosition(),Se=P.scaleX();T({x:F.left+(Ae.x+I.width()*Se/2)*Se,y:F.top+Ae.y*Se});},[p,pe,Ko,da]),useEffect(()=>{if(!pe){D(null);return}let w=da.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,da]);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 Xe=w.target.getStage()?.getPointerPosition();if(!Xe)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let B=mc(Xe,g);ao(B);}},[n,ao,so,g]),ld=useCallback(w=>{if(td)return;let I=w.target.getStage()?.getPointerPosition();if(!I)return;let P=mc(I,g);qr(P);},[qr,td,g]),dd=useCallback(()=>{Hr();},[Hr]),wm=useCallback(w=>{Ur(w,Y);},[Ur,Y]),Sm=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,Xe=Ae;Ae+Se>Bt&&(Xe=Ae-Se),F+ae>wt&&(tt=F-ae),L({x:tt,y:Xe,elementId:I,elementType:P}),Ke(I);},[Ke,r.enabled]),ud=useCallback(w=>{s(Jo(w)),s(fa(true));},[s]),Lm=useCallback(w=>{s(jo(w)),s(Ba(true));},[s]),Im=useCallback((w,I)=>{if(!C)return;let{elementId:P,elementType:F}=C;switch(w){case "order":if(I){let M=I.target.getBoundingClientRect();U({x:M.right+5,y:M.top,type:"order"});}break;case "lock":if(I){let M=I.target.getBoundingClientRect();U({x:M.right+5,y:M.top,type:"lock"});}break;case "link":if(L(null),F==="line")break;let Ae=i?F==="image"?i.images.find(M=>M.id===P):i.videos.find(M=>M.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(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="text"?i.texts.find(M=>M.id===P):F==="flashcard"?i.flashcards.find(M=>M.id===P):F==="photoFrame"?i.photoFrames.find(M=>M.id===P):F==="mcq"?i.multipleChoices.find(M=>M.id===P):F==="fillInTheBlanks"?i.fillInTheBlanks.find(M=>M.id===P):F==="longAnswer"?i.LongAnswer.find(M=>M.id===P):F==="shortAnswer"?i.shortAnswers.find(M=>M.id===P):F==="trueFalse"?i.trueFalses.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.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(M=>M.id===P):F==="trueFalse"?ae=i?.trueFalses.find(M=>M.id===P):F==="shortAnswer"?ae=i?.shortAnswers.find(M=>M.id===P):F==="longAnswer"?ae=i?.LongAnswer.find(M=>M.id===P):F==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(M=>M.id===P)),ae&&ud(ae);break;case "editFlashcard":L(null);let Bt=i?.flashcards.find(M=>M.id===P);Bt&&Lm(Bt);break;case "color":L(null);let wt=i?.shapes.find(M=>M.id===P);ne({elementId:P,elementType:"shape",defaultColor:wt?.color||"#096B76"});break;case "crop":if(L(null),F==="image"){let M=i?.images.find(Dm=>Dm.id===P);M&&re({elementId:P,imageSrc:M.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 M=0;M<tt;M++)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 Xe=`#response-${P}`;s(ce()),s(ys({id:P,type:F,link:Xe})),(i?F==="image"?i.images.find(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.id===P):F==="flashcard"?i.flashcards.find(M=>M.id===P):F==="photoFrame"?i.photoFrames.find(M=>M.id===P):i.multipleChoices.find(M=>M.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(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.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]),Cm=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]),km=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]),Mm=useCallback(w=>{if(!_)return;let{elementId:I,elementType:P}=_;s(ce()),s(Ss({id:I,type:P,audioData:w})),Y(),H(null);},[_,s,Y]),Tm=useCallback(()=>{if(!_)return;let{elementId:w,elementType:I}=_;s(ce()),s(Ss({id:w,type:I,audioData:""})),Y();},[_,s,Y]),Am=useCallback(w=>{if(!E)return;let{elementId:I}=E;s(ce()),s(lo({id:I,color:w})),Y(),ne(null);},[E,s,Y]),Pm=useCallback(w=>{if(!O)return;let{elementId:I}=O;s(ce()),s(io({id:I,src:w})),Y(),re(null);},[O,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});}),sm.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});}),cm.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});}),ia.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});}),la.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",Xe=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||Xe?void 0:ae.color,strokeWidth:tt||Xe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Xe?wt?"black":ae.color:void 0,closed:tt||Xe,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 M=B.target.getStage();M&&(M.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:B=>{let M=B.target.getStage();M&&(M.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},F):jsxs(be__default.Fragment,{children:[jsx(Group,{id:St,ref:B=>{B?na.current.set(St,B):na.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 M=B.target.getStage();M&&(M.container().style.cursor="move");}},onMouseLeave:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="default");}},onContextMenu:B=>{let M=B.evt;M.preventDefault(),yt(M,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?wt?"black":ae.color:void 0,closed:tt||Xe,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 M=na.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!M),M&&M.visible()&&(B.nodes([M]),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:nm,handleShapeResizeEnd:im,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=Gr.current.get(p);M&&M.visible()&&(B.nodes([M]),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:wm,onTransform:An,onSelect:Ke,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=ro.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Sm,onDragEnd:ge,onTransformEnd:se,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=oe.current.get(p);M&&M.visible()&&(B.nodes([M]),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:da,onDragEnd:lm,onTransformEnd:dm,onSelect:Ke,onContextMenu:yt,onDoubleClick:um,editingTextId:pe,editingValue:ad,onEditingChange:od}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=da.current.get(p);M&&M.visible()&&(B.nodes([M]),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:fm,onTransform:mm,onSelect:Ke,onNext:pm,onPrevious:hm,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=jr.current.get(p);M&&M.visible()&&(B.nodes([M]),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:gm,onTransform:xm,onSelect:Ke,onStartCamera:bm,onCapture:vm,cameraStreams:ym,onContextMenu:yt}),Se&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&fe.current!==B){fe.current=B;let M=Xr.current.get(p);M&&M.visible()&&(B.nodes([M]),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(Au,{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 M=Ne.current.get(p);M&&M.visible()&&(B.nodes([M]),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(Ru,{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 M=Ue.current.get(p);M&&M.visible()&&(B.nodes([M]),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(Qu,{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 M=Ra.current.get(p);M&&M.visible()&&(B.nodes([M]),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(ic,{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 M=Ra.current.get(p);M&&M.visible()&&(B.nodes([M]),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(sc,{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 M=zr.current.get(p);M&&M.visible()&&(B.nodes([M]),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:Im,onClose:Cm,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:km,onClose:()=>W(null)}),E&&jsx(Es,{defaultColor:E.defaultColor,onConfirm:Am,onCancel:()=>ne(null)}),O&&jsx(wu,{imageSrc:O.imageSrc,onConfirm:Pm,onCancel:()=>re(null)}),G&&jsx(lr,{onClose:()=>N(false),stageRef:c}),_&&jsx(Lu,{elementId:_.elementId,elementType:_.elementType,existingAudio:_.existingAudio,onSave:Mm,onDelete:Tm,onClose:()=>H(null)}),K&&jsx(ku,{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(zu,{editElement:d}),v&&(()=>{let w=pe||p;if(!w)return null;let I=Ko.find(P=>P.id===w);return I?jsx(ju,{text:I,position:v}):null})(),V&&pe&&(()=>{let w=Ko.find(I=>I.id===pe);return w?jsx($u,{text:w,editingValue:ad,onEditingChange:od,onFinish:Dn,position:{top:V.top,left:V.left},scale:V.scale,textareaRef:Z},pe):null})()]})},wb=yb;function gl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Ye(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function pc(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=pc(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():pc(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,y=c?.[e]?.[l]||i,h=be.useMemo(()=>p,Object.values(p));return jsx(y.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 Qt({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 xc(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 vc(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 wc(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=wc(`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=y=>{let{scope:h,children:b}=y,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((y,h)=>{let{scope:b,children:x}=y,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((y,h)=>{let{scope:b,children:x,...g}=y,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(y){let h=s(e+"CollectionConsumer",y);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 Ic=["PageUp","PageDown"],Cc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],kc={"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),[Mc]=Ca(No,[zb]),[Gb,dn]=Mc(No),Tc=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,...y}=e,h=be.useRef(new Set),b=be.useRef(0),g=n==="horizontal"?Kb:_b,[S=[],k]=Qt({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);V(D,q);}function v(D){V(D,b.current);}function T(){let D=C.current[b.current];S[b.current]!==D&&c(S);}function V(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 O=$b(ne,E,q);if(ev(O,l*s)){b.current=O.indexOf(E);let re=String(O)!==String(ne);return re&&U&&c(O),re?O: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,...y,ref:o,onPointerDown:Ye(y.onPointerDown,()=>{i||(C.current=S);}),min:a,max:r,inverted:m,onSlideStart:i?void 0:L,onSlideMove:i?void 0:v,onSlideEnd:i?void 0:T,onHomeKeyDown:()=>!i&&V(a,0,{commit:true}),onEndKeyDown:()=>!i&&V(r,S.length-1,{commit:true}),onStepKeyDown:({event:D,direction:q})=>{if(!i){let W=Ic.includes(D.key)||D.shiftKey&&Cc.includes(D.key)?10:1,E=b.current,ne=S[E],O=s*W*q;V(ne+O,E,{commit:true});}}})})})})});Tc.displayName=No;var[Ac,Pc]=Mc(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),y=Oo(r),h=y==="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(Ac,{scope:e.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:jsx(Dc,{dir:y,"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=kc[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(y){let h=c.current||f.current.getBoundingClientRect(),b=[0,h.height],g=Sl(b,m?[a,t]:[t,a]);return c.current=h,g(y-h.top)}return jsx(Ac,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:jsx(Dc,{"data-orientation":"vertical",...d,ref:u,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{let h=p(y.clientY);s?.(h);},onSlideMove:y=>{let h=p(y.clientY);n?.(h);},onSlideEnd:()=>{c.current=void 0,i?.();},onStepKeyDown:y=>{let b=kc[m?"from-bottom":"from-top"].includes(y.key);l?.({event:y,direction:b?-1:1});}})})}),Dc=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:Ye(e.onKeyDown,u=>{u.key==="Home"?(n(u),u.preventDefault()):u.key==="End"?(i(u),u.preventDefault()):Ic.concat(Cc).includes(u.key)&&(l(u),u.preventDefault());}),onPointerDown:Ye(e.onPointerDown,u=>{let c=u.target;c.setPointerCapture(u.pointerId),u.preventDefault(),f.thumbs.has(c)?c.focus():a(u);}),onPointerMove:Ye(e.onPointerMove,u=>{u.target.hasPointerCapture(u.pointerId)&&r(u);}),onPointerUp:Ye(e.onPointerUp,u=>{let c=u.target;c.hasPointerCapture(u.pointerId)&&(c.releasePointerCapture(u.pointerId),s(u));})})}),Rc="SliderTrack",Ec=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=dn(Rc,t);return jsx(it.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});Ec.displayName=Rc;var yl="SliderRange",Fc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=dn(yl,t),s=Pc(yl,t),n=be.useRef(null),i=Pt(o,n),l=r.values.length,d=r.values.map(c=>Nc(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+"%"}})});Fc.displayName=yl;var wl="SliderThumb",Bc=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=Pc(wl,t),[l,d]=be.useState(null),f=Pt(o,x=>d(x)),u=l?n.form||!!l.closest("form"):true,c=vc(l),m=n.values[a],p=m===void 0?0:Nc(m,n.min,n.max),y=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"]||y,"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:Ye(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),u&&jsx(Oc,{name:r??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:m},a)]})});Bc.displayName=wl;var Xb="RadioBubbleInput",Oc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),s=Pt(r,a),n=xc(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})});Oc.displayName=Xb;function $b(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,s)=>r-s)}function Nc(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 Vc=Tc,qc=Ec,Hc=Fc,Uc=Bc;function Wc(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=Wc(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=Wc(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}),jc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var zc=[],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 Xc(i,l,o)},getConflictingClassGroupIds:(n,i)=>{if(i){let l=a[n],d=t[n];return l?d?rv(d,l):l:d||zc}return t[n]||zc}}},Xc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],s=t.nextPart.get(r);if(s){let d=Xc(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=jc();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:$c(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,$c(o,i),t,a);}},$c=(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=jc(),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=[],Gc=(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 y=0;y<f;y++){let h=r[y];if(n===0&&i===0){if(h===":"){s.push(r.slice(l,y)),l=y+1;continue}if(h==="/"){d=y;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 Gc(s,m,c,p)};if(o){let r=o+":",s=a;a=n=>n.startsWith(r)?s(n.slice(r.length)):Gc(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:y}=t(f);if(u){l=f+(l.length>0?" "+l:l);continue}let h=!!y,b=a(h?p.substring(0,y):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=Yc(t))&&(r&&(r+=" "),r+=a);return r},Yc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Yc(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},Jc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Zc=/^\((?:(\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)),ea=e=>Mv.test(e),Rv=()=>true,Ev=e=>Tv.test(e)&&!Av.test(e),Qc=()=>false,Fv=e=>Pv.test(e),Bv=e=>Dv.test(e),Ov=e=>!X(e)&&!$(e),Nv=e=>qo(e,af,Qc),X=e=>Jc.test(e),$a=e=>qo(e,of,Ev),Il=e=>qo(e,Wv,de),Kc=e=>qo(e,ef,Qc),Vv=e=>qo(e,tf,Bv),cn=e=>qo(e,rf,Fv),$=e=>Zc.test(e),Dr=e=>Ho(e,of),qv=e=>Ho(e,zv),_c=e=>Ho(e,ef),Hv=e=>Ho(e,af),Uv=e=>Ho(e,tf),fn=e=>Ho(e,rf,true),qo=(e,o,t)=>{let a=Jc.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Ho=(e,o,t=false)=>{let a=Zc.exec(e);return a?a[1]?o(a[1]):t:false},ef=e=>e==="position"||e==="percentage",tf=e=>e==="image"||e==="url",af=e=>e==="length"||e==="size"||e==="bg-size",of=e=>e==="length",Wv=e=>e==="number",zv=e=>e==="family-name",rf=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"),y=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"],v=()=>[$,X,l],T=()=>[Vo,"full","auto",...v()],V=()=>[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",...v()],ne=()=>[Vo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],O=()=>[e,$,X],re=()=>[...S(),_c,Kc,{position:[$,X]}],G=()=>["no-repeat",{repeat:["","x","y","space","round"]}],N=()=>["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,_c,Kc],le=()=>["","none",p,$,X],Ie=()=>["none",de,$,X],Y=()=>["none",de,$,X],Me=()=>[de,$,X],Be=()=>[Vo,"full",...v()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ea],breakpoint:[ea],color:[Rv],container:[ea],"drop-shadow":[ea],ease:["in","out","in-out"],font:[Ov],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ea],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ea],shadow:[ea],spacing:["px",de],text:[ea],"text-shadow":[ea],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:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{start:T()}],end:[{end:T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[ka,"auto",$,X]}],basis:[{basis:[Vo,"full","auto",i,...v()]}],"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":V()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":V()}],"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:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"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: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: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":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"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,...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:O()}],"text-color":[{text:O()}],"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:O()}],"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:re()}],"bg-repeat":[{bg:G()}],"bg-size":[{bg:N()}],"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:O()}],"gradient-from-pos":[{from:_()}],"gradient-via-pos":[{via:_()}],"gradient-to-pos":[{to:_()}],"gradient-from":[{from:O()}],"gradient-via":[{via:O()}],"gradient-to":[{to:O()}],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:O()}],"border-color-x":[{"border-x":O()}],"border-color-y":[{"border-y":O()}],"border-color-s":[{"border-s":O()}],"border-color-e":[{"border-e":O()}],"border-color-t":[{"border-t":O()}],"border-color-r":[{"border-r":O()}],"border-color-b":[{"border-b":O()}],"border-color-l":[{"border-l":O()}],"divide-color":[{divide:O()}],"outline-style":[{outline:[...te(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,$,X]}],"outline-w":[{outline:["",de,Dr,$a]}],"outline-color":[{outline:O()}],shadow:[{shadow:["","none",f,fn,cn]}],"shadow-color":[{shadow:O()}],"inset-shadow":[{"inset-shadow":["none",u,fn,cn]}],"inset-shadow-color":[{"inset-shadow":O()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:O()}],"ring-offset-w":[{"ring-offset":[de,$a]}],"ring-offset-color":[{"ring-offset":O()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":O()}],"text-shadow":[{"text-shadow":["none",c,fn,cn]}],"text-shadow-color":[{"text-shadow":O()}],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":O()}],"mask-image-linear-to-color":[{"mask-linear-to":O()}],"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":O()}],"mask-image-t-to-color":[{"mask-t-to":O()}],"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":O()}],"mask-image-r-to-color":[{"mask-r-to":O()}],"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":O()}],"mask-image-b-to-color":[{"mask-b-to":O()}],"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":O()}],"mask-image-l-to-color":[{"mask-l-to":O()}],"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":O()}],"mask-image-x-to-color":[{"mask-x-to":O()}],"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":O()}],"mask-image-y-to-color":[{"mask-y-to":O()}],"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":O()}],"mask-image-radial-to-color":[{"mask-radial-to":O()}],"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":O()}],"mask-image-conic-to-color":[{"mask-conic-to":O()}],"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:N()}],"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":O()}],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",b,$,X]}],delay:[{delay:[de,$,X]}],animate:[{animate:["none",x,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,$,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:O()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:O()}],"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",...O()]}],"stroke-w":[{stroke:[de,Dr,$a,Il]}],stroke:[{stroke:["none",...O()]}],"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 sf=Iv(Gv);function Ma(...e){return sf(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(Vc,{"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(qc,{"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(Hc,{"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(Uc,{"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 lf=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}},df=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}},uf=e=>URL.createObjectURL(e);var jv=be[" useId ".trim().toString()]||(()=>{}),Xv=0;function cf(e){let[o,t]=be.useState(jv());return Bo(()=>{t(a=>a??String(Xv++));},[e]),(o?`radix-${o}`:"")}function ff(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,mf,Yv]=ln(Rr),[Jv,Dl]=Ca(Rr,[Yv]),[Zv,Qv]=Jv(Rr),pf=be.forwardRef((e,o)=>jsx(Pl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Pl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(ey,{...e,ref:o})})}));pf.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),[y,h]=Qt({prop:n,defaultProp:i??null,onChange:l,caller:Rr}),[b,x]=be.useState(false),g=ff(d),S=mf(t),k=be.useRef(false),[C,L]=be.useState(0);return be.useEffect(()=>{let v=c.current;if(v)return v.addEventListener(Al,g),()=>v.removeEventListener(Al,g)},[g]),jsx(Zv,{scope:t,orientation:a,dir:p,loop:r,currentTabStopId:y,onItemFocus:be.useCallback(v=>h(v),[h]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>L(v=>v+1),[]),onFocusableItemRemove:be.useCallback(()=>L(v=>v-1),[]),children:jsx(it.div,{tabIndex:b||C===0?-1:0,"data-orientation":a,...u,ref:m,style:{outline:"none",...e.style},onMouseDown:Ye(e.onMouseDown,()=>{k.current=true;}),onFocus:Ye(e.onFocus,v=>{let T=!k.current;if(v.target===v.currentTarget&&T&&!b){let V=new CustomEvent(Al,$v);if(v.currentTarget.dispatchEvent(V),!V.defaultPrevented){let D=S().filter(E=>E.focusable),q=D.find(E=>E.active),U=D.find(E=>E.id===y),W=[q,U,...D].filter(Boolean).map(E=>E.ref.current);xf(W,f);}}k.current=false;}),onBlur:Ye(e.onBlur,()=>x(false))})})}),hf="RovingFocusGroupItem",gf=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:s,children:n,...i}=e,l=cf(),d=s||l,f=Qv(hf,t),u=f.currentTabStopId===d,c=mf(t),{onFocusableItemAdd:m,onFocusableItemRemove:p,currentTabStopId:y}=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:Ye(e.onMouseDown,h=>{a?f.onItemFocus(d):h.preventDefault();}),onFocus:Ye(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:Ye(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(()=>xf(g));}}),children:typeof n=="function"?n({isCurrentTabStop:u,hasTabStop:y!=null}):n})})});gf.displayName=hf;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 xf(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 bf=pf,vf=gf;var wf="Toggle",Rl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...s}=e,[n,i]=Qt({prop:t,onChange:r,defaultProp:a??false,caller:wf});return jsx(it.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...s,ref:o,onClick:Ye(e.onClick,()=>{e.disabled||i(!n);})})});Rl.displayName=wf;var Ta="ToggleGroup",[Lf]=Ca(Ta,[Dl]),If=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[Cf,kf]=Lf(Ta),iy=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Qt({prop:t,defaultProp:a??"",onChange:r,caller:Ta});return jsx(Cf,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:i,onItemDeactivate:be__default.useCallback(()=>i(""),[i]),children:jsx(Mf,{...s,ref:o})})}),ly=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Qt({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(Cf,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:l,onItemDeactivate:d,children:jsx(Mf,{...s,ref:o})})});El.displayName=Ta;var[dy,uy]=Lf(Ta),Mf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:s,dir:n,loop:i=true,...l}=e,d=If(t),f=Oo(n),u={role:"group",dir:f,...l};return jsx(dy,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(bf,{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=kf(hn,e.__scopeToggleGroup),a=uy(hn,e.__scopeToggleGroup),r=If(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(vf,{asChild:true,...r,focusable:!n,active:s,ref:l,children:jsx(Sf,{...i,ref:o})}):jsx(Sf,{...i,ref:o})});cy.displayName=hn;var Sf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,s=kf(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);}})}),Tf=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(Tf,{"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"},Ef=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:qP,setFontFamily:HP,setFontStyle:UP,setFontWeight:WP,setTextDecoration:zP,setTextColor:GP}=Ef.actions,Ff=Ef.reducer;var Bf=({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),y=useRef(null),h=useRef(null);useEffect(()=>((async()=>{try{let v=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});d(v),u(!0),h.current&&(h.current.srcObject=v);}catch(v){console.error("Error accessing camera:",v),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),l&&l.getTracks().forEach(v=>v.stop());}),[]);let b=()=>{l&&(l.getTracks().forEach(L=>L.stop()),d(null),u(false));},x=async()=>{try{let L=null,v=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{v=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let T=[...L.getVideoTracks()];v&&T.push(...v.getAudioTracks());let V=new MediaStream(T),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(V,{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),y.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(A.src);},V.getTracks().forEach(W=>W.stop()),L&&L.getTracks().forEach(W=>W.stop()),v&&v.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),v=document.createElement("a");v.href=L,v.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(v),v.click(),document.body.removeChild(v),URL.revokeObjectURL(L);}},k=L=>{let v=Math.floor(L/60),T=L%60;return `${v.toString().padStart(2,"0")}:${T.toString().padStart(2,"0")}`},C=jsx("div",{className:"konva-editor-root",children:jsx("div",{className:"fixed inset-0 z-100 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&&y.current&&(o(r,y.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})})});return createPortal(C,document.body)};var ta=40,Nf=({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=ta-a.length;if(S<=0){alert(`You can only upload a maximum of ${ta} images`);return}let k=Array.from(g).slice(0,S);k.length<g.length&&alert(`Only ${S} more images can be added (max ${ta} total)`);let C=k.map(L=>new Promise((v,T)=>{let V=new FileReader;V.onload=D=>{D.target?.result?v(D.target.result):T(new Error("Failed to read file"));},V.onerror=T,V.readAsDataURL(L);}));Promise.all(C).then(L=>{r(v=>[...v,...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=ta-a.length;if(S<=0){alert(`You can only upload a maximum of ${ta} images`);return}let k=g.slice(0,S);k.length<g.length&&alert(`Only ${S} more images can be added (max ${ta} total)`);let C=k.map(L=>new Promise((v,T)=>{let V=new FileReader;V.onload=D=>{D.target?.result?v(D.target.result):T(new Error("Failed to read file"));},V.onerror=T,V.readAsDataURL(L);}));Promise.all(C).then(L=>{r(v=>[...v,...L]);});},m=x=>{x.preventDefault(),l(true);},p=()=>{l(false);},y=x=>{r(g=>g.filter((S,k)=>k!==x));},b=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:d,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$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>=ta?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ta," images"]}):jsxs("span",{children:[a.length,"/",ta," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:u,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop: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:()=>y(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),y=useMemo(()=>Nl(r),[r]),{tools:h,actions:b}=y,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),v=Q(R=>R.toolbar.textColor),[T,V]=useState(false),[D,q]=useState(false),[U,A]=useState(false),[W,E]=useState(false),[ne,O]=useState(false),[re,G]=useState(false),[N,_]=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,la)=>{let Ea=setTimeout(()=>la(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ea),Ft();},se.onerror=()=>{clearTimeout(Ea),la(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Ft,la)=>{let Ea=setTimeout(()=>la(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 la=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ft();},5e3);se.onseeked=()=>{clearTimeout(la),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 ia=we.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",ia.length),s(ce());let Ra=960-Te/2,Pn=540-Ue/2,Wr=v4();await Ya(Wr,ye,ia),s(Zr({id:Wr,objectUrl:ge,thumbnailDataUrl:ia,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})),O(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:v,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?V(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},kn=()=>{q(true);},na=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 ia=setTimeout(()=>Yt(new Error("Metadata load timeout")),1e4);ge.onloadedmetadata=()=>{clearTimeout(ia),Ue();},ge.onerror=()=>{clearTimeout(ia),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})),V(!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(fa(!c));},Tn=()=>{s(jo(null)),s(Ba(true)),O(false);},ro=()=>{A(!U);},Ur=()=>{E(!W);},An=()=>{O(!ne);};return useEffect(()=>{if(!N)return;let R=oe=>{p.current&&!p.current.contains(oe.target)&&_(false);};return document.addEventListener("mousedown",R),()=>{document.removeEventListener("mousedown",R);}},[N]),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),O(false),oo(R.name);return}else if(R.name==="shapes"){ro(),E(false),O(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),O(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:()=>_(!N),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${N?"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})})}),N&&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&&T&&t&&jsx(lr,{onClose:()=>V(false),stageRef:t,onRecordingComplete:na}),D&&jsx(Bf,{onClose:()=>q(false),onRecordingComplete:na}),m&&jsx(Nf,{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),[y,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(),y=ut(er),h=ut(yi),b=e??(h?y.title:"")??"Untitled",x=o??(h?y.description:"")??"Add a description...",[g,S]=useState(false),[k,C]=useState(false),[L,v]=useState(b),[T,V]=useState(x),D=useRef(null),q=useRef(null);useEffect(()=>{v(b);},[b]),useEffect(()=>{V(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()||v(b);},E=()=>{C(false),T.trim()&&T!==x?s?s(T.trim()):p(gi(T.trim())):T.trim()||V(x);},ne=re=>{re.key==="Enter"?W():re.key==="Escape"&&(v(b),S(false));},O=re=>{re.key==="Enter"?E():re.key==="Escape"&&(V(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=>v(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:T,onChange:re=>V(re.target.value),onBlur:E,onKeyDown:O,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:T,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:T})]})]}),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 Uf=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(),Wf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var zf={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 Kf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:s,iconNode:n,...i},l)=>createElement("svg",{ref:l,...zf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:yn("lucide",r),...!s&&!Wf(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(Kf,{ref:s,iconNode:o,className:yn(`lucide-${Uf(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 jf=({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(y=>y.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,y)=>jsx(jf,{slide:p,index:y,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",Yf="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 df(),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:Yf,...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(Yf);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,Jf=(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:Ff,canvas:gd},middleware:e=>e({serializableCheck:false}).concat(Jf)});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},Zf=(e,o=1.5)=>{if(e.length<=4)return e;let t=$w(e),a=ed(t,o);return Yw(a)},Qf=(e,o=1.5)=>({...e,points:Zf(e.points,o)}),Jw=(e,o=1.5)=>e.map(t=>Qf(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 em=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 em(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),y=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:y};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 y={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,y.audioBuffer=h,y.audioMimeType=b;}f.push(y);}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),y=zo(c.capturedImageUrl);i+=p.byteLength,m.buffer=p,m.mimeType=y;}if(c.audioData&&c.audioData.startsWith("data:")){let p=to(c.audioData),y=zo(c.audioData);i+=p.byteLength,m.audioBuffer=p,m.audioMimeType=y;}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 lf(),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=uf(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 am=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||""})),om=new WeakSet,rm=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await 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||om.has(a))return;om.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=am(r);e(no({slides:l,currentSlideId:i})),await rm(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=am(r);e(no({slides:l,currentSlideId:i})),await rm(l);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
7
7
 
8
8
  lucide-react/dist/esm/shared/src/utils.js:
9
9
  lucide-react/dist/esm/defaultAttributes.js:
@@ -18,5 +18,5 @@ lucide-react/dist/esm/lucide-react.js:
18
18
  * This source code is licensed under the ISC license.
19
19
  * See the LICENSE file in the root directory of this source tree.
20
20
  *)
21
- */export{By as BASIC_EDITOR_TOOLBAR_CONFIG,Sw as BottomToolbar,Sb as Canvas,Ey as DEFAULT_CONTEXT_MENU_CONFIG,gn as DEFAULT_TOOLBAR_CONFIG,Lw as EditorRoot,Wl as PublishButton,lr as ScreenRecorder,Fw as SlideNavigation,uw as Toolbar,hw as TopNavBar,Fy as VIEWER_TOOLBAR_CONFIG,si as addFillInTheBlanks,jn as addFlashcard,Gn as addImage,Zn as addImageAnnotation,zn as addLine,ri as addLongAnswer,ti as addMultipleChoice,Yn as addPhotoFrame,ei as addPhotoFrameAnnotation,Kn as addShape,oi as addShortAnswer,Nn as addSlide,_n as addText,ai as addTrueFalse,Zr as addVideo,aS as arrayBufferToBase64,ii as bringToFront,fi as clearCanvas,qm as clearImageAnnotations,Sn as clearLocalData,Um as clearPhotoFrameAnnotations,On as createEmptySlide,bs as deleteFillInTheBlanks,ns as deleteFlashcard,Yr as deleteImage,Is as deleteLineById,gs as deleteLongAnswer,us as deleteMultipleChoice,ls as deletePhotoFrame,os as deleteShape,ps as deleteShortAnswer,Vn as deleteSlide,rs as deleteText,fs as deleteTrueFalse,es as deleteVideo,vs as duplicateFillInTheBlanks,is as duplicateFlashcard,Jr as duplicateImage,ci as duplicateLine,xs as duplicateLongAnswer,cs as duplicateMultipleChoice,ds as duplicatePhotoFrame,as as duplicateShape,hs as duplicateShortAnswer,qn as duplicateSlide,ss as duplicateText,ms as duplicateTrueFalse,ts as duplicateVideo,jo as editFlashcard,Wm as editMultipleChoice,jw as exportSlideAsBlob,_w as exportSlideAsImage,ui as finalizeDrawing,Qw as getCompressionStats,Xw as getSlideDataURL,$l as loadCurrentSlideId,jl as loadFromIndexedDB,xi as loadPresentationMetadata,Zl as loadPresentationMetadataFromDB,no as loadSlides,Nl as mergeToolbarConfig,Xn as nextFlashcard,oS as prepareFormData,tS as prepareSlidesForPublishing,$n as previousFlashcard,pi as redo,$r as removeLine,Nm as reorderSlides,Jl as savePresentationMetadata,ce as saveToHistory,fo as selectAllSlides,bi as selectAllSlidesIncludingInactive,vi as selectCanAddSlide,he as selectCurrentSlide,co as selectCurrentSlideId,yi as selectMetadataLoaded,er as selectPresentationMetadata,jm as selectSlideById,li as sendToBack,ni as setActivityType,ws as setAltText,Ss as setAudioData,Wn as setBackgroundColor,Hn as setCurrentSlide,Jo as setEditingActivity,Qo as setEditingTextId,Gm as setLines,ys as setLink,Cs as setMetadataLoaded,Wo as setPenColor,gi as setPresentationDescription,hi as setPresentationTitle,Ba as setShowFlashcardForm,fa as setShowMcqForm,ct as setSketchMode,Er as setStrokeWidth,Wt as setTool,Qf as simplifyFlatPoints,em as simplifyLine,Zw as simplifyLines,Kw as store,Jn as toggleImageDrawingMode,di as toggleLock,Qn as togglePhotoFrameDrawingMode,_m as toggleSketchMode,_o as toggleVideoPlaying,mi as undo,Zo as updateElementOrder,Yo as updateFillInTheBlanks,uo as updateFlashcard,io as updateImage,Vm as updateImageAnnotation,zm as updateLastLine,Km as updateLinePosition,Ls as updateLineTransform,$o as updateLongAnswer,ua as updateMultipleChoice,Fa as updatePhotoFrame,Hm as updatePhotoFrameAnnotation,lo as updateShape,Xo as updateShortAnswer,Un as updateSlideThumbnail,Lt as updateText,ca as updateTrueFalse,Qr as updateVideo,xe as useDispatch,iS as useInitialSlides,Q as useSelector,nS as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
+ */export{Fy as BASIC_EDITOR_TOOLBAR_CONFIG,ww as BottomToolbar,wb as Canvas,Ry as DEFAULT_CONTEXT_MENU_CONFIG,gn as DEFAULT_TOOLBAR_CONFIG,Sw as EditorRoot,Wl as PublishButton,lr as ScreenRecorder,Ew as SlideNavigation,dw as Toolbar,pw as TopNavBar,Ey as VIEWER_TOOLBAR_CONFIG,si as addFillInTheBlanks,jn as addFlashcard,Gn as addImage,Zn as addImageAnnotation,zn as addLine,ri as addLongAnswer,ti as addMultipleChoice,Yn as addPhotoFrame,ei as addPhotoFrameAnnotation,Kn as addShape,oi as addShortAnswer,Nn as addSlide,_n as addText,ai as addTrueFalse,Zr as addVideo,tS as arrayBufferToBase64,ii as bringToFront,fi as clearCanvas,Vm as clearImageAnnotations,Sn as clearLocalData,Hm as clearPhotoFrameAnnotations,On as createEmptySlide,bs as deleteFillInTheBlanks,ns as deleteFlashcard,Yr as deleteImage,Is as deleteLineById,gs as deleteLongAnswer,us as deleteMultipleChoice,ls as deletePhotoFrame,os as deleteShape,ps as deleteShortAnswer,Vn as deleteSlide,rs as deleteText,fs as deleteTrueFalse,es as deleteVideo,vs as duplicateFillInTheBlanks,is as duplicateFlashcard,Jr as duplicateImage,ci as duplicateLine,xs as duplicateLongAnswer,cs as duplicateMultipleChoice,ds as duplicatePhotoFrame,as as duplicateShape,hs as duplicateShortAnswer,qn as duplicateSlide,ss as duplicateText,ms as duplicateTrueFalse,ts as duplicateVideo,jo as editFlashcard,Um as editMultipleChoice,_w as exportSlideAsBlob,Kw as exportSlideAsImage,ui as finalizeDrawing,Zw as getCompressionStats,jw as getSlideDataURL,$l as loadCurrentSlideId,jl as loadFromIndexedDB,xi as loadPresentationMetadata,Zl as loadPresentationMetadataFromDB,no as loadSlides,Nl as mergeToolbarConfig,Xn as nextFlashcard,aS as prepareFormData,eS as prepareSlidesForPublishing,$n as previousFlashcard,pi as redo,$r as removeLine,Om as reorderSlides,Jl as savePresentationMetadata,ce as saveToHistory,fo as selectAllSlides,bi as selectAllSlidesIncludingInactive,vi as selectCanAddSlide,he as selectCurrentSlide,co as selectCurrentSlideId,yi as selectMetadataLoaded,er as selectPresentationMetadata,_m as selectSlideById,li as sendToBack,ni as setActivityType,ws as setAltText,Ss as setAudioData,Wn as setBackgroundColor,Hn as setCurrentSlide,Jo as setEditingActivity,Qo as setEditingTextId,zm as setLines,ys as setLink,Cs as setMetadataLoaded,Wo as setPenColor,gi as setPresentationDescription,hi as setPresentationTitle,Ba as setShowFlashcardForm,fa as setShowMcqForm,ct as setSketchMode,Er as setStrokeWidth,Wt as setTool,Zf as simplifyFlatPoints,Qf as simplifyLine,Jw as simplifyLines,Gw as store,Jn as toggleImageDrawingMode,di as toggleLock,Qn as togglePhotoFrameDrawingMode,Km as toggleSketchMode,_o as toggleVideoPlaying,mi as undo,Zo as updateElementOrder,Yo as updateFillInTheBlanks,uo as updateFlashcard,io as updateImage,Nm as updateImageAnnotation,Wm as updateLastLine,Gm as updateLinePosition,Ls as updateLineTransform,$o as updateLongAnswer,ua as updateMultipleChoice,Fa as updatePhotoFrame,qm as updatePhotoFrameAnnotation,lo as updateShape,Xo as updateShortAnswer,Un as updateSlideThumbnail,Lt as updateText,ca as updateTrueFalse,Qr as updateVideo,xe as useDispatch,nS as useInitialSlides,Q as useSelector,sS as useSlidesPersistence};//# sourceMappingURL=index.js.map
22
22
  //# sourceMappingURL=index.js.map