@turnix-co/konva-editor 4.0.1 → 4.0.3

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,8 +1,8 @@
1
1
  "use client";
2
- export{default as Konva}from'konva';import*as Le from'react';import Le__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,createContext,useState,useMemo,createElement,useContext,useId,useLayoutEffect}from'react';import {createPortal}from'react-dom';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {CameraPlus,Camera,Stop,X,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Palette,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Rectangle,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,List,Plus,Export,CaretLeft,CaretDown,CaretUp,SidebarSimple,CaretRight,ArrowsOut,SpeakerHifiIcon,NotePencilIcon,FrameCorners,PencilSimple,CopySimple,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,TextUnderline,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Copy,Pen}from'@phosphor-icons/react/dist/ssr';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import _d from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import Xu from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {Stack as Stack$1,X as X$1,DotsSixVertical,Question,FrameCorners as FrameCorners$1,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Od=e=>{throw TypeError(e)};var Nd=(e,o,t)=>o.has(e)||Od("Cannot "+t);var $=(e,o,t)=>(Nd(e,o,"read from private field"),t?t.call(e):o.get(e)),Ne=(e,o,t)=>o.has(e)?Od("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),De=(e,o,t,a)=>(Nd(e,o,"write to private field"),o.set(e,t),t);var Hd=(e,o,t,a)=>({set _(n){De(e,o,n);},get _(){return $(e,o,a)}});var Se=()=>useDispatch(),J=e=>useSelector(e),_e=Se,Re=J;var oi=20,dt=(()=>{let e=0;return o=>`${o}-${Date.now()}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`})();function wp(e){let o=JSON.parse(JSON.stringify(e));return o.id=dt("slide"),o.name=`${e.name} (Copy)`,o.createdAt=Date.now(),o.updatedAt=Date.now(),o.isActive=true,o.showMcqForm=false,o.showFlashcardForm=false,o.editingActivity=null,o.editingFlashcard=null,o.lines=o.lines.map(t=>({...t,id:dt("line")})),o.shapes=o.shapes.map(t=>({...t,id:dt("shape")})),o.images=o.images.map(t=>({...t,id:dt("img"),annotations:t.annotations?.map(a=>({...a,id:dt("line")}))??[]})),o.videos=o.videos.map(t=>({...t,id:dt("vid"),isPlaying:false,videoBlob:void 0})),o.flashcards=o.flashcards.map(t=>({...t,id:dt("flashcard")})),o.photoFrames=o.photoFrames.map(t=>({...t,id:dt("photoframe"),isCapturing:false,annotations:t.annotations?.map(a=>({...a,id:dt("line")}))??[]})),o.texts=o.texts.map(t=>({...t,id:dt("text")})),o.multipleChoices=o.multipleChoices.map(t=>({...t,id:dt("mcq"),data:{...t.data,responseOptions:{...t.data.responseOptions,selectedIndices:void 0,isCorrect:void 0,attempts:void 0}}})),o.trueFalses=o.trueFalses.map(t=>({...t,id:dt("truefalse"),data:{...t.data,responseOptions:{...t.data.responseOptions,selectedResponse:void 0,isCorrect:void 0,attempts:void 0}}})),o.shortAnswers=o.shortAnswers.map(t=>({...t,id:dt("shortAnswer"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0,isCorrect:void 0,attempts:void 0}}})),o.LongAnswer=o.LongAnswer.map(t=>({...t,id:dt("longAnswer"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0}}})),o.fillInTheBlanks=o.fillInTheBlanks.map(t=>({...t,id:dt("fillInTheBlank"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0,isCorrect:void 0,attempts:void 0}}})),o}var ni=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}),ai=ni("Page 1"),Sp={slides:[ai],currentSlideId:ai.id,history:{[ai.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false,editingOverlayPosition:null,zoomLevel:1},qd=createSlice({name:"canvas",initialState:Sp,reducers:{addSlide:e=>{if(e.slides.length>=oi)return;let o=ni(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(u=>u.isActive).length<=1)return;let r=e.slides.findIndex(u=>u.id===t);if(r===-1)return;let s=e.slides[r];if(a?(s.isActive=false,s.updatedAt=Date.now()):(e.slides.splice(r,1),delete e.history[t]),e.currentSlideId===t){let u=e.slides.filter(i=>i.isActive);u.length>0&&(e.currentSlideId=u[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=oi)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],n=wp(a);e.slides.splice(t+1,0,n),e.currentSlideId=n.id,e.history[n.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},setViewerMode:(e,o)=>{e.viewerMode=o.payload;},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[n]=e.slides.splice(t,1);e.slides.splice(a,0,n);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(n=>n.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload);if(a){let n={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(n),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,newTimestamp:r}=o.payload;switch(n){case "image":let s=t.images.find(b=>b.id===a);s&&(s.timestamp=r);break;case "video":let u=t.videos.find(b=>b.id===a);u&&(u.timestamp=r);break;case "shape":let i=t.shapes.find(b=>b.id===a);i&&(i.timestamp=r);break;case "text":let c=t.texts.find(b=>b.id===a);c&&(c.timestamp=r);break;case "flashcard":let f=t.flashcards.find(b=>b.id===a);f&&(f.timestamp=r);break;case "photoFrame":let d=t.photoFrames.find(b=>b.id===a);d&&(d.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(b=>b.id===a);l&&(l.timestamp=r);break;case "trueFalse":let m=t.trueFalses.find(b=>b.id===a);m&&(m.timestamp=r);break;case "shortAnswer":let h=t.shortAnswers.find(b=>b.id===a);h&&(h.timestamp=r);break;case "longAnswer":let p=t.LongAnswer.find(b=>b.id===a);p&&(p.timestamp=r);break;case "fillInTheBlanks":let v=t.fillInTheBlanks.find(b=>b.id===a);v&&(v.timestamp=r);break;case "line":let y=t.lines.find(b=>b.id===a);y&&(y.timestamp=r);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);if(a){let n={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(n),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(n=>n.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(n=>n.id===o.payload);if(a){let n={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(n),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(n=>n.id===o.payload);if(a){let n={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(n),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let n=t.multipleChoices[t.multipleChoices.length-1];a.x=n.x+20,a.y=n.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},updateMultipleChoiceDragAndDrop(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a].dragDropPos=o.payload.dragDropPos,t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(n=>n.id===o.payload);if(a){let n={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(n),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let n=t.trueFalses[t.trueFalses.length-1];a.x=n.x+20,a.y=n.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(n=>n.id===o.payload);if(a){let n={...JSON.parse(JSON.stringify(a)),id:`truefalse-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(n),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let n=t.shortAnswers[t.shortAnswers.length-1];a.x=n.x+20,a.y=n.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(n=>n.id===o.payload);if(a){let n={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(n),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let n=t.LongAnswer[t.LongAnswer.length-1];a.x=n.x+20,a.y=n.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload);if(a){let n={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(n),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let n=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=n.x+20,a.y=n.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(n=>n.id===o.payload);if(a){let n={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(n),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.images.splice(r,1);t.images.push(s);}}else if(n==="video"){let r=t.videos.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.videos.splice(r,1);t.videos.push(s);}}else if(n==="shape"){let r=t.shapes.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shapes.splice(r,1);t.shapes.push(s);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.flashcards.splice(r,1);t.flashcards.push(s);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.photoFrames.splice(r,1);t.photoFrames.push(s);}}else if(n==="text"){let r=t.texts.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.texts.splice(r,1);t.texts.push(s);}}else if(n==="trueFalse"){let r=t.trueFalses.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.trueFalses.splice(r,1);t.trueFalses.push(s);}}else if(n==="shortAnswer"){let r=t.shortAnswers.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shortAnswers.splice(r,1);t.shortAnswers.push(s);}}else if(n==="fillInTheBlanks"){let r=t.fillInTheBlanks.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.fillInTheBlanks.splice(r,1);t.fillInTheBlanks.push(s);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.images.splice(r,1);t.images.unshift(s);}}else if(n==="video"){let r=t.videos.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.videos.splice(r,1);t.videos.unshift(s);}}else if(n==="shape"){let r=t.shapes.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shapes.splice(r,1);t.shapes.unshift(s);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.flashcards.splice(r,1);t.flashcards.unshift(s);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.photoFrames.splice(r,1);t.photoFrames.unshift(s);}}else if(n==="text"){let r=t.texts.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.texts.splice(r,1);t.texts.unshift(s);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload,s=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);s&&(s.locked=!s.locked,"draggable"in s&&(s.draggable=!s.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,link:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="mcq"?t.multipleChoices:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.link=r,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,altText:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.altText=r,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,audioData:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.audioData=r,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},editingOverlayPosition:(e,o)=>{e.editingOverlayPosition=o.payload;},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(n=>n.id===o.payload);if(a){let n={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(n),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);if(a){let n={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(n),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let n=a.images.map((r,s)=>s).filter(r=>r!==a.currentIndex);if(n.length>0){let r=n[Math.floor(Math.random()*n.length)];a.navigationHistory.push(r),a.currentIndex=r;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);if(a){let n={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(n),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let n=o.past.pop();e.slides[t]=n;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let n=o.future.shift();e.slides[t]=n;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let n=JSON.parse(JSON.stringify(t));a.past.push(n),a.future=[],a.past.length>20&&a.past.shift();}catch(n){console.warn("Failed to save to history - data too large:",n),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;},setZoomLevel:(e,o)=>{e.zoomLevel=Math.max(.5,Math.min(2,o.payload));},zoomIn:e=>{e.zoomLevel=Math.min(2,e.zoomLevel+.25);},zoomOut:e=>{e.zoomLevel=Math.max(.5,e.zoomLevel-.25);},resetZoom:e=>{e.zoomLevel=1;}}}),{addSlide:ur,deleteSlide:cr,duplicateSlide:fr,setCurrentSlide:mr,setViewerMode:Lp,updateSlideThumbnail:si,setBackgroundColor:pr,reorderSlides:Ip,loadSlides:Io,addLine:ii,removeLine:xn,addImage:li,updateImage:Co,deleteImage:bn,duplicateImage:vn,addVideo:ko,updateVideo:yn,deleteVideo:wn,duplicateVideo:Sn,toggleVideoPlaying:Xa,addShape:di,updateShape:Ya,duplicateShape:Ln,deleteShape:In,addText:ui,editingOverlayPosition:Vd,updateText:Ft,deleteText:Cn,duplicateText:kn,addFlashcard:ci,updateFlashcard:To,deleteFlashcard:Tn,duplicateFlashcard:Mn,editFlashcard:hr,nextFlashcard:fi,previousFlashcard:mi,addPhotoFrame:pi,updatePhotoFrame:Za,deletePhotoFrame:An,duplicatePhotoFrame:Pn,toggleImageDrawingMode:hi,addImageAnnotation:gi,updateImageAnnotation:Cp,clearImageAnnotations:kp,togglePhotoFrameDrawingMode:xi,addPhotoFrameAnnotation:bi,updatePhotoFrameAnnotation:Tp,clearPhotoFrameAnnotations:Mp,addMultipleChoice:vi,updateMultipleChoice:gt,updateMultipleChoiceDragAndDrop:yi,editMultipleChoice:Ap,deleteMultipleChoice:En,duplicateMultipleChoice:Dn,addTrueFalse:wi,updateTrueFalse:ot,deleteTrueFalse:Rn,duplicateTrueFalse:Fn,addShortAnswer:Si,updateShortAnswer:sa,deleteShortAnswer:Bn,duplicateShortAnswer:On,addLongAnswer:Li,updateLongAnswer:Ja,deleteLongAnswer:Nn,duplicateLongAnswer:Hn,addFillInTheBlanks:Ii,updateFillInTheBlanks:Sa,deleteFillInTheBlanks:qn,duplicateFillInTheBlanks:Vn,setShowMcqForm:La,setShowFlashcardForm:Qa,setActivityType:Ci,setEditingActivity:gr,bringToFront:ki,sendToBack:Ti,toggleLock:Mi,setLink:zn,setAltText:Wn,setAudioData:Un,updateLastLine:Pp,finalizeDrawing:Ai,setLines:Ep,updateLinePosition:Dp,updateLineTransform:Kn,deleteLineById:Gn,duplicateLine:Pi,updateElementOrder:xr,clearCanvas:br,undo:Mo,redo:Ao,saveToHistory:de,toggleSketchMode:Rp,setSketchMode:It,setEditingTextId:vr,setPresentationTitle:Ei,setPresentationDescription:Di,loadPresentationMetadata:Ri,setMetadataLoaded:jn,setZoomLevel:WL,zoomIn:UL,zoomOut:KL,resetZoom:zd}=qd.actions;var Wd=e=>e.canvas.slides,Ia=e=>e.canvas.currentSlideId,ve=createSelector([Wd,Ia],(e,o)=>e.find(t=>t.id===o)),Ca=createSelector([Wd],e=>e.filter(o=>o.isActive!==false)),Fi=e=>e.canvas.slides,yr=createSelector([Ca],e=>e.length<oi),Fp=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},wr=e=>e.canvas.presentationMetadata,Bi=e=>e.canvas.metadataLoaded,_n=e=>e.canvas.viewerMode,Oi=qd.reducer;var Kd=e=>{let o=Se(),t=useRef(null),a=useRef(false),n=J(m=>m.toolbar.selectedTool),r=J(m=>m.toolbar.penColor),s=J(m=>m.toolbar.strokeWidth),u=J(m=>m.canvas.isSketchMode),i=J(m=>m.canvas.slides.find(p=>p.id===m.canvas.currentSlideId)?.lines||[]),c=useCallback(m=>{t.current=m;},[]),f=useCallback(m=>{n==="pen"&&t.current&&(o(de()),t.current.startDrawing(m),a.current=true);},[n,o]),d=useCallback(m=>{!t.current||!a.current||t.current.draw(m);},[]),l=useCallback(()=>{if(!t.current||!a.current)return;let m=t.current.stopDrawing();a.current=false,m&&m.points.length>=4&&o(ii(m)),o(Ai()),e?.();},[o,e]);return {lines:i,tool:n,color:r,strokeWidth:s,isSketchMode:u,setCanvasRef:c,startDrawing:f,draw:d,stopDrawing:l}};var $d=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:n,isSketchMode:r,style:s,xOffset:u=0,yOffset:i=0},c)=>{let f=useRef(null),d=useRef(false),l=useRef([]),m=useRef([]),h=useRef(null),p=useRef(t),v=useRef(a),y=useRef(n),b=useRef(r),g=useRef(u),C=useRef(i);useEffect(()=>{p.current=t,v.current=a,y.current=n,b.current=r,g.current=u,C.current=i;},[t,a,n,r,u,i]);let I=useCallback(()=>{let k=f.current;if(!k)return;let x=k.getContext("2d");x&&x.clearRect(0,0,k.width,k.height);},[]),B=useCallback(()=>{let k=f.current,x=m.current;if(!k||x.length<1)return;let S=k.getContext("2d");if(!S)return;if(S.clearRect(0,0,k.width,k.height),p.current==="eraser"?(S.globalCompositeOperation="destination-out",S.fillStyle="rgba(0,0,0,1)"):(S.globalCompositeOperation="source-over",S.fillStyle=v.current),x.length===1){S.beginPath(),S.arc(x[0].x,x[0].y,y.current/2,0,Math.PI*2),S.fill();return}let T=_d(x,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:q=>q,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(T.length<2)){S.beginPath(),S.moveTo(T[0][0],T[0][1]);for(let q=1;q<T.length;q++)S.lineTo(T[q][0],T[q][1]);S.closePath(),S.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:k=>{d.current=true;let x={x:k.x-g.current,y:k.y-C.current};l.current=[{x:k.x,y:k.y}],m.current=[x],h.current=k,B();},draw:k=>{if(!d.current||!h.current)return;let x=k.x-h.current.x,S=k.y-h.current.y;if(Math.sqrt(x*x+S*S)<2)return;let T={x:k.x-g.current,y:k.y-C.current};l.current.push({x:k.x,y:k.y}),m.current.push(T),h.current=k,B();},stopDrawing:()=>{if(!d.current)return null;if(d.current=false,l.current.length<2)return l.current=[],m.current=[],h.current=null,I(),null;let x=_d(l.current,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:w=>w,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(w=>[w[0],w[1]]),S={tool:p.current,points:x,color:v.current,strokeWidth:y.current,isSketch:true};return l.current=[],m.current=[],h.current=null,I(),S},clear:()=>{I(),l.current=[],m.current=[],h.current=null,d.current=false;},isDrawing:()=>d.current,getCanvasElement:()=>f.current}),[I,B]),useEffect(()=>{let k=f.current;k&&(k.width=e,k.height=o);},[e,o]),jsx("canvas",{ref:f,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});$d.displayName="DirectDrawingCanvas";var Xd=$d;var Zd=e=>{let o=Se(),a=J(ve)?.images||[],n=useRef(new Map),r=useRef(new Map),s=useRef(new Set);useEffect(()=>{let f=new Set(a.map(d=>d.id));s.current.forEach(d=>{if(!f.has(d)){let l=r.current.get(d);l&&(l.src="",r.current.delete(d)),n.current.delete(d);}}),s.current=f;},[a]),useEffect(()=>()=>{r.current.forEach(f=>{f.src="";}),r.current.clear(),n.current.clear();},[]);let u=useCallback(f=>{if(r.current.has(f.id))return r.current.get(f.id);let d=new window.Image;return (f.src.startsWith("http://")||f.src.startsWith("https://"))&&(d.crossOrigin="anonymous"),d.src=f.src,r.current.set(f.id,d),d},[]),i=useCallback((f,d)=>{let l=f.target,m=l.id();a.find(p=>p.id===m)&&(o(Co({id:m,x:l.x(),y:l.y(),width:l.width(),height:l.height(),rotation:l.rotation()})),d?.());},[a,o]),c=useCallback((f,d)=>{let l=d.target,m=n.current.get(f);if(!m){console.error("\u274C Image node not found for id:",f);return}let h=l.scaleX(),p=l.scaleY(),v=l.rotation(),y=m.width(),b=m.height(),g=Math.max(5,y*h),C=Math.max(5,b*p);l.scaleX(1),l.scaleY(1),m.width(g),m.height(C),o(Co({id:f,width:g,height:C,x:l.x(),y:l.y(),rotation:v})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:u,imageRefs:n,handleDragEnd:i,handleImageTransformEnd:c}};var Jd=e=>{let o=useDispatch(),t=useSelector(ve),a=useRef(new Map),n=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((u,i)=>{let c=i.target,f=c.scaleX(),d=c.scaleY(),l=c.rotation();o(gt({id:u,scaleX:f,scaleY:d,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:n,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(u,i)=>{o(gt({id:i,x:u.target.x(),y:u.target.y()})),e?.();}}};var Qd=e=>{let o=useDispatch(),t=useSelector(ve),a=useRef(new Map),n=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((u,i)=>{let c=i.target,f=c.scaleX(),d=c.scaleY(),l=c.rotation(),m=Math.max(5,c.width()*f),h=Math.max(5,c.height()*d);c.scaleX(1),c.scaleY(1),c.width(m),c.height(h),o(ot({id:u,width:m,height:h,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:n,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(u,i)=>{o(ot({id:i,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var eu=e=>{let o=Se(),a=J(ve)?.videos||[],n=useRef(new Map),r=useCallback(i=>{o(Xa(i));},[o]),s=useCallback((i,c)=>{let f=c.target;o(yn({id:i,x:f.x(),y:f.y()})),e?.();},[o,e]),u=useCallback((i,c)=>{let f=c.target,d=f.scaleX(),l=f.scaleY(),m=f.rotation(),h=Math.max(5,f.width()*d),p=Math.max(5,f.height()*l);f.scaleX(1),f.scaleY(1),f.width(h),f.height(p),o(yn({id:i,width:h,height:p,x:f.x(),y:f.y(),rotation:m})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:n,handleVideoClick:r,handleVideoDragEnd:s,handleVideoTransformEnd:u}};var ou=e=>{let o=Se(),a=J(ve)?.shapes||[],n=useRef(new Map),r=useRef(new Map),[s,u]=useState(false),i=useCallback((f,d)=>{let l=d.target;o(Ya({id:f,x:l.x(),y:l.y()})),e?.();},[o,e]),c=useCallback((f,d)=>{let l=d.target,m=a.find(g=>g.id===f);if(!m)return;let h=l.scaleX(),p=l.scaleY(),v=m.type?.toLowerCase();v==="arrow"||v==="line"||(l.scaleX(1),l.scaleY(1));let b={id:f,x:l.x(),y:l.y(),width:Math.max(5,l.width()*h),height:Math.max(5,l.height()*p),rotation:l.rotation()};switch(v){case "circle":b.radius=l.width()*h/2;break;case "star":b.innerRadius=l.width()*h/4,b.outerRadius=l.width()*h/2;break;case "triangle":b.radius=l.width()*h/2;break;case "ellipse":b.radiusX=l.width()*h/2,b.radiusY=l.height()*p/2;break;case "polygon":b.radius=l.width()*h/2;break;case "ring":let g=h;b.innerRadius=m.innerRadius&&m.innerRadius*g,b.outerRadius=m.outerRadius&&m.outerRadius*g;break;case "wedge":b.radius=m.radius&&m.radius*h;break;case "arc":b.innerRadius=m.innerRadius&&m.innerRadius*h,b.outerRadius=m.outerRadius&&m.outerRadius*h;break;case "arrow":case "line":{b.scaleX=h,b.scaleY=p,delete b.width,delete b.height;break}}o(Ya(b)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:n,isDragging:s,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:c}};var nu=(e,o)=>{let t=_e(),n=J(ve)?.texts||[],r=useRef(new Map),[s,u]=useState(null),[i,c]=useState("");return {texts:n,textRefs:r,handleDragEnd:(v,y)=>{let b=v.target;t(de()),t(Ft({id:y,x:b.x(),y:b.y()})),e();},handleTransformEnd:v=>{let y=r.current.get(v);if(!y)return;let b=y.scaleX(),g=y.scaleY(),C=n.find(B=>B.id===v);if(!C)return;let I=(b+g)/2;y.scaleX(1),y.scaleY(1),t(de()),t(Ft({id:v,x:y.x(),y:y.y(),width:Math.max(5,(C.width||100)*b),height:Math.max(5,(C.height||50)*g),fontSize:Math.round(Math.max(8,C.fontSize*I)),rotation:y.rotation()})),e();},handleDoubleClick:v=>{let y=n.find(b=>b.id===v);y&&!y.locked&&(u(v),c(y.text));},startEditing:v=>{let y=n.find(b=>b.id===v);y&&!y.locked&&(u(v),c(y.text));},editingTextId:s,editingValue:i,handleEditingChange:v=>{c(v);},finishEditing:()=>{if(s){let v=r.current.get(s),y=n.find(g=>g.id===s);t(de());let b={id:s,text:i};if(y&&(y.fontWeight!==void 0&&(b.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(b.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(b.textDecoration=y.textDecoration)),o?.current&&i.trim()){let g=o.current,C=g.offsetWidth,I=g.offsetHeight,B=1;if(v){let V=v.getStage();V&&(B=V.scaleX());}let k=14,x=(C-k)/B,S=(I-k)/B,w=i.split(`
3
- `).length,q=n.find(V=>V.id===s)?.fontSize||24,F=w*q*1.2+10;b.width=Math.max(200,x),b.height=Math.max(50,S,F);}else if(v&&i.trim()){let g=v.text(),C=v.width();v.text(i),v.width(void 0);let I=v.width(),B=v.height();v.text(g),v.width(C),b.width=Math.max(200,I+20),b.height=Math.max(50,B+20);}t(Ft(b)),u(null),c(""),t(vr(null)),e();}}}};var su=e=>{let o=useDispatch(),a=useSelector(ve)?.shortAnswers||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(sa({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:n,handleShortAnswerDragEnd:r}};var iu=e=>{let o=useDispatch(),t=useSelector(ve),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),n=useCallback((r,s)=>{let u=r.target;o(Ja({id:s,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:n}};var du=e=>{let o=Se(),a=J(ve)?.flashcards||[],n=useRef(new Map),r=useRef(new Map),s=useCallback((d,l)=>{if(r.current.has(l))return r.current.get(l);let m=new window.Image;return (d.startsWith("http://")||d.startsWith("https://"))&&(m.crossOrigin="anonymous"),m.src=d,r.current.set(l,m),m},[]),u=useCallback(d=>{let l=d.target,m=l.id();a.find(p=>p.id===m)&&(o(To({id:m,x:l.x(),y:l.y()})),e?.());},[a,o,e]),i=useCallback((d,l)=>{let m=l.target,h=m.scaleX(),p=m.scaleY(),v=m.rotation(),y=Math.max(50,m.width()*h),b=Math.max(50,m.height()*p);m.scaleX(1),m.scaleY(1),m.width(y),m.height(b),o(To({id:d,width:y,height:b,x:m.x(),y:m.y(),rotation:v})),m.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(d=>{o(fi(d)),e?.();},[o,e]),f=useCallback(d=>{o(mi(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:n,handleDragEnd:u,handleFlashcardTransformEnd:i,handleNext:c,handlePrevious:f}};var fu=e=>{let o=Se(),a=J(ve)?.photoFrames||[],n=useRef(new Map),[r,s]=useState(new Map),u=useCallback((m,h)=>{console.log("handleDragEnd"),o(Za({id:h,x:m.target.x(),y:m.target.y()})),e?.();},[o,e]),i=useCallback((m,h)=>{let p=h.target,v=p.scaleX(),y=p.scaleY(),b=p.rotation(),g=a.find(B=>B.id===m);if(!g)return;let C=Math.max(100,g.width*v),I=Math.max(100,g.height*y);p.scaleX(1),p.scaleY(1),o(Za({id:m,width:C,height:I,x:p.x(),y:p.y(),rotation:b})),p.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async m=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(p=>{let v=new Map(p);return v.set(m,h),v}),o(Za({id:m,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),f=useCallback(m=>{let h=r.get(m);h&&(h.getTracks().forEach(p=>p.stop()),s(p=>{let v=new Map(p);return v.delete(m),v}),o(Za({id:m,isCapturing:false})),e?.());},[r,o,e]),d=useCallback((m,h)=>{let p=document.createElement("canvas");p.width=h.videoWidth,p.height=h.videoHeight;let v=p.getContext("2d");if(v){v.drawImage(h,0,0,p.width,p.height);let y=p.toDataURL("image/jpeg",.8);return o(Za({id:m,capturedImageUrl:y,isCapturing:false})),f(m),e?.(),y}return null},[o,f,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(m=>{m.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:n,handleDragEnd:u,handlePhotoFrameTransformEnd:i,startCamera:c,stopCamera:f,capturePhoto:d,cameraStreams:r}};var mu=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,s)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...s,width:Math.max(o.minWidth,Math.min(s.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(s.height,o.maxHeight))}:s,[o]),a=useCallback((r,s,u,i,c,f,d,l=[])=>{if(e.current){if(r&&!l.find(p=>p.id===r)?.isPlaying){let p=s.get(r)||u.get(r)||i.get(r)||c.get(r)||f.get(r)||(d?d.get(r):null);if(p){e.current.boundBoxFunc(t),e.current.nodes([p]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),n=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:n,boundBoxFunc:t}};var lh=(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])},xu=(e,o)=>{let t=_e(),a=Re(_n),n=useRef(e);useEffect(()=>{n.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(si({id:n.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),s=lh(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var uh=e=>e.flatMap(o=>[o[0],o[1]]),Xn=(e,o)=>{let t=_d(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 uh(t)};var bu=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null),u=J(g=>g.toolbar.selectedTool),i=J(g=>g.toolbar.penColor),c=J(g=>g.toolbar.strokeWidth),f=J(g=>g.canvas.isSketchMode),d=J(g=>g.canvas.slides.find(I=>I.id===g.canvas.currentSlideId)?.images.find(I=>I.id===e)),l=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(g=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,n.current=[{x:g.x,y:g.y}];let C=g.x/h,I=g.y/p;s({tool:u,points:[C,I],color:i,strokeWidth:c/h,isSketch:f});},[u,i,c,f,h,p]),y=useCallback(g=>{if(!t.current||!r)return;a.current=true;let C=n.current[n.current.length-1];if(Math.sqrt(Math.pow(g.x-C.x,2)+Math.pow(g.y-C.y,2))<2)return;n.current.push({x:g.x,y:g.y});let B;if(f)B=Xn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,S)=>S%2===0?x/h:x/p);else {let k=g.x/h,x=g.y/p;B=[...r.points,k,x];}s(k=>k?{...k,points:B}:null);},[f,c,r,h,p]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(gi({imageId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:m,startDrawing:v,draw:y,stopDrawing:b,tool:u}};function Ve({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),n=useRef(null);return {createHandlers:useCallback((s,u)=>({onTouchStart:i=>{let c=i.evt.touches[0];n.current={x:c.clientX,y:c.clientY},a.current=setTimeout(()=>{e(s,u)(i.evt);},o);},onTouchMove:i=>{if(!n.current)return;let c=i.evt.touches[0],f=Math.abs(c.clientX-n.current.x),d=Math.abs(c.clientY-n.current.y);(f>t||d>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),n.current=null;}}),[e,o,t])}}var Lu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u})=>{let{annotations:i,activeLine:c,stopDrawing:l,tool:m}=bu(e.id),{createHandlers:h}=Ve({onLongPress:u});useEffect(()=>{let g=t.current.get(e.id);g&&(g.width()!==e.width||g.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:g.width(),konvaHeight:g.height()}),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[l,p]);let v=g=>{{r(e.id);return}},y=g=>{return;},b=g=>{};return jsxs(Group,{listening:m!=="pen"&&m!=="eraser",children:[jsx(Image$1,{id:e.id,ref:g=>{if(g)t.current.set(e.id,g),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw();else {let C=t.current.get(e.id);C?._contextMenuCleanup&&C._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:m!=="pen"&&m!=="eraser",onDragEnd:a,onTransformEnd:g=>n(e.id,g),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:g=>{g.evt.preventDefault();let C=g.evt;s(C,e.id,"image");},...m!=="pen"&&m!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onMouseMove:y,onMouseUp:b,...h(e.id,"image")}:{}}),i?.map((g,C)=>{let I=g.points.map((k,x)=>x%2===0?k*e.width+e.x:k*e.height+e.y),B=g.strokeWidth*e.width;return jsx(Line,{points:I,stroke:g.tool==="eraser"?"white":g.color,strokeWidth:B,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:g.tool==="eraser"?"destination-out":"source-over",fill:g.isSketch?g.color:void 0,closed:g.isSketch,listening:false},C)}),c&&jsx(Line,{points:c.points.map((g,C)=>C%2===0?g*e.width+e.x:g*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});Lu.displayName="ImageWithDrawing";var Ui=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u})=>jsx(Fragment,{children:e.map(i=>{let c=o(i);return c?jsx(Lu,{img:i,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u},i.id):null})}));Ui.displayName="ImageLayer";var wh=({src:e,x:o,id:t,y:a,width:n,height:r,isSelected:s,rotation:u=0,onTransformEnd:i,onDragEnd:c})=>{let f=Se(),d=useRef(null),l=m=>{f(Xa(m));};return jsxs(Group,{draggable:true,x:o,y:a,width:n,height:r,rotation:u,onDragEnd:c,onTransformEnd:i,children:[jsx(Rect,{width:n,height:r,fill:"black",stroke:s?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${n}px`,height:`${r}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>l(t),onSeeking:m=>m.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Iu=wh;var Ah=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,nodeRef:s})=>{let[u,i]=useState(null),c=useSelector(p=>p.toolbar.selectedTool),f=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let p=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(p.crossOrigin="anonymous"),p.src=e.thumbnailDataUrl,p.onload=()=>{i(p);};}},[e.thumbnailDataUrl]),!u)return null;let d=e.width/2,l=e.height/2,m=Math.min(e.width,e.height)*.08,h=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:n},ref:p=>{if(s(p),p){let v=p.getStage()?.container();if(v){let y=b=>{let g=p.getStage()?.getPointerPosition();if(g){let C={x:e.x,y:e.y,width:e.width,height:e.height};g.x>=C.x&&g.x<=C.x+C.width&&g.y>=C.y&&g.y<=C.y+C.height&&r(b);}};v.addEventListener("contextmenu",y),p._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",y);};}}},children:[jsx(Image$1,{image:u,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:d,y:l,radius:h,fill:"white",listening:!f,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...f?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:l,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!f,...f?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:l,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!f,...f?{}:{onClick:t,onTap:t}})]})},ku=Ah;var ji=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:n,onTransformEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(u=>jsxs(Le__default.Fragment,{children:[jsx(ku,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>a(u.id),onDragEnd:i=>n(u.id,i),onTransformEnd:i=>r(u.id,i),onContextMenu:i=>s(i,u.id,"video"),nodeRef:i=>{i?t.current.set(u.id,i):t.current.delete(u.id);}}),u.isPlaying&&!u.isRecorded&&jsx(Iu,{id:u.id,src:u.objectUrl,x:u.x,y:u.y,width:u.width,height:u.height,isSelected:false,rotation:u.rotation,onTransformEnd:i=>r(u.id,i),onDragEnd:i=>n(u.id,i)})]},u.id))}));ji.displayName="VideoLayer";var _i=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:n,handleShapeDragStart:r,onContextMenu:s,onLongPress:u})=>{let i=useSelector(d=>d.toolbar.selectedTool),c=i==="pen"||i==="eraser",{createHandlers:f}=Ve({onLongPress:u});return jsx(Fragment,{children:e.map((d,l)=>{let m=d.id||l,h={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!c,listening:!c,fill:d.color||"#096B76",stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?2:0,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radius:d.radius||d.width/2,width:d.width,height:d.width},m);case "star":return jsx(Star,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},m);case "triangle":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},sides:3,radius:d.radius||d.width/2},m);case "polygon":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},sides:d.sides||6,radius:d.radius||d.width/2},m);case "ellipse":return jsx(Ellipse,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},m);case "ring":return jsx(Ring,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},m);case "wedge":return jsx(Wedge,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radius:d.radius||d.width/2,angle:d.angle||60},m);case "arrow":return jsx(Arrow,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?d.strokeWidth||3:0,fill:"transparent"},m);case "line":return jsx(Line,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},points:d.points||[0,0,d.width,0],stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?d.strokeWidth||3:0,fill:"transparent"},m);case "arc":return jsx(Arc,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},m);case "rectangle":default:return jsx(Rect,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},m)}})})});_i.displayName="ShapeLayer";var Au=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:n,onContextMenu:r,onDoubleClick:s,editingTextId:u,onLongPress:i})=>{useEffect(()=>{e.forEach(l=>{let m=o.current.get(l.id);m&&(m.cache(),m.getLayer()?.batchDraw());});},[e,o]);let c=useSelector(l=>l.toolbar.selectedTool),f=c==="pen"||c==="eraser",{createHandlers:d}=Ve({onLongPress:i});return jsx(Fragment,{children:e.map(l=>{let m=l.id===u,h=l.fontWeight==="bold",p=h?Math.max(1,l.fontSize/25):0;return jsx(Text,{id:l.id,ref:v=>{v?o.current.set(l.id,v):o.current.delete(l.id);},text:l.text,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:!l.locked&&!m&&!f,listening:!f,fontSize:l.fontSize,fontFamily:l.fontFamily,fontStyle:l.fontStyle,fontWeight:l.fontWeight,textDecoration:l.textDecoration,fill:l.fill,stroke:h?l.fill:void 0,strokeWidth:p,align:l.align,wrap:"word",lineHeight:1.2,opacity:m?0:1,visible:!m,...f?{}:{onClick:()=>n(l.id),onTap:()=>n(l.id),onDblClick:()=>s(l.id),onDblTap:()=>s(l.id),onDragEnd:v=>t(v,l.id),onTransformEnd:()=>a(l.id),onContextMenu:v=>{v.evt.preventDefault();let y=v.evt;r(y,l.id,"text");},...d(l.id,"text")}},l.id)})})};var tg=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onNext:s,onPrevious:u,nodeRef:i,touchHandlers:c,currentTool:f})=>{let[d,l]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let b=new window.Image,g=e.images[e.currentIndex];(g.startsWith("http://")||g.startsWith("https://"))&&(b.crossOrigin="anonymous"),b.src=g,b.onload=()=>{l(b);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let m=8,h=2,p=Math.min(e.width,e.height)*.08,v=Math.max(16,Math.min(p,32)),y=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked&&f==="select",x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:n,...c,ref:b=>{if(i(b),b){let g=b.getStage()?.container();if(g){let C=I=>{let B=b.getStage()?.getPointerPosition();if(B){let k={x:e.x,y:e.y,width:e.width,height:e.height};B.x>=k.x&&B.x<=k.x+k.width&&B.y>=k.y&&B.y<=k.y+k.height&&r(I);}};g.addEventListener("contextmenu",C),b._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",C);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:m,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:m,stroke:"#E5E7EB",strokeWidth:h,listening:false}),jsx(Image$1,{x:h+4,y:h+4,image:d,width:e.width-(h+4)*2,height:e.height-(h+4)*2,cornerRadius:m-h,onClick:t,onTap:t}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:y+v,y:e.height/2,onClick:b=>{b.cancelBubble=true,u();},onTap:b=>{b.cancelBubble=true,u();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-y-v,y:e.height/2,onClick:b=>{b.cancelBubble=true,s();},onTap:b=>{b.cancelBubble=true,s();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Du=tg;var Zi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onNext:s,onPrevious:u,onContextMenu:i,onLongPress:c})=>{let{createHandlers:f}=Ve({onLongPress:c}),d=J(l=>l.toolbar.selectedTool);return jsx(Fragment,{children:e.map(l=>jsx(Du,{flashcard:l,isSelected:t===l.id,onClick:()=>r(l.id),currentTool:d,onDragEnd:a,onTransformEnd:m=>n(l.id,m),onContextMenu:m=>i(m,l.id,"flashcard"),onNext:()=>s(l.id),onPrevious:()=>u(l.id),touchHandlers:f(l.id,"flashcard"),nodeRef:m=>{m?o.current.set(l.id,m):o.current.delete(l.id);}},l.id))})});Zi.displayName="FlashcardLayer";var Fu=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null);J(g=>g.toolbar.selectedTool);let i=J(g=>g.toolbar.penColor),c=J(g=>g.toolbar.strokeWidth),f=J(g=>g.canvas.isSketchMode),d=J(g=>g.canvas.slides.find(I=>I.id===g.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),l=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(g=>{if(!m)return;t.current=true,a.current=false,n.current=[{x:g.x,y:g.y}];let C=g.x/h,I=g.y/p;s({tool:"pen",points:[C,I],color:i,strokeWidth:c/h,isSketch:f});},[m,i,c,f,h,p]),y=useCallback(g=>{if(!t.current||!r)return;a.current=true;let C=n.current[n.current.length-1];if(Math.sqrt(Math.pow(g.x-C.x,2)+Math.pow(g.y-C.y,2))<2)return;n.current.push({x:g.x,y:g.y});let B;if(f)B=Xn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,S)=>S%2===0?x/h:x/p);else {let k=g.x/h,x=g.y/p;B=[...r.points,k,x];}s(k=>k?{...k,points:B}:null);},[f,c,r,h,p]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(bi({frameId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:m,startDrawing:v,draw:y,stopDrawing:b}};var dg=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onStartCamera:s,onCapture:u,cameraStream:i,nodeRef:c,touchHandlers:f})=>{let[d,l]=useState(null),[m,h]=useState(null),p=useRef(null),v=useRef(null),y=useRef(null),b=useRef(null),g=useRef(0),C=33,I=useSelector(P=>P.toolbar.selectedTool),B=I==="pen"||I==="eraser",{annotations:k,activeLine:x,isDrawingMode:S,startDrawing:w,draw:T,stopDrawing:q}=Fu(e.id);useEffect(()=>{if(!S)return;let P=()=>{q();},N=()=>{q();};return window.addEventListener("mouseup",P),window.addEventListener("touchend",N),()=>{window.removeEventListener("mouseup",P),window.removeEventListener("touchend",N);}},[q,S]),useEffect(()=>{if(e.capturedImageUrl){let P=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(P.crossOrigin="anonymous"),P.src=e.capturedImageUrl,P.onload=()=>{l(P);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),v.current||(v.current=document.createElement("canvas"));let P=p.current,N=v.current;P.srcObject=i;let _=()=>{N.width=P.videoWidth||640,N.height=P.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",N.width,N.height);let Q=re=>{if(re-g.current<C){y.current=requestAnimationFrame(Q);return}g.current=re;let j=N.getContext("2d");if(j&&P.readyState===P.HAVE_ENOUGH_DATA){j.drawImage(P,0,0,N.width,N.height);let pe=N.toDataURL("image/jpeg",.6),ge=new window.Image;ge.onload=()=>{h(ge);},ge.src=pe;}y.current=requestAnimationFrame(Q);};y.current=requestAnimationFrame(Q);};return P.onloadedmetadata=_,P.readyState>=P.HAVE_METADATA&&_(),P.play().catch(Q=>console.error("Error playing video:",Q)),()=>{y.current&&(cancelAnimationFrame(y.current),y.current=null);}}return ()=>{h(null),b.current&&(b.current.src="");}},[e.isCapturing,i]);let H=()=>{p.current&&e.isCapturing&&u(p.current);},F=P=>{if(e.capturedImageUrl){if(!S){t();return}let N=P.currentTarget,_=N.getAbsoluteTransform().copy(),re=N.getStage()?.getPointerPosition();if(re){_.invert();let j=_.point(re);w(j);}P.cancelBubble=true;}else t();},V=P=>{if(!S||!e.capturedImageUrl)return;let N=P.currentTarget,_=N.getAbsoluteTransform().copy(),re=N.getStage()?.getPointerPosition();if(re){_.invert();let j=_.point(re);T(j);}},U=()=>{!S||!e.capturedImageUrl||q();},K=e.isCapturing?m:d,R=Math.min(e.width,e.height)*.12,z=Math.max(25,Math.min(R,50)),ne=e.width/2,X=e.height/2;return jsxs(Group,{id:e.id,draggable:!S&&!B,listening:true,onClick:t,onTap:t,x:e.x,y:e.y,...f,...B?{}:{onDragEnd:a,onTransformEnd:n},rotation:e.rotation,width:e.width,height:e.height,ref:P=>{if(c(P),P){let N=P.getStage()?.container();if(N){let _=Q=>{let re=P.getStage()?.getPointerPosition();if(re){let j={x:e.x,y:e.y,width:e.width,height:e.height};re.x>=j.x&&re.x<=j.x+j.width&&re.y>=j.y&&re.y<=j.y+j.height&&r(Q);}};N.addEventListener("contextmenu",_),P._contextMenuCleanup=()=>{N.removeEventListener("contextmenu",_);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:K?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),K&&jsx(Image$1,{image:K,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:F,onTap:F,onMouseDown:F,onTouchStart:F,onMouseMove:V,onTouchMove:V,onMouseUp:U,onTouchEnd:U,...B?{}:{onDragEnd:a,onTransformEnd:n}}),k?.map((P,N)=>{let _=P.points.map((re,j)=>j%2===0?re*e.width:re*e.height),Q=P.strokeWidth*e.width;return jsx(Line,{points:_,stroke:P.tool==="eraser"?"white":P.color,strokeWidth:Q,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:P.tool==="eraser"?"destination-out":"source-over",fill:P.isSketch?P.color:void 0,closed:P.isSketch,listening:false},N)}),x&&jsx(Line,{points:x.points.map((P,N)=>N%2===0?P*e.width:P*e.height),stroke:x.tool==="eraser"?"white":x.color,strokeWidth:x.strokeWidth*e.width,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},"active"),!K&&!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:X-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:ne-z+6,y:X-60,width:z*1.6,height:z*1.6,radius:z,fill:"white",cornerRadius:8,listening:true,onClick:P=>{P.cancelBubble=true,e.isCapturing?H():s();},onTap:P=>{P.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:ne-12,y:X-40,width:z*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:P=>{P.stopPropagation(),e.isCapturing?H():s();}})})]}),jsx(Text,{x:0,y:X,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:X+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:ne-24,y:X+104,width:z*1.6,height:z*1.6,radius:z,fill:"#096B76",cornerRadius:z,listening:true,onClick:P=>{P.cancelBubble=true,e.isCapturing?H():s();},onTap:P=>{P.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:ne-8,y:X+120,width:z*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:P=>{P.stopPropagation(),e.isCapturing?H():s();}})})]}),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:ne-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:P=>{P.stopPropagation(),H();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},Hu=dg;var ol=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onStartCamera:s,onCapture:u,cameraStreams:i,onContextMenu:c,onLongPress:f})=>{let{createHandlers:d}=Ve({onLongPress:f});return jsx(Fragment,{children:e.map(l=>jsx(Hu,{photoFrame:l,isSelected:t===l.id,onClick:()=>r(l.id),onDragEnd:m=>a(m,l.id),onContextMenu:m=>c(m,l.id,"photoFrame"),onStartCamera:()=>s(l.id),onCapture:m=>u(l.id,m),cameraStream:i.get(l.id),touchHandlers:d(l.id,"photoFrame"),nodeRef:m=>{m?o.current.set(l.id,m):o.current.delete(l.id);}},l.id))})});ol.displayName="PhotoFrameLayer";var Wu=({x:e,y:o,onAction:t,onClose:a,type:n,isDrawingMode:r,menuRef:s})=>{useEffect(()=>{let f=l=>{s?.current&&!s.current.contains(l.target)&&a();},d=l=>{l.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",d);}},[a]);let u=useMemo(()=>[{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"border",label:"Toggle Border",icon:jsx(FrameCorners,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"draw",label:r?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line","video"]},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(d=>!(d.showForTypes&&!d.showForTypes.includes(n)||d.hideForTypes&&d.hideForTypes.includes(n))),[n,r]),i=(f,d)=>{f==="order"||f==="lock"?t(f,d):(t(f),a());},c=jsx("div",{ref:s,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:u.map((f,d)=>jsxs("button",{onClick:l=>i(f.action,l),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${f.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[f.icon,jsx("span",{className:`font-medium ${f.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:f.label})]}),f.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},d))})});return createPortal(c,document.body)};var Uu=({x:e,y:o,items:t,onClose:a})=>{let n=useRef(null);return useEffect(()=>{let r=s=>{n.current&&!n.current.contains(s.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:n,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((r,s)=>jsx("button",{onClick:()=>{r.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:r.label})},s))})})};var Gu=createContext(null),rl=()=>useContext(Gu);function Pg({children:e,className:o="",style:t}){let a=useRef(null),[n,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Gu.Provider,{value:n,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function ze(){let e=rl();return typeof document>"u"?null:e||document.body}var ju=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:n,onClose:r})=>{let[s,u]=useState(a),i=useRef(null),c=ze();useEffect(()=>{i.current?.focus();},[]);let f=()=>{n(s),r();},d=m=>{m.key==="Enter"?f():m.key==="Escape"&&r();};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:i,type:"text",value:s,onChange:m=>u(m.target.value),onKeyDown:d,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:r,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:f,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),c):null};var es=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,n]=useState(e),r=useRef(null),s=ze();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let u=d=>{d.preventDefault(),o(a);},i=(d,l,m)=>{m/=100;let h=l*Math.min(m,1-m)/100,p=v=>{let y=(v+d/30)%12,b=m-h*Math.max(Math.min(y-3,9-y,1),-1);return Math.round(255*b).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!s)return null;let f=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:r,className:"max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:u,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:d=>n(d.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:d=>n(d.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:d=>{let l=parseInt(d.target.value),m=i(l,100,50);n(m);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(d=>jsx("button",{type:"button",onClick:()=>n(d),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===d.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:d},title:d},d))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(f,s)};var Xg=({imageSrc:e,onCrop:o})=>{let[t]=Xu(e),a=useRef(null),n=useRef(null),r=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),u=useMemo(()=>{let l=s.width*.5,m=s.height*.5,h=(s.width-l)/2,p=(s.height-m)/2;return {x:h,y:p,width:l,height:m}},[s]),[i,c]=useState(u);useEffect(()=>{c(u);},[u]),useEffect(()=>{r.current&&n.current&&(r.current.nodes([n.current]),r.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let f=()=>{let l=n.current;if(!l)return;let m=l.scaleX(),h=l.scaleY();l.scaleX(1),l.scaleY(1),c({x:l.x(),y:l.y(),width:Math.max(20,l.width()*m),height:Math.max(20,l.height()*h)});},d=()=>{let l=n.current;l&&c({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:s.width,height:s.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:s.width,height:s.height}),jsx(Rect,{x:0,y:0,width:s.width,height:s.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:n,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:f,dragBoundFunc:l=>{let m=Math.max(0,Math.min(l.x,s.width-i.width)),h=Math.max(0,Math.min(l.y,s.height-i.height));return {x:m,y:h}}}),jsx(Transformer,{ref:r,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(l,m)=>m.width<20||m.height<20||m.x<0||m.y<0||m.x+m.width>s.width||m.y+m.height>s.height?l:m})]})})},Yu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[n,r]=useState({x:0,y:0,width:0,height:0}),[s]=Xu(e),u=ze();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let i=(d,l,m,h)=>{r({x:d,y:l,width:m,height:h});},c=()=>{if(!s)return;let m=Math.min(600/s.width,400/s.height),h=n.x/m,p=n.y/m,v=n.width/m,y=n.height/m,b=document.createElement("canvas");b.width=v,b.height=y;let g=b.getContext("2d");if(!g)return;g.drawImage(s,h,p,v,y,0,0,v,y);let C=b.toDataURL("image/png");o(C);};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{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(Xg,{imageSrc:e,onCrop:i})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:c,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),u):null};var eo=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let n=ze(),[r,s]=useState(false),[u,i]=useState(null),[c,f]=useState(0),[d,l]=useState(true),m=useRef(null),h=useRef([]),p=useRef(null),v=useRef(null),y=useRef(null),b=useRef(null),g=useRef(null),C=useRef(null);useEffect(()=>()=>{y.current&&cancelAnimationFrame(y.current),p.current&&clearInterval(p.current),v.current&&v.current.getTracks().forEach(w=>w.stop());},[]);let I=async()=>{try{let w,T=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let U=o.current.getLayers();console.log("Konva layers:",U.length),U.forEach((_,Q)=>{let re=_.getChildren();console.log(`Layer ${Q} children count:`,re.length);});let K=document.createElement("canvas");K.width=o.current.width(),K.height=o.current.height();let R=K.getContext("2d",{willReadFrequently:!1});if(!R){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",K.width,"x",K.height),g.current=K;let z=()=>{if(R.clearRect(0,0,K.width,K.height),U.forEach(_=>{let Q=_.getCanvas()._canvas;Q&&R.drawImage(Q,0,0);}),a?.current){let _=a.current;R.drawImage(_,0,0);}};C.current=z,o.current.draw(),z(),await new Promise(_=>setTimeout(_,100)),console.log("Creating captureStream..."),w=K.captureStream(30),console.log("Canvas stream created, tracks:",w.getTracks().length);let X=w.getVideoTracks()[0];X&&console.log("Video track:",X.label,"state:",X.readyState);let P=0,N=()=>{z(),o?.current&&(o.current.getLayers().forEach(Q=>{Q.batchDraw();}),P++,P%60===0&&console.log("Drawing frame:",P)),y.current=requestAnimationFrame(N);};N();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{T=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let q=[...w.getVideoTracks()];T&&q.push(...T.getAudioTracks());let H=new MediaStream(q);v.current=H;let F="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?F="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?F="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?F="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(F="video/webm;codecs=vp8"),console.log("Using mimeType:",F);let V=new MediaRecorder(H,{mimeType:F,videoBitsPerSecond:25e5});m.current=V,h.current=[],V.ondataavailable=U=>{console.log("Data available, size:",U.data.size),U.data.size>0&&h.current.push(U.data);},V.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let U=new Blob(h.current,{type:F});console.log("Final blob size:",U.size),o?.current&&C.current&&g.current&&(o.current.draw(),o.current.getLayers().forEach(R=>{R.batchDraw();}),C.current(),b.current=g.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",b.current.length)),H.getTracks().forEach(K=>K.stop()),p.current&&clearInterval(p.current),y.current&&(cancelAnimationFrame(y.current),y.current=null),i(U);},V.onerror=U=>{console.error("MediaRecorder error:",U);},console.log("Starting recording..."),V.start(1e3),s(!0),f(0),p.current=setInterval(()=>{f(U=>U+1);},1e3);}catch(w){console.error("Error starting screen recording:",w),alert("Failed to start recording. Please ensure you granted permission.");}},B=()=>{m.current&&r&&(console.log("Stopping recording, state:",m.current.state),m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),s(false));},k=()=>{if(u){let w=URL.createObjectURL(u),T=document.createElement("a");T.href=w,T.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(w);}},x=w=>{let T=Math.floor(w/60),q=w%60;return `${T.toString().padStart(2,"0")}:${q.toString().padStart(2,"0")}`};if(!n)return null;if(r){let w=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:x(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:B,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(w,n)}let S=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!u&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>l(!d),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${d?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:d?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:I,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),u&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(u),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",x(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&b.current&&(t(u,b.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:k,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),f(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})});return createPortal(S,n)};var ec=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:n})=>{let r=ze(),[s,u]=useState(false),[i,c]=useState(null),[f,d]=useState(false),[l,m]=useState(0),h=useRef(null),p=useRef([]),v=useRef(null),y=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(w=>w.blob()).then(w=>c(w)).catch(w=>console.error("Error loading audio:",w));},[o,i]);let b=async()=>{try{let w=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),T=new MediaRecorder(w);h.current=T,p.current=[],T.ondataavailable=q=>{q.data.size>0&&p.current.push(q.data);},T.onstop=()=>{let q=new Blob(p.current,{type:"audio/webm"});c(q),w.getTracks().forEach(H=>H.stop()),v.current&&clearInterval(v.current);},T.start(),u(!0),m(0),v.current=setInterval(()=>{m(q=>q+1);},1e3);}catch(w){console.error("Error starting audio recording:",w),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{h.current&&s&&(h.current.stop(),u(false));},C=()=>{if(i){let w=URL.createObjectURL(i),T=new Audio(w);y.current=T,T.onended=()=>{d(false),URL.revokeObjectURL(w);},T.play(),d(true);}},I=()=>{y.current&&(y.current.pause(),y.current.currentTime=0,d(false));},B=async()=>{if(i){let w=new FileReader;w.onloadend=()=>{let T=w.result;t(T),n();},w.readAsDataURL(i);}},k=()=>{c(null),a();},x=w=>{let T=Math.floor(w/60),q=w%60;return `${T.toString().padStart(2,"0")}:${q.toString().padStart(2,"0")}`};if(!r)return null;if(s){let w=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:x(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:g,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(w,r)}let S=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick: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:f?I:C,className:"flex w-full cursor-pointer 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"}),f?"Playing...":"Play Audio"]}),jsxs("button",{onClick:k,className:"flex w-full cursor-pointer items-center gap-2 rounded-lg border border-red-300 bg-red-600 px-4 py-3 text-white transition-colors hover:bg-red-700",children:[jsx(Trash,{className:"h-5 w-5",weight:"fill"}),"Delete Audio"]})]}),jsx("button",{onClick:B,className:"w-full cursor-pointer rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:n,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})});return createPortal(S,r)};var Nt=({audioData:e,x:o,y:t,width:a,scale:n=1,offsetX:r=0,offsetY:s=0,containerTop:u=90,containerRight:i=320})=>{let[c,f]=useState(false),d=useRef(null),l=p=>{if(p.stopPropagation(),c&&d.current)d.current.pause(),d.current.currentTime=0,f(false);else {let v=new Audio(e);d.current=v,v.onended=()=>{f(false);},v.onerror=()=>{console.error("Error playing audio"),f(false);},v.play(),f(true);}},m=(o+a)*n+r-15,h=t*n+s+u-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${c?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${m}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var oc=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=Se(),n=J(ve),r=ze(),s=useMemo(()=>{if(!n)return [];let y=[];return n.images?.forEach(b=>{y.push({id:b.id,type:"image",name:"Image",timestamp:b.timestamp||0});}),n.videos?.forEach(b=>{y.push({id:b.id,type:"video",name:"Video",timestamp:b.timestamp||0});}),n.shapes?.forEach(b=>{y.push({id:b.id,type:"shape",name:`${b.type} Shape`,timestamp:b.timestamp||0});}),n.texts?.forEach(b=>{y.push({id:b.id,type:"text",name:b.text.substring(0,20)+(b.text.length>20?"...":""),timestamp:b.timestamp||0});}),n.flashcards?.forEach(b=>{y.push({id:b.id,type:"flashcard",name:`Flashcard (${b.images.length} images)`,timestamp:b.timestamp||0});}),n.photoFrames?.forEach(b=>{y.push({id:b.id,type:"photoFrame",name:"Photo Frame",timestamp:b.timestamp||0});}),n.multipleChoices?.forEach(b=>{y.push({id:b.id,type:"mcq",name:"Multiple Choice",timestamp:b.timestamp||0});}),n.trueFalses?.forEach(b=>{y.push({id:b.id,type:"trueFalse",name:"True/False",timestamp:b.timestamp||0});}),n.shortAnswers?.forEach(b=>{y.push({id:b.id,type:"shortAnswer",name:"Short Answer",timestamp:b.timestamp||0});}),n.LongAnswer?.forEach(b=>{y.push({id:b.id,type:"longAnswer",name:"Long Answer",timestamp:b.timestamp||0});}),n.fillInTheBlanks?.forEach(b=>{y.push({id:b.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:b.timestamp||0});}),n.lines?.forEach(b=>{b.id&&y.push({id:b.id,type:"line",name:"Drawn Line",timestamp:b.timestamp||0});}),y.sort((b,g)=>g.timestamp-b.timestamp)},[n]),[u,i]=useState(s),[c,f]=useState(false);useEffect(()=>{c||i(s);},[s]);let d=y=>{let b="h-5 w-5";switch(y){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$1,{className:b});case "line":return jsx(Pen,{className:b});default:return jsx(Question,{className:b})}},h=y=>{f(true),i(y);},p=()=>{f(false);let y=Date.now();u.forEach((b,g)=>{let C=y-g;a(xr({id:b.id,type:b.type,newTimestamp:C}));});};if(!r)return null;let v=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-50 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-50 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:u.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:u,onReorder:h,className:"space-y-1",children:u.map(y=>{let b=y.id===e;return jsxs(Reorder.Item,{value:y,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${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(y.id,y.type),className:`font-medium ${b?"text-[#096B76]":"text-[#00000099]"}`,children:y.name})}),jsx("div",{className:`${b?"text-[#096B76]":"text-[#00000099]"}`,children:d(y.type)})]},y.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[u.length," Layers"]})]})]})]});return createPortal(v,r)};var ss=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},rc=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,touchHandlers:s,onUpdate:u})=>{let i=useSelector(F=>F.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(null),l=e.data.responseOptions.attempts||0,m=useRef(null),h=useDispatch(),[p,v]=useState(new Set(e.data.responseOptions.selectedIndices||[])),[y,b]=useState(false);useEffect(()=>{let F=m.current;if(F)return a.current.set(e.id,F),()=>{a.current.delete(e.id);}},[e.id,a]);let g=new Set(e.data.responseOptions.correctIndex),C=g.size>1,I=F=>{if(y)return;let V;C?(V=new Set(p),V.has(F)?V.delete(F):V.add(F)):V=new Set([F]),v(V);let U=Array.from(V),K=U.length===e.data.responseOptions.correctIndex.length&&U.every(R=>e.data.responseOptions.correctIndex.includes(R));h(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:U,isCorrect:K}}})),u?.();},B=()=>{p.size>0&&(b(true),h(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},k=()=>{b(false),v(new Set);},x=p.size===g.size&&Array.from(p).every(F=>g.has(F)),S=Array.from(p).filter(F=>g.has(F)),w=C&&S.length>0&&!x,T=()=>x?"\u2713 Correct! Great job! \u{1F389}":w?`\u26A0 Partially correct (${S.length}/${g.size})`:"\u2717 Try again!",q=()=>x?{bg:"#dcfce7",text:"#166534"}:w?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},H=useMemo(()=>{let X=e.data.feedbackMode==="practice"?48:0,P=12,N=e.width-48,_=N-80,Q=Math.max(60,ss(e.data.question,20,N,"bold")+20),re=`Select ${g.size} answers (${p.size}/${g.size} selected)`,j=C&&!y&&e.data.feedbackMode==="practice"?ss(re,14,N)+10:0,pe=y&&e.data.feedbackMode==="practice"?Math.max(60,ss(T(),16,N-40)+30):0,ge=e.data.responseOptions.options.map(xe=>{let St=ss(xe,16,_);return Math.max(55,St+20)}),le=Q+j+pe,ye=ge.reduce((xe,St)=>xe+St+8,-8),we=le+ye+P+X+24;return {padding:24,questionHeight:Q,instructionHeight:j,feedbackHeight:pe,optionsStartY:le,optionHeights:ge,totalHeight:we,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:X,buttonTopMargin:P,availableWidth:N,optionTextWidth:_}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,y,p.size,g.size,C,T]);return jsxs(Group,{ref:m,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:H.totalHeight,onTransformEnd:F=>o(e.id,F),...s,...c?{}:{onDragEnd:n,onClick:F=>t&&t(e.id),onTap:F=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:H.totalHeight,width:e.width,onContextMenu:F=>{F.cancelBubble=true,r(F.evt,e.id,"mcq");}}),jsx(Text,{x:H.padding+8,y:H.padding,text:e.data.question,fontSize:H.questionFontSize,fontStyle:"bold",fill:"#111827",width:H.availableWidth,height:H.questionHeight-H.padding,wrap:"word",ellipsis:true,listening:false}),H.instructionHeight>0&&jsx(Text,{x:H.padding,y:H.questionHeight,text:`Select ${g.size} answers (${p.size}/${g.size} selected)`,fontSize:H.instructionFontSize,fill:"#6b7280",width:H.availableWidth,wrap:"word",listening:false}),y&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:H.padding+24,y:H.questionHeight+H.instructionHeight+10,width:H.availableWidth-40,height:H.feedbackHeight-20,fill:q().bg,cornerRadius:8}),jsx(Text,{x:H.padding+24,y:H.questionHeight+H.instructionHeight+10,width:H.availableWidth-40,height:H.feedbackHeight-20,text:T()+` (${l} attempts)`,fontSize:H.feedbackFontSize,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((F,V)=>{let U=g.has(V),K=p.has(V),R=H.optionsStartY;for(let N=0;N<V;N++)R+=H.optionHeights[N]+H.optionGap;let z=H.optionHeights[V],ne="#e5e7eb",X="#ffffff",P="#111827";return y&&K&&!U?(ne="#ef4444",X="#fee2e2",P="#ef4444"):K&&(ne="#096B76",X="#ECFFF8",P="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:H.padding+12,y:R+(z-20)/2,width:20,height:20,fill:K?"#096B76":"white",stroke:K?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:C?4:10,onClick:N=>{N.cancelBubble=true,I(V);},onTap:N=>{N.cancelBubble=true,I(V);}}),K&&jsx(Text,{x:H.padding+12,y:R+(z-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:H.padding+44,y:R,width:H.availableWidth-60,height:z,fill:X,stroke:ne,strokeWidth:2,cornerRadius:8,onClick:N=>{N.cancelBubble=true,I(V);},onTap:N=>{N.cancelBubble=true,I(V);}}),jsx(Text,{x:H.padding+60,y:R+10,width:H.optionTextWidth,height:z-20,text:F,fontSize:H.optionFontSize,fill:P,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},V)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:H.optionsStartY+H.optionHeights.reduce((F,V)=>F+V+H.optionGap,-H.optionGap)+H.buttonTopMargin,children:[jsxs(Group,{onMouseDown:F=>{F.cancelBubble=true,d("check");},onMouseUp:F=>{F.cancelBubble=true,d(null),B();},onMouseLeave:F=>{F.cancelBubble=true,d(null);},onTouchStart:F=>{F.cancelBubble=true,d("check");},onTouchEnd:F=>{F.cancelBubble=true,d(null),B();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:H.padding+14,width:(H.availableWidth-24)/(y?2:1),height:H.buttonHeight,fill:p.size===0||y?"#9ca3af":"#096B76",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:H.padding+14,width:(H.availableWidth-24)/(y?2:1),height:H.buttonHeight,text:y?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),y&&jsxs(Group,{x:(e.width-H.padding*2)/2+8,onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),k();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),k();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:H.padding,width:(H.availableWidth-8)/2,height:H.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:H.padding,width:(H.availableWidth-8)/2,height:H.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});rc.displayName="MultipleChoice";var nc=rc;var Vx=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},dl=({multipleChoice:e,onContextMenu:o,handleSelect:t,mcqRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(R=>R.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,f]=useState(false),d=e.data.responseOptions.selectedIndices??[],l=useMemo(()=>new Set(d),[d]),m=e.data.responseOptions.attempts??0,h=m>0,[p,v]=useState(false),[y,b]=useState(0),g=new Set(e.data.responseOptions.correctIndex),C=Array.from(l).filter(R=>g.has(R)),I=l.size===g.size&&Array.from(l).every(R=>g.has(R)),B=C.length>0&&!I,k=()=>I?"\u2713 Correct! Great job!":B?`\u26A0 Partially correct (${C.length}/${g.size})`:"\u2717 Try again!",x=useCallback(R=>{let z=R.target;s(yi({id:e.id,dragDropPos:{x:z.x(),y:z.y()}})),r?.();},[s,e.id,r]),S=useMemo(()=>{let z=Math.max(window.innerWidth*.3,500),ne=20,X=18,P=28,N=40,_=50,Q=20,re=60,j=Math.max(z-40,400),pe=Math.max(60,Vx(e.data.question,ne,j,"bold")),ge=Math.max(z-Q*2,400),le=Math.max(150,window.innerHeight*.2),ye=e.data.feedbackMode==="practice",we=pe+20+le+(h?re+18:0)+(ye?N+(h?_:0)+20:0),xe=we+100;return {screenWidth:z,screenHeight:xe,dropZoneWidth:ge,dropZoneHeight:le,questionFontSize:ne,questionHeight:pe,feedbackFontSize:X,feedbackHeight:re,dropHereFontSize:P,buttonHeight:N,buttonGap:_,padding:Q,contentWidth:j,totalContentHeight:we,isPracticeMode:ye}},[e.data.question,e.data.feedbackMode,h]),w=useRef(null);useEffect(()=>{let R=w.current;if(R)return a.current.set(e.id,R),()=>{a.current.delete(e.id);}},[e.id,a]);let T=R=>{s(yi({id:e.id,dragDropPos:{x:R.target.x(),y:R.target.y()}})),r?.();},q=R=>{let z=R.target,ne=z.x(),X=z.y(),P=window.innerWidth*.2,N=50,_=S.padding,Q=S.padding+S.dropZoneWidth,re=S.questionHeight+20,j=S.questionHeight+20+S.dropZoneHeight,pe=ne+P>_&&ne<Q&&X+N>re&&X<j;f(pe),r?.();},H=(R,z)=>{let ne=z.target,X=ne.x(),P=ne.y(),N=window.innerWidth*.2,_=50;s(gt({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[R]:{x:X,y:P}}}));let Q=S.padding,re=S.padding+S.dropZoneWidth,j=S.questionHeight+20,pe=S.questionHeight+20+S.dropZoneHeight,ge=X+N>Q&&X<re&&P+_>j&&P<pe,le;ge?le=new Set(l).add(R):(le=new Set(l),le.delete(R)),f(false);let ye=Array.from(le),we=ye.length===g.size&&ye.every(xe=>g.has(xe));s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:ye,isCorrect:we}}})),r?.();},F=()=>{s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},V=()=>{s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),f(false),b(R=>R+1),r?.();},U=()=>I?{bg:"#dcfce7",text:"#166534"}:B?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},K=()=>h?I?"#4CAF50":B?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:w,x:e.dragDropPos?.x,y:e.dragDropPos?.y,name:"mcq-element",width:S.screenWidth,height:S.screenHeight,draggable:!i,listening:!i,onDragMove:x,...n,...i?{}:{onClick:R=>t&&t(e.id),onTap:R=>t&&t(e.id),onContextMenu:R=>{R.evt.preventDefault(),o(R.evt,e.id,"mcq");}},children:[jsxs(Group,{rotation:e.rotation,onDragEnd:T,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:S.totalContentHeight+20,width:S.screenWidth,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:S.padding,y:S.padding,width:S.contentWidth,height:S.questionHeight-S.padding,text:e.data.question,fontSize:S.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:S.padding,y:S.questionHeight+20,width:S.dropZoneWidth,height:S.dropZoneHeight,fill:"#EBF6F7",stroke:K(),strokeWidth:3,dash:[10,10],cornerRadius:8}),h&&jsxs(Fragment,{children:[jsx(Rect,{x:S.padding+3,y:S.questionHeight+20+S.dropZoneHeight+18,width:S.dropZoneWidth-5,height:S.feedbackHeight,fill:U().bg,cornerRadius:8}),jsx(Text,{x:S.padding,y:S.questionHeight+20+S.dropZoneHeight+20,width:S.dropZoneWidth,height:S.feedbackHeight,text:k()+` (${m} attempts)`,fontSize:S.feedbackFontSize,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),l.size===0&&!h&&jsx(Text,{x:S.padding,y:S.questionHeight+20,width:S.dropZoneWidth,height:S.dropZoneHeight,text:g.size>1?`Drop ${g.size} Correct Answers Here`:"Drop Here",fontSize:S.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),S.isPracticeMode?jsxs(Group,{x:S.padding,y:S.questionHeight+20+S.dropZoneHeight+(h?S.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,!(h||l.size===0)&&(v(true),F());},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),F();},onTouchEnd:()=>v(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:h||l.size===0?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:S.buttonHeight,width:S.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:h||l.size===0?"#9ca3af":"white",width:S.dropZoneWidth,height:S.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),h&&jsxs(Group,{y:S.buttonGap,onMouseDown:V,onTouchStart:V,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:S.buttonHeight,width:S.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:S.dropZoneWidth,height:S.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((R,z)=>{let ne=z%2,X=Math.floor(z/2),P=S.dropZoneWidth/2+25,N=50,_=10,Q=l.has(z),re=g.has(z),j=h&&Q,pe="transparent";j?pe=re?"#4CAF50":"#ef4444":Q&&(pe="#4CAF50");let ge=h&&!Q?0:1,le=e.optionDragDropPos?.[z],ye=le?.x??ne*(P+_),we=le?.y??S.totalContentHeight+30+X*(N+_);return jsxs(Group,{x:ye,y:we,draggable:!h,onDragStart:xe=>{xe.cancelBubble=true;},onDragMove:xe=>{xe.cancelBubble=true,q(xe);},onDragEnd:xe=>{xe.cancelBubble=true,H(z,xe);},opacity:ge,children:[jsx(Rect,{width:P-20,height:N,fill:"white",stroke:pe,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:P-20,height:N,text:R,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${z}-${y}`)})]})};dl.displayName="MultipleChoiceDragAndDrop";var ic=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(nc,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:f=>n(f,c.id),onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id):jsx(dl,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id))})};var lc=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},dc=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s,onUpdate:u})=>{let i=useSelector(T=>T.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(false),l=e.data.responseOptions.attempts||0,[m,h]=useState(null),p=useDispatch(),[v,y]=useState(e.data.responseOptions.selectedResponse??null),b=useRef(null);useEffect(()=>{let T=b.current;if(T)return a.current.set(e.id,T),()=>{a.current.delete(e.id);}},[e.id]);let g=()=>{v!==null&&d(true),p(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},C=()=>{d(false),y(null);},I=e.data.responseOptions.correctAnswer,B=v===I,k=T=>{if(f)return;y(T);let q=T===e.data.responseOptions.correctAnswer;p(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:T,isCorrect:q}}})),u?.();},x=()=>B?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",S=()=>B?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},w=useMemo(()=>{let K=e.data.feedbackMode==="practice"?48:0,R=12,z=e.width-48,ne=Math.max(60,lc(e.data.question,20,z,"bold")+20),X=f&&e.data.feedbackMode==="practice"?Math.max(60,lc(x(),16,z-40)+30):0,P=ne+X,N=164,_=P+N+R+K+24;return {padding:24,questionHeight:ne,feedbackHeight:X,optionsStartY:P,optionsHeight:N,totalHeight:_,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:K,buttonTopMargin:R,availableWidth:z}},[e.width,e.data.question,e.data.feedbackMode,f,x]);return jsxs(Group,{ref:b,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:w.totalHeight,...s,...c?{}:{onDragEnd:T=>r(T,e.id),onClick:T=>t&&t(e.id),onTap:T=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:w.totalHeight,width:e.width,onTransformEnd:T=>o(e.id,T),onContextMenu:T=>{T.cancelBubble=true,n(T.evt,e.id,"trueFalse");}}),jsx(Text,{x:w.padding+8,y:w.padding,text:e.data.question,fontSize:w.questionFontSize,fontStyle:"bold",fill:"#111827",width:w.availableWidth,height:w.questionHeight-w.padding,wrap:"word",ellipsis:true,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:w.padding+24,y:w.questionHeight+10,width:w.availableWidth-40,height:w.feedbackHeight-20,fill:S().bg,cornerRadius:8}),jsx(Text,{x:w.padding+24,y:w.questionHeight+10,width:w.availableWidth-40,height:w.feedbackHeight-20,text:x()+` (${l} attempts)`,fontSize:w.feedbackFontSize,fontStyle:"bold",fill:S().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((T,q)=>{let H=I===T.value,F=v===T.value,V=(e.width-w.padding*3)/2,U=w.padding+q*(V+w.padding),K=w.optionsStartY,R=T.value===true,z=R?"#10b981":"#ef4444",ne="#ffffff",X="#ffffff",P="#e5e7eb";return f&&F&&(H?(X=R?"#f0fdf4":"#fef2f2",P=R?"#86efac":"#fecaca"):(X="#fee2e2",P="#ef4444")),F&&!f&&(P="#096B76",X="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:U,y:K,width:V,height:w.optionHeight+50,fill:X,stroke:P,strokeWidth:2,cornerRadius:12,onClick:N=>{N.cancelBubble=true,k(T.value);},onTap:N=>{N.cancelBubble=true,k(T.value);}}),jsx(Circle,{x:U+V/2,y:K+40,radius:28,fill:z,listening:false}),R?jsx(Text,{x:U+V/2-14,y:K+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:ne,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:U+V/2-14,y:K+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:ne,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:U,y:K+85,width:V,height:30,text:T.label,fontSize:w.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},T.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:w.optionsStartY+2*(w.optionHeight+w.optionGap)+w.buttonTopMargin,children:[jsxs(Group,{onMouseDown:T=>{T.cancelBubble=true,h("check");},onMouseUp:T=>{T.cancelBubble=true,h(null),g();},onMouseLeave:T=>{T.cancelBubble=true,h(null);},onTouchStart:T=>{T.cancelBubble=true,h("check");},onTouchEnd:T=>{T.cancelBubble=true,h(null),g();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:w.padding+14,width:(w.availableWidth-24)/(f?2:1),height:w.buttonHeight,fill:v===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:w.padding+14,width:(w.availableWidth-24)/(f?2:1),height:w.buttonHeight,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-w.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),C();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),C();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:w.padding,width:(w.availableWidth-8)/2,height:w.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:w.padding,width:(w.availableWidth-8)/2,height:w.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});dc.displayName="TrueFalse";var uc=dc;var ab="#FFFFFF",ml=({trueFalse:e,onContextMenu:o,handleSelect:t,trueFalseRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(P=>P.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,f]=useState(false),d=e.data.responseOptions.selectedResponse??null,l=(e.data.responseOptions.attempts??0)>0,[m,h]=useState(false),[p,v]=useState(0),y=e.data.responseOptions.attempts||0,b=340,g=100,C=Math.max(window.innerWidth*.3,400),I=window.innerHeight*.5,B=useRef(null);useEffect(()=>{let P=B.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id]);let x=Math.max(60,((P,N,_,Q)=>{let j=document.createElement("canvas").getContext("2d");if(!j)return N;j.font=`${Q} ${N}px Arial, sans-serif`;let pe=P.split(" "),ge=[],le="";return pe.forEach(ye=>{let we=le?`${le} ${ye}`:ye;j.measureText(we).width>_&&le!==""?(ge.push(le),le=ye):le=we;}),le&&ge.push(le),ge.length*N*1.2})(e.data.question,20,C-40,"bold")+20),S=x+10,w=C-40,T=I-x-250,q=useCallback(P=>{let N=P.target;s(ot({id:e.id,dragDropPos:{x:N.x(),y:N.y()}})),r?.();},[s,e.id,r]),H=P=>{s(ot({id:e.id,dragDropPos:{x:P.target.x(),y:P.target.y()}})),r?.();},F=P=>{let N=P.target,_=N.x(),Q=N.y(),re=window.innerWidth*.2-40,j=50,pe=20,ge=20+w,le=S,ye=S+T,we=_+re>pe&&_<ge&&Q+j>le&&Q<ye;f(we),r?.();},V=(P,N)=>{let _=P?"true":"false",Q=N.target;s(ot({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[_]:{x:Q.x(),y:Q.y()}}}));let re=Q.x(),j=Q.y(),pe=window.innerWidth*.2-40,ge=50,le=20,ye=20+w,we=S,xe=S+T;if(!(re+pe>le&&re<ye&&j+ge>we&&j<xe)){f(false);return}f(false);let ae=P===e.data.responseOptions.correctAnswer;s(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:P,isCorrect:ae}}}));},U=()=>{s(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},K=()=>{s(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),f(false),v(P=>P+1),r?.();},R=e.data.responseOptions.correctAnswer,z=d===R,ne=()=>z?"\u2713 Correct! Great job!":"\u2717 Try again!",X=()=>z?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:B,name:"trueFalse-element",width:C,height:I,x:e.dragDropPos?.x,y:e.dragDropPos?.y,draggable:!i,listening:!i,onDragMove:q,...n,...i?{}:{onClick:P=>t&&t(e.id),onTap:P=>t&&t(e.id),onContextMenu:P=>{P.evt.preventDefault(),o(P.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:g,rotation:e.rotation,onDragEnd:H,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:l?I:e.data.feedbackMode==="practice"?I-50:I-100,width:C,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:C-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:S,width:w,height:T,fill:"transparent",stroke:c?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:S,width:w,height:60,fill:X().bg,cornerRadius:8}),jsx(Text,{x:20,y:S,width:w,height:60,text:ne()+" ("+y+" attempts)",fontSize:18,fontStyle:"bold",fill:X().text,align:"center",verticalAlign:"middle"})]}),d===null&&!l&&jsx(Text,{x:20,y:S,width:w,height:T,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),[{value:true,label:"True"},{value:false,label:"False"}].map((P,N)=>{let _=w/2+20,Q=50,re=10,j=d===P.value,pe=R===P.value,ge=l&&j,le=P.value?"true":"false",ye=16+N*(_+re),we=g+I-300,xe=e.optionDragDropPos?.[le],St="transparent";return ge?St=pe?"#4CAF50":"#ef4444":j&&(St="#4CAF50"),jsxs(Group,{x:xe?.x??ye,y:xe?.y??we,draggable:!l,onDragStart:ae=>{ae.cancelBubble=true;},onDragMove:ae=>{ae.cancelBubble=true,F(ae);},onDragEnd:ae=>{ae.cancelBubble=true,V(P.value,ae);},opacity:l&&!j?.5:1,children:[jsx(Rect,{width:_-40,height:Q,fill:"#075560",stroke:St,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:_-40,height:Q,text:P.label,fontSize:18,fontStyle:"bold",fill:ab,align:"center",verticalAlign:"middle",listening:false})]},`${P.value}-${p}`)}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:I-100,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,!(l||d===null)&&d!==null&&(h(true),U());},onMouseUp:()=>h(false),onMouseLeave:()=>h(false),onTouchStart:()=>{d!==null&&(h(true),U());},onTouchEnd:()=>h(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:l||d===null?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:w}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:l||d===null?"#9ca3af":"white",width:w,height:40,align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{y:50,onMouseDown:K,onTouchStart:K,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:w}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:w,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]})})};ml.displayName="TrueFalseDragAndDrop";var cc=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(uc,{trueFalse:c,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id):jsx(ml,{trueFalse:c,handleSelect:t,trueFalseRefs:a,onContextMenu:r,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id))})};var Aa=new WeakMap,zo=new WeakMap,Rr={current:[]},hl=false,Dr=0,Er=new Set,is=new Map;function fc(e){let o=Array.from(e).sort((t,a)=>t instanceof jt&&t.options.deps.includes(a)?1:a instanceof jt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(Rr.current.includes(t))continue;Rr.current.push(t),t.recompute();let a=zo.get(t);if(a)for(let n of a){let r=Aa.get(n);r&&fc(r);}}}function nb(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function sb(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function ls(e){if(Dr>0&&!is.has(e)&&is.set(e,e.prevState),Er.add(e),!(Dr>0)&&!hl)try{for(hl=!0;Er.size>0;){let o=Array.from(Er);Er.clear();for(let t of o){let a=is.get(t)??t.prevState;t.prevState=a,nb(t);}for(let t of o){let a=Aa.get(t);a&&(Rr.current.push(t),fc(a));}for(let t of o){let a=Aa.get(t);if(a)for(let n of a)sb(n);}}}finally{hl=false,Rr.current=[],is.clear();}}function Mt(e){Dr++;try{e();}finally{if(Dr--,Dr===0){let o=Er.values().next().value;o&&ls(o);}}}function mc(e){return typeof e=="function"}var ea=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var n,r;this.listeners.add(a);let s=(r=(n=this.options)==null?void 0:n.onSubscribe)==null?void 0:r.call(n,a,this);return ()=>{this.listeners.delete(a),s?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,n;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):mc(o)?this.state=o(this.prevState):this.state=o,(n=(a=this.options)==null?void 0:a.onUpdate)==null||n.call(a),ls(this);}};var jt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),n=new Array(t);for(let r=0;r<t;r++){let s=this.options.deps[r];a[r]=s.prevState,n[r]=s.state;}return this.lastSeenDepValues=n,{prevDepVals:a,currDepVals:n,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let n=this.getDepVals();this.state=this.options.fn(n),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let r of this.options.deps)r instanceof e&&r.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:n}=this.getDepVals();for(let r=0;r<n.length;r++)if(n[r]!==a[r]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,n;this.listeners.add(t);let r=(n=(a=this.options).onSubscribe)==null?void 0:n.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof ea){let a=Aa.get(t);a||(a=new Set,Aa.set(t,a)),a.add(this);let n=zo.get(this);n||(n=new Set,zo.set(this,n)),n.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof ea){let a=Aa.get(t);a&&a.delete(this);let n=zo.get(this);n&&n.delete(t);}}};function ib(e){return typeof e=="function"}function gl(e,...o){return ib(e)?e(...o):e}function pc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Pa,bt,ft,Fr,Ea,ro,la,Wo,Br,ds,Or,Uo,no=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:n=1e3}){Ne(this,Pa,true);Ne(this,bt);Ne(this,ft);Ne(this,Fr);Ne(this,Ea);Ne(this,ro);Ne(this,la);Ne(this,Wo);Ne(this,Br,0);Ne(this,ds,5);Ne(this,Or,()=>{this.debugLog("Connected to event bus"),De(this,ro,true),this.debugLog("Emitting queued events",$(this,Ea)),$(this,Ea).forEach(o=>this.emitEventToBus(o)),De(this,Ea,[]),this.stopConnectLoop(),$(this,ft).call(this).removeEventListener("tanstack-connect-success",$(this,Or));});Ne(this,Uo,()=>{if($(this,ft).call(this).addEventListener("tanstack-connect-success",$(this,Or)),$(this,Br)<$(this,ds)){Hd(this,Br)._++,this.dispatchCustomEvent("tanstack-connect",{});return}$(this,ft).call(this).removeEventListener("tanstack-connect",$(this,Uo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});De(this,bt,o),De(this,Pa,a),De(this,ft,this.getGlobalTarget),De(this,Fr,t),this.debugLog(" Initializing event subscription for plugin",$(this,bt)),De(this,Ea,[]),De(this,ro,false),De(this,la,null),De(this,Wo,n);}startConnectLoop(){$(this,la)!==null||$(this,ro)||(this.debugLog(`Starting connect loop (every ${$(this,Wo)}ms)`),De(this,la,setInterval($(this,Uo),$(this,Wo))));}stopConnectLoop(){$(this,la)!==null&&(clearInterval($(this,la)),De(this,la,null),this.debugLog("Stopped connect loop"));}debugLog(...o){$(this,Fr)&&console.log(`\u{1F334} [tanstack-devtools:${$(this,bt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return $(this,bt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});$(this,ft).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{$(this,ft).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!$(this,Pa)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!$(this,ro)){this.debugLog("Bus not available, will be pushed as soon as connected"),$(this,Ea).push({type:`${$(this,bt)}:${o}`,payload:t,pluginId:$(this,bt)}),typeof CustomEvent<"u"&&($(this,Uo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${$(this,bt)}:${o}`,payload:t,pluginId:$(this,bt)})}on(o,t){let a=`${$(this,bt)}:${o}`;if(!$(this,Pa))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let n=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return $(this,ft).call(this).addEventListener(a,n),this.debugLog("Registered event to bus",a),()=>{$(this,ft).call(this).removeEventListener(a,n);}}onAll(o){if(!$(this,Pa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;o(n);};return $(this,ft).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,ft).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!$(this,Pa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;$(this,bt)&&n.pluginId!==$(this,bt)||o(n);};return $(this,ft).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,ft).call(this).removeEventListener("tanstack-devtools-global",t)}};Pa=new WeakMap,bt=new WeakMap,ft=new WeakMap,Fr=new WeakMap,Ea=new WeakMap,ro=new WeakMap,la=new WeakMap,Wo=new WeakMap,Br=new WeakMap,ds=new WeakMap,Or=new WeakMap,Uo=new WeakMap;var xl=class extends no{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},hc=(e,o)=>{bl.emit(e,o);},bl=new xl;function gc(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var lb={enabled:true,leading:true,trailing:true,wait:0},Da,At,so,io,lo,Ko,us=class{constructor(o,t){Ne(this,Da);Ne(this,At);Ne(this,so);Ne(this,io);Ne(this,lo);Ne(this,Ko);this.fn=o,this.store=new ea(gc()),this.setOptions=a=>{this.options={...this.options,...a},$(this,so).call(this)||this.cancel();},De(this,At,a=>{this.store.setState(n=>{let r={...n,...a},{isPending:s}=r;return {...r,status:$(this,so).call(this)?s?"pending":"idle":"disabled"}}),hc("Throttler",this);}),De(this,so,()=>!!gl(this.options.enabled,this)),De(this,io,()=>gl(this.options.wait,this)),this.maybeExecute=(...a)=>{$(this,At).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let n=Date.now(),r=n-this.store.state.lastExecutionTime,s=$(this,io).call(this);if(this.options.leading&&r>=s)$(this,lo).call(this,...a);else if($(this,At).call(this,{lastArgs:a}),!$(this,Da)&&this.options.trailing){let u=this.store.state.lastExecutionTime?n-this.store.state.lastExecutionTime:0,i=s-u;$(this,At).call(this,{isPending:true}),De(this,Da,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&$(this,lo).call(this,...c);},i));}},De(this,lo,(...a)=>{if(!$(this,so).call(this))return;this.fn(...a);let n=Date.now(),r=n+$(this,io).call(this);$(this,Ko).call(this),$(this,At).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:n,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||$(this,At).call(this,{nextExecutionTime:void 0});},$(this,io).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&$(this,lo).call(this,...this.store.state.lastArgs);},De(this,Ko,()=>{$(this,Da)&&(clearTimeout($(this,Da)),De(this,Da,void 0));}),this.cancel=()=>{$(this,Ko).call(this),$(this,At).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{$(this,At).call(this,gc());},this.key=pc(t.key),this.options={...lb,...t},$(this,At).call(this,this.options.initialState??{}),bl.on("d-Throttler",a=>{a.payload.key===this.key&&($(this,At).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Da=new WeakMap,At=new WeakMap,so=new WeakMap,io=new WeakMap,lo=new WeakMap,Ko=new WeakMap;function vl(e,o){return new us(e,o).maybeExecute}function Ra(e,o){return typeof e=="function"?e(o):e}function Fa(e,o){return ps(o).reduce((a,n)=>{if(a===null)return null;if(typeof a<"u")return a[n]},e)}function Go(e,o,t){let a=ps(o);function n(r){if(!a.length)return Ra(t,r);let s=a.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[s]:n(r[s])}):{[s]:n()};if(Array.isArray(r)&&typeof s=="number"){let u=r.slice(0,s);return [...u.length?u:new Array(s),n(r[s]),...r.slice(s+1)]}return [...new Array(s),n()]}return n(e)}function wl(e,o){let t=ps(o);function a(n){if(!n)return;if(t.length===1){let s=t[0];if(Array.isArray(n)&&typeof s=="number")return n.filter((c,f)=>f!==s);let{[s]:u,...i}=n;return i}let r=t.shift();if(typeof r=="string"&&typeof n=="object")return {...n,[r]:a(n[r])};if(typeof r=="number"&&Array.isArray(n)){if(r>=n.length)return n;let s=n.slice(0,r);return [...s.length?s:new Array(r),a(n[r]),...n.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var db=/^(\d+)$/gm,ub=/\.(\d+)(?=\.)/gm,cb=/^(\d+)\./gm,fb=/\.(\d+$)/gm,mb=/\.{2,}/gm,yl="__int__",cs=`${yl}$1`;function ps(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(db,cs).replace(ub,`.${cs}.`).replace(cb,`${cs}.`).replace(fb,`.${cs}`).replace(mb,".").split(".").map(o=>{if(o.startsWith(yl)){let t=o.substring(yl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Sl(e){return !(Array.isArray(e)&&e.length===0)}function jo(e,o){let t=a=>a.validators.filter(Boolean).map(n=>({cause:n.cause,validate:n.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function _o(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:n,onDynamicAsyncDebounceMs:r}=o.validators||{},s=t??0,u=i=>i.validators.filter(Boolean).map(c=>{let f=c?.cause||e,d=s;switch(f){case "change":d=n??s;break;case "blur":d=a??s;break;case "dynamic":d=r??s;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:f,validate:c.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var Nr=e=>!!e&&typeof e=="object"&&"fields"in e;function Ba(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[n,r]of e)if(!o.has(n)||!Object.is(r,o.get(n)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let n of e)if(!o.has(n))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let n of t)if(!a.includes(n)||!Ba(e[n],o[n]))return false;return true}var hs=({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},gs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Qe(e,o){return e==null?o:{...e,...o}}var uo=256,ms=[],fs;for(;uo--;)ms[uo]=(uo+256).toString(16).substring(1);function Ll(){let e=0,o,t="";if(!fs||uo+16>256){for(fs=new Array(256),e=256;e--;)fs[e]=256*Math.random()|0;e=0,uo=0;}for(;e<16;e++)o=fs[uo+e],e===6?t+=ms[o&15|64]:e===8?t+=ms[o&63|128]:t+=ms[o],e&1&&e>1&&e<11&&(t+="-");return uo++,t}var Oa=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},n={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},s=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,n,r,s],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[n,s],form:e.form});case "change":return e.runValidation({validators:[a,s],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function pb(e,o){let t=new Map;for(let a of e){let n=a.path??[],r=o,s="";for(let u=0;u<n.length;u++){let i=n[u];if(i===void 0)continue;let c=typeof i=="object"?i.key:i,f=Number(c);Array.isArray(r)&&!Number.isNaN(f)?s+=`[${f}]`:s+=(u>0?".":"")+String(c),typeof r=="object"&&r!==null?r=r[c]:r=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var xc=(e,o)=>{let t=pb(e,o);return {form:t,fields:t}},Na={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:xc(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:xc(a.issues,e)}},xs=e=>!!e&&"~standard"in e;var $o={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function Hr(e){function o(d,l,m,h){let p=a(d,l,m,h);({insert:()=>u(p,d,l),remove:()=>i(p),swap:()=>h!==void 0&&f(p,d,l,h),move:()=>h!==void 0&&c(p,d,l,h)})[m]();}function t(d,l){return `${d}[${l}]`}function a(d,l,m,h){let p=[t(d,l)];if(m==="swap")p.push(t(d,h));else if(m==="move"){let[v,y]=[Math.min(l,h),Math.max(l,h)];for(let b=v;b<=y;b++)p.push(t(d,b));}else {let v=e.getFieldValue(d),y=Array.isArray(v)?v.length:0;for(let b=l+1;b<y;b++)p.push(t(d,b));}return Object.keys(e.fieldInfo).filter(v=>p.some(y=>v.startsWith(y)))}function n(d,l){return d.replace(/\[(\d+)\]/,(m,h)=>{let p=parseInt(h,10);return `[${l==="up"?p+1:Math.max(0,p-1)}]`})}function r(d,l){(l==="up"?d:[...d].reverse()).forEach(h=>{let p=n(h.toString(),l),v=e.getFieldMeta(p);v?e.setFieldMeta(h,v):e.setFieldMeta(h,s());});}let s=()=>$o,u=(d,l,m)=>{r(d,"down"),d.forEach(h=>{h.toString().startsWith(t(l,m))&&e.setFieldMeta(h,s());});},i=d=>{r(d,"up");},c=(d,l,m,h)=>{let p=new Map(Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,m))).map(v=>[v,e.getFieldMeta(v)]));r(d,m<h?"up":"down"),Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,h))).forEach(v=>{let y=v.replace(t(l,h),t(l,m)),b=p.get(y);b&&e.setFieldMeta(v,b);});},f=(d,l,m,h)=>{d.forEach(p=>{if(!p.toString().startsWith(t(l,m)))return;let v=p.toString().replace(t(l,m),t(l,h)),[y,b]=[e.getFieldMeta(p),e.getFieldMeta(v)];y&&e.setFieldMeta(v,y),b&&e.setFieldMeta(p,b);});};return {handleArrayFieldMetaShift:o}}var Il=class extends no{constructor(){super({pluginId:"form-devtools"});}},Pt=new Il;function Cl(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 Vr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),n=this.store.mount(),r=()=>{a(),n(),Pt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return Pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),s&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let n=this.options;this.options=a;let r=!!a.transform?.deps?.some((i,c)=>i!==this.prevTransformArray[c]),s=a.defaultValues&&!Ba(a.defaultValues,n.defaultValues)&&!this.state.isTouched,u=!Ba(a.defaultState,n.defaultState)&&!this.state.isTouched;!s&&!u&&!r||(Mt(()=>{this.baseStore.setState(()=>Cl(Object.assign({},this.state,u?a.defaultState:{},s?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),Pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,n)=>{let{fieldMeta:r}=this.state,s=this.resetFieldMeta(r);a&&!n?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Cl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let n=[];return Mt(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;let u=s.instance;n.push(Promise.resolve().then(()=>u.validate(a,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(n)).flat()},this.validateArrayFieldsStartingFrom=async(a,n,r)=>{let s=this.getFieldValue(a),u=Array.isArray(s)?Math.max(s.length-1,0):null,i=[`${a}[${n}]`];for(let l=n+1;l<=(u??0);l++)i.push(`${a}[${l}]`);let c=Object.keys(this.fieldInfo).filter(l=>i.some(m=>l.startsWith(m))),f=[];return Mt(()=>{c.forEach(l=>{f.push(Promise.resolve().then(()=>this.validateField(l,r)));});}),(await Promise.all(f)).flat()},this.validateField=(a,n)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(s=>({...s,isTouched:true})),r.validate(n)):[]},this.validateSync=a=>{let n=jo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Oa}),r=false,s={};return Mt(()=>{for(let c of n){if(!c.validate)continue;let f=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:l}=bs(f),m=qr(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let p=this.getFieldMeta(h);if(!p)continue;let{errorMap:v,errorSourceMap:y}=p,b=l?.[h],{newErrorValue:g,newSource:C}=hs({newFormValidatorError:b,isPreviousErrorFromFormValidator:y?.[m]==="form",previousErrorValue:v?.[m]});C==="form"&&(s[h]={...s[h],[m]:b}),v?.[m]!==g&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[m]:g},errorSourceMap:{...I.errorSourceMap,[m]:C}}));}this.state.errorMap?.[m]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[m]:d}})),(d||l)&&(r=!0);}let u=qr("submit");this.state.errorMap?.[u]&&a!=="submit"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let i=qr("server");this.state.errorMap?.[i]&&a!=="server"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[i]:void 0}}));}),{hasErrored:r,fieldsErrorMap:s}},this.validateAsync=async a=>{let n=_o(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Oa});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let r=[],s;for(let c of n){if(!c.validate)continue;let f=qr(c.cause);this.state.validationMetaMap[f]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[f]={lastAbortController:l},r.push(new Promise(async m=>{let h;try{h=await new Promise((b,g)=>{setTimeout(async()=>{if(l.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(C){g(C);}},c.debounceMs);});}catch(b){h=b;}let{formError:p,fieldErrors:v}=bs(h);v&&(s=s?{...s,...v}:v);let y=qr(c.cause);for(let b of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[b]===void 0)continue;let g=this.getFieldMeta(b);if(!g)continue;let{errorMap:C,errorSourceMap:I}=g,B=s?.[b],{newErrorValue:k,newSource:x}=hs({newFormValidatorError:B,isPreviousErrorFromFormValidator:I?.[y]==="form",previousErrorValue:C?.[y]});C?.[y]!==k&&this.setFieldMeta(b,S=>({...S,errorMap:{...S.errorMap,[y]:k},errorSourceMap:{...S.errorSourceMap,[y]:x}}));}this.baseStore.setState(b=>({...b,errorMap:{...b.errorMap,[y]:p}})),m(s?{fieldErrors:s,errorMapKey:y}:void 0);}));}let u=[],i={};if(r.length){u=await Promise.all(r);for(let c of u)if(c?.fieldErrors){let{errorMapKey:f}=c;for(let[d,l]of Object.entries(c.fieldErrors)){let h={...i[d]||{},[f]:l};i[d]=h;}}}return this.baseStore.setState(c=>({...c,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(a);return n&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Fa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var n;return (n=this.fieldInfo)[a]||(n[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,n)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Ra(n,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((n,r)=>{let s=r;return n[s]=$o,n},{}),this.setFieldValue=(a,n,r)=>{let s=r?.dontUpdateMeta??false,u=r?.dontRunListeners??false,i=r?.dontValidate??false;Mt(()=>{s||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:Go(c.values,a,n)}));}),u||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(s=>{let u=a.toString();return s!==u&&s.startsWith(u)}),a];this.baseStore.setState(s=>{let u={...s};return r.forEach(i=>{u.values=wl(u.values,i),delete this.fieldInfo[i],delete u.fieldMetaBase[i];}),u});},this.pushFieldValue=(a,n,r)=>{this.setFieldValue(a,s=>[...Array.isArray(s)?s:[],n],r);},this.insertFieldValue=async(a,n,r,s)=>{this.setFieldValue(a,i=>[...i.slice(0,n),r,...i.slice(n)],Qe(s,{dontValidate:true}));let u=s?.dontValidate??false;u||await this.validateField(a,"change"),Hr(this).handleArrayFieldMetaShift(a,n,"insert"),u||await this.validateArrayFieldsStartingFrom(a,n,"change");},this.replaceFieldValue=async(a,n,r,s)=>{this.setFieldValue(a,i=>i.map((c,f)=>f===n?r:c),Qe(s,{dontValidate:true})),(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.removeFieldValue=async(a,n,r)=>{let s=this.getFieldValue(a),u=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,c=>c.filter((f,d)=>d!==n),Qe(r,{dontValidate:true})),Hr(this).handleArrayFieldMetaShift(a,n,"remove"),u!==null){let c=`${a}[${u}]`;this.deleteField(c);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.swapFieldValues=(a,n,r,s)=>{this.setFieldValue(a,i=>{let c=i[n],f=i[r];return Go(Go(i,`${n}`,f),`${r}`,c)},Qe(s,{dontValidate:true})),Hr(this).handleArrayFieldMetaShift(a,n,"swap",r),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,n,r,s)=>{this.setFieldValue(a,i=>{let c=[...i];return c.splice(r,0,c.splice(n,1)[0]),c},Qe(s,{dontValidate:true})),Hr(this).handleArrayFieldMetaShift(a,n,"move",r),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,n)=>{let r=this.getFieldValue(a),s=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],Qe(n,{dontValidate:true})),s!==null)for(let i=0;i<=s;i++){let c=`${a}[${i}]`;this.deleteField(c);}(n?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:$o},values:this.options.defaultValues?Go(n.values,a,Fa(this.options.defaultValues,a)):n.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[n,r])=>(Object.keys(r).length&&r.errors.length&&(a[n]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Na.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Na.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Ll(),this._devtoolsSubmissionOverride=false,this.baseStore=new ea(Cl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new jt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=0,f={};for(let d of Object.keys(i.fieldMetaBase)){let l=i.fieldMetaBase[d],m=u?.fieldMetaBase[d],h=s?.[d],p=Fa(i.values,d),v=h?.errors;if(!m||l.errorMap!==m.errorMap){v=Object.values(l.errorMap??{}).filter(I=>I!==void 0);let C=this.getFieldInfo(d)?.instance;C&&!C.options.disableErrorFlat&&(v=v?.flat(1));}let y=!Sl(v??[]),b=!l.isDirty,g=Ba(p,Fa(this.options.defaultValues,d))||Ba(p,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===b&&h.isValid===y&&h.isDefaultValue===g&&h.errors===v&&l===m){f[d]=h,c++;continue}f[d]={...l,errors:v,isPristine:b,isValid:y,isDefaultValue:g};}return Object.keys(i.fieldMetaBase).length&&s&&c===Object.keys(i.fieldMetaBase).length?s:f}}),this.store=new jt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=n[1],f=Object.values(c).filter(Boolean),d=f.some(F=>F.isValidating),l=f.every(F=>F.isValid),m=f.some(F=>F.isTouched),h=f.some(F=>F.isBlurred),p=f.every(F=>F.isDefaultValue),v=m&&i.errorMap?.onMount,y=f.some(F=>F.isDirty),b=!y,g=!!(i.errorMap?.onMount||f.some(F=>F?.errorMap?.onMount)),C=!!d,I=s?.errors??[];(!u||i.errorMap!==u.errorMap)&&(I=Object.values(i.errorMap).reduce((F,V)=>V===void 0?F:V&&Nr(V)?(F.push(V.form),F):(F.push(V),F),[]));let B=I.length===0,k=l&&B,x=this.options.canSubmitWhenInvalid??false,S=i.submissionAttempts===0&&!m&&!g||!C&&!i.isSubmitting&&k||x,w=i.errorMap;if(v&&(I=I.filter(F=>F!==i.errorMap.onMount),w=Object.assign(w,{onMount:void 0})),s&&u&&s.errorMap===w&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===I&&s.isFieldsValidating===d&&s.isFieldsValid===l&&s.isFormValid===B&&s.isValid===k&&s.canSubmit===S&&s.isTouched===m&&s.isBlurred===h&&s.isPristine===b&&s.isDefaultValue===p&&s.isDirty===y&&Ba(u,i))return s;let T={...i,errorMap:w,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:l,isFormValid:B,isValid:k,canSubmit:S,isTouched:m,isBlurred:h,isPristine:b,isDefaultValue:p,isDirty:y},q=this.options.transform?.deps??[];if(q.length!==this.prevTransformArray.length||q.some((F,V)=>F!==this.prevTransformArray[V])){let F=Object.assign({},this,{state:T});this.options.transform?.fn(F),T=F.state,this.prevTransformArray=q;}return T}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=vl(a=>Pt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),Pt.on("request-form-state",a=>{a.payload.id===this._formId&&Pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Pt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),Pt.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 xs(o.validate)?Na[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(n=>({...n,isSubmitted:false,submissionAttempts:n.submissionAttempts+1,isSubmitSuccessful:false})),Mt(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance&&(n.instance.state.meta.isTouched||n.instance.setMeta(r=>({...r,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(n=>({...n,isSubmitting:true}));let a=()=>{this.baseStore.setState(n=>({...n,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(n=>n.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}Mt(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance?.options.listeners?.onSubmit?.({value:n.instance.state.value,fieldApi:n.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),Mt(()=>{this.baseStore.setState(n=>({...n,isSubmitted:!0,isSubmitSuccessful:!0})),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(n){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:n}),a(),n}}setErrorMap(o){Mt(()=>{Object.entries(o).forEach(([t,a])=>{let n=t;if(Nr(a)){let{formError:r,fieldErrors:s}=bs(a);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,c=>({...c,errorMap:{...c.errorMap,[n]:s?.[u]},errorSourceMap:{...c.errorSourceMap,[n]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[n]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[n]:a}}));});});}};function bs(e){if(e){if(Nr(e)){let o=bs(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function qr(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}var zr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:n}=this.options.validators||{};if(n){let r=this.runValidator({validate:n,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:r},errorSourceMap:{...s?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let n=Fa(t.form.options.defaultValues,t.name),r=t.defaultValue??n;a?this.setValue(s=>s||r,{dontUpdateMeta:true}):r!==void 0&&this.setValue(r,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Qe(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,Qe(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,n)=>{this.form.insertFieldValue(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,n)=>{this.form.replaceFieldValue(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Qe(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,n)=>{this.form.swapFieldValues(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,n)=>{this.form.moveFieldValues(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Qe(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),n=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:s,onBlurListenTo:u}=r.instance.options.validators||{};t==="change"&&s?.includes(this.name)&&n.push(r.instance),t==="blur"&&u?.includes(this.name)&&n.push(r.instance);}return n},this.validateSync=(t,a)=>{let n=jo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Oa}),s=this.getLinkedFields(t).reduce((c,f)=>{let d=jo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Oa});return d.forEach(l=>{l.field=f;}),c.concat(d)},[]),u=false;Mt(()=>{let c=(f,d)=>{let l=vs(d.cause),m=d.validate?bc(f.runValidator({validate:d.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,h=a[l],{newErrorValue:p,newSource:v}=gs({formLevelError:h,fieldLevelError:m});f.state.meta.errorMap?.[l]!==p&&f.setMeta(y=>({...y,errorMap:{...y.errorMap,[l]:p},errorSourceMap:{...y.errorSourceMap,[l]:v}})),p&&(u=!0);};for(let f of n)c(this,f);for(let f of s)f.validate&&c(f.field,f);});let i=vs("submit");return this.state.meta.errorMap?.[i]&&t!=="submit"&&!u&&this.setMeta(c=>({...c,errorMap:{...c.errorMap,[i]:void 0},errorSourceMap:{...c.errorSourceMap,[i]:void 0}})),{hasErrored:u}},this.validateAsync=async(t,a)=>{let n=_o(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Oa}),r=await a,s=this.getLinkedFields(t),u=s.reduce((l,m)=>{let h=_o(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Oa});return h.forEach(p=>{p.field=m;}),l.concat(h)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of s)l.setMeta(m=>({...m,isValidating:true}));let i=[],c=[],f=(l,m,h)=>{let p=vs(m.cause);l.getInfo().validationMetaMap[p]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:y},h.push(new Promise(async b=>{let g;try{g=await new Promise((x,S)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(y.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:m.validate,value:{value:l.store.state.value,fieldApi:l,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(w){S(w);}},m.debounceMs);});}catch(x){g=x;}if(y.signal.aborted)return b(void 0);let C=bc(g),I=r[this.name]?.[p],{newErrorValue:B,newSource:k}=gs({formLevelError:I,fieldLevelError:C});l.setMeta(x=>({...x,errorMap:{...x?.errorMap,[p]:B},errorSourceMap:{...x.errorSourceMap,[p]:k}})),b(B);}));};for(let l of n)l.validate&&f(this,l,i);for(let l of u)l.validate&&f(l.field,l,c);let d=[];(i.length||c.length)&&(d=await Promise.all(i),await Promise.all(c)),this.setMeta(l=>({...l,isValidating:false}));for(let l of s)l.setMeta(m=>({...m,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:n}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,n[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[vs(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},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=>Na.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Na.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new jt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...$o,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return xs(o.validate)?Na[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 bc(e){if(e)return e}function vs(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 ys(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,gb)}function gb(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,n]of e)if(!o.has(a)||!Object.is(n,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=vc(e);if(t.length!==vc(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 vc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Xo=typeof window<"u"?useLayoutEffect:useEffect;function Lb(e){let[o]=useState(()=>{let a=new zr({...e,form:e.form,name:e.name});return a.Field=kl,a});return Xo(o.mount,[o]),Xo(()=>{o.update(e);}),ys(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var kl=(({children:e,...o})=>{let t=Lb(o),a=useMemo(()=>Ra(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function kb({form:e,selector:o,children:t}){let a=ys(e.store,o);return Ra(t,a)}function Tl(e){let o=useId(),[t]=useState(()=>{let a=new Vr({...e,formId:o}),n=a;return n.Field=function(s){return jsx(kl,{...s,form:a})},n.Subscribe=function(s){return jsx(kb,{form:a,selector:s.selector,children:s.children})},n});return Xo(t.mount,[]),Xo(()=>{t.update(e);}),t}function Ml({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 Ob=({editElement:e})=>{let o=useDispatch(),t=useSelector(ve),a=useRef(null),n=ze(),r=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[u,i]=useState(s),c=Tl({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:l})=>{if(l.questionType==="true-false"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctAnswer:l.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,dragDropPos:{x:r&&"dragDropPos"in e?e.dragDropPos?.x??400:200,y:r&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?ot(m):wi(m));}else if(l.questionType==="multiple-choice"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctIndex:l.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,dragDropPos:{x:r&&"dragDropPos"in e?e.dragDropPos?.x??400:400,y:r&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?gt(m):vi(m));}else if(l.questionType==="short-answer"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?sa(m):Si(m));}else if(l.questionType==="fill-in-the-blank"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Sa(m):Ii(m));}else if(l.questionType==="long-answer"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctLongAnswer:l.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Ja(m):Li(m));}o(La(false));}}),f=()=>{o(La(false));};if(!n)return null;let d=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:l=>{l.preventDefault(),l.stopPropagation(),c.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{f();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(c.Field,{name:"questionType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:m=>{l.handleChange(m.target.value),i(m.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(Ml,{field:l})]})}),u&&!["short-answer","fill-in-the-blank","long-answer"].includes(u)&&jsx(c.Field,{name:"responseType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:m=>l.handleChange(m.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(Ml,{field:l})]})})]}),jsx(c.Field,{name:"feedbackMode",children:l=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${u==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>l.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>l.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),u==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(Ml,{field:l})]})}),jsx(c.Field,{name:"question",validators:{onChange:({value:l})=>l?void 0:"A question is required"},children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:l.state.value,onChange:m=>l.handleChange(m.target.value),onBlur:l.handleBlur,placeholder:"Enter Your Question"})}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),u==="true-false"&&jsx(c.Field,{name:"responseOptions.correctAnswer",children:l=>{let m=l.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>l.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${m===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"}),m===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>l.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${m===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"}),m===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value:l})=>{if(l.options.filter(h=>!h.trim()).length>0)return "All options must have text";if(!l.correctIndex||l.correctIndex.length===0)return "Please select at least one correct answer"}},children:l=>{let m=(y,b)=>{let g=[...l.state.value.options];g[y]=b,l.handleChange({...l.state.value,options:g});},h=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},p=y=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let b=l.state.value.options.filter((C,I)=>I!==y),g=l.state.value.correctIndex?.filter(C=>C!==y).map(C=>C>y?C-1:C);l.handleChange({...l.state.value,options:b,correctIndex:g});},v=y=>{let b=l.state.value.correctIndex||[];if(b.includes(y))l.handleChange({...l.state.value,correctIndex:b.filter(C=>C!==y)});else {if(b.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...b,y]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:l.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:l.state.value.options.map((y,b)=>{let g=!y.trim(),C=l.state.value.correctIndex?.includes(b),I=l.state.meta.isTouched&&g;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>v(b),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${C?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:C&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${I?"border-red-500 bg-red-50":C?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${b+1}`,value:y,onChange:B=>m(b,B.target.value),onBlur:l.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),l.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>p(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:h,disabled:l.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),l.state.value.correctIndex.length===0||l.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:l.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.Field,{name:"responseOptions.correctShortAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:l.state.value,onChange:m=>{l.handleChange(m.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),u==="long-answer"&&jsx(c.Field,{name:"responseOptions.correctLongAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:l.state.value,onChange:m=>{l.handleChange(m.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),jsx(c.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,m])=>jsx("button",{type:"submit",disabled:!l,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:m?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(d,n)},Sc=Ob;var kc=({text:e,position:o})=>{let t=Se(),a=(f,d,l,m,h)=>{let v=document.createElement("canvas").getContext("2d");if(!v)return {width:e.width,height:e.height};v.font=`${h} ${m} ${d}px ${l}`;let y=f.split(`
4
- `),b=0;for(let I of y){let B=v.measureText(I||" ");B.width>b&&(b=B.width);}let C=y.length*d*1.2;return {width:Math.max(200,b+40),height:Math.max(50,C+20)}},n=f=>{let d=Math.max(12,Math.min(72,e.fontSize+f)),l=a(e.text,d,e.fontFamily,e.fontWeight,e.fontStyle);t(de()),t(Ft({id:e.id,fontSize:d,width:l.width,height:l.height}));},r=f=>{t(de()),t(Ft({id:e.id,fill:f}));},s=()=>{let f=e.fontWeight==="bold"?"normal":"bold",d=a(e.text,e.fontSize,e.fontFamily,f,e.fontStyle);t(de()),t(Ft({id:e.id,fontWeight:f,width:d.width,height:d.height}));},u=()=>{let f=e.fontStyle==="italic"?"normal":"italic",d=a(e.text,e.fontSize,e.fontFamily,e.fontWeight,f);t(de()),t(Ft({id:e.id,fontStyle:f,width:d.width,height:d.height}));},i=()=>{t(de()),t(Ft({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},c=f=>{let d=a(e.text,e.fontSize,f,e.fontWeight,e.fontStyle);t(de()),t(Ft({id:e.id,fontFamily:f,width:d.width,height:d.height}));};return jsxs("div",{className:"absolute z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:"50%",top:100,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:f=>f.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:f=>c(f.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:()=>n(-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:()=>n(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:u,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:f=>r(f.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 Mc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:n,scale:r,textareaRef:s})=>{let u=useRef(null),i=useMemo(()=>({fontSize:`${e.fontSize*r}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,r]),c=useCallback(f=>{f.style.height="auto",f.style.height=`${f.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(f).font,d.style.fontSize=f.style.fontSize,d.style.fontFamily=f.style.fontFamily,d.style.fontWeight=f.style.fontWeight,d.style.fontStyle=f.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let l=f.value.split(`
5
- `),m=0;document.body.appendChild(d);for(let p of l){d.textContent=p||" ";let v=d.offsetWidth;v>m&&(m=v);}document.body.removeChild(d);let h=10;f.style.width=`${Math.max(200,m+h+20)}px`;},[]);return useEffect(()=>{let f=u.current;f&&(f.style.fontSize=`${e.fontSize*r}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,c(f));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,c]),jsx("div",{style:{position:"absolute",top:`${n.top}px`,left:`${n.left}px`,zIndex:1e3},children:jsx("textarea",{ref:f=>{if(u.current=f,s.current=f,f){f.focus();let d=f.value.length;f.setSelectionRange(d,d),c(f);}},value:o,onChange:f=>{t(f.target.value);},onKeyDown:f=>{f.key==="Escape"&&a();},style:i},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Xb=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},Ac=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s})=>{let u=useSelector(w=>w.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useDispatch(),f=useRef(null),[d,l]=useState(null),m=e.data.responseOptions.attempts||0,[h,p]=useState(e.data.responseOptions.userAnswer||""),[v,y]=useState(false);useEffect(()=>{let w=f.current;if(w)return a.current.set(e.id,w),()=>{a.current.delete(e.id);}},[e.id,a]);let b=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=v&&h.trim().toLowerCase()===b,C=w=>{p(w);let T=w.trim(),q=T.toLowerCase()===b;c(sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:T,isCorrect:q}}}));},I=()=>{y(false),p(""),c(sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:"",isCorrect:false}}}));},B=()=>g?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",k=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},x=e.data.feedbackMode==="practice",S=useMemo(()=>{let V=x?48:0,U=12,K=30,R=e.width-48,z=Math.max(60,Xb(e.data.question,18,R,"bold")+20),ne=v?40:0,X=v?54:20,P=z+ne+K+50+12+U+V+24;return {padding:24,questionHeight:z,questionFontSize:18,feedbackHeight:ne,feedbackFontSize:12,inputY:X,inputHeight:50,inputMargin:12,buttonHeight:V,buttonTopMargin:U,placeholderHeight:K,contentWidth:R,totalHeight:P}},[e.width,e.data.question,v,g,x,B]);return jsxs(Group,{ref:f,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:S.totalHeight,name:"sa-element",...s,...i?{}:{onDragEnd:r,onClick:()=>o&&o(e.id),onTap:()=>o&&o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:S.totalHeight,onTransformEnd:w=>t(e.id,w),onContextMenu:w=>{w.cancelBubble=true,n(w.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:S.padding+8,y:S.padding,fontSize:S.questionFontSize,fontStyle:"bold",fill:"#111827",width:S.contentWidth,height:S.questionHeight-S.padding,wrap:"word",listening:false}),jsx(Rect,{x:S.padding,y:S.questionHeight+S.feedbackHeight+S.placeholderHeight-S.inputY,width:S.contentWidth+4,height:S.inputHeight+6,fill:"#ffffff",stroke:g?"#22c55e":v?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:S.padding,y:S.questionHeight+S.feedbackHeight+S.placeholderHeight-S.inputY},divProps:{style:{width:`${S.contentWidth-4}px`,height:`${S.inputHeight}px`,pointerEvents:v?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:w=>C(w.target.value),disabled:v,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:v?"none":"auto"}})}),v&&jsxs(Fragment,{children:[jsx(Rect,{x:S.padding,y:S.questionHeight+80,width:S.contentWidth,height:S.feedbackHeight,fill:k().bg,cornerRadius:8}),jsx(Text,{x:36,y:S.questionHeight+80,width:S.contentWidth,height:S.feedbackHeight,text:B()+` (${m} attempts)`,fontSize:S.feedbackFontSize,fontStyle:"bold",fill:k().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:S.questionHeight+S.feedbackHeight+S.placeholderHeight+S.inputHeight+S.inputMargin+S.buttonTopMargin,children:[jsxs(Group,{onMouseDown:w=>{w.cancelBubble=true,l("check");},onMouseUp:w=>{w.cancelBubble=true,l(null),h.length>0&&(y(true),c(sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},onMouseLeave:w=>{w.cancelBubble=true,l(null);},onTouchStart:w=>{w.cancelBubble=true,l("check");},onTouchEnd:w=>{w.cancelBubble=true,l(null),h.length>0&&y(true);},scaleX:d==="check"?.95:1,scaleY:d==="check"?.95:1,children:[jsx(Rect,{x:S.padding+14,width:(S.contentWidth-24)/(v?2:1),height:S.buttonHeight,fill:h.length===0||v?"#9ca3af":"#096B76",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:S.padding+14,width:(S.contentWidth-24)/(v?2:1),height:S.buttonHeight,text:v?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),v&&jsxs(Group,{x:(e.width-S.padding*2)/2+8,onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),I();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),I();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:S.padding,width:(S.contentWidth-8)/2,height:S.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:S.padding,width:(S.contentWidth-8)/2,height:S.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ac.displayName="ShortAnswer";var Pc=Ac;var Dc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Pc,{shortAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"shortAnswer")},i.id))})};var Rc=e=>{let o=useDispatch(),a=useSelector(ve)?.fillInTheBlanks||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(Sa({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:n,handleFillInTheBlanksDragEnd:r}};var El=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},Fc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:n,fibRefs:r,touchHandlers:s})=>{let u=useSelector(w=>w.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),f=useDispatch(),[d,l]=useState(null),m=e.data.responseOptions.attempts||0,[h,p]=useState(e.data.responseOptions.userAnswer||""),[v,y]=useState(false);useEffect(()=>{let w=c.current;if(w)return r.current.set(e.id,w),()=>{r.current.delete(e.id);}},[e.id,r]);let b=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=v&&h.trim().toLowerCase()===b,C=w=>{p(w);let T=w.trim(),q=T.toLowerCase()===b;f(Sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:T,isCorrect:q}}}));},I=()=>{y(false),p("");},B=()=>{h.length>0&&(y(true),f(Sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},k=e.data.feedbackMode==="practice",x=useMemo(()=>{let K=e.width-48,R=(K-15)/2,z=24,ne=z,X=Math.max(60,El(e.data.question.replace("_____","________"),24,K,"bold")+20);z+=X;let P=z,N=Math.max(35,El("Enter your answer in the blank.",16,K)+10);z+=N;let _=z;z+=67;let Q=z,re=v?Math.max(32,El(g?"Right Answer, Great Job!":"Wrong Answer",14,K-40)+16):0;v&&(z+=re+16);let j=z;return k&&(z+=64),z+=24,{padding:24,questionY:ne,questionHeight:X,questionFontSize:24,helperTextY:P,helperTextHeight:N,helperTextFontSize:16,inputY:_,inputHeight:51,feedbackY:Q,feedbackHeight:re,feedbackFontSize:14,buttonsY:j,buttonHeight:64,buttonGap:15,buttonWidth:R,contentWidth:K,totalHeight:z}},[e.width,e.data.question,v,g,k]),S=()=>v?g?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...s,...i?{}:{onDragEnd:w=>a(w,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:x.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:w=>t(e.id,w),onContextMenu:w=>{w.cancelBubble=true,n?.(w.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:x.padding,y:x.questionY,fontSize:x.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:x.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:x.padding,y:x.helperTextY,fontSize:x.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:x.contentWidth,height:x.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:x.padding,y:x.inputY,width:x.contentWidth,height:x.inputHeight,fill:"#ffffff",stroke:S(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:x.padding,y:x.inputY},divProps:{style:{width:`${x.contentWidth}px`,height:`${x.inputHeight}px`,pointerEvents:v?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:w=>C(w.target.value),disabled:v,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"}})}),v&&jsxs(Group,{y:x.feedbackY,children:[jsx(Rect,{x:x.padding,width:x.contentWidth,height:x.feedbackHeight,fill:g?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:g?"\u2713":"\u2717",x:x.padding+10,y:0,width:16,height:x.feedbackHeight,fontSize:x.feedbackFontSize,fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:g?`Right Answer, Great Job! (${m} attempts)`:`Wrong Answer (${m} attempts)`,x:x.padding+30,y:0,height:x.feedbackHeight,fontSize:x.feedbackFontSize,fontStyle:"600",fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),k&&jsxs(Group,{y:x.buttonsY,children:[jsxs(Group,{x:x.padding,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true,onMouseDown:w=>{w.cancelBubble=true,l("reset");},onMouseUp:w=>{w.cancelBubble=true,l(null),I();},onMouseLeave:w=>{w.cancelBubble=true,l(null);},onTouchStart:w=>{w.cancelBubble=true,l("reset");},onTouchEnd:w=>{w.cancelBubble=true,l(null),I();},scaleX:d==="reset"?.98:1,scaleY:d==="reset"?.98:1,children:[jsx(Rect,{width:x.buttonWidth,height:x.buttonHeight,fill:v?"#096b76":"#9ca3af",cornerRadius:8}),jsx(Text,{width:x.buttonWidth,height:x.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:x.padding+x.buttonWidth+x.buttonGap,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true,onMouseDown:w=>{w.cancelBubble=true,!v&&l("submit");},onMouseUp:w=>{w.cancelBubble=true,!v&&(l(null),B());},onMouseLeave:w=>{w.cancelBubble=true,l(null);},onTouchStart:w=>{w.cancelBubble=true,!v&&l("submit");},onTouchEnd:w=>{w.cancelBubble=true,!v&&(l(null),B());},scaleX:d==="submit"?.98:1,scaleY:d==="submit"?.98:1,children:[jsx(Rect,{width:x.buttonWidth,height:x.buttonHeight,fill:h.length===0||v?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:x.buttonWidth,height:x.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Fc.displayName="FillInTheBlanks";var Bc=Fc;var Nc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,onLongPress:r,fibRefs:s})=>{let{createHandlers:u}=Ve({onLongPress:r});return jsx(Fragment,{children:e.map(i=>jsx(Bc,{fillInTheBlank:i,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,fibRefs:s,touchHandlers:u(i.id,"fillInTheBlanks")},i.id))})};var Fl=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},Ol=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,touchHandlers:r,handleDragEnd:s})=>{let u=useSelector(x=>x.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),f=useDispatch(),[d,l]=useState(null),[m,h]=useState(e.data.responseOptions.userAnswer||""),[p,v]=useState(false);useEffect(()=>{let x=c.current;if(x)return a.current.set(e.id,x),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",b=p&&m.trim().toLowerCase()===y,g=x=>{h(x);let S=x.trim();S.toLowerCase()===y;f(Ja({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:S}}}));},C=()=>{v(false),h("");},I=()=>b?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",B=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},k=useMemo(()=>{let U=e.width-48,K=Math.max(60,Fl(e.data.question,20,U,"bold")+20),R=p?Math.max(60,Fl(I(),14,U)+30):0,ne=Math.max(30,Fl("Answer (Extended response):",14,U)+10),X=K+R+ne+120+12+12+48+24;return {padding:24,questionHeight:K,questionFontSize:20,feedbackHeight:R,feedbackFontSize:14,placeholderHeight:ne,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:U,totalHeight:X}},[e.width,e.data.question,p,b,I]);return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:k.totalHeight,...r,name:"la-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:x=>{let S=c.current?.getStage()?.getPointerPosition();if(!S||!n)return;let w={x:e.x,y:e.y,width:e.width,height:k.totalHeight};S.x>=w.x&&S.x<=w.x+w.width&&S.y>=w.y&&S.y<=w.y+w.height&&n(x.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:k.totalHeight-50,onTransformEnd:x=>t(e.id,x)}),jsx(Text,{text:e.data.question,x:k.padding+8,y:k.padding,fontSize:k.questionFontSize,fontStyle:"bold",fill:"#111827",width:k.contentWidth,wrap:"word",listening:false}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:k.padding,y:k.questionHeight,width:k.contentWidth,height:k.feedbackHeight,fill:B().bg,cornerRadius:8}),jsx(Text,{x:k.padding,y:k.questionHeight,width:k.contentWidth,height:k.feedbackHeight,text:I(),fontSize:k.feedbackFontSize,fontStyle:"bold",fill:B().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),jsx(Text,{text:"Answer:",x:k.padding,y:k.questionHeight+k.feedbackHeight+k.textareaMargin,fontSize:k.placeholderFontSize,fill:"#6b7280",width:k.contentWidth,wrap:"word",listening:false}),jsx(Rect,{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight,width:k.contentWidth,height:k.textareaHeight,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight},divProps:{style:{width:`${k.contentWidth}px`,height:`${k.textareaHeight}px`,pointerEvents:p?"none":"auto"}},children:jsx("textarea",{value:m,onChange:x=>g(x.target.value),disabled:p,placeholder:"Type your extended answer here...",className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"18px",pointerEvents:p?"none":"auto"}})}),jsx(Group,{y:k.questionHeight+k.feedbackHeight+k.placeholderHeight+k.textareaHeight+k.textareaMargin+k.buttonTopMargin,children:p&&jsxs(Group,{onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),C();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),C();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:k.padding,width:k.contentWidth,height:k.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:x=>x.cancelBubble=true,onTap:x=>x.cancelBubble=true}),jsx(Text,{x:k.padding,width:k.contentWidth,height:k.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Ol.displayName="LongAnswer";var qc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Ol,{longAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"longAnswer")},i.id))})};var fo=1600,mo=900,Uc=3200,Kc=1800,Iv=e=>{let o=0,t=0,a=fo,n=mo;if(!e)return {minX:o,minY:t,maxX:a,maxY:n,width:fo,height:mo};let r=(i,c,f,d)=>{o=Math.min(o,i),t=Math.min(t,c),a=Math.max(a,i+f),n=Math.max(n,c+d);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let c=i.x||0,f=i.y||0,d=i.scaleX||1,l=i.scaleY||1;for(let m=0;m<i.points.length;m+=2){let h=c+i.points[m]*d,p=f+i.points[m+1]*l;o=Math.min(o,h),t=Math.min(t,p),a=Math.max(a,h),n=Math.max(n,p);}}}),e.images?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>r(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>r(i.x,i.y,i.width,i.height));let s=Math.min(a-o,Uc),u=Math.min(n-t,Kc);return o=Math.max(o,a-Uc),t=Math.max(t,n-Kc),{minX:o,minY:t,maxX:a,maxY:n,width:s,height:u}},Cv=(e,o,t={minX:0,minY:0,maxX:fo,maxY:mo,width:fo,height:mo})=>{let a=Math.max(t.width,fo),n=Math.max(t.height,mo),r=e/o,s=a/n,u,i,c,f=0;if(r>s)i=n,u=Math.round(i*r),c=o/i;else {u=a,i=Math.round(u/r),c=e/u;let d=n*c;f=(o-d)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:u,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},Gc=(e,o,t=1)=>{let a=o.contentOffsetX||0,n=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/(o.scale*t)+a,y:(e.y-o.offsetY)/(o.scale*t)+n}},kv=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:n={enabled:true}}={})=>{let r=_e(),s=ze(),u=J(L=>L.toolbar.selectedTool),i=J(ve),c=J(Ia),f=J(_n),d=J(L=>L.canvas.zoomLevel),m=(i?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),h=!!m,p=useCallback(()=>{m&&r(Xa(m.id));},[r,m]),v=i?.editingActivity,y=i?.showMcqForm,b=i?.lines||[],g=useRef(null),C=useRef(null),[I,B]=useState(null),k=useRef(null),[x,S]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:fo,stageHeight:mo,offsetX:0,offsetY:0,baseWidth:fo,baseHeight:mo,contentOffsetX:0,contentOffsetY:0}),w=useMemo(()=>Iv(i||null),[c]),[T,q]=useState(null),[H,F]=useState(null),[V,U]=useState(null),[K,R]=useState(null),[z,ne]=useState(null),[X$1,P]=useState(null),[N,_]=useState(null),[Q,re]=useState(false),[j,pe]=useState(null),[ge,le]=useState(false),ye=useRef(null),we=useRef(null),xe=useRef(null),{debouncedGenerateThumbnail:St}=xu(c,g);useEffect(()=>{let L=()=>{if(C.current){let E=C.current.getBoundingClientRect(),O=Cv(E.width,E.height,w);S(O);}};L();let M=new ResizeObserver(L);return C.current&&M.observe(C.current),window.addEventListener("resize",L),()=>{M.disconnect(),window.removeEventListener("resize",L);}},[w]),useEffect(()=>{if(g.current){let L=g.current.container();L&&(L.style.cursor="");}},[u]);let ae=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(M=>M.batchDraw()),!f)try{St();}catch(M){console.warn("Preview generation failed (CORS):",M);}});},[St,f]),rn=useRef(c);useEffect(()=>{rn.current!==c&&(rn.current=c,ae());},[c,ae]);let yo=useRef(null),nn=useRef(true);useEffect(()=>{if(!i)return;let L=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),M=yo.current?.count!==L;!nn.current&&M&&setTimeout(()=>{ae();},100),yo.current={slideId:c,count:L},nn.current=false;},[i,c,ae]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{xe.current&&a&&a(xe);},[a]);let{startDrawing:sn,draw:ln,stopDrawing:dn,setCanvasRef:Ks,tool:Gs,color:Ga,strokeWidth:js,isSketchMode:_s}=Kd(ae),ja=useRef(new Map),{images:$s,getLoadedImage:un,imageRefs:_a,handleDragEnd:cn,handleImageTransformEnd:Xs}=Zd(ae),{videos:ir,videoRefs:wo,handleVideoClick:fn,handleVideoDragEnd:Ys,handleVideoTransformEnd:Zs}=eu(ae),{multipleChoice:A,handleMcqTransform:te,mcqRefs:ke,handleDragEnd:Ie}=Jd(ae),{trueFalse:ce,handleTrueFalseTransform:se,trueFalseRefs:Ee,handleTrueFalseDragEnd:it}=Qd(ae),{shortAnswers:ra,saRefs:Ye,handleShortAnswerDragEnd:Oe}=su(ae),{longAnswers:lt,handleLongAnswerDragEnd:na}=iu(ae),{fillInTheBlanks:va,handleFillInTheBlanksDragEnd:Js,fibRefs:So}=Rc(ae),{transformerRef:ie,boundBoxFunc:Ze}=mu(),{shapes:ya,shapeRefs:Jt,isDragging:Cd,handleShapeDragEnd:_m,handleShapeResizeEnd:$m}=ou(ae),{texts:lr,textRefs:wa,handleDragEnd:Xm,handleTransformEnd:Ym,handleDoubleClick:Zm,startEditing:mn,editingTextId:be,editingValue:kd,handleEditingChange:Td,finishEditing:Qs}=nu(ae,ye);useEffect(()=>{t&&t(mn);},[t,mn]);let pn=J(L=>L.canvas.editingTextId);useEffect(()=>{pn&&pn!==be&&mn(pn);},[pn,be,mn]);let{flashcards:Jm,flashcardRefs:hn,handleDragEnd:Qm,handleFlashcardTransformEnd:ep,handleNext:tp,handlePrevious:ap}=du(ae),{photoFrames:Md,photoFrameRefs:gn,handleDragEnd:op,handlePhotoFrameTransformEnd:rp,startCamera:np,capturePhoto:sp,cameraStreams:ip}=fu(ae);useEffect(()=>{if(ie.current){if(be){ie.current.nodes([]),ie.current.getLayer()?.batchDraw();return}if(I&&!ir.find(E=>E.id===I)?.isPlaying){let E=ja.current.get(I)||_a.current.get(I)||wo.current.get(I)||Jt.current.get(I)||wa.current.get(I)||ke.current.get(I)||hn.current.get(I)||gn.current.get(I)||Ye.current.get(I)||Ee.current.get(I)||So.current.get(I);if(E){let O=E.attrs?.locked;if(E.visible()&&O!==true){ie.current.nodes([E]),ie.current.getLayer()?.batchDraw();return}}}ie.current.nodes([]),ie.current.getLayer()?.batchDraw();}},[I,be,ir,ja,_a,wo,Jt,wa,hn,gn,Md,ke,Ee,So,ie]);let We=useCallback(L=>{B(L),o?.(L);},[o]),Lo=useCallback(()=>{B(null),o?.(null),ie.current&&(ie.current.nodes([]),ie.current.getLayer()?.batchDraw());},[ie,o]),Ad=useCallback(L=>i?i.lines?.some(M=>M.id===L)?"line":i.images?.some(M=>M.id===L)?"image":i.videos?.some(M=>M.id===L)?"video":i.shapes?.some(M=>M.id===L)?"shape":i.texts?.some(M=>M.id===L)?"text":i.flashcards?.some(M=>M.id===L)?"flashcard":i.photoFrames?.some(M=>M.id===L)?"photoFrame":i.multipleChoices?.some(M=>M.id===L)?"mcq":i.trueFalses?.some(M=>M.id===L)?"trueFalse":i.shortAnswers?.some(M=>M.id===L)?"shortAnswer":i.LongAnswer?.some(M=>M.id===L)?"longAnswer":i.fillInTheBlanks?.some(M=>M.id===L)?"fillInTheBlanks":null:null,[i]),Pd=useCallback((L,M)=>{switch(r(de()),M){case "line":r(Gn(L));break;case "image":r(bn(L));break;case "video":r(wn(L));break;case "shape":r(In(L));break;case "text":r(Cn(L));break;case "flashcard":r(Tn(L));break;case "photoFrame":r(An(L));break;case "mcq":r(En(L));break;case "trueFalse":r(Rn(L));break;case "shortAnswer":r(Bn(L));break;case "longAnswer":r(Nn(L));break;case "fillInTheBlanks":r(qn(L));break}Lo(),ae();},[r,Lo,ae]);useEffect(()=>{let L=M=>{if(M.key!=="Delete"&&M.key!=="Backspace"||!I||be)return;let E=document.activeElement;if(E instanceof HTMLInputElement||E instanceof HTMLTextAreaElement||E?.getAttribute("contenteditable")==="true")return;M.preventDefault();let Ce=Ad(I);Ce&&Pd(I,Ce);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[I,be,Ad,Pd]),useEffect(()=>{let L=ie.current;return ()=>{L&&L.nodes([]);}},[c]),useEffect(()=>{let L=M=>{be&&M.target.tagName!=="TEXTAREA"&&Qs();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[be,Qs]),useEffect(()=>{let L=be||I;if(!L||I&&be){F(null);return}let M=wa.current.get(L),E=g.current;if(!M||!E){F(null);return}let O=E.container().getBoundingClientRect(),Ce=M.absolutePosition(),he=E.scaleX();F({x:O.left+(Ce.x+M.width()*he/2)*he+x.offsetX,y:O.top+Ce.y*he+x.offsetY-70});},[I,be,lr,wa,x.offsetX,x.offsetY]),useEffect(()=>{if(!be){U(null);return}let L=wa.current.get(be),M=g.current;if(!L||!M){U(null);return}let E=L.getClientRect({relativeTo:M}),O=M.container().getBoundingClientRect(),Ce=M.scaleX(),he=M.position(),oe={top:O.top+he.y+E.y*Ce,left:O.left+he.x+E.x*Ce,scale:Ce};U(oe),r(Vd(oe));},[be,lr,wa,x.offsetY,x.offsetX]);let Ed=useCallback(L=>{let M=L.target.getClassName(),E=L.target===L.target.getStage(),O=M==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",Ce=M==="Image",he=M==="Text",oe=M==="Group"||L.target.getParent()?.getClassName()==="Group",pt=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&L.target.attrs.id,ht=M==="Group";if(E&&!O&&!Ce&&!he&&!oe&&!pt&&!ht&&Lo(),!(u==="pen"||u==="eraser")&&(Ce||he||O||oe||pt||ht))return;let Ue=L.target.getStage()?.getPointerPosition();if(!Ue)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let W=Gc(Ue,x,d);sn(W);}},[u,sn,Lo,x,d]),Dd=useCallback(L=>{if(Cd)return;let M=L.target.getStage()?.getPointerPosition();if(!M)return;let E=Gc(M,x,d);ln(E);},[ln,Cd,x,d]),Rd=useCallback(()=>{dn();},[dn]),lp=useCallback(L=>{cn(L,ae);},[cn,ae]),dp=useCallback(L=>{fn(L),We(L);},[fn,We]),Rt=useCallback((L,M,E)=>{if(L.preventDefault(),!n.enabled)return;let O=L.clientX,Ce=L.clientY,he=k.current?.offsetHeight||250,oe=k.current?.offsetWidth||200,pt=window.innerHeight,ht=window.innerWidth,tt=O,Ue=Ce;Ce+he>pt&&(Ue=Ce-he),O+oe>ht&&(tt=O-oe),We(M),q({x:tt,y:Ue,elementId:M,elementType:E});},[We,n.enabled]),$a=useRef(null),dr=useRef(null),Lt=useCallback((L,M)=>E=>{if(!n.enabled)return;E.preventDefault();let O=E.changedTouches[0];if(!O)return;let Ce=O.clientX,he=O.clientY,oe=k.current?.offsetHeight||200,pt=k.current?.offsetWidth||200,ht=window.innerHeight,tt=window.innerWidth,Ue=Ce,at=he;he+oe>ht&&(at=he-oe),Ce+pt>tt&&(Ue=Ce-pt),We(L),q({x:Ue,y:at,elementId:L,elementType:M});},[We,n.enabled]),up=useCallback((L,M)=>({onTouchStart:E=>{let O=E.evt.touches[0];dr.current={x:O.clientX,y:O.clientY},$a.current=setTimeout(()=>{Lt(L,M)(E.evt);},500);},onTouchMove:E=>{if(!dr.current)return;let O=E.evt.touches[0],Ce=Math.abs(O.clientX-dr.current.x),he=Math.abs(O.clientY-dr.current.y);(Ce>10||he>10)&&$a.current&&(clearTimeout($a.current),$a.current=null);},onTouchEnd:()=>{$a.current&&(clearTimeout($a.current),$a.current=null),dr.current=null;}}),[Lt]),Fd=useCallback(L=>{r(gr(L)),r(La(true));},[r]),Bd=useCallback(L=>{r(hr(L)),r(Qa(true));},[r]),cp=useCallback((L,M)=>{if(!T)return;let{elementId:E,elementType:O}=T;switch(L){case "order":if(M){let D=M.target.getBoundingClientRect();R({x:D.right+5,y:D.top,type:"order"});}break;case "lock":if(M){let D=M.target.getBoundingClientRect();R({x:D.right+5,y:D.top,type:"lock"});}break;case "link":if(q(null),O==="line")break;let Ce=i?O==="image"?i.images.find(D=>D.id===E):i.videos.find(D=>D.id===E):null;ne({type:"link",defaultValue:Ce?.link||""});break;case "voice":if(q(null),O==="line")break;let he=i?O==="image"?i.images.find(D=>D.id===E):O==="video"?i.videos.find(D=>D.id===E):O==="text"?i.texts.find(D=>D.id===E):O==="flashcard"?i.flashcards.find(D=>D.id===E):O==="photoFrame"?i.photoFrames.find(D=>D.id===E):O==="mcq"?i.multipleChoices.find(D=>D.id===E):O==="fillInTheBlanks"?i.fillInTheBlanks.find(D=>D.id===E):O==="longAnswer"?i.LongAnswer.find(D=>D.id===E):O==="shortAnswer"?i.shortAnswers.find(D=>D.id===E):O==="trueFalse"?i.trueFalses.find(D=>D.id===E):O==="shape"?i.shapes.find(D=>D.id===E):null:null;pe({elementId:E,elementType:O,existingAudio:he?.audioData});break;case "edit":q(null);let oe=null;O==="mcq"?oe=i?.multipleChoices.find(D=>D.id===E):O==="trueFalse"?oe=i?.trueFalses.find(D=>D.id===E):O==="shortAnswer"?oe=i?.shortAnswers.find(D=>D.id===E):O==="longAnswer"?oe=i?.LongAnswer.find(D=>D.id===E):O==="fillInTheBlanks"&&(oe=i?.fillInTheBlanks.find(D=>D.id===E)),oe&&Fd(oe);break;case "editFlashcard":q(null);let pt=i?.flashcards.find(D=>D.id===E);pt&&Bd(pt);break;case "color":q(null);let ht=i?.shapes.find(D=>D.id===E);P({elementId:E,elementType:"shape",defaultColor:ht?.color||"#096B76"});break;case "border":if(q(null),O==="shape"){r(de());let D=i?.shapes.find(ti=>ti.id===E);D&&r(Ya({id:E,hasBorder:!D.hasBorder})),ae();}break;case "crop":if(q(null),O==="image"){let D=i?.images.find(ti=>ti.id===E);D&&_({elementId:E,imageSrc:D.src});}break;case "draw":q(null),O==="image"?r(hi(E)):O==="photoFrame"&&r(xi(E));break;case "duplicate":r(de()),O==="line"?r(Pi(E)):O==="image"?r(vn(E)):O==="video"?r(Sn(E)):O==="shape"?r(Ln(E)):O==="text"?r(kn(E)):O==="flashcard"?r(Mn(E)):O==="photoFrame"?r(Pn(E)):O==="mcq"?r(Dn(E)):O==="trueFalse"?r(Fn(E)):O==="shortAnswer"?r(On(E)):O==="fillInTheBlanks"?r(Vn(E)):O==="longAnswer"&&r(Hn(E)),ae();break;case "infinite-clone":r(de());let tt=5;for(let D=0;D<tt;D++)O==="image"?r(vn(E)):O==="video"?r(Sn(E)):O==="shape"?r(Ln(E)):O==="text"?r(kn(E)):O==="flashcard"?r(Mn(E)):O==="photoFrame"?r(Pn(E)):O==="mcq"?r(Dn(E)):O==="trueFalse"?r(Fn(E)):O==="shortAnswer"?r(On(E)):O==="fillInTheBlanks"?r(Vn(E)):O==="longAnswer"&&r(Hn(E));ae();break;case "make-response":if(q(null),O==="line")break;let Ue=`#response-${E}`;r(de()),r(zn({id:E,type:O,link:Ue})),(i?O==="image"?i.images.find(D=>D.id===E):O==="video"?i.videos.find(D=>D.id===E):O==="shape"?i.shapes.find(D=>D.id===E):O==="flashcard"?i.flashcards.find(D=>D.id===E):O==="photoFrame"?i.photoFrames.find(D=>D.id===E):i.multipleChoices.find(D=>D.id===E):null)?.altText||r(Wn({id:E,type:O,altText:"Interactive response area"})),ae(),console.log(`Element ${E} marked as interactive response area`);break;case "accessibility":if(q(null),O==="line")break;let W=i?O==="image"?i.images.find(D=>D.id===E):O==="video"?i.videos.find(D=>D.id===E):O==="shape"?i.shapes.find(D=>D.id===E):null:null;ne({type:"altText",defaultValue:W?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),q(null),le(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(de()),O==="line"?r(Gn(E)):O==="image"?r(bn(E)):O==="video"?r(wn(E)):O==="shape"?r(In(E)):O==="text"?r(Cn(E)):O==="flashcard"?r(Tn(E)):O==="photoFrame"?r(An(E)):O==="mcq"?r(En(E)):O==="trueFalse"?r(Rn(E)):O==="shortAnswer"?r(Bn(E)):O==="longAnswer"?r(Nn(E)):O==="fillInTheBlanks"&&r(qn(E)),Lo(),ae();break}},[T,r,ae,Lo,i,Fd,Bd]),fp=useCallback(()=>{q(null),R(null);},[]),ei=useCallback(L=>{if(!T)return;let{elementId:M,elementType:E}=T;switch(r(de()),L){case "bring-to-front":E!=="line"&&r(ki({id:M,type:E}));break;case "send-to-back":E!=="line"&&r(Ti({id:M,type:E}));break;case "lock":case "unlock":E!=="line"&&r(Mi({id:M,type:E}));break}ae(),q(null),R(null);},[T,r,ae]),mp=useCallback(L=>{if(!T||!z)return;let{elementId:M,elementType:E}=T;r(de()),z.type==="link"&&E!=="line"?r(zn({id:M,type:E,link:L})):z.type==="altText"&&E!=="line"&&r(Wn({id:M,type:E,altText:L})),ae(),ne(null);},[T,z,r,ae]),pp=useCallback(L=>{if(!j)return;let{elementId:M,elementType:E}=j;r(de()),r(Un({id:M,type:E,audioData:L})),ae(),pe(null);},[j,r,ae]),hp=useCallback(()=>{if(!j)return;let{elementId:L,elementType:M}=j;r(de()),r(Un({id:L,type:M,audioData:""})),ae();},[j,r,ae]),gp=useCallback(L=>{if(!X$1)return;let{elementId:M}=X$1;r(de()),r(Ya({id:M,color:L})),ae(),P(null);},[X$1,r,ae]),xp=useCallback(L=>{if(!N)return;let{elementId:M}=N;r(de()),r(Co({id:M,src:L})),ae(),_(null);},[N,r,ae]);return jsxs("div",{ref:C,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Xd,{ref:L=>{if(we.current=L,Ks(L),L){let M=L.getCanvasElement();M&&(xe.current=M,a&&a(xe));}},width:x.baseWidth,height:x.baseHeight,tool:Gs,color:Ga,strokeWidth:js/(x.scale*d),isSketchMode:_s,xOffset:x.contentOffsetX,yOffset:x.contentOffsetY-x.offsetY/x.scale,style:{width:x.stageWidth,height:x.stageHeight}}),jsxs(Stage,{ref:g,width:x.stageWidth,height:x.stageHeight,scaleX:x.scaleX*d,scaleY:x.scaleY*d,x:x.offsetX,y:0,onMouseDown:Ed,onMouseMove:Dd,onMouseUp:Rd,onTouchStart:Ed,onTouchMove:Dd,onTouchEnd:Rd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:x.baseWidth,height:x.stageHeight/x.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-x.contentOffsetX,y:x.offsetY/x.scale-x.contentOffsetY,children:(()=>{let L=[];return b.forEach((M,E)=>{L.push({type:"line",timestamp:M.timestamp||E,element:{...M,id:M.id??`line-${E}`},index:E});}),ya.forEach(M=>{L.push({type:"shape",timestamp:M.timestamp||0,element:M});}),$s.forEach(M=>{L.push({type:"image",timestamp:M.timestamp||0,element:M});}),ir.forEach(M=>{L.push({type:"video",timestamp:M.timestamp||0,element:M});}),lr.forEach(M=>{L.push({type:"text",timestamp:M.timestamp||0,element:M});}),Jm.forEach(M=>{L.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Md.forEach(M=>{L.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),A.forEach(M=>{L.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),ce.forEach(M=>{L.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),ra.forEach(M=>{L.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),lt.forEach(M=>{L.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),va.forEach(M=>{L.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),L.sort((M,E)=>M.timestamp-E.timestamp),L.map((M,E)=>{let O=`${M.type}-${"id"in M.element&&M.element.id||M.index||E}`,Ce="id"in M.element?M.element.id:void 0,he=Ce&&I===Ce;switch(M.type){case "line":let oe=M.element,pt=M.index||0,ht=oe.tool==="eraser",tt=oe.isSketch&&oe.tool==="pen",Ue=oe.isSketch&&ht,at=oe.id||`line-${pt}`;return oe.x===void 0&&(oe.x=0),oe.y===void 0&&(oe.y=0),oe.scaleX===void 0&&(oe.scaleX=1),oe.scaleY===void 0&&(oe.scaleY=1),oe.rotation===void 0&&(oe.rotation=0),u==="eraser"?jsx(Group,{x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,children:jsx(Line,{points:oe.points||[],stroke:tt||Ue?void 0:oe.color,strokeWidth:tt||Ue?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Ue?ht?"black":oe.color:void 0,closed:tt||Ue,tension:0,globalCompositeOperation:ht?"destination-out":"source-over",listening:true,onClick:()=>{r(de()),r(xn(pt));},onTap:()=>{r(de()),r(xn(pt));},hitStrokeWidth:Math.max(20,(oe.strokeWidth??0)*2),onMouseEnter:W=>{let D=W.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:W=>{let D=W.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},O):jsxs(Le__default.Fragment,{children:[jsx(Group,{id:at,ref:W=>{W?ja.current.set(at,W):ja.current.delete(at);},x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",at),We(at));},onTap:()=>{u==="select"&&(console.log("Line tapped:",at),We(at));},onDragEnd:W=>{r(de()),r(Kn({id:at,x:W.target.x(),y:W.target.y(),scaleX:W.target.scaleX(),scaleY:W.target.scaleY(),rotation:W.target.rotation()})),ae();},onTransformEnd:W=>{r(de()),r(Kn({id:at,x:W.target.x(),y:W.target.y(),scaleX:W.target.scaleX(),scaleY:W.target.scaleY(),rotation:W.target.rotation()})),ae();},onMouseEnter:W=>{if(u==="select"){let D=W.target.getStage();D&&(D.container().style.cursor="move");}},onMouseLeave:W=>{if(u==="select"){let D=W.target.getStage();D&&(D.container().style.cursor="default");}},onContextMenu:W=>{let D=W.evt;D.preventDefault(),Rt(D,at,"line");},...up(at,"line"),children:jsx(Line,{points:oe.points||[],stroke:tt||Ue?void 0:oe.color,strokeWidth:tt||Ue?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Ue?ht?"black":oe.color:void 0,closed:tt||Ue,tension:0,globalCompositeOperation:ht?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=ja.current.get(I);console.log("Line Transformer - selectedId:",I,"node found:",!!D),D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shape":return jsxs(Le__default.Fragment,{children:[jsx(_i,{onSelect:We,shapes:[M.element],shapeRefs:Jt,handleShapeDragEnd:_m,handleShapeResizeEnd:$m,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Jt.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "image":return jsxs(Le__default.Fragment,{children:[jsx(Ui,{images:[M.element],getLoadedImage:un,imageRefs:_a,onDragEnd:lp,onTransform:Xs,onSelect:We,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=_a.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "video":return jsxs(Le__default.Fragment,{children:[jsx(ji,{videos:[M.element],selectedId:I,videoRefs:wo,onVideoClick:dp,onDragEnd:Ys,onTransformEnd:Zs,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=wo.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "text":return jsxs(Le__default.Fragment,{children:[jsx(Au,{texts:[M.element],textRefs:wa,onDragEnd:Xm,onTransformEnd:Ym,onSelect:We,onContextMenu:Rt,onLongPress:Lt,onDoubleClick:Zm,editingTextId:be,editingValue:kd,onEditingChange:Td}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=wa.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "flashcard":return jsxs(Le__default.Fragment,{children:[jsx(Zi,{flashcards:[M.element],flashcardRefs:hn,selectedId:I,onDragEnd:Qm,onTransform:ep,onSelect:We,onNext:tp,onPrevious:ap,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=hn.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "photoFrame":return jsxs(Le__default.Fragment,{children:[jsx(ol,{photoFrames:[M.element],photoFrameRefs:gn,selectedId:I,onDragEnd:op,onTransform:rp,onSelect:We,onStartCamera:np,onCapture:sp,cameraStreams:ip,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=gn.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "mcq":return jsxs(Le__default.Fragment,{children:[jsx(ic,{handleMcqTransform:te,multipleChoice:[M.element],handleSelect:We,mcqRefs:ke,handleDragEnd:Ie,onContextMenu:Rt,onLongPress:Lt,onUpdate:ae}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=ke.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "trueFalse":return jsxs(Le__default.Fragment,{children:[jsx(cc,{trueFalses:[M.element],handleTrueFalseTransform:se,handleSelect:We,trueFalseRefs:Ee,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:it,onUpdate:ae}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Ee.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shortAnswer":return jsxs(Le__default.Fragment,{children:[jsx(Dc,{shortAnswers:[M.element],handleSelect:We,handleTransform:te,saRefs:Ye,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:Oe}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Ye.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "longAnswer":return jsxs(Le__default.Fragment,{children:[jsx(qc,{longAnswer:[M.element],handleSelect:We,handleTransform:te,saRefs:Ye,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:na}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Ye.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "fillInTheBlanks":return jsxs(Le__default.Fragment,{children:[jsx(Nc,{fillInTheBlanks:[M.element],handleSelect:We,handleTransform:te,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:Js,fibRefs:So}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=So.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);default:return null}})})()})]}),T&&jsx(Wu,{menuRef:k,x:T.x,y:T.y,type:T.elementType,onAction:cp,onClose:fp,isDrawingMode:T.elementType==="image"?i?.images.find(L=>L.id===T.elementId)?.isDrawingMode:T.elementType==="photoFrame"?i?.photoFrames.find(L=>L.id===T.elementId)?.isDrawingMode:false}),K&&T&&jsx(Uu,{x:K.x,y:K.y,items:K.type==="order"?[{label:"Bring to Front",onClick:()=>ei("bring-to-front")},{label:"Send to Back",onClick:()=>ei("send-to-back")}]:[{label:i&&(T.elementType==="image"?i.images.find(L=>L.id===T.elementId)?.locked:i.videos.find(L=>L.id===T.elementId)?.locked)?"Unlock":"Lock",onClick:()=>ei(i&&(T.elementType==="image"?i.images.find(L=>L.id===T.elementId)?.locked:i.videos.find(L=>L.id===T.elementId)?.locked)?"unlock":"lock")}],onClose:()=>R(null)}),z&&jsx(ju,{title:z.type==="link"?"Add Link":"Add Alt Text",label:z.type==="link"?"URL":"Alternative Text",placeholder:z.type==="link"?"https://example.com":"Describe this image/video",defaultValue:z.defaultValue,onSave:mp,onClose:()=>ne(null)}),X$1&&jsx(es,{defaultColor:X$1.defaultColor,onConfirm:gp,onCancel:()=>P(null)}),N&&jsx(Yu,{imageSrc:N.imageSrc,onConfirm:xp,onCancel:()=>_(null)}),Q&&jsx(eo,{onClose:()=>re(false),stageRef:g}),j&&jsx(ec,{elementId:j.elementId,elementType:j.elementType,existingAudio:j.existingAudio,onSave:pp,onDelete:hp,onClose:()=>pe(null)}),ge&&jsx(oc,{selectedElementId:I||void 0,onClose:()=>le(false),onSelectElement:L=>{We(L),le(false);}}),i?.images.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.videos.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.shapes?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.texts?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),y&&jsx(Sc,{editElement:v}),H&&(()=>{let L=be||I;if(!L)return null;let M=lr.find(E=>E.id===L);return M?jsx(kc,{text:M,position:H}):null})(),V&&be&&(()=>{let L=lr.find(M=>M.id===be);return L?jsx(Mc,{text:L,editingValue:kd,onEditingChange:Td,onFinish:Qs,position:{top:V.top,left:V.left},scale:V.scale,textareaRef:ye},be):null})(),h&&s&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:m?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:p})}),jsx("button",{onClick:p,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),s)]})},Tv=kv;var Av="SchooplaVideoStorage";var ta="videos",Cs=()=>new Promise((e,o)=>{let t=indexedDB.open(Av,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(ta)||n.createObjectStore(ta,{keyPath:"id"});};}),da=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Cs(),r=a.transaction([ta],"readwrite").objectStore(ta),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,i)=>{let c=r.put(s);c.onsuccess=()=>u(!0),c.onerror=()=>i(c.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var jc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Cs(),t=e.transaction([ta],"readonly").objectStore(ta);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let s=r.result,u=new Map;s.forEach(i=>{u.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),a(u);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Nl=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Cs(),a=o.transaction([ta],"readwrite").objectStore(ta);await new Promise((n,r)=>{let s=a.delete(e);s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},_c=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Cs(),t=e.transaction([ta],"readwrite").objectStore(ta);await new Promise((a,n)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>n(r.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},$c=e=>URL.createObjectURL(e);function Ha(e,o=[]){let t=[];function a(r,s){let u=Le.createContext(s),i=t.length;t=[...t,s];let c=d=>{let{scope:l,children:m,...h}=d,p=l?.[e]?.[i]||u,v=Le.useMemo(()=>h,Object.values(h));return jsx(p.Provider,{value:v,children:m})};c.displayName=r+"Provider";function f(d,l){let m=l?.[e]?.[i]||u,h=Le.useContext(m);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${r}\``)}return [c,f]}let n=()=>{let r=t.map(s=>Le.createContext(s));return function(u){let i=u?.[e]||r;return Le.useMemo(()=>({[`__scope${e}`]:{...u,[e]:i}}),[u,i])}};return n.scopeName=e,[a,Ev(n,...o)]}function Ev(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(n=>({useScope:n(),scopeName:n.scopeName}));return function(r){let s=a.reduce((u,{useScope:i,scopeName:c})=>{let d=i(r)[`__scope${c}`];return {...u,...d}},{});return Le.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function Xc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function $r(...e){return o=>{let t=false,a=e.map(n=>{let r=Xc(n,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let n=0;n<a.length;n++){let r=a[n];typeof r=="function"?r():Xc(e[n],null);}}}}function Ut(...e){return Le.useCallback($r(...e),e)}function Jc(e){let o=Dv(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Fv);if(i){let c=i.props.children,f=u.map(d=>d===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Dv(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Ov(n),u=Bv(r,n.props);return n.type!==Le.Fragment&&(u.ref=a?$r(a,s):s),Le.cloneElement(n,u)}return Le.Children.count(n)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Rv=Symbol("radix.slottable");function Fv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Rv}function Bv(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let i=r(...u);return n(...u),i}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function Ov(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 qv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],yt=qv.reduce((e,o)=>{let t=Jc(`Primitive.${o}`),a=Le.forwardRef((n,r)=>{let{asChild:s,...u}=n,i=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...u,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function nt(e,o,{checkForDefaultPrevented:t=true}={}){return function(n){if(e?.(n),t===false||!n.defaultPrevented)return o?.(n)}}function Hl(e){let o=Vv(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Wv);if(i){let c=i.props.children,f=u.map(d=>d===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Vv(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Kv(n),u=Uv(r,n.props);return n.type!==Le.Fragment&&(u.ref=a?$r(a,s):s),Le.cloneElement(n,u)}return Le.Children.count(n)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var zv=Symbol("radix.slottable");function Wv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===zv}function Uv(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let i=r(...u);return n(...u),i}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function Kv(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 ks(e){let o=e+"CollectionProvider",[t,a]=Ha(o),[n,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=p=>{let{scope:v,children:y}=p,b=Le__default.useRef(null),g=Le__default.useRef(new Map).current;return jsx(n,{scope:v,itemMap:g,collectionRef:b,children:y})};s.displayName=o;let u=e+"CollectionSlot",i=Hl(u),c=Le__default.forwardRef((p,v)=>{let{scope:y,children:b}=p,g=r(u,y),C=Ut(v,g.collectionRef);return jsx(i,{ref:C,children:b})});c.displayName=u;let f=e+"CollectionItemSlot",d="data-radix-collection-item",l=Hl(f),m=Le__default.forwardRef((p,v)=>{let{scope:y,children:b,...g}=p,C=Le__default.useRef(null),I=Ut(v,C),B=r(f,y);return Le__default.useEffect(()=>(B.itemMap.set(C,{ref:C,...g}),()=>void B.itemMap.delete(C))),jsx(l,{[d]:"",ref:I,children:b})});m.displayName=f;function h(p){let v=r(e+"CollectionConsumer",p);return Le__default.useCallback(()=>{let b=v.collectionRef.current;if(!b)return [];let g=Array.from(b.querySelectorAll(`[${d}]`));return Array.from(v.itemMap.values()).sort((B,k)=>g.indexOf(B.ref.current)-g.indexOf(k.ref.current))},[v.collectionRef,v.itemMap])}return [{Provider:s,Slot:c,ItemSlot:m},h,a]}var Zo=globalThis?.document?Le.useLayoutEffect:()=>{};var Gv=Le[" useId ".trim().toString()]||(()=>{}),jv=0;function af(e){let[o,t]=Le.useState(Gv());return Zo(()=>{t(a=>a??String(jv++));},[e]),(o?`radix-${o}`:"")}function of(e){let o=Le.useRef(e);return Le.useEffect(()=>{o.current=e;}),Le.useMemo(()=>(...t)=>o.current?.(...t),[])}var _v=Le[" useInsertionEffect ".trim().toString()]||Zo;function ca({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[n,r,s]=$v({defaultProp:o,onChange:t}),u=e!==void 0,i=u?e:n;{let f=Le.useRef(e!==void 0);Le.useEffect(()=>{let d=f.current;d!==u&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${u?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=u;},[u,a]);}let c=Le.useCallback(f=>{if(u){let d=Xv(f)?f(e):f;d!==e&&s.current?.(d);}else r(f);},[u,e,r,s]);return [i,c]}function $v({defaultProp:e,onChange:o}){let[t,a]=Le.useState(e),n=Le.useRef(t),r=Le.useRef(o);return _v(()=>{r.current=o;},[o]),Le.useEffect(()=>{n.current!==t&&(r.current?.(t),n.current=t);},[t,n]),[t,a,r]}function Xv(e){return typeof e=="function"}var Yv=Le.createContext(void 0);function Qo(e){let o=Le.useContext(Yv);return e||o||"ltr"}var zl="rovingFocusGroup.onEntryFocus",Zv={bubbles:false,cancelable:true},Xr="RovingFocusGroup",[Wl,rf,Jv]=ks(Xr),[Qv,Ul]=Ha(Xr,[Jv]),[ey,ty]=Qv(Xr),nf=Le.forwardRef((e,o)=>jsx(Wl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Wl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(ay,{...e,ref:o})})}));nf.displayName=Xr;var ay=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:n=false,dir:r,currentTabStopId:s,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:i,onEntryFocus:c,preventScrollOnEntryFocus:f=false,...d}=e,l=Le.useRef(null),m=Ut(o,l),h=Qo(r),[p,v]=ca({prop:s,defaultProp:u??null,onChange:i,caller:Xr}),[y,b]=Le.useState(false),g=of(c),C=rf(t),I=Le.useRef(false),[B,k]=Le.useState(0);return Le.useEffect(()=>{let x=l.current;if(x)return x.addEventListener(zl,g),()=>x.removeEventListener(zl,g)},[g]),jsx(ey,{scope:t,orientation:a,dir:h,loop:n,currentTabStopId:p,onItemFocus:Le.useCallback(x=>v(x),[v]),onItemShiftTab:Le.useCallback(()=>b(true),[]),onFocusableItemAdd:Le.useCallback(()=>k(x=>x+1),[]),onFocusableItemRemove:Le.useCallback(()=>k(x=>x-1),[]),children:jsx(yt.div,{tabIndex:y||B===0?-1:0,"data-orientation":a,...d,ref:m,style:{outline:"none",...e.style},onMouseDown:nt(e.onMouseDown,()=>{I.current=true;}),onFocus:nt(e.onFocus,x=>{let S=!I.current;if(x.target===x.currentTarget&&S&&!y){let w=new CustomEvent(zl,Zv);if(x.currentTarget.dispatchEvent(w),!w.defaultPrevented){let T=C().filter(U=>U.focusable),q=T.find(U=>U.active),H=T.find(U=>U.id===p),V=[q,H,...T].filter(Boolean).map(U=>U.ref.current);df(V,f);}}I.current=false;}),onBlur:nt(e.onBlur,()=>b(false))})})}),sf="RovingFocusGroupItem",lf=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:n=false,tabStopId:r,children:s,...u}=e,i=af(),c=r||i,f=ty(sf,t),d=f.currentTabStopId===c,l=rf(t),{onFocusableItemAdd:m,onFocusableItemRemove:h,currentTabStopId:p}=f;return Le.useEffect(()=>{if(a)return m(),()=>h()},[a,m,h]),jsx(Wl.ItemSlot,{scope:t,id:c,focusable:a,active:n,children:jsx(yt.span,{tabIndex:d?0:-1,"data-orientation":f.orientation,...u,ref:o,onMouseDown:nt(e.onMouseDown,v=>{a?f.onItemFocus(c):v.preventDefault();}),onFocus:nt(e.onFocus,()=>f.onItemFocus(c)),onKeyDown:nt(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){f.onItemShiftTab();return}if(v.target!==v.currentTarget)return;let y=ny(v,f.orientation,f.dir);if(y!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let g=l().filter(C=>C.focusable).map(C=>C.ref.current);if(y==="last")g.reverse();else if(y==="prev"||y==="next"){y==="prev"&&g.reverse();let C=g.indexOf(v.currentTarget);g=f.loop?sy(g,C+1):g.slice(C+1);}setTimeout(()=>df(g));}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:p!=null}):s})})});lf.displayName=sf;var oy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ry(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ny(e,o,t){let a=ry(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return oy[a]}function df(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 uf=nf,cf=lf;var mf="Toggle",Kl=Le.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:n,...r}=e,[s,u]=ca({prop:t,onChange:n,defaultProp:a??false,caller:mf});return jsx(yt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:nt(e.onClick,()=>{e.disabled||u(!s);})})});Kl.displayName=mf;var qa="ToggleGroup",[hf]=Ha(qa,[Ul]),gf=Ul(),Gl=Le__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(dy,{...a,ref:o});if(t==="multiple")return jsx(uy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${qa}\``)});Gl.displayName=qa;var[xf,bf]=hf(qa),dy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=ca({prop:t,defaultProp:a??"",onChange:n,caller:qa});return jsx(xf,{scope:e.__scopeToggleGroup,type:"single",value:Le__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:u,onItemDeactivate:Le__default.useCallback(()=>u(""),[u]),children:jsx(vf,{...r,ref:o})})}),uy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=ca({prop:t,defaultProp:a??[],onChange:n,caller:qa}),i=Le__default.useCallback(f=>u((d=[])=>[...d,f]),[u]),c=Le__default.useCallback(f=>u((d=[])=>d.filter(l=>l!==f)),[u]);return jsx(xf,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:c,children:jsx(vf,{...r,ref:o})})});Gl.displayName=qa;var[cy,fy]=hf(qa),vf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:n=true,orientation:r,dir:s,loop:u=true,...i}=e,c=gf(t),f=Qo(s),d={role:"group",dir:f,...i};return jsx(cy,{scope:t,rovingFocus:n,disabled:a,children:n?jsx(uf,{asChild:true,...c,orientation:r,dir:f,loop:u,children:jsx(yt.div,{...d,ref:o})}):jsx(yt.div,{...d,ref:o})})}),As="ToggleGroupItem",my=Le__default.forwardRef((e,o)=>{let t=bf(As,e.__scopeToggleGroup),a=fy(As,e.__scopeToggleGroup),n=gf(e.__scopeToggleGroup),r=t.value.includes(e.value),s=a.disabled||e.disabled,u={...e,pressed:r,disabled:s},i=Le__default.useRef(null);return a.rovingFocus?jsx(cf,{asChild:true,...n,focusable:!s,active:r,ref:i,children:jsx(pf,{...u,ref:o})}):jsx(pf,{...u,ref:o})});my.displayName=As;var pf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...n}=e,r=bf(As,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=r.type==="single"?s:void 0;return jsx(Kl,{...u,...n,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),yf=Gl;function wf(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var n=e.length;for(o=0;o<n;o++)e[o]&&(t=wf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Ps(){for(var e,o,t=0,a="",n=arguments.length;t<n;t++)(e=arguments[t])&&(o=wf(e))&&(a&&(a+=" "),a+=o);return a}var hy=(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},gy=(e,o)=>({classGroupId:e,validator:o}),kf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Sf=[],xy="arbitrary..",by=e=>{let o=yy(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return vy(s);let u=s.split("-"),i=u[0]===""&&u.length>1?1:0;return Tf(u,i,o)},getConflictingClassGroupIds:(s,u)=>{if(u){let i=a[s],c=t[s];return i?c?hy(c,i):i:c||Sf}return t[s]||Sf}}},Tf=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let n=e[o],r=t.nextPart.get(n);if(r){let c=Tf(e,o+1,r);if(c)return c}let s=t.validators;if(s===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),i=s.length;for(let c=0;c<i;c++){let f=s[c];if(f.validator(u))return f.classGroupId}},vy=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?xy+a:void 0})(),yy=e=>{let{theme:o,classGroups:t}=e;return wy(t,o)},wy=(e,o)=>{let t=kf();for(let a in e){let n=e[a];$l(n,t,a,o);}return t},$l=(e,o,t,a)=>{let n=e.length;for(let r=0;r<n;r++){let s=e[r];Sy(s,o,t,a);}},Sy=(e,o,t,a)=>{if(typeof e=="string"){Ly(e,o,t);return}if(typeof e=="function"){Iy(e,o,t,a);return}Cy(e,o,t,a);},Ly=(e,o,t)=>{let a=e===""?o:Mf(o,e);a.classGroupId=t;},Iy=(e,o,t,a)=>{if(ky(e)){$l(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(gy(t,e));},Cy=(e,o,t,a)=>{let n=Object.entries(e),r=n.length;for(let s=0;s<r;s++){let[u,i]=n[s];$l(i,Mf(o,u),t,a);}},Mf=(e,o)=>{let t=e,a=o.split("-"),n=a.length;for(let r=0;r<n;r++){let s=a[r],u=t.nextPart.get(s);u||(u=kf(),t.nextPart.set(s,u)),t=u;}return t},ky=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Ty=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),n=(r,s)=>{t[r]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let s=t[r];if(s!==void 0)return s;if((s=a[r])!==void 0)return n(r,s),s},set(r,s){r in t?t[r]=s:n(r,s);}}};var My=[],Lf=(e,o,t,a,n)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:n}),Ay=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=n=>{let r=[],s=0,u=0,i=0,c,f=n.length;for(let p=0;p<f;p++){let v=n[p];if(s===0&&u===0){if(v===":"){r.push(n.slice(i,p)),i=p+1;continue}if(v==="/"){c=p;continue}}v==="["?s++:v==="]"?s--:v==="("?u++:v===")"&&u--;}let d=r.length===0?n:n.slice(i),l=d,m=false;d.endsWith("!")?(l=d.slice(0,-1),m=true):d.startsWith("!")&&(l=d.slice(1),m=true);let h=c&&c>i?c-i:void 0;return Lf(r,m,l,h)};if(o){let n=o+":",r=a;a=s=>s.startsWith(n)?r(s.slice(n.length)):Lf(My,false,s,void 0,true);}if(t){let n=a;a=r=>t({className:r,parseClassName:n});}return a},Py=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],n=[];for(let r=0;r<t.length;r++){let s=t[r],u=s[0]==="[",i=o.has(s);u||i?(n.length>0&&(n.sort(),a.push(...n),n=[]),a.push(s)):n.push(s);}return n.length>0&&(n.sort(),a.push(...n)),a}},Ey=e=>({cache:Ty(e.cacheSize),parseClassName:Ay(e),sortModifiers:Py(e),...by(e)}),Dy=/\s+/,Ry=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:n,sortModifiers:r}=o,s=[],u=e.trim().split(Dy),i="";for(let c=u.length-1;c>=0;c-=1){let f=u[c],{isExternal:d,modifiers:l,hasImportantModifier:m,baseClassName:h,maybePostfixModifierPosition:p}=t(f);if(d){i=f+(i.length>0?" "+i:i);continue}let v=!!p,y=a(v?h.substring(0,p):h);if(!y){if(!v){i=f+(i.length>0?" "+i:i);continue}if(y=a(h),!y){i=f+(i.length>0?" "+i:i);continue}v=false;}let b=l.length===0?"":l.length===1?l[0]:r(l).join(":"),g=m?b+"!":b,C=g+y;if(s.indexOf(C)>-1)continue;s.push(C);let I=n(y,v);for(let B=0;B<I.length;++B){let k=I[B];s.push(g+k);}i=f+(i.length>0?" "+i:i);}return i},Fy=(...e)=>{let o=0,t,a,n="";for(;o<e.length;)(t=e[o++])&&(a=Af(t))&&(n&&(n+=" "),n+=a);return n},Af=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Af(e[a]))&&(t&&(t+=" "),t+=o);return t},By=(e,...o)=>{let t,a,n,r,s=i=>{let c=o.reduce((f,d)=>d(f),e());return t=Ey(c),a=t.cache.get,n=t.cache.set,r=u,u(i)},u=i=>{let c=a(i);if(c)return c;let f=Ry(i,t);return n(i,f),f};return r=s,(...i)=>r(Fy(...i))},Oy=[],je=e=>{let o=t=>t[e]||Oy;return o.isThemeGetter=true,o},Pf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Ef=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Ny=/^\d+\/\d+$/,Hy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,qy=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Vy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,zy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Wy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,er=e=>Ny.test(e),ue=e=>!!e&&!Number.isNaN(Number(e)),Va=e=>!!e&&Number.isInteger(Number(e)),jl=e=>e.endsWith("%")&&ue(e.slice(0,-1)),fa=e=>Hy.test(e),Uy=()=>true,Ky=e=>qy.test(e)&&!Vy.test(e),Df=()=>false,Gy=e=>zy.test(e),jy=e=>Wy.test(e),_y=e=>!Y(e)&&!Z(e),$y=e=>tr(e,Bf,Df),Y=e=>Pf.test(e),go=e=>tr(e,Of,Ky),_l=e=>tr(e,Qy,ue),If=e=>tr(e,Rf,Df),Xy=e=>tr(e,Ff,jy),Es=e=>tr(e,Nf,Gy),Z=e=>Ef.test(e),Yr=e=>ar(e,Of),Yy=e=>ar(e,ew),Cf=e=>ar(e,Rf),Zy=e=>ar(e,Bf),Jy=e=>ar(e,Ff),Ds=e=>ar(e,Nf,true),tr=(e,o,t)=>{let a=Pf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},ar=(e,o,t=false)=>{let a=Ef.exec(e);return a?a[1]?o(a[1]):t:false},Rf=e=>e==="position"||e==="percentage",Ff=e=>e==="image"||e==="url",Bf=e=>e==="length"||e==="size"||e==="bg-size",Of=e=>e==="length",Qy=e=>e==="number",ew=e=>e==="family-name",Nf=e=>e==="shadow";var tw=()=>{let e=je("color"),o=je("font"),t=je("text"),a=je("font-weight"),n=je("tracking"),r=je("leading"),s=je("breakpoint"),u=je("container"),i=je("spacing"),c=je("radius"),f=je("shadow"),d=je("inset-shadow"),l=je("text-shadow"),m=je("drop-shadow"),h=je("blur"),p=je("perspective"),v=je("aspect"),y=je("ease"),b=je("animate"),g=()=>["auto","avoid","all","avoid-page","page","left","right","column"],C=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...C(),Z,Y],B=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],x=()=>[Z,Y,i],S=()=>[er,"full","auto",...x()],w=()=>[Va,"none","subgrid",Z,Y],T=()=>["auto",{span:["full",Va,Z,Y]},Va,Z,Y],q=()=>[Va,"auto",Z,Y],H=()=>["auto","min","max","fr",Z,Y],F=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],V=()=>["start","end","center","stretch","center-safe","end-safe"],U=()=>["auto",...x()],K=()=>[er,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...x()],R=()=>[e,Z,Y],z=()=>[...C(),Cf,If,{position:[Z,Y]}],ne=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",Zy,$y,{size:[Z,Y]}],P=()=>[jl,Yr,go],N=()=>["","none","full",c,Z,Y],_=()=>["",ue,Yr,go],Q=()=>["solid","dashed","dotted","double"],re=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],j=()=>[ue,jl,Cf,If],pe=()=>["","none",h,Z,Y],ge=()=>["none",ue,Z,Y],le=()=>["none",ue,Z,Y],ye=()=>[ue,Z,Y],we=()=>[er,"full",...x()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[fa],breakpoint:[fa],color:[Uy],container:[fa],"drop-shadow":[fa],ease:["in","out","in-out"],font:[_y],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[fa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[fa],shadow:[fa],spacing:["px",ue],text:[fa],"text-shadow":[fa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",er,Y,Z,v]}],container:["container"],columns:[{columns:[ue,Y,Z,u]}],"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:I()}],overflow:[{overflow:B()}],"overflow-x":[{"overflow-x":B()}],"overflow-y":[{"overflow-y":B()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:S()}],"inset-x":[{"inset-x":S()}],"inset-y":[{"inset-y":S()}],start:[{start:S()}],end:[{end:S()}],top:[{top:S()}],right:[{right:S()}],bottom:[{bottom:S()}],left:[{left:S()}],visibility:["visible","invisible","collapse"],z:[{z:[Va,"auto",Z,Y]}],basis:[{basis:[er,"full","auto",u,...x()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ue,er,"auto","initial","none",Y]}],grow:[{grow:["",ue,Z,Y]}],shrink:[{shrink:["",ue,Z,Y]}],order:[{order:[Va,"first","last","none",Z,Y]}],"grid-cols":[{"grid-cols":w()}],"col-start-end":[{col:T()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":w()}],"row-start-end":[{row:T()}],"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":H()}],"auto-rows":[{"auto-rows":H()}],gap:[{gap:x()}],"gap-x":[{"gap-x":x()}],"gap-y":[{"gap-y":x()}],"justify-content":[{justify:[...F(),"normal"]}],"justify-items":[{"justify-items":[...V(),"normal"]}],"justify-self":[{"justify-self":["auto",...V()]}],"align-content":[{content:["normal",...F()]}],"align-items":[{items:[...V(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...V(),{baseline:["","last"]}]}],"place-content":[{"place-content":F()}],"place-items":[{"place-items":[...V(),"baseline"]}],"place-self":[{"place-self":["auto",...V()]}],p:[{p:x()}],px:[{px:x()}],py:[{py:x()}],ps:[{ps:x()}],pe:[{pe:x()}],pt:[{pt:x()}],pr:[{pr:x()}],pb:[{pb:x()}],pl:[{pl:x()}],m:[{m:U()}],mx:[{mx:U()}],my:[{my:U()}],ms:[{ms:U()}],me:[{me:U()}],mt:[{mt:U()}],mr:[{mr:U()}],mb:[{mb:U()}],ml:[{ml:U()}],"space-x":[{"space-x":x()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":x()}],"space-y-reverse":["space-y-reverse"],size:[{size:K()}],w:[{w:[u,"screen",...K()]}],"min-w":[{"min-w":[u,"screen","none",...K()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[s]},...K()]}],h:[{h:["screen","lh",...K()]}],"min-h":[{"min-h":["screen","lh","none",...K()]}],"max-h":[{"max-h":["screen","lh",...K()]}],"font-size":[{text:["base",t,Yr,go]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,Z,_l]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",jl,Y]}],"font-family":[{font:[Yy,Y,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[n,Z,Y]}],"line-clamp":[{"line-clamp":[ue,"none",Z,_l]}],leading:[{leading:[r,...x()]}],"list-image":[{"list-image":["none",Z,Y]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Z,Y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:R()}],"text-color":[{text:R()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Q(),"wavy"]}],"text-decoration-thickness":[{decoration:[ue,"from-font","auto",Z,go]}],"text-decoration-color":[{decoration:R()}],"underline-offset":[{"underline-offset":[ue,"auto",Z,Y]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:x()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Z,Y]}],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",Z,Y]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:ne()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Va,Z,Y],radial:["",Z,Y],conic:[Va,Z,Y]},Jy,Xy]}],"bg-color":[{bg:R()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:R()}],"gradient-via":[{via:R()}],"gradient-to":[{to:R()}],rounded:[{rounded:N()}],"rounded-s":[{"rounded-s":N()}],"rounded-e":[{"rounded-e":N()}],"rounded-t":[{"rounded-t":N()}],"rounded-r":[{"rounded-r":N()}],"rounded-b":[{"rounded-b":N()}],"rounded-l":[{"rounded-l":N()}],"rounded-ss":[{"rounded-ss":N()}],"rounded-se":[{"rounded-se":N()}],"rounded-ee":[{"rounded-ee":N()}],"rounded-es":[{"rounded-es":N()}],"rounded-tl":[{"rounded-tl":N()}],"rounded-tr":[{"rounded-tr":N()}],"rounded-br":[{"rounded-br":N()}],"rounded-bl":[{"rounded-bl":N()}],"border-w":[{border:_()}],"border-w-x":[{"border-x":_()}],"border-w-y":[{"border-y":_()}],"border-w-s":[{"border-s":_()}],"border-w-e":[{"border-e":_()}],"border-w-t":[{"border-t":_()}],"border-w-r":[{"border-r":_()}],"border-w-b":[{"border-b":_()}],"border-w-l":[{"border-l":_()}],"divide-x":[{"divide-x":_()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":_()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Q(),"hidden","none"]}],"divide-style":[{divide:[...Q(),"hidden","none"]}],"border-color":[{border:R()}],"border-color-x":[{"border-x":R()}],"border-color-y":[{"border-y":R()}],"border-color-s":[{"border-s":R()}],"border-color-e":[{"border-e":R()}],"border-color-t":[{"border-t":R()}],"border-color-r":[{"border-r":R()}],"border-color-b":[{"border-b":R()}],"border-color-l":[{"border-l":R()}],"divide-color":[{divide:R()}],"outline-style":[{outline:[...Q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ue,Z,Y]}],"outline-w":[{outline:["",ue,Yr,go]}],"outline-color":[{outline:R()}],shadow:[{shadow:["","none",f,Ds,Es]}],"shadow-color":[{shadow:R()}],"inset-shadow":[{"inset-shadow":["none",d,Ds,Es]}],"inset-shadow-color":[{"inset-shadow":R()}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:R()}],"ring-offset-w":[{"ring-offset":[ue,go]}],"ring-offset-color":[{"ring-offset":R()}],"inset-ring-w":[{"inset-ring":_()}],"inset-ring-color":[{"inset-ring":R()}],"text-shadow":[{"text-shadow":["none",l,Ds,Es]}],"text-shadow-color":[{"text-shadow":R()}],opacity:[{opacity:[ue,Z,Y]}],"mix-blend":[{"mix-blend":[...re(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":re()}],"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":[ue]}],"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":R()}],"mask-image-linear-to-color":[{"mask-linear-to":R()}],"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":R()}],"mask-image-t-to-color":[{"mask-t-to":R()}],"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":R()}],"mask-image-r-to-color":[{"mask-r-to":R()}],"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":R()}],"mask-image-b-to-color":[{"mask-b-to":R()}],"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":R()}],"mask-image-l-to-color":[{"mask-l-to":R()}],"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":R()}],"mask-image-x-to-color":[{"mask-x-to":R()}],"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":R()}],"mask-image-y-to-color":[{"mask-y-to":R()}],"mask-image-radial":[{"mask-radial":[Z,Y]}],"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":R()}],"mask-image-radial-to-color":[{"mask-radial-to":R()}],"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":C()}],"mask-image-conic-pos":[{"mask-conic":[ue]}],"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":R()}],"mask-image-conic-to-color":[{"mask-conic-to":R()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:ne()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Z,Y]}],filter:[{filter:["","none",Z,Y]}],blur:[{blur:pe()}],brightness:[{brightness:[ue,Z,Y]}],contrast:[{contrast:[ue,Z,Y]}],"drop-shadow":[{"drop-shadow":["","none",m,Ds,Es]}],"drop-shadow-color":[{"drop-shadow":R()}],grayscale:[{grayscale:["",ue,Z,Y]}],"hue-rotate":[{"hue-rotate":[ue,Z,Y]}],invert:[{invert:["",ue,Z,Y]}],saturate:[{saturate:[ue,Z,Y]}],sepia:[{sepia:["",ue,Z,Y]}],"backdrop-filter":[{"backdrop-filter":["","none",Z,Y]}],"backdrop-blur":[{"backdrop-blur":pe()}],"backdrop-brightness":[{"backdrop-brightness":[ue,Z,Y]}],"backdrop-contrast":[{"backdrop-contrast":[ue,Z,Y]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ue,Z,Y]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ue,Z,Y]}],"backdrop-invert":[{"backdrop-invert":["",ue,Z,Y]}],"backdrop-opacity":[{"backdrop-opacity":[ue,Z,Y]}],"backdrop-saturate":[{"backdrop-saturate":[ue,Z,Y]}],"backdrop-sepia":[{"backdrop-sepia":["",ue,Z,Y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":x()}],"border-spacing-x":[{"border-spacing-x":x()}],"border-spacing-y":[{"border-spacing-y":x()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Z,Y]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ue,"initial",Z,Y]}],ease:[{ease:["linear","initial",y,Z,Y]}],delay:[{delay:[ue,Z,Y]}],animate:[{animate:["none",b,Z,Y]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,Z,Y]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:ge()}],"rotate-x":[{"rotate-x":ge()}],"rotate-y":[{"rotate-y":ge()}],"rotate-z":[{"rotate-z":ge()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":["scale-3d"],skew:[{skew:ye()}],"skew-x":[{"skew-x":ye()}],"skew-y":[{"skew-y":ye()}],transform:[{transform:[Z,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:we()}],"translate-x":[{"translate-x":we()}],"translate-y":[{"translate-y":we()}],"translate-z":[{"translate-z":we()}],"translate-none":["translate-none"],accent:[{accent:R()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:R()}],"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",Z,Y]}],"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":x()}],"scroll-mx":[{"scroll-mx":x()}],"scroll-my":[{"scroll-my":x()}],"scroll-ms":[{"scroll-ms":x()}],"scroll-me":[{"scroll-me":x()}],"scroll-mt":[{"scroll-mt":x()}],"scroll-mr":[{"scroll-mr":x()}],"scroll-mb":[{"scroll-mb":x()}],"scroll-ml":[{"scroll-ml":x()}],"scroll-p":[{"scroll-p":x()}],"scroll-px":[{"scroll-px":x()}],"scroll-py":[{"scroll-py":x()}],"scroll-ps":[{"scroll-ps":x()}],"scroll-pe":[{"scroll-pe":x()}],"scroll-pt":[{"scroll-pt":x()}],"scroll-pr":[{"scroll-pr":x()}],"scroll-pb":[{"scroll-pb":x()}],"scroll-pl":[{"scroll-pl":x()}],"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",Z,Y]}],fill:[{fill:["none",...R()]}],"stroke-w":[{stroke:[ue,Yr,go,_l]}],stroke:[{stroke:["none",...R()]}],"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 Hf=By(tw);function za(...e){return Hf(Ps(e))}var ow=Le.createContext({size:"default",variant:"default",spacing:0});function Wa({className:e,variant:o,size:t,spacing:a=1,children:n,...r}){return jsx(yf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:za("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(ow.Provider,{value:{variant:o,size:t,spacing:a},children:n})})}var nw={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Uf=createSlice({name:"toolbar",initialState:nw,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:aa,setPenColor:ma,setStrokeWidth:Zr,setFontSize:zD,setFontFamily:WD,setFontStyle:UD,setFontWeight:KD,setTextDecoration:GD,setTextColor:jD}=Uf.actions,Yl=Uf.reducer;var Gf=e=>jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",...e,children:jsx("ellipse",{cx:"12",cy:"12",rx:"10.5",ry:"7.5"})});var _f=e=>jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",...e,children:[jsx("circle",{cx:"12",cy:"12",r:"10",fill:"currentColor"}),jsx("circle",{cx:"12",cy:"12",r:"6",fill:"white"})]});var Rs=({onClose:e,onRecordingComplete:o})=>{let t=ze(),[a,n]=useState(false),[r,s]=useState(null),[u,i]=useState(0),[c,f]=useState(null),[d,l]=useState(false),m=useRef(null),h=useRef([]),p=useRef(null),v=useRef(null),y=useRef(null);useEffect(()=>((async()=>{try{let S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});f(S),l(!0),y.current&&(y.current.srcObject=S);}catch(S){console.error("Error accessing camera:",S),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),c&&c.getTracks().forEach(S=>S.stop());}),[]);let b=()=>{c&&(c.getTracks().forEach(x=>x.stop()),f(null),l(false));},g=async()=>{try{let x=null,S=null;try{x=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(F){console.error("Error accessing camera for recording:",F),alert("Failed to access camera for recording.");return}try{S=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(F){console.warn("Microphone access denied:",F);}let w=[...x.getVideoTracks()];S&&w.push(...S.getAudioTracks());let T=new MediaStream(w),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");let H=new MediaRecorder(T,{mimeType:q,videoBitsPerSecond:25e5});m.current=H,h.current=[],H.ondataavailable=F=>{F.data.size>0&&h.current.push(F.data);},H.onstop=()=>{let F=new Blob(h.current,{type:q}),V=document.createElement("video");V.src=URL.createObjectURL(F),V.muted=!0,V.currentTime=.1,V.onseeked=()=>{let U=document.createElement("canvas");U.width=V.videoWidth,U.height=V.videoHeight;let K=U.getContext("2d");K&&(K.drawImage(V,0,0),v.current=U.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(V.src);},T.getTracks().forEach(U=>U.stop()),x&&x.getTracks().forEach(U=>U.stop()),S&&S.getTracks().forEach(U=>U.stop()),p.current&&clearInterval(p.current),s(F),b();},H.onerror=F=>{console.error("MediaRecorder error:",F);},H.start(1e3),n(!0),i(0),p.current=setInterval(()=>{i(F=>F+1);},1e3);}catch(x){console.error("Error starting camera recording:",x),alert("Failed to start recording. Please check permissions.");}},C=()=>{m.current&&a&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),n(false));},I=()=>{if(r){let x=URL.createObjectURL(r),S=document.createElement("a");S.href=x,S.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(S),S.click(),document.body.removeChild(S),URL.revokeObjectURL(x);}},B=x=>{let S=Math.floor(x/60),w=x%60;return `${S.toString().padStart(2,"0")}:${w.toString().padStart(2,"0")}`};if(!t)return null;let k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:x=>{x.target===x.currentTarget&&e(),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",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:x=>x.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,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:y,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:g,disabled:!d,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!d&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:C,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:B(u)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",B(u)]}),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:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&v.current&&(o(r,v.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(k,t)};var pa=40,Xf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,n]=useState(t?.images||[]),[r,s]=useState(t?.order||"sequential"),[u,i]=useState(false),c=useRef(null),f=ze(),d=useRef(null);useEffect(()=>{let g=C=>{C.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let l=g=>{let C=g.target.files;if(!C||C.length===0)return;let I=pa-a.length;if(I<=0){alert(`You can only upload a maximum of ${pa} images`);return}let B=Array.from(C).slice(0,I);B.length<C.length&&alert(`Only ${I} more images can be added (max ${pa} total)`);let k=B.map(x=>new Promise((S,w)=>{let T=new FileReader;T.onload=q=>{q.target?.result?S(q.target.result):w(new Error("Failed to read file"));},T.onerror=w,T.readAsDataURL(x);}));Promise.all(k).then(x=>{n(S=>[...S,...x]),d.current&&(d.current.value="");});},m=g=>{g.preventDefault(),i(false);let C=Array.from(g.dataTransfer.files).filter(x=>x.type.startsWith("image/"));if(C.length===0)return;let I=pa-a.length;if(I<=0){alert(`You can only upload a maximum of ${pa} images`);return}let B=C.slice(0,I);B.length<C.length&&alert(`Only ${I} more images can be added (max ${pa} total)`);let k=B.map(x=>new Promise((S,w)=>{let T=new FileReader;T.onload=q=>{q.target?.result?S(q.target.result):w(new Error("Failed to read file"));},T.onerror=w,T.readAsDataURL(x);}));Promise.all(k).then(x=>{n(S=>[...S,...x]);});},h=g=>{g.preventDefault(),i(true);},p=()=>{i(false);},v=g=>{n(C=>C.filter((I,B)=>B!==g));},y=g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!f)return null;let b=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:y,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=pa?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",pa," images"]}):jsxs("span",{children:[a.length,"/",pa," images"]})})]}),jsx("input",{ref:d,type:"file",accept:"image/*",multiple:true,onChange:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:h,onDragLeave:p,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>s("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>s("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,C)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${C+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(C),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:C+1})]},C))})]}),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,f)};var Fs={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},Sw={enabled:true};function Ql(e){return e?{tools:{...Fs.tools,...e.tools},actions:{...Fs.actions,...e.actions}}:Fs}var Lw={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Iw={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};function ed(e,[o,t]){return Math.min(t,Math.max(o,e))}function Yf(e){let o=Le.useRef({value:e,previous:e});return Le.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Jf(e){let[o,t]=Le.useState(void 0);return Zo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(n=>{if(!Array.isArray(n)||!n.length)return;let r=n[0],s,u;if("borderBoxSize"in r){let i=r.borderBoxSize,c=Array.isArray(i)?i[0]:i;s=c.inlineSize,u=c.blockSize;}else s=e.offsetWidth,u=e.offsetHeight;t({width:s,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var Qf=["PageUp","PageDown"],em=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],tm={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},or="Slider",[td,kw,Tw]=ks(or),[am]=Ha(or,[Tw]),[Mw,Os]=am(or),om=Le.forwardRef((e,o)=>{let{name:t,min:a=0,max:n=100,step:r=1,orientation:s="horizontal",disabled:u=false,minStepsBetweenThumbs:i=0,defaultValue:c=[a],value:f,onValueChange:d=()=>{},onValueCommit:l=()=>{},inverted:m=false,form:h,...p}=e,v=Le.useRef(new Set),y=Le.useRef(0),g=s==="horizontal"?Aw:Pw,[C=[],I]=ca({prop:f,defaultProp:c,onChange:T=>{[...v.current][y.current]?.focus(),d(T);}}),B=Le.useRef(C);function k(T){let q=Bw(C,T);w(T,q);}function x(T){w(T,y.current);}function S(){let T=B.current[y.current];C[y.current]!==T&&l(C);}function w(T,q,{commit:H}={commit:false}){let F=qw(r),V=Vw(Math.round((T-a)/r)*r+a,F),U=ed(V,[a,n]);I((K=[])=>{let R=Rw(K,U,q);if(Hw(R,i*r)){y.current=R.indexOf(U);let z=String(R)!==String(K);return z&&H&&l(R),z?R:K}else return K});}return jsx(Mw,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:n,valueIndexToChangeRef:y,thumbs:v.current,values:C,orientation:s,form:h,children:jsx(td.Provider,{scope:e.__scopeSlider,children:jsx(td.Slot,{scope:e.__scopeSlider,children:jsx(g,{"aria-disabled":u,"data-disabled":u?"":void 0,...p,ref:o,onPointerDown:nt(p.onPointerDown,()=>{u||(B.current=C);}),min:a,max:n,inverted:m,onSlideStart:u?void 0:k,onSlideMove:u?void 0:x,onSlideEnd:u?void 0:S,onHomeKeyDown:()=>!u&&w(a,0,{commit:true}),onEndKeyDown:()=>!u&&w(n,C.length-1,{commit:true}),onStepKeyDown:({event:T,direction:q})=>{if(!u){let V=Qf.includes(T.key)||T.shiftKey&&em.includes(T.key)?10:1,U=y.current,K=C[U],R=r*V*q;w(K+R,U,{commit:true});}}})})})})});om.displayName=or;var[rm,nm]=am(or,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Aw=Le.forwardRef((e,o)=>{let{min:t,max:a,dir:n,inverted:r,onSlideStart:s,onSlideMove:u,onSlideEnd:i,onStepKeyDown:c,...f}=e,[d,l]=Le.useState(null),m=Ut(o,g=>l(g)),h=Le.useRef(void 0),p=Qo(n),v=p==="ltr",y=v&&!r||!v&&r;function b(g){let C=h.current||d.getBoundingClientRect(),I=[0,C.width],k=rd(I,y?[t,a]:[a,t]);return h.current=C,k(g-C.left)}return jsx(rm,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx(sm,{dir:p,"data-orientation":"horizontal",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:g=>{let C=b(g.clientX);s?.(C);},onSlideMove:g=>{let C=b(g.clientX);u?.(C);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:g=>{let I=tm[y?"from-left":"from-right"].includes(g.key);c?.({event:g,direction:I?-1:1});}})})}),Pw=Le.forwardRef((e,o)=>{let{min:t,max:a,inverted:n,onSlideStart:r,onSlideMove:s,onSlideEnd:u,onStepKeyDown:i,...c}=e,f=Le.useRef(null),d=Ut(o,f),l=Le.useRef(void 0),m=!n;function h(p){let v=l.current||f.current.getBoundingClientRect(),y=[0,v.height],g=rd(y,m?[a,t]:[t,a]);return l.current=v,g(p-v.top)}return jsx(rm,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:jsx(sm,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:p=>{let v=h(p.clientY);r?.(v);},onSlideMove:p=>{let v=h(p.clientY);s?.(v);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:p=>{let y=tm[m?"from-bottom":"from-top"].includes(p.key);i?.({event:p,direction:y?-1:1});}})})}),sm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:n,onSlideEnd:r,onHomeKeyDown:s,onEndKeyDown:u,onStepKeyDown:i,...c}=e,f=Os(or,t);return jsx(yt.span,{...c,ref:o,onKeyDown:nt(e.onKeyDown,d=>{d.key==="Home"?(s(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):Qf.concat(em).includes(d.key)&&(i(d),d.preventDefault());}),onPointerDown:nt(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),f.thumbs.has(l)?l.focus():a(d);}),onPointerMove:nt(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&n(d);}),onPointerUp:nt(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),r(d));})})}),im="SliderTrack",lm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Os(im,t);return jsx(yt.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...a,ref:o})});lm.displayName=im;var ad="SliderRange",dm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Os(ad,t),r=nm(ad,t),s=Le.useRef(null),u=Ut(o,s),i=n.values.length,c=n.values.map(l=>fm(l,n.min,n.max)),f=i>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(yt.span,{"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,...a,ref:u,style:{...e.style,[r.startEdge]:f+"%",[r.endEdge]:d+"%"}})});dm.displayName=ad;var od="SliderThumb",um=Le.forwardRef((e,o)=>{let t=kw(e.__scopeSlider),[a,n]=Le.useState(null),r=Ut(o,u=>n(u)),s=Le.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(Ew,{...e,ref:r,index:s})}),Ew=Le.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:n,...r}=e,s=Os(od,t),u=nm(od,t),[i,c]=Le.useState(null),f=Ut(o,b=>c(b)),d=i?s.form||!!i.closest("form"):true,l=Jf(i),m=s.values[a],h=m===void 0?0:fm(m,s.min,s.max),p=Fw(a,s.values.length),v=l?.[u.size],y=v?Ow(v,h,u.direction):0;return Le.useEffect(()=>{if(i)return s.thumbs.add(i),()=>{s.thumbs.delete(i);}},[i,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${y}px)`},children:[jsx(td.ItemSlot,{scope:e.__scopeSlider,children:jsx(yt.span,{role:"slider","aria-label":e["aria-label"]||p,"aria-valuemin":s.min,"aria-valuenow":m,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...r,ref:f,style:m===void 0?{display:"none"}:e.style,onFocus:nt(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),d&&jsx(cm,{name:n??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:m},a)]})});um.displayName=od;var Dw="RadioBubbleInput",cm=Le.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let n=Le.useRef(null),r=Ut(n,a),s=Yf(o);return Le.useEffect(()=>{let u=n.current;if(!u)return;let i=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==o&&f){let d=new Event("input",{bubbles:true});f.call(u,o),u.dispatchEvent(d);}},[s,o]),jsx(yt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});cm.displayName=Dw;function Rw(e=[],o,t){let a=[...e];return a[t]=o,a.sort((n,r)=>n-r)}function fm(e,o,t){let r=100/(t-o)*(e-o);return ed(r,[0,100])}function Fw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Bw(e,o){if(e.length===1)return 0;let t=e.map(n=>Math.abs(n-o)),a=Math.min(...t);return t.indexOf(a)}function Ow(e,o,t){let a=e/2,r=rd([0,50],[0,a]);return (a-r(o)*t)*t}function Nw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Hw(e,o){if(o>0){let t=Nw(e);return Math.min(...t)>=o}return true}function rd(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 qw(e){return (String(e).split(".")[1]||"").length}function Vw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var mm=om,pm=lm,hm=dm,gm=um;function Ns({className:e,defaultValue:o,value:t,min:a=0,max:n=100,rangeClassName:r,trackClassName:s,thumbClassName:u,...i}){let c=Le.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,n],[t,o,a,n]);return jsxs(mm,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:n,className:za("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[jsx(pm,{"data-slot":"slider-track",className:za("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",s),children:jsx(hm,{"data-slot":"slider-range",className:za("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(f,d)=>jsx(gm,{"data-slot":"slider-thumb",className:za("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",u)},d))]})}var gS=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a,onVisibilityChange:n}={})=>{let r=Se(),s=J(A=>A.canvas.slides.find(te=>te.id===A.canvas.currentSlideId)),u=s?.videos||[],i=s?.editingFlashcard,c=J(A=>A.toolbar.selectedTool),f=J(A=>A.toolbar.penColor),d=J(A=>A.toolbar.strokeWidth),l=J(A=>A.canvas.editingOverlayPosition),m=s?.showMcqForm,h=s?.showFlashcardForm,p=useRef(null);useEffect(()=>{let A=te=>{(te.ctrlKey||te.metaKey)&&te.key==="z"&&!te.shiftKey&&(te.preventDefault(),r(Mo())),(te.ctrlKey&&te.shiftKey&&te.key==="Z"||te.ctrlKey&&te.key==="y")&&(te.preventDefault(),r(Ao()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[r]);let v=useMemo(()=>Ql(a),[a]),{tools:y,actions:b}=v,g=u.some(A=>A.isRecorded&&A.isPlaying),C=J(A=>A.toolbar.fontSize),I=J(A=>A.toolbar.fontFamily),B=J(A=>A.toolbar.fontStyle),k=J(A=>A.toolbar.fontWeight),x=J(A=>A.toolbar.textDecoration),S=J(A=>A.toolbar.textColor),[w,T]=useState(false),[q,H]=useState(false),[F,V]=useState(false),[U,K]=useState(false),[R,z]=useState(false),[ne,X]=useState(false),[P,N]=useState(false),[_,Q]=useState(false),[re,j]=useState(true),pe=useRef(null),ge=useRef(null),le=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],ye=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"style",icon:Palette,label:"Style",configKey:"style"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),we=useMemo(()=>[{name:"rectangle",icon:Square,label:"Square"},{name:"rectangle",icon:Rectangle,label:"Rectangle"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Gf,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:_f,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"}],[]),xe=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),St=useMemo(()=>ye.filter(A=>{let te=y[A.configKey];return typeof te=="boolean"?te:Array.isArray(te)?te.length>0:true}),[y,ye]),ae=useMemo(()=>{let A=y.shapes;return A===false?[]:A===true?we:Array.isArray(A)?we.filter(te=>A.includes(te.name)):we},[y.shapes,we]),rn=useMemo(()=>{let A=y.activities;return A===false?[]:A===true?xe:Array.isArray(A)?xe.filter(te=>A.includes(te.name)):xe},[y.activities,xe]),yo=useMemo(()=>{let A=y.media;return A===false?{photoFrame:false,image:false,video:false}:A===true?{photoFrame:true,image:true,video:true}:Array.isArray(A)?{photoFrame:A.includes("photo-frame"),image:A.includes("image"),video:A.includes("video")}:{photoFrame:true,image:true,video:true}},[y.media]),nn=useMemo(()=>{let A=y.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[y.activities]),sn=A=>{let te=A.target.files;!te||te.length===0||(r(aa("select")),r(It(false)),K(false),Array.from(te).forEach(ke=>{let Ie=new FileReader;Ie.onload=ce=>{let se=new window.Image;se.src=ce.target?.result,se.onload=()=>{let Ee=se.width/se.height,it=300,ra=300,Ye=se.width,Oe=se.height;Ye>it&&(Ye=it,Oe=Ye/Ee),Oe>ra&&(Oe=ra,Ye=Oe*Ee),r(de());let lt=l?.left||800-Ye/2,na=l?.top||450-Oe/2;r(li({id:v4(),src:se.src,x:lt,y:na,width:Ye,height:Oe,draggable:true,rotation:0}));};},Ie.readAsDataURL(ke);}),A.target.value="");},ln=async A=>{let te=A.target.files;if(!(!te||te.length===0)){console.log("files",A),r(aa("select")),r(It(false)),K(false);for(let ke of Array.from(te))try{let Ie=URL.createObjectURL(ke),ce=document.createElement("video");console.log("video",ce),ce.src=Ie,ce.muted=!0,ce.playsInline=!0,ce.preload="auto",ce.load(),await new Promise((Ze,ya)=>{let Jt=setTimeout(()=>ya(new Error("Metadata load timeout")),1e4);ce.onloadedmetadata=()=>{clearTimeout(Jt),Ze();},ce.onerror=()=>{clearTimeout(Jt),ya(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ce.duration,width:ce.videoWidth,height:ce.videoHeight}),await new Promise((Ze,ya)=>{let Jt=setTimeout(()=>ya(new Error("Video load timeout")),1e4);ce.readyState>=2?(clearTimeout(Jt),Ze()):ce.onloadeddata=()=>{clearTimeout(Jt),Ze();};});let se=Math.min(.8,ce.duration/2);console.log("Seeking to:",se),ce.currentTime=se,await new Promise(Ze=>{let ya=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ze();},5e3);ce.onseeked=()=>{clearTimeout(ya),console.log("Seek completed"),Ze();};});let Ee=document.createElement("canvas"),it=ce.videoWidth/ce.videoHeight,ra=400,Ye=400,Oe=ce.videoWidth,lt=ce.videoHeight;Oe>ra&&(Oe=ra,lt=Oe/it),lt>Ye&&(lt=Ye,Oe=lt*it),Ee.width=Oe,Ee.height=lt;let na=Ee.getContext("2d",{willReadFrequently:!1});if(!na)throw new Error("Failed to get canvas context");if(await new Promise(Ze=>setTimeout(Ze,100)),ce.videoWidth===0||ce.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Oe,height:lt}),na.drawImage(ce,0,0,Oe,lt);let va=Ee.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",va.length),r(de());let Js=800-Oe/2,So=450-lt/2,ie=v4();await da(ie,ke,va),r(ko({id:ie,objectUrl:Ie,thumbnailDataUrl:va,videoBlob:ke,x:Js,y:So,width:Oe,height:lt,draggable:!0,isPlaying:!1,rotation:0})),ce.src="",ce.load(),console.log(`Video uploaded: ${ke.name}`);}catch(Ie){console.error("Error processing video:",Ie),alert(`Failed to process video: ${ke.name}`);}A.target.value="";}},dn=(A,te,ke)=>{r(de()),r(aa("select")),r(It(false));let Ie=300,ce=300,se=800-Ie/2,Ee=450-ce/2;r(ke?To({id:ke,images:A,order:te,x:se,y:Ee,width:Ie,height:ce,rotation:0,draggable:true}):ci({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:te,x:se,y:Ee,width:Ie,height:ce,rotation:0,draggable:true})),r(Qa(false));},Ks=()=>{r(de()),r(aa("select")),r(It(false));let A=400,te=300,ke=800-A/2,Ie=450-te/2;r(pi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ke,y:Ie,width:A,height:te,rotation:0,draggable:true,isCapturing:false})),K(false);},Gs=A=>{let se={};switch(A.name){case "rectangle":A.label==="Rectangle"?(se.width=120,se.height=80):(se.width=100,se.height=100);break;case "circle":case "ring":case "wedge":case "arc":se.radius=50,(A.name==="ring"||A.name==="arc")&&(se.innerRadius=25,se.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(se.angle=A.name==="wedge"?60:90);break;case "ellipse":se.radiusX=60,se.radiusY=40;break;case "triangle":se.radius=50,se.sides=3;break;case "polygon":se.radius=50,se.sides=6;break;case "star":se.innerRadius=25,se.outerRadius=50,se.numPoints=5;break;case "arrow":case "line":se.points=[0,0,100,0],A.name==="arrow"&&(se.pointerLength=10,se.pointerWidth=10);break}let Ee={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:f,...se};r(de()),r(It(false)),r(aa(A.name)),r(di(Ee)),V(false);},Ga=A=>{if(r(aa(A)),A==="select")r(It(false));else if(A==="text"){r(It(false)),r(de());let te=200,ke=50,Ie=800-te/2,ce=450-ke/2,Ee=window.innerWidth<768?Math.max(C,32):C,it=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(ui({id:it,text:"",x:Ie,y:ce,width:te,height:ke,rotation:0,draggable:true,fontSize:Ee,fontFamily:I,fontStyle:B,fontWeight:k,textDecoration:x,fill:S,align:"left"})),setTimeout(()=>{r(vr(it));},100),t&&t(it);}else r(It(true));},js=()=>{r(br()),r(It(false));},_s=()=>{e?e():o?T(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},ja=()=>{H(true);},$s=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:Ks,enabled:yo.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>pe.current?.click(),enabled:yo.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>ge.current?.click(),enabled:yo.video}],un=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Mo()),enabled:b.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(Ao()),enabled:b.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:_s,enabled:b.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:ja,enabled:b.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:js,enabled:b.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],_a=async(A,te)=>{try{r(aa("select")),r(It(!1));let ke=URL.createObjectURL(A),Ie=document.createElement("video");Ie.src=ke,Ie.muted=!0,Ie.playsInline=!0,Ie.preload="auto",await new Promise((lt,na)=>{let va=setTimeout(()=>na(new Error("Metadata load timeout")),1e4);Ie.onloadedmetadata=()=>{clearTimeout(va),lt();},Ie.onerror=()=>{clearTimeout(va),na(new Error("Failed to load video"));};});let ce=640,se=Ie.videoWidth/Ie.videoHeight,Ee=ce,it=Ee/se;r(de());let ra=800-Ee/2,Ye=450-it/2,Oe=v4();await da(Oe,A,te),r(ko({id:Oe,objectUrl:ke,thumbnailDataUrl:te,videoBlob:A,x:ra,y:Ye,width:Ee,height:it,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),T(!1),H(!1);}catch(ke){console.error("Error adding recorded video to canvas:",ke),alert("Failed to add video to canvas. Please try again.");}},cn=A=>{r(aa("select")),r(It(false)),r(gr(null)),A&&r(Ci(A)),r(La(!m)),z(false);},Xs=()=>{r(hr(null)),r(Qa(true)),z(false);},ir=()=>{V(!F);},wo=()=>{K(!U);},fn=()=>{z(!R);},Ys=()=>{X(!ne);},Zs=()=>{let A=!re;A||(V(false),K(false),z(false),X(false),Q(false),N(false)),j(A),n?.(A);};return useEffect(()=>{if(!_)return;let A=te=>{p.current&&!p.current.contains(te.target)&&Q(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[_]),g?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:Zs,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:re?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),re&&jsxs("div",{className:"fixed scrollbar-hide top-[168px] bottom-4 left-4 z-50 flex flex-col gap-4 overflow-y-auto",children:[jsxs("div",{className:"flex items-center",children:[jsx(Wa,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:St.map((A,te)=>jsx("div",{title:A.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.name===c?"bg-primary/10":A.name==="style"?"md:hidden":""}`,onClick:()=>{A.name==="image"?(wo(),V(false),z(false),X(false),Ga(A.name)):A.name==="shapes"?(ir(),K(false),z(false),X(false),Ga(A.name)):A.name==="activities"?(Ga(A.name),fn(),V(false),K(false),X(false)):A.name==="style"?(Ys(),V(false),K(false),z(false),Ga(A.name)):(Ga(A.name),V(false),K(false),z(false),X(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},te))}),F&&jsx(Wa,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:ae.map((A,te)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Gs(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},te))}),U&&jsx(Wa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:$s.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),R&&jsxs(Wa,{type:"single",className:"mx-1 mt-auto mb-10 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl lg:mb-11",children:[nn&&jsx("div",{title:"Flashcard",onClick:()=>Xs(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),rn.map((A,te)=>jsx("div",{title:A.label,onClick:()=>cn(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},te))]}),ne&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Ns,{value:[d],onValueChange:A=>{r(Zr(A[0]));},max:28,min:6,step:1,className:"w-28",rangeClassName:"bg-gray-300",thumbClassName:"bg-gray-600 border-none h-4 w-4"}),jsx("div",{className:"h-5 w-5 rounded-full bg-gray-800"})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"COLOR"}),jsxs("div",{className:"flex flex-wrap gap-1",children:[le.map(A=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${f===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{r(ma(A.value)),X(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:f,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>r(ma(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:f,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{r(pr(A.target.value)),X(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),un.some(A=>A.enabled)&&jsx(Wa,{type:"single",className:"hidden flex-col border bg-white p-1 shadow-xl md:flex",children:un.filter(A=>A.enabled).map(A=>jsx("button",{onClick:A.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.colorClass}`,title:A.title,children:jsx(A.icon,{weight:A.iconWeight,className:"text-lg md:text-xl"})},A.key))})]}),jsx("input",{ref:pe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:sn}),jsx("input",{ref:ge,type:"file",accept:"video/*",className:"hidden",onChange:ln}),!e&&w&&o&&jsx(eo,{onClose:()=>T(false),stageRef:o,onRecordingComplete:_a}),q&&jsx(Rs,{onClose:()=>H(false),onRecordingComplete:_a}),h&&jsx(Xf,{editingFlashcard:i,onConfirm:dn,onCancel:()=>r(Qa(false))}),P&&jsx(es,{defaultColor:f,onConfirm:A=>{r(ma(A)),N(false);},onCancel:()=>N(false)})]})},xS=gS;var dd=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let n=Re(Ca),r=Re(Fi),s=a?r:n,u=Re(wr),f=(Re(b=>b.canvas.slides.find(g=>g.id===b.canvas.currentSlideId))?.videos||[]).some(b=>b.isRecorded&&b.isPlaying),[d,l]=useState(false),[m,h]=useState(null),[p,v]=useState(null),y=async()=>{if(n.length===0){v({type:"error",message:"No slides to publish"});return}if(!e){v({type:"error",message:"No publish handler provided"});return}l(true),v(null);try{let b=await e(s,u,g=>{h(g);});b.success?v({type:"success",message:b.message}):v({type:"error",message:b.message});}catch(b){v({type:"error",message:b instanceof Error?b.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),v(null);},3e3);}console.log("For checking>>>>>>>>>>>",s,"<<<<<<<<<<<<<");};return f?null:jsxs("button",{onClick:y,disabled:d||n.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var SS=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:n,onDescriptionChange:r,showPublishButton:s=true,showBackButton:u=true,editableTitle:i=true,editableDescription:c=true,className:f="",rightContent:d,leftContent:l,includeInactiveSlides:m=false})=>{let h=_e(),p=Re(wr),v=Re(Bi),y=e??(v?p.title:"")??"Untitled",b=o??(v?p.description:"")??"Add a description...",[g,C]=useState(false),[I,B]=useState(false),[k,x]=useState(y),[S,w]=useState(b),T=useRef(null),q=useRef(null);useEffect(()=>{x(y);},[y]),useEffect(()=>{w(b);},[b]),useEffect(()=>{g&&T.current&&(T.current.focus(),T.current.select());},[g]),useEffect(()=>{I&&q.current&&(q.current.focus(),q.current.select());},[I]);let H=()=>{i&&C(true);},F=()=>{c&&B(true);},V=()=>{C(false),k.trim()&&k!==y?n?n(k.trim()):h(Ei(k.trim())):k.trim()||x(y);},U=()=>{B(false),S.trim()&&S!==b?r?r(S.trim()):h(Di(S.trim())):S.trim()||w(b);},K=z=>{z.key==="Enter"?V():z.key==="Escape"&&(x(y),C(false));},R=z=>{z.key==="Enter"?U():z.key==="Escape"&&(w(b),B(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${f}`,children:[l||jsxs("div",{className:"flex items-center gap-4",children:[u&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[g?jsx("input",{ref:T,type:"text",value:k,onChange:z=>x(z.target.value),onBlur:V,onKeyDown:K,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:H,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${i?"hover:border-primary cursor-text":""}`,children:k}),I?jsx("input",{ref:q,type:"text",value:S,onChange:z=>w(z.target.value),onBlur:U,onKeyDown:R,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:F,title:S,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${c?"hover:border-primary cursor-text":""}`,children:S})]})]}),d||s&&a&&jsx(dd,{onPublish:a,includeInactiveSlides:m})]})};var MS=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],AS=({colors:e=MS,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:n=""})=>{let[r,s]=useState(true),u=J(ve),i=J(l=>l.toolbar.penColor),c=J(l=>l.toolbar.strokeWidth),f=u?.backgroundColor,d=Se();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:r?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-16 left-1/2 z-50 hidden w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-3 shadow-2xl md:bottom-6 md:flex md:p-5 2xl:px-8 2xl:py-6 ${n}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-black md:h-3 md:w-3"}),jsx(Ns,{defaultValue:[20],max:36,min:8,step:2,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:l=>d(Zr(l[0]))}),jsx("div",{className:"h-5 w-5 rounded-full bg-black md:h-7 md:w-7 lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"COLOR"}),jsxs(Wa,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${i===l.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:l.value},onClick:()=>d(ma(l.value))},l.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>d(ma("#2D2F50"))}),jsxs("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] md:h-10 md:w-10 lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(ma(l.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:f},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(pr(l.target.value))})})]})}),jsx("div",{className:"absolute -top-6 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2 md:-top-4",children:jsx("button",{onClick:()=>s(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{weight:"bold",className:"text-gray-600 md:text-xl"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>s(true),className:"fixed bottom-20 left-1/2 z-50 hidden -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl md:bottom-3 md:flex","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var Lm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),PS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),cd=e=>{let o=PS(e);return o.charAt(0).toUpperCase()+o.slice(1)},zs=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Im=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Cm={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 Tm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:n="",children:r,iconNode:s,...u},i)=>createElement("svg",{ref:i,...Cm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:zs("lucide",n),...!r&&!Im(u)&&{"aria-hidden":"true"},...u},[...s.map(([c,f])=>createElement(c,f)),...Array.isArray(r)?r:[r]]));var Ws=(e,o)=>{let t=forwardRef(({className:a,...n},r)=>createElement(Tm,{ref:r,iconNode:o,className:zs(`lucide-${Lm(cd(e))}`,`lucide-${e}`,a),...n}));return t.displayName=cd(e),t};var FS=[["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"}]],en=Ws("copy",FS);var BS=[["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"}]],tn=Ws("trash-2",BS);var Am=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:s})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:n,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(en,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),s();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(tn,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-white",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 qS=({softDelete:e=false})=>{let o=_e(),t=Re(Ca),a=Re(Ia),n=Re(yr),[r,s]=useState(true),c=(Re(h=>h.canvas.slides.find(p=>p.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),f=()=>{n&&o(ur());},d=h=>{o(mr(h));},l=h=>{o(fr(h));},m=h=>{t.length>1&&o(cr({id:h,softDelete:e}));};return c?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>s(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((h,p)=>jsx(Am,{slide:h,index:p,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>l(h.id),onDelete:()=>m(h.id)},h.id))}),jsxs("button",{onClick:f,disabled:!n,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${n?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>s(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 rr=20,$S=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:s})=>jsxs("div",{className:`relative h-[122px] w-[166px] shrink-0 cursor-pointer rounded-lg border bg-[#fafafa] transition-all ${t?"border-[#096b76]":"border-black/10"}`,onClick:n,children:[jsx("div",{className:"absolute top-1 right-1 bottom-1 left-1 overflow-hidden rounded bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"size-full object-contain"}):jsx("div",{className:"flex size-full items-center justify-center",children:jsx("span",{className:"text-xs text-black/20",children:"No preview"})})}),jsx("div",{className:"absolute top-3 left-3 flex h-5 w-5 items-center justify-center rounded-full bg-[#333c48]",children:jsx("span",{className:"text-xs font-bold text-white",children:o+1})}),jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"absolute top-3 right-3 flex cursor-pointer items-center justify-center rounded-md bg-[#3B75E0] p-1.5 text-white transition-colors hover:bg-[#2d5fc0]",title:"Duplicate Page",children:jsx(Copy,{size:18,weight:"bold"})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),s();},className:"absolute right-3 bottom-6 flex cursor-pointer items-center justify-center rounded-md bg-[#E53935] p-1.5 text-white transition-colors hover:bg-[#c62828]",title:"Delete Page",children:jsx(Trash,{size:18,weight:"bold"})}),jsxs("p",{className:"absolute bottom-2 left-3 text-sm text-black/40",children:["Page ",o+1]})]}),XS=({softDelete:e=false})=>{let o=_e(),t=Re(Ca),a=Re(Ia),n=Re(yr),[r,s]=useState(false),[u,i]=useState(false),[c,f]=useState(false),d=useRef(null),h=(Re(I=>I.canvas.slides.find(B=>B.id===I.canvas.currentSlideId))?.videos||[]).some(I=>I.isRecorded&&I.isPlaying),p=()=>{n&&t.length<rr&&o(ur());},v=I=>{o(mr(I));},y=I=>{t.length<rr&&o(fr(I));},b=I=>{t.length>1&&o(cr({id:I,softDelete:e}));},g=()=>{if(!d.current)return;let{scrollLeft:I,scrollWidth:B,clientWidth:k}=d.current,x=B>k+5;i(x&&I>5),f(x&&I<B-k-5);},C=I=>{if(!d.current)return;let B=177,k=I==="left"?d.current.scrollLeft-B:d.current.scrollLeft+B;d.current.scrollTo({left:k,behavior:"smooth"});};return useEffect(()=>{if(r){let I=setTimeout(()=>{requestAnimationFrame(()=>{g();});},350);return ()=>clearTimeout(I)}},[t,r]),useEffect(()=>{let I=d.current;if(!(!I||!r))return I.addEventListener("scroll",g),window.addEventListener("resize",g),()=>{I.removeEventListener("scroll",g),window.removeEventListener("resize",g);}},[r]),h?null:jsx("div",{className:"fixed bottom-0 left-1/2 z-50 flex w-full -translate-x-1/2 flex-col gap-4 md:hidden",children:jsxs(AnimatePresence,{mode:"wait",children:[r&&jsxs(motion.div,{initial:{y:230,opacity:0},animate:{y:0,opacity:1},exit:{y:230,opacity:0},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},onAnimationComplete:()=>g(),className:"border bg-white md:hidden",children:[jsxs("div",{className:"flex w-full items-center justify-between px-4 py-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Cards,{size:24,weight:"fill",className:"text-[#096b76]"}),jsx("span",{className:"text-base font-bold text-black/80",children:"Pages"}),jsxs("span",{className:"text-base font-bold text-black/80",children:["(",t.length,"/",rr,")"]})]}),jsx("button",{onClick:()=>s(false),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretDown,{size:16,weight:"bold",className:"text-black/60"})})]}),jsxs("div",{className:"relative",children:[u&&jsx("button",{onClick:()=>C("left"),className:"absolute top-1/2 left-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll left",children:jsx(CaretLeft,{size:20,weight:"bold",className:"text-black/80"})}),c&&jsx("button",{onClick:()=>C("right"),className:"absolute top-1/2 right-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll right",children:jsx(CaretRight,{size:20,weight:"bold",className:"text-black/80"})}),jsx("div",{ref:d,className:"scrollbar-hide flex gap-[11px] overflow-x-auto px-4 pb-4",children:t.map((I,B)=>jsx($S,{slide:I,index:B,isSelected:I.id===a,isSingleSlide:t.length===1,onSelect:()=>v(I.id),onDuplicate:()=>y(I.id),onDelete:()=>b(I.id)},I.id))})]}),jsx("button",{onClick:p,disabled:!n||t.length>=rr,className:`px-4 pb-4 text-base font-bold ${n&&t.length<rr?"cursor-pointer text-[#096b76]":"cursor-not-allowed text-black/30"}`,children:"+ Add Page"})]},"open"),!r&&jsxs(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{type:"tween",duration:.2},className:"flex cursor-pointer items-center justify-between gap-2 border border-black/10 bg-white px-4 py-3 shadow-lg md:hidden",children:[jsxs("div",{className:"flex gap-2",children:[jsx(Cards,{size:20,weight:"fill",className:"text-[#096b76]"}),jsxs("span",{className:"text-sm font-bold text-black/80",children:["Pages (",t.length,"/",rr,")"]})]}),jsx("button",{onClick:()=>s(true),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretUp,{size:16,weight:"bold",className:"text-black/60"})})]},"close")]})})},md=XS;var oL=({stageRef:e,onScreenRecord:o,visible:t=true,config:a={}})=>{let n=_e(),[r,s]=useState(false),[u,i]=useState(false),c=Re(C=>C.canvas.slides.find(I=>I.id===C.canvas.currentSlideId)),f=Re(C=>C.canvas.zoomLevel),l=(c?.videos||[]).some(C=>C.isRecorded&&C.isPlaying),m={undo:a.undo??true,redo:a.redo??true,screenRecord:a.screenRecord??true,cameraRecord:a.cameraRecord??true,clear:a.clear??true,zoomOut:a.zoomOut??true,zoomIn:a.zoomIn??true,resetZoom:a.resetZoom??true},h=()=>{o?o():s(true);},p=()=>{i(true);},v=()=>{n(br());},y=async(C,I)=>{let B=v4(),k=URL.createObjectURL(C),x=document.createElement("video");x.src=k,x.muted=true,x.playsInline=true,x.preload="auto",await new Promise((H,F)=>{let V=setTimeout(()=>F(new Error("Metadata load timeout")),1e4);x.onloadedmetadata=()=>{clearTimeout(V),H();},x.onerror=()=>{clearTimeout(V),F(new Error("Failed to load video"));};});let S=640,w=x.videoWidth/x.videoHeight,T=S,q=T/w;await da(B,C,I),n(ko({id:B,objectUrl:k,thumbnailDataUrl:I,videoBlob:C,x:100,y:100,width:T,height:q,draggable:true,isPlaying:false,rotation:0,isRecorded:true}));},g=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>n(Mo()),enabled:m.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>n(Ao()),enabled:m.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:h,enabled:m.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:p,enabled:m.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:v,enabled:m.clear,iconWeight:"fill",colorClass:"text-[#E92222]"},{key:"resetZoom",title:"Reset Zoom",icon:ArrowsOut,onClick:()=>n(zd()),enabled:m.resetZoom&&f!==1,iconWeight:"bold",colorClass:"text-primary"}].filter(C=>C.enabled);return !t||l||g.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fixed bottom-[74px] left-1/2 z-50 flex w-11/12 -translate-x-1/2 items-center justify-between rounded-md border bg-white px-4 py-1 shadow-lg md:hidden",children:g.map(C=>jsx("button",{onClick:C.onClick,className:`flex size-10 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-black/5 ${C.colorClass}`,title:C.title,children:jsx(C.icon,{weight:C.iconWeight,className:"text-xl"})},C.key))}),!o&&r&&e&&jsx(eo,{onClose:()=>s(false),stageRef:e,onRecordingComplete:y}),u&&jsx(Rs,{onClose:()=>i(false),onRecordingComplete:y})]})},pd=oL;var sL=({stageRef:e,onScreenRecord:o,softDelete:t=false,actionButtonsVisible:a=true,actionButtonsConfig:n})=>jsxs(Fragment,{children:[jsx(pd,{stageRef:e,onScreenRecord:o,visible:a,config:n}),jsx(md,{softDelete:t})]}),iL=sL;var uL="SchooplaEditorDB",cL=1,Ua="slides",Ka="metadata",hd="schoopla_current_slide_id",Nm="presentation_metadata",on=()=>new Promise((e,o)=>{let t=indexedDB.open(uL,cL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(Ua)||n.createObjectStore(Ua,{keyPath:"id"}),n.objectStoreNames.contains(Ka)||n.createObjectStore(Ka,{keyPath:"id"});};}),gd=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await on(),a=o.transaction([Ua],"readwrite").objectStore(Ua);await new Promise((n,r)=>{let s=a.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);});for(let n of e)await new Promise((r,s)=>{let u=a.add(n);u.onsuccess=()=>r(!0),u.onerror=()=>s(u.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},xd=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await on(),t=e.transaction([Ua],"readonly").objectStore(Ua);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let s=r.result;console.log("\u2705 Loaded from IndexedDB:",s.length,"slides"),s.length>0&&s[0].images&&console.log("First slide images:",s[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(s.length>0?s:null);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Us=async()=>{try{let e=await on(),o=e.transaction([Ua,Ka],"readwrite"),t=o.objectStore(Ua),a=o.objectStore(Ka);await new Promise((n,r)=>{let s=t.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),await new Promise((n,r)=>{let s=a.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(hd),localStorage.removeItem("schoopla_presentation_metadata"),await _c(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},bd=e=>{try{localStorage.setItem(hd,e);}catch(o){console.error("Error saving current slide ID:",o);}},vd=()=>{try{return localStorage.getItem(hd)}catch(e){return console.error("Error loading current slide ID:",e),null}},yd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},wd=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await on(),a=o.transaction([Ka],"readwrite").objectStore(Ka);await new Promise((n,r)=>{let s=a.put({id:Nm,...e});s.onsuccess=()=>n(!0),s.onerror=()=>r(s.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);}}},Sd=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await on(),t=e.transaction([Ka],"readonly").objectStore(Ka);return new Promise((a,n)=>{let r=t.get(Nm);r.onsuccess=()=>{e.close();let s=r.result;if(s){let{id:u,...i}=s;console.log("\u2705 Loaded presentation metadata:",i),a(i);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var fL=["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"],mL=["canvas/clearCanvas"],pL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],hL=yd((e,o)=>{gd(e),bd(o);},500),gL=yd(e=>{wd(e);},500),xL=(e,o)=>{gd(e),bd(o);},Ld=false,Hm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Nl(r).catch(s=>{console.error("Error deleting video blob:",s);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,u=e.getState().canvas.slides.find(i=>i.id===r);u&&u.videos&&u.videos.length>0&&u.videos.forEach(i=>{Nl(i.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,s=e.getState(),i=s.canvas.slides.find(c=>c.id===s.canvas.currentSlideId)?.videos.find(c=>c.id===r);i&&i.videoBlob&&setTimeout(()=>{let c=e.getState(),d=c.canvas.slides.find(l=>l.id===c.canvas.currentSlideId)?.videos.find(l=>l.id!==r&&l.x===i.x+20&&l.y===i.y+20);d&&i.videoBlob&&da(d.id,i.videoBlob,d.thumbnailDataUrl).catch(l=>{console.error("Error saving duplicated video blob:",l);});},0);}let a=o(t),n=e.getState();if(n.canvas.viewerMode)return a;if(t.type&&mL.includes(t.type)){if(!Ld){Ld=true;try{let{slides:r,currentSlideId:s}=n.canvas;xL(r,s);}finally{setTimeout(()=>{Ld=false;},0);}}}else if(t.type&&fL.includes(t.type)){let{slides:r,currentSlideId:s}=n.canvas;hL(r,s);}else if(t.type&&pL.includes(t.type)){let{presentationMetadata:r}=n.canvas;gL(r);}return a});new QueryClient;var vL=configureStore({reducer:{toolbar:Yl,canvas:Oi},middleware:e=>e({serializableCheck:false}).concat(Hm)}),yL=()=>configureStore({reducer:{toolbar:Yl,canvas:Oi},middleware:e=>e({serializableCheck:false})});var wL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2,fileName:r=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:s,quality:a,pixelRatio:n}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=u,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},SL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o;return new Promise((r,s)=>{try{let u=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:u,quality:a,pixelRatio:n});fetch(i).then(c=>c.blob()).then(c=>r(c)).catch(c=>s(c));}catch(u){s(u);}})},LL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:n})};var IL=(e,o,t)=>{let a=t.x-o.x,n=t.y-o.y;if(a===0&&n===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+n*n,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*n)/r)),u=o.x+s*a,i=o.y+s*n;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-i,2))},Id=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,n=e[0],r=e[e.length-1];for(let s=1;s<e.length-1;s++){let u=IL(e[s],n,r);u>t&&(t=u,a=s);}if(t>o){let s=Id(e.slice(0,a+1),o),u=Id(e.slice(a),o);return [...s.slice(0,-1),...u]}return [n,r]},CL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},kL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Vm=(e,o=1.5)=>{if(e.length<=4)return e;let t=CL(e),a=Id(t,o);return kL(a)},zm=(e,o=1.5)=>({...e,points:Vm(e.points,o)}),TL=(e,o=1.5)=>e.map(t=>zm(t,o)),ML=(e,o)=>{let t=e.length/2,a=o.length/2,n=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${n}%`}};var AL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Wm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:n=.85}=o;return new Promise((r,s)=>{let u=new Image;u.onload=()=>{let{width:i,height:c}=u;if(i>t||c>a){let h=i/c;i>c?(i=Math.min(i,t),c=i/h):(c=Math.min(c,a),i=c*h);}let f=document.createElement("canvas");f.width=i,f.height=c;let d=f.getContext("2d");if(!d){s(new Error("Failed to get canvas context"));return}d.drawImage(u,0,0,i,c);let l=AL(e),m=f.toDataURL(l,n);r(m);},u.onerror=s,u.src=e;})};var vo=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let n=0;n<t.length;n++)a[n]=t.charCodeAt(n);return a.buffer},nr=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",sr=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",PL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:n=1080,imageQuality:r=.85}=o,s=[],u=0;for(let i of e){let c=[],f=[],d=[];for(let l of i.images){let m=l.src;if(t&&m.startsWith("data:"))try{m=await Wm(m,{maxWidth:a,maxHeight:n,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(m.startsWith("data:")){let h=vo(m),p=nr(m);u+=h.byteLength;let v={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,buffer:h,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let y=vo(l.audioData),b=nr(l.audioData);u+=y.byteLength,v.audioBuffer=y,v.audioMimeType=b;}c.push(v);}}for(let l of i.videos){let m,h;if(l.videoBlob)m=await l.videoBlob.arrayBuffer(),h=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))m=vo(l.videoData),h=nr(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}u+=m.byteLength;let p={id:l.id,thumbnailDataUrl:l.thumbnailDataUrl,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,isPlaying:l.isPlaying,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isRecorded:l.isRecorded,buffer:m,mimeType:h};if(l.audioData&&l.audioData.startsWith("data:")){let v=vo(l.audioData),y=nr(l.audioData);u+=v.byteLength,p.audioBuffer=v,p.audioMimeType=y;}f.push(p);}for(let l of i.photoFrames){let m={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:l.draggable,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isCapturing:l.isCapturing};if(l.capturedImageUrl&&l.capturedImageUrl.startsWith("data:")){let h=vo(l.capturedImageUrl),p=nr(l.capturedImageUrl);u+=h.byteLength,m.buffer=h,m.mimeType=p;}if(l.audioData&&l.audioData.startsWith("data:")){let h=vo(l.audioData),p=nr(l.audioData);u+=h.byteLength,m.audioBuffer=h,m.audioMimeType=p;}d.push(m);}s.push({...i,images:c,videos:f,photoFrames:d});}return {slides:s,totalSize:u}},EL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},DL=e=>{let o=new FormData,t=e.slides.map((a,n)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,mimeType:r.mimeType,fileKey:`slide_${n}_image_${s}`,audioFileKey:r.audioBuffer?`slide_${n}_image_${s}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,isPlaying:r.isPlaying,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isRecorded:r.isRecorded,mimeType:r.mimeType,fileKey:`slide_${n}_video_${s}`,thumbnailFileKey:`slide_${n}_video_${s}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${n}_video_${s}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,rotation:r.rotation,draggable:r.draggable,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isCapturing:r.isCapturing,mimeType:r.mimeType,fileKey:r.buffer?`slide_${n}_photoframe_${s}`:void 0,audioFileKey:r.audioBuffer?`slide_${n}_photoframe_${s}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,n)=>{a.images.forEach((r,s)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${sr(r.mimeType)}`;if(o.append(`slide_${n}_image_${s}`,u,i),r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),f=`${r.id}_audio.${sr(r.audioMimeType)}`;o.append(`slide_${n}_image_${s}_audio`,c,f);}}),a.videos.forEach((r,s)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${sr(r.mimeType)}`;if(o.append(`slide_${n}_video_${s}`,u,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let c=vo(r.thumbnailDataUrl),f=new Blob([c],{type:"image/jpeg"}),d=`${r.id}_thumbnail.jpg`;o.append(`slide_${n}_video_${s}_thumbnail`,f,d);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),f=`${r.id}_audio.${sr(r.audioMimeType)}`;o.append(`slide_${n}_video_${s}_audio`,c,f);}}),a.photoFrames.forEach((r,s)=>{if(r.buffer&&r.mimeType){let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${sr(r.mimeType)}`;o.append(`slide_${n}_photoframe_${s}`,u,i);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${sr(r.audioMimeType)}`;o.append(`slide_${n}_photoframe_${s}_audio`,u,i);}});}),o};var BL=()=>{let e=_e(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let n=await xd(),r=vd(),s=await Sd();if(n&&n.length>0){let u=await jc(),i=n.map(f=>{if(f.videos&&f.videos.length>0){let d=f.videos.map(l=>{let m=u.get(l.id);if(m){let h=$c(m.blob);return {...l,objectUrl:h,thumbnailDataUrl:m.thumbnailDataUrl,videoBlob:m.blob}}else return l});return {...f,videos:d}}return f}),c=r&&i.find(f=>f.id===r)?r:i[0].id;e(Io({slides:i,currentSlideId:c}));}e(s?Ri({title:s.title,description:s.description}):jn(!0));}catch(n){console.error("Error loading persisted slides:",n),e(jn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var Km=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||""})),Gm=new WeakSet,jm=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 da(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},OL=()=>{let e=_e(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Gm.has(a))return;Gm.add(a);let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await Us(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,i=Km(n);e(Io({slides:i,currentSlideId:u})),await jm(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await Us(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,i=Km(n);e(Io({slides:i,currentSlideId:u})),await jm(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
2
+ export{default as Konva}from'konva';import*as Le from'react';import Le__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,createContext,useState,useMemo,createElement,useContext,useId,useLayoutEffect}from'react';import {createPortal}from'react-dom';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {CameraPlus,Camera,Stop,X,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Palette,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Rectangle,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,List,Plus,Export,CaretLeft,CaretDown,CaretUp,SidebarSimple,CaretRight,ArrowsOut,SpeakerHifiIcon,NotePencilIcon,FrameCorners,PencilSimple,CopySimple,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ArrowSquareOut,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,TextUnderline,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Copy,Pen}from'@phosphor-icons/react/dist/ssr';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import Yd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import Ju from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {Stack as Stack$1,X as X$1,DotsSixVertical,Question,FrameCorners as FrameCorners$1,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var qd=e=>{throw TypeError(e)};var Vd=(e,o,t)=>o.has(e)||qd("Cannot "+t);var _=(e,o,t)=>(Vd(e,o,"read from private field"),t?t.call(e):o.get(e)),Ne=(e,o,t)=>o.has(e)?qd("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Re=(e,o,t,a)=>(Vd(e,o,"write to private field"),o.set(e,t),t);var zd=(e,o,t,a)=>({set _(r){Re(e,o,r);},get _(){return _(e,o,a)}});var Se=()=>useDispatch(),Q=e=>useSelector(e),_e=Se,Fe=Q;var si=20,it=(()=>{let e=0;return o=>`${o}-${Date.now()}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`})();function Pp(e){let o=JSON.parse(JSON.stringify(e));return o.id=it("slide"),o.name=`${e.name} (Copy)`,o.createdAt=Date.now(),o.updatedAt=Date.now(),o.isActive=true,o.showMcqForm=false,o.showFlashcardForm=false,o.editingActivity=null,o.editingFlashcard=null,o.lines=o.lines.map(t=>({...t,id:it("line")})),o.shapes=o.shapes.map(t=>({...t,id:it("shape")})),o.images=o.images.map(t=>({...t,id:it("img"),annotations:t.annotations?.map(a=>({...a,id:it("line")}))??[]})),o.videos=o.videos.map(t=>({...t,id:it("vid"),isPlaying:false,videoBlob:void 0})),o.flashcards=o.flashcards.map(t=>({...t,id:it("flashcard")})),o.photoFrames=o.photoFrames.map(t=>({...t,id:it("photoframe"),isCapturing:false,annotations:t.annotations?.map(a=>({...a,id:it("line")}))??[]})),o.texts=o.texts.map(t=>({...t,id:it("text")})),o.multipleChoices=o.multipleChoices.map(t=>({...t,id:it("mcq"),data:{...t.data,responseOptions:{...t.data.responseOptions,selectedIndices:void 0,isCorrect:void 0,attempts:void 0}}})),o.trueFalses=o.trueFalses.map(t=>({...t,id:it("truefalse"),data:{...t.data,responseOptions:{...t.data.responseOptions,selectedResponse:void 0,isCorrect:void 0,attempts:void 0}}})),o.shortAnswers=o.shortAnswers.map(t=>({...t,id:it("shortAnswer"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0,isCorrect:void 0,attempts:void 0}}})),o.LongAnswer=o.LongAnswer.map(t=>({...t,id:it("longAnswer"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0}}})),o.fillInTheBlanks=o.fillInTheBlanks.map(t=>({...t,id:it("fillInTheBlank"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0,isCorrect:void 0,attempts:void 0}}})),o}var li=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}),ni=li("Page 1"),Ap={slides:[ni],currentSlideId:ni.id,history:{[ni.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false,editingOverlayPosition:null,zoomLevel:1},Wd=createSlice({name:"canvas",initialState:Ap,reducers:{addSlide:e=>{if(e.slides.length>=si)return;let o=li(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(c=>c.isActive).length<=1)return;let n=e.slides.findIndex(c=>c.id===t);if(n===-1)return;let s=e.slides[n];if(a?(s.isActive=false,s.updatedAt=Date.now()):(e.slides.splice(n,1),delete e.history[t]),e.currentSlideId===t){let c=e.slides.filter(l=>l.isActive);c.length>0&&(e.currentSlideId=c[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=si)return;let t=e.slides.findIndex(n=>n.id===o.payload);if(t===-1)return;let a=e.slides[t],r=Pp(a);e.slides.splice(t+1,0,r),e.currentSlideId=r.id,e.history[r.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},setViewerMode:(e,o)=>{e.viewerMode=o.payload;},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[r]=e.slides.splice(t,1);e.slides.splice(a,0,r);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(r=>r.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload);if(a){let r={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(r),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,newTimestamp:n}=o.payload;switch(r){case "image":let s=t.images.find(g=>g.id===a);s&&(s.timestamp=n);break;case "video":let c=t.videos.find(g=>g.id===a);c&&(c.timestamp=n);break;case "shape":let l=t.shapes.find(g=>g.id===a);l&&(l.timestamp=n);break;case "text":let u=t.texts.find(g=>g.id===a);u&&(u.timestamp=n);break;case "flashcard":let f=t.flashcards.find(g=>g.id===a);f&&(f.timestamp=n);break;case "photoFrame":let d=t.photoFrames.find(g=>g.id===a);d&&(d.timestamp=n);break;case "mcq":let i=t.multipleChoices.find(g=>g.id===a);i&&(i.timestamp=n);break;case "trueFalse":let m=t.trueFalses.find(g=>g.id===a);m&&(m.timestamp=n);break;case "shortAnswer":let h=t.shortAnswers.find(g=>g.id===a);h&&(h.timestamp=n);break;case "longAnswer":let p=t.LongAnswer.find(g=>g.id===a);p&&(p.timestamp=n);break;case "fillInTheBlanks":let x=t.fillInTheBlanks.find(g=>g.id===a);x&&(x.timestamp=n);break;case "line":let v=t.lines.find(g=>g.id===a);v&&(v.timestamp=n);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);if(a){let r={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(r),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);if(a){let r={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(r),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(r),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let r=t.multipleChoices[t.multipleChoices.length-1];a.x=r.x+20,a.y=r.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},updateMultipleChoiceDragAndDrop(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].dragDropPos=o.payload.dragDropPos,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={...JSON.parse(JSON.stringify(a)),id:`truefalse-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(r),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let r=t.shortAnswers[t.shortAnswers.length-1];a.x=r.x+20,a.y=r.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(r=>r.id===o.payload);if(a){let r={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(r),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let r=t.LongAnswer[t.LongAnswer.length-1];a.x=r.x+20,a.y=r.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload);if(a){let r={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(r),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let r=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=r.x+20,a.y=r.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(r=>r.id===o.payload);if(a){let r={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(r),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.images.splice(n,1);t.images.push(s);}}else if(r==="video"){let n=t.videos.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.videos.splice(n,1);t.videos.push(s);}}else if(r==="shape"){let n=t.shapes.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shapes.splice(n,1);t.shapes.push(s);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.flashcards.splice(n,1);t.flashcards.push(s);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.photoFrames.splice(n,1);t.photoFrames.push(s);}}else if(r==="text"){let n=t.texts.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.texts.splice(n,1);t.texts.push(s);}}else if(r==="trueFalse"){let n=t.trueFalses.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.trueFalses.splice(n,1);t.trueFalses.push(s);}}else if(r==="shortAnswer"){let n=t.shortAnswers.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shortAnswers.splice(n,1);t.shortAnswers.push(s);}}else if(r==="fillInTheBlanks"){let n=t.fillInTheBlanks.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.fillInTheBlanks.splice(n,1);t.fillInTheBlanks.push(s);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.images.splice(n,1);t.images.unshift(s);}}else if(r==="video"){let n=t.videos.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.videos.splice(n,1);t.videos.unshift(s);}}else if(r==="shape"){let n=t.shapes.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shapes.splice(n,1);t.shapes.unshift(s);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.flashcards.splice(n,1);t.flashcards.unshift(s);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.photoFrames.splice(n,1);t.photoFrames.unshift(s);}}else if(r==="text"){let n=t.texts.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.texts.splice(n,1);t.texts.unshift(s);}}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,s=(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(c=>c.id===a);s&&(s.locked=!s.locked,"draggable"in s&&(s.draggable=!s.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,link:n}=o.payload,c=(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);c&&(c.link=n,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,altText:n}=o.payload,c=(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);c&&(c.altText=n,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,audioData:n}=o.payload,c=(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);c&&(c.audioData=n,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},editingOverlayPosition:(e,o)=>{e.editingOverlayPosition=o.payload;},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(r=>r.id===o.payload);if(a){let r={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(r),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a){let r={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(r),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let r=a.images.map((n,s)=>s).filter(n=>n!==a.currentIndex);if(r.length>0){let n=r[Math.floor(Math.random()*r.length)];a.navigationHistory.push(n),a.currentIndex=n;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);if(a){let r={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(r),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let r=o.past.pop();e.slides[t]=r;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let r=o.future.shift();e.slides[t]=r;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let r=JSON.parse(JSON.stringify(t));a.past.push(r),a.future=[],a.past.length>20&&a.past.shift();}catch(r){console.warn("Failed to save to history - data too large:",r),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;},setZoomLevel:(e,o)=>{e.zoomLevel=Math.max(.5,Math.min(2,o.payload));},zoomIn:e=>{e.zoomLevel=Math.min(2,e.zoomLevel+.25);},zoomOut:e=>{e.zoomLevel=Math.max(.5,e.zoomLevel-.25);},resetZoom:e=>{e.zoomLevel=1;}}}),{addSlide:cr,deleteSlide:fr,duplicateSlide:mr,setCurrentSlide:pr,setViewerMode:Ep,updateSlideThumbnail:di,setBackgroundColor:hr,reorderSlides:Dp,loadSlides:Co,addLine:ui,removeLine:yn,addImage:ci,updateImage:ko,deleteImage:wn,duplicateImage:Sn,addVideo:To,updateVideo:Ln,deleteVideo:In,duplicateVideo:Cn,toggleVideoPlaying:Ya,addShape:fi,updateShape:Za,duplicateShape:kn,deleteShape:Tn,addText:mi,editingOverlayPosition:Ud,updateText:Ot,deleteText:Mn,duplicateText:Pn,addFlashcard:pi,updateFlashcard:Mo,deleteFlashcard:An,duplicateFlashcard:En,editFlashcard:gr,nextFlashcard:hi,previousFlashcard:gi,addPhotoFrame:xi,updatePhotoFrame:Ja,deletePhotoFrame:Dn,duplicatePhotoFrame:Rn,toggleImageDrawingMode:bi,addImageAnnotation:vi,updateImageAnnotation:Rp,clearImageAnnotations:Fp,togglePhotoFrameDrawingMode:yi,addPhotoFrameAnnotation:wi,updatePhotoFrameAnnotation:Bp,clearPhotoFrameAnnotations:Op,addMultipleChoice:Si,updateMultipleChoice:ht,updateMultipleChoiceDragAndDrop:Li,editMultipleChoice:Np,deleteMultipleChoice:Fn,duplicateMultipleChoice:Bn,addTrueFalse:Ii,updateTrueFalse:tt,deleteTrueFalse:On,duplicateTrueFalse:Nn,addShortAnswer:Ci,updateShortAnswer:la,deleteShortAnswer:Hn,duplicateShortAnswer:qn,addLongAnswer:ki,updateLongAnswer:Qa,deleteLongAnswer:Vn,duplicateLongAnswer:zn,addFillInTheBlanks:Ti,updateFillInTheBlanks:Ca,deleteFillInTheBlanks:Wn,duplicateFillInTheBlanks:Un,setShowMcqForm:ka,setShowFlashcardForm:eo,setActivityType:Mi,setEditingActivity:xr,bringToFront:Pi,sendToBack:Ai,toggleLock:Ei,setLink:Kn,setAltText:Gn,setAudioData:jn,updateLastLine:Hp,finalizeDrawing:Di,setLines:qp,updateLinePosition:Vp,updateLineTransform:_n,deleteLineById:$n,duplicateLine:Ri,updateElementOrder:br,clearCanvas:vr,undo:Po,redo:Ao,saveToHistory:le,toggleSketchMode:zp,setSketchMode:It,setEditingTextId:yr,setPresentationTitle:Fi,setPresentationDescription:Bi,loadPresentationMetadata:Oi,setMetadataLoaded:Xn,setZoomLevel:QL,zoomIn:eI,zoomOut:tI,resetZoom:Kd}=Wd.actions;var Gd=e=>e.canvas.slides,Ta=e=>e.canvas.currentSlideId,ve=createSelector([Gd,Ta],(e,o)=>e.find(t=>t.id===o)),Ma=createSelector([Gd],e=>e.filter(o=>o.isActive!==false)),Ni=e=>e.canvas.slides,wr=createSelector([Ma],e=>e.length<si),Wp=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},Sr=e=>e.canvas.presentationMetadata,Hi=e=>e.canvas.metadataLoaded,Yn=e=>e.canvas.viewerMode,qi=Wd.reducer;var _d=e=>{let o=Se(),t=useRef(null),a=useRef(false),r=Q(m=>m.toolbar.selectedTool),n=Q(m=>m.toolbar.penColor),s=Q(m=>m.toolbar.strokeWidth),c=Q(m=>m.canvas.isSketchMode),l=Q(m=>m.canvas.slides.find(p=>p.id===m.canvas.currentSlideId)?.lines||[]),u=useCallback(m=>{t.current=m;},[]),f=useCallback(m=>{r==="pen"&&t.current&&(o(le()),t.current.startDrawing(m),a.current=true);},[r,o]),d=useCallback(m=>{!t.current||!a.current||t.current.draw(m);},[]),i=useCallback(()=>{if(!t.current||!a.current)return;let m=t.current.stopDrawing();a.current=false,m&&m.points.length>=4&&o(ui(m)),o(Di()),e?.();},[o,e]);return {lines:l,tool:r,color:n,strokeWidth:s,isSketchMode:c,setCanvasRef:u,startDrawing:f,draw:d,stopDrawing:i}};var Zd=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:r,isSketchMode:n,style:s,xOffset:c=0,yOffset:l=0},u)=>{let f=useRef(null),d=useRef(false),i=useRef([]),m=useRef([]),h=useRef(null),p=useRef(t),x=useRef(a),v=useRef(r),g=useRef(n),y=useRef(c),S=useRef(l);useEffect(()=>{p.current=t,x.current=a,v.current=r,g.current=n,y.current=c,S.current=l;},[t,a,r,n,c,l]);let C=useCallback(()=>{let T=f.current;if(!T)return;let w=T.getContext("2d");w&&w.clearRect(0,0,T.width,T.height);},[]),k=useCallback(()=>{let T=f.current,w=m.current;if(!T||w.length<1)return;let b=T.getContext("2d");if(!b)return;if(b.clearRect(0,0,T.width,T.height),p.current==="eraser"?(b.globalCompositeOperation="destination-out",b.fillStyle="rgba(0,0,0,1)"):(b.globalCompositeOperation="source-over",b.fillStyle=x.current),w.length===1){b.beginPath(),b.arc(w[0].x,w[0].y,v.current/2,0,Math.PI*2),b.fill();return}let P=Yd(w,{size:v.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:H=>H,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(P.length<2)){b.beginPath(),b.moveTo(P[0][0],P[0][1]);for(let H=1;H<P.length;H++)b.lineTo(P[H][0],P[H][1]);b.closePath(),b.fill();}},[]);return useImperativeHandle(u,()=>({startDrawing:T=>{d.current=true;let w={x:T.x-y.current,y:T.y-S.current};i.current=[{x:T.x,y:T.y}],m.current=[w],h.current=T,k();},draw:T=>{if(!d.current||!h.current)return;let w=T.x-h.current.x,b=T.y-h.current.y;if(Math.sqrt(w*w+b*b)<2)return;let P={x:T.x-y.current,y:T.y-S.current};i.current.push({x:T.x,y:T.y}),m.current.push(P),h.current=T,k();},stopDrawing:()=>{if(!d.current)return null;if(d.current=false,i.current.length<2)return i.current=[],m.current=[],h.current=null,C(),null;let w=Yd(i.current,{size:v.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:I=>I,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(I=>[I[0],I[1]]),b={tool:p.current,points:w,color:x.current,strokeWidth:v.current,isSketch:true};return i.current=[],m.current=[],h.current=null,C(),b},clear:()=>{C(),i.current=[],m.current=[],h.current=null,d.current=false;},isDrawing:()=>d.current,getCanvasElement:()=>f.current}),[C,k]),useEffect(()=>{let T=f.current;T&&(T.width=e,T.height=o);},[e,o]),jsx("canvas",{ref:f,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});Zd.displayName="DirectDrawingCanvas";var Jd=Zd;var eu=e=>{let o=Se(),a=Q(ve)?.images||[],r=useRef(new Map),n=useRef(new Map),s=useRef(new Set),[c,l]=useState(new Set);useEffect(()=>{let m=new Set(a.map(h=>h.id));s.current.forEach(h=>{if(!m.has(h)){let p=n.current.get(h);p&&(p.src="",n.current.delete(h)),r.current.delete(h);}}),s.current=m;},[a]),useEffect(()=>()=>{n.current.forEach(m=>{m.src="";}),n.current.clear(),r.current.clear();},[]);let u=useCallback(m=>{if(n.current.has(m.id))return n.current.get(m.id);let h=new window.Image;return (m.src.startsWith("http://")||m.src.startsWith("https://"))&&(h.crossOrigin="anonymous"),h.onload=()=>{l(p=>new Set([...p,m.id]));},h.src=m.src,n.current.set(m.id,h),h},[]),f=useCallback((m,h)=>{let p=m.target,x=p.id();a.find(g=>g.id===x)&&(o(ko({id:x,x:p.x(),y:p.y(),width:p.width(),height:p.height(),rotation:p.rotation()})),h?.());},[a,o]),d=useCallback((m,h)=>{let p=h.target,x=r.current.get(m);if(!x){console.error("\u274C Image node not found for id:",m);return}let v=p.scaleX(),g=p.scaleY(),y=p.rotation(),S=x.width(),C=x.height(),k=Math.max(5,S*v),T=Math.max(5,C*g);p.scaleX(1),p.scaleY(1),x.width(k),x.height(T),o(ko({id:m,width:k,height:T,x:p.x(),y:p.y(),rotation:y})),p.getLayer()?.batchDraw(),e?.();},[o,e]),i=a.length===0||a.every(m=>c.has(m.id));return {images:a,getLoadedImage:u,imageRefs:r,handleDragEnd:f,handleImageTransformEnd:d,allImagesLoaded:i}};var tu=e=>{let o=useDispatch(),t=useSelector(ve),a=useRef(new Map),r=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),n=useCallback((c,l)=>{let u=l.target,f=u.scaleX(),d=u.scaleY(),i=u.rotation();o(ht({id:c,scaleX:f,scaleY:d,x:u.x(),y:u.y(),rotation:i})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:n,mcqRefs:a,handleDragEnd:(c,l)=>{o(ht({id:l,x:c.target.x(),y:c.target.y()})),e?.();}}};var au=e=>{let o=useDispatch(),t=useSelector(ve),a=useRef(new Map),r=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),n=useCallback((c,l)=>{let u=l.target,f=u.scaleX(),d=u.scaleY(),i=u.rotation(),m=Math.max(5,u.width()*f),h=Math.max(5,u.height()*d);u.scaleX(1),u.scaleY(1),u.width(m),u.height(h),o(tt({id:c,width:m,height:h,x:u.x(),y:u.y(),rotation:i})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:n,handleTrueFalseDragEnd:(c,l)=>{o(tt({id:l,x:c.target.x(),y:c.target.y()})),e?.();},trueFalseRefs:a}};var ou=e=>{let o=Se(),a=Q(ve)?.videos||[],r=useRef(new Map),n=useCallback(l=>{o(Ya(l));},[o]),s=useCallback((l,u)=>{let f=u.target;o(Ln({id:l,x:f.x(),y:f.y()})),e?.();},[o,e]),c=useCallback((l,u)=>{let f=u.target,d=f.scaleX(),i=f.scaleY(),m=f.rotation(),h=Math.max(5,f.width()*d),p=Math.max(5,f.height()*i);f.scaleX(1),f.scaleY(1),f.width(h),f.height(p),o(Ln({id:l,width:h,height:p,x:f.x(),y:f.y(),rotation:m})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:r,handleVideoClick:n,handleVideoDragEnd:s,handleVideoTransformEnd:c}};var su=e=>{let o=Se(),a=Q(ve)?.shapes||[],r=useRef(new Map),n=useRef(new Map),[s,c]=useState(false),l=useCallback((f,d)=>{let i=d.target;o(Za({id:f,x:i.x(),y:i.y()})),e?.();},[o,e]),u=useCallback((f,d)=>{let i=d.target,m=a.find(y=>y.id===f);if(!m)return;let h=i.scaleX(),p=i.scaleY(),x=m.type?.toLowerCase();x==="arrow"||x==="line"||(i.scaleX(1),i.scaleY(1));let g={id:f,x:i.x(),y:i.y(),width:Math.max(5,i.width()*h),height:Math.max(5,i.height()*p),rotation:i.rotation()};switch(x){case "circle":g.radius=i.width()*h/2;break;case "star":g.innerRadius=i.width()*h/4,g.outerRadius=i.width()*h/2;break;case "triangle":g.radius=i.width()*h/2;break;case "ellipse":g.radiusX=i.width()*h/2,g.radiusY=i.height()*p/2;break;case "polygon":g.radius=i.width()*h/2;break;case "ring":let y=h;g.innerRadius=m.innerRadius&&m.innerRadius*y,g.outerRadius=m.outerRadius&&m.outerRadius*y;break;case "wedge":g.radius=m.radius&&m.radius*h;break;case "arc":g.innerRadius=m.innerRadius&&m.innerRadius*h,g.outerRadius=m.outerRadius&&m.outerRadius*h;break;case "arrow":case "line":{g.scaleX=h,g.scaleY=p,delete g.width,delete g.height;break}}o(Za(g)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:r,isDragging:s,loadedShapesRef:n,handleShapeDragEnd:l,handleShapeResizeEnd:u}};var lu=(e,o)=>{let t=_e(),r=Q(ve)?.texts||[],n=useRef(new Map),[s,c]=useState(null),[l,u]=useState("");return {texts:r,textRefs:n,handleDragEnd:(x,v)=>{let g=x.target;t(le()),t(Ot({id:v,x:g.x(),y:g.y()})),e();},handleTransformEnd:x=>{let v=n.current.get(x);if(!v)return;let g=v.scaleX(),y=v.scaleY(),S=r.find(k=>k.id===x);if(!S)return;let C=(g+y)/2;v.scaleX(1),v.scaleY(1),t(le()),t(Ot({id:x,x:v.x(),y:v.y(),width:Math.max(5,(S.width||100)*g),height:Math.max(5,(S.height||50)*y),fontSize:Math.round(Math.max(8,S.fontSize*C)),rotation:v.rotation()})),e();},handleDoubleClick:x=>{let v=r.find(g=>g.id===x);v&&!v.locked&&(c(x),u(v.text));},startEditing:x=>{let v=r.find(g=>g.id===x);v&&!v.locked&&(c(x),u(v.text));},editingTextId:s,editingValue:l,handleEditingChange:x=>{u(x);},finishEditing:()=>{if(s){let x=n.current.get(s),v=r.find(y=>y.id===s);t(le());let g={id:s,text:l};if(v&&(v.fontWeight!==void 0&&(g.fontWeight=v.fontWeight),v.fontStyle!==void 0&&(g.fontStyle=v.fontStyle),v.textDecoration!==void 0&&(g.textDecoration=v.textDecoration)),o?.current&&l.trim()){let y=o.current,S=y.offsetWidth,C=y.offsetHeight,k=1;if(x){let V=x.getStage();V&&(k=V.scaleX());}let T=14,w=(S-T)/k,b=(C-T)/k,I=l.split(`
3
+ `).length,H=r.find(V=>V.id===s)?.fontSize||24,B=I*H*1.2+10;g.width=Math.max(200,w),g.height=Math.max(50,b,B);}else if(x&&l.trim()){let y=x.text(),S=x.width();x.text(l),x.width(void 0);let C=x.width(),k=x.height();x.text(y),x.width(S),g.width=Math.max(200,C+20),g.height=Math.max(50,k+20);}t(Ot(g)),c(null),u(""),t(yr(null)),e();}}}};var du=e=>{let o=useDispatch(),a=useSelector(ve)?.shortAnswers||[],r=useRef(new Map),n=useCallback((s,c)=>{let l=s.target;o(la({id:c,x:l.x(),y:l.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:n}};var uu=e=>{let o=useDispatch(),t=useSelector(ve),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((n,s)=>{let c=n.target;o(Qa({id:s,x:c.x(),y:c.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var fu=e=>{let o=Se(),a=Q(ve)?.flashcards||[],r=useRef(new Map),n=useRef(new Map),s=useCallback((d,i)=>{if(n.current.has(i))return n.current.get(i);let m=new window.Image;return (d.startsWith("http://")||d.startsWith("https://"))&&(m.crossOrigin="anonymous"),m.src=d,n.current.set(i,m),m},[]),c=useCallback(d=>{let i=d.target,m=i.id();a.find(p=>p.id===m)&&(o(Mo({id:m,x:i.x(),y:i.y()})),e?.());},[a,o,e]),l=useCallback((d,i)=>{let m=i.target,h=m.scaleX(),p=m.scaleY(),x=m.rotation(),v=Math.max(50,m.width()*h),g=Math.max(50,m.height()*p);m.scaleX(1),m.scaleY(1),m.width(v),m.height(g),o(Mo({id:d,width:v,height:g,x:m.x(),y:m.y(),rotation:x})),m.getLayer()?.batchDraw(),e?.();},[o,e]),u=useCallback(d=>{o(hi(d)),e?.();},[o,e]),f=useCallback(d=>{o(gi(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:r,handleDragEnd:c,handleFlashcardTransformEnd:l,handleNext:u,handlePrevious:f}};var hu=e=>{let o=Se(),a=Q(ve)?.photoFrames||[],r=useRef(new Map),[n,s]=useState(new Map),c=useCallback((m,h)=>{console.log("handleDragEnd"),o(Ja({id:h,x:m.target.x(),y:m.target.y()})),e?.();},[o,e]),l=useCallback((m,h)=>{let p=h.target,x=p.scaleX(),v=p.scaleY(),g=p.rotation(),y=a.find(k=>k.id===m);if(!y)return;let S=Math.max(100,y.width*x),C=Math.max(100,y.height*v);p.scaleX(1),p.scaleY(1),o(Ja({id:m,width:S,height:C,x:p.x(),y:p.y(),rotation:g})),p.getLayer()?.batchDraw(),e?.();},[o,e,a]),u=useCallback(async m=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(p=>{let x=new Map(p);return x.set(m,h),x}),o(Ja({id:m,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),f=useCallback(m=>{let h=n.get(m);h&&(h.getTracks().forEach(p=>p.stop()),s(p=>{let x=new Map(p);return x.delete(m),x}),o(Ja({id:m,isCapturing:false})),e?.());},[n,o,e]),d=useCallback((m,h)=>{let p=document.createElement("canvas");p.width=h.videoWidth,p.height=h.videoHeight;let x=p.getContext("2d");if(x){x.drawImage(h,0,0,p.width,p.height);let v=p.toDataURL("image/jpeg",.8);return o(Ja({id:m,capturedImageUrl:v,isCapturing:false})),f(m),e?.(),v}return null},[o,f,e]),i=useRef(n);return useEffect(()=>{i.current=n;},[n]),useEffect(()=>()=>{i.current.forEach(m=>{m.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:c,handlePhotoFrameTransformEnd:l,startCamera:u,stopCamera:f,capturePhoto:d,cameraStreams:n}};var gu=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((n,s)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...s,width:Math.max(o.minWidth,Math.min(s.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(s.height,o.maxHeight))}:s,[o]),a=useCallback((n,s,c,l,u,f,d,i=[])=>{if(e.current){if(n&&!i.find(p=>p.id===n)?.isPlaying){let p=s.get(n)||c.get(n)||l.get(n)||u.get(n)||f.get(n)||(d?d.get(n):null);if(p){e.current.boundBoxFunc(t),e.current.nodes([p]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var xh=(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])},yu=(e,o)=>{let t=_e(),a=Fe(Yn),r=useRef(e);useEffect(()=>{r.current=e;},[e]);let n=useCallback(()=>{if(!(!o.current||a))try{let c=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});c&&c.startsWith("data:")&&t(di({id:r.current,thumbnail:c}));}catch(c){console.warn("Could not generate thumbnail (likely CORS issue with images):",c);}},[o,t,a]),s=xh(n,500);return {generateThumbnail:n,debouncedGenerateThumbnail:s}};var vh=e=>e.flatMap(o=>[o[0],o[1]]),Jn=(e,o)=>{let t=Yd(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 vh(t)};var wu=e=>{let o=Se(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null),c=Q(y=>y.toolbar.selectedTool),l=Q(y=>y.toolbar.penColor),u=Q(y=>y.toolbar.strokeWidth),f=Q(y=>y.canvas.isSketchMode),d=Q(y=>y.canvas.slides.find(C=>C.id===y.canvas.currentSlideId)?.images.find(C=>C.id===e)),i=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,x=useCallback(y=>{if(c!=="pen"&&c!=="eraser")return;t.current=true,a.current=false,r.current=[{x:y.x,y:y.y}];let S=y.x/h,C=y.y/p;s({tool:c,points:[S,C],color:l,strokeWidth:u/h,isSketch:f});},[c,l,u,f,h,p]),v=useCallback(y=>{if(!t.current||!n)return;a.current=true;let S=r.current[r.current.length-1];if(Math.sqrt(Math.pow(y.x-S.x,2)+Math.pow(y.y-S.y,2))<2)return;r.current.push({x:y.x,y:y.y});let k;if(f)k=Jn(r.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((w,b)=>b%2===0?w/h:w/p);else {let T=y.x/h,w=y.y/p;k=[...n.points,T,w];}s(T=>T?{...T,points:k}:null);},[f,u,n,h,p]),g=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(vi({imageId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:i,activeLine:n,isDrawingMode:m,startDrawing:x,draw:v,stopDrawing:g,tool:c}};function Ve({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),r=useRef(null);return {createHandlers:useCallback((s,c)=>({onTouchStart:l=>{let u=l.evt.touches[0];r.current={x:u.clientX,y:u.clientY},a.current=setTimeout(()=>{e(s,c)(l.evt);},o);},onTouchMove:l=>{if(!r.current)return;let u=l.evt.touches[0],f=Math.abs(u.clientX-r.current.x),d=Math.abs(u.clientY-r.current.y);(f>t||d>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),r.current=null;}}),[e,o,t])}}var ku=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onDragMove:r,onTransform:n,onSelect:s,onContextMenu:c,onLongPress:l})=>{let{annotations:u,activeLine:f,stopDrawing:m,tool:h}=wu(e.id),{createHandlers:p}=Ve({onLongPress:l});useEffect(()=>{let S=t.current.get(e.id);S&&(S.width()!==e.width||S.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:S.width(),konvaHeight:S.height()}),S.width(e.width),S.height(e.height),S.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let x=false;useEffect(()=>{return;},[m,x]);let v=S=>{{s(e.id);return}},g=S=>{return;},y=S=>{};return jsxs(Group,{listening:h!=="pen"&&h!=="eraser",children:[jsx(Image$1,{id:e.id,ref:S=>{if(S)t.current.set(e.id,S),S.width(e.width),S.height(e.height),S.getLayer()?.batchDraw();else {let C=t.current.get(e.id);C?._contextMenuCleanup&&C._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:h!=="pen"&&h!=="eraser",onDragEnd:a,onDragMove:S=>r?.(e.id,S.target.x(),S.target.y()),onTransformEnd:S=>n(e.id,S),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:S=>{S.evt.preventDefault();let C=S.evt;c(C,e.id,"image");},...h!=="pen"&&h!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onMouseMove:g,onMouseUp:y,...p(e.id,"image")}:{}}),u?.map((S,C)=>{let k=S.points.map((w,b)=>b%2===0?w*e.width+e.x:w*e.height+e.y),T=S.strokeWidth*e.width;return jsx(Line,{points:k,stroke:S.tool==="eraser"?"white":S.color,strokeWidth:T,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:S.tool==="eraser"?"destination-out":"source-over",fill:S.isSketch?S.color:void 0,closed:S.isSketch,listening:false},C)}),f&&jsx(Line,{points:f.points.map((S,C)=>C%2===0?S*e.width+e.x:S*e.height+e.y),stroke:f.tool==="eraser"?"white":f.color,strokeWidth:f.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:f.tool==="eraser"?"destination-out":"source-over",fill:f.isSketch?f.color:void 0,closed:f.isSketch,listening:false},"active")]})});ku.displayName="ImageWithDrawing";var ji=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onDragMove:r,onTransform:n,onSelect:s,onContextMenu:c,onLongPress:l})=>jsx(Fragment,{children:e.map(u=>{let f=o(u);return f?jsx(ku,{img:u,loadedImage:f,imageRefs:t,onDragEnd:a,onDragMove:r,onTransform:n,onSelect:s,onContextMenu:c,onLongPress:l},u.id):null})}));ji.displayName="ImageLayer";var Ah=({src:e,x:o,id:t,y:a,width:r,height:n,isSelected:s,rotation:c=0,onTransformEnd:l,onDragEnd:u})=>{let f=Se(),d=useRef(null),i=m=>{f(Ya(m));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:n,rotation:c,onDragEnd:u,onTransformEnd:l,children:[jsx(Rect,{width:r,height:n,fill:"black",stroke:s?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${n}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>i(t),onSeeking:m=>m.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Tu=Ah;var Hh=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,nodeRef:s})=>{let[c,l]=useState(null),u=useSelector(p=>p.toolbar.selectedTool),f=u==="pen"||u==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let p=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(p.crossOrigin="anonymous"),p.src=e.thumbnailDataUrl,p.onload=()=>{l(p);};}},[e.thumbnailDataUrl]),!c)return null;let d=e.width/2,i=e.height/2,m=Math.min(e.width,e.height)*.08,h=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:p=>{if(s(p),p){let x=p.getStage()?.container();if(x){let v=g=>{let y=p.getStage()?.getPointerPosition();if(y){let S={x:e.x,y:e.y,width:e.width,height:e.height};y.x>=S.x&&y.x<=S.x+S.width&&y.y>=S.y&&y.y<=S.y+S.height&&n(g);}};x.addEventListener("contextmenu",v),p._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",v);};}}},children:[jsx(Image$1,{image:c,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:d,y:i,radius:h,fill:"white",listening:!f,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...f?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:i,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!f,...f?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:i,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!f,...f?{}:{onClick:t,onTap:t}})]})},Pu=Hh;var Xi=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(c=>jsxs(Le__default.Fragment,{children:[jsx(Pu,{video:c,isSelected:!c.isPlaying&&o===c.id,onClick:()=>a(c.id),onDragEnd:l=>r(c.id,l),onTransformEnd:l=>n(c.id,l),onContextMenu:l=>s(l,c.id,"video"),nodeRef:l=>{l?t.current.set(c.id,l):t.current.delete(c.id);}}),c.isPlaying&&!c.isRecorded&&jsx(Tu,{id:c.id,src:c.objectUrl,x:c.x,y:c.y,width:c.width,height:c.height,isSelected:false,rotation:c.rotation,onTransformEnd:l=>n(c.id,l),onDragEnd:l=>r(c.id,l)})]},c.id))}));Xi.displayName="VideoLayer";var Yi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:n,onContextMenu:s,onLongPress:c})=>{let l=useSelector(d=>d.toolbar.selectedTool),u=l==="pen"||l==="eraser",{createHandlers:f}=Ve({onLongPress:c});return jsx(Fragment,{children:e.map((d,i)=>{let m=d.id||i,h={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!u,listening:!u,fill:d.color||"#096B76",stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?2:0,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radius:d.radius||d.width/2,width:d.width,height:d.width},m);case "star":return jsx(Star,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},m);case "triangle":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},sides:3,radius:d.radius||d.width/2},m);case "polygon":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},sides:d.sides||6,radius:d.radius||d.width/2},m);case "ellipse":return jsx(Ellipse,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},m);case "ring":return jsx(Ring,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},m);case "wedge":return jsx(Wedge,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radius:d.radius||d.width/2,angle:d.angle||60},m);case "arrow":return jsx(Arrow,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?d.strokeWidth||3:0,fill:"transparent"},m);case "line":return jsx(Line,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},points:d.points||[0,0,d.width,0],stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?d.strokeWidth||3:0,fill:"transparent"},m);case "arc":return jsx(Arc,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},m);case "rectangle":default:return jsx(Rect,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!u,...u?{}:{onDragStart:p=>{n?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>r(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},m)}})})});Yi.displayName="ShapeLayer";var Du=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:n,onDoubleClick:s,editingTextId:c,onLongPress:l})=>{useEffect(()=>{e.forEach(i=>{let m=o.current.get(i.id);m&&(m.cache(),m.getLayer()?.batchDraw());});},[e,o]);let u=useSelector(i=>i.toolbar.selectedTool),f=u==="pen"||u==="eraser",{createHandlers:d}=Ve({onLongPress:l});return jsx(Fragment,{children:e.map(i=>{let m=i.id===c,h=i.fontWeight==="bold",p=h?Math.max(1,i.fontSize/25):0;return jsx(Text,{id:i.id,ref:x=>{x?o.current.set(i.id,x):o.current.delete(i.id);},text:i.text,x:i.x,y:i.y,width:i.width,height:i.height,rotation:i.rotation,draggable:!i.locked&&!m&&!f,listening:!f,fontSize:i.fontSize,fontFamily:i.fontFamily,fontStyle:i.fontStyle,fontWeight:i.fontWeight,textDecoration:i.textDecoration,fill:i.fill,stroke:h?i.fill:void 0,strokeWidth:p,align:i.align,wrap:"word",lineHeight:1.2,opacity:m?0:1,visible:!m,...f?{}:{onClick:()=>r(i.id),onTap:()=>r(i.id),onDblClick:()=>s(i.id),onDblTap:()=>s(i.id),onDragEnd:x=>t(x,i.id),onTransformEnd:()=>a(i.id),onContextMenu:x=>{x.evt.preventDefault();let v=x.evt;n(v,i.id,"text");},...d(i.id,"text")}},i.id)})})};var ug=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onNext:s,onPrevious:c,nodeRef:l,touchHandlers:u,currentTool:f})=>{let[d,i]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let g=new window.Image,y=e.images[e.currentIndex];(y.startsWith("http://")||y.startsWith("https://"))&&(g.crossOrigin="anonymous"),g.src=y,g.onload=()=>{i(g);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let m=8,h=2,p=Math.min(e.width,e.height)*.08,x=Math.max(16,Math.min(p,32)),v=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked&&f==="select",x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:r,...u,ref:g=>{if(l(g),g){let y=g.getStage()?.container();if(y){let S=C=>{let k=g.getStage()?.getPointerPosition();if(k){let T={x:e.x,y:e.y,width:e.width,height:e.height};k.x>=T.x&&k.x<=T.x+T.width&&k.y>=T.y&&k.y<=T.y+T.height&&n(C);}};y.addEventListener("contextmenu",S),g._contextMenuCleanup=()=>{y.removeEventListener("contextmenu",S);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:m,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:m,stroke:"#E5E7EB",strokeWidth:h,listening:false}),jsx(Image$1,{x:h+4,y:h+4,image:d,width:e.width-(h+4)*2,height:e.height-(h+4)*2,cornerRadius:m-h,onClick:t,onTap:t}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:v+x,y:e.height/2,onClick:g=>{g.cancelBubble=true,c();},onTap:g=>{g.cancelBubble=true,c();},children:[jsx(Circle,{radius:x,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-v-x,y:e.height/2,onClick:g=>{g.cancelBubble=true,s();},onTap:g=>{g.cancelBubble=true,s();},children:[jsx(Circle,{radius:x,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"})]})},Bu=ug;var el=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onNext:s,onPrevious:c,onContextMenu:l,onLongPress:u})=>{let{createHandlers:f}=Ve({onLongPress:u}),d=Q(i=>i.toolbar.selectedTool);return jsx(Fragment,{children:e.map(i=>jsx(Bu,{flashcard:i,isSelected:t===i.id,onClick:()=>n(i.id),currentTool:d,onDragEnd:a,onTransformEnd:m=>r(i.id,m),onContextMenu:m=>l(m,i.id,"flashcard"),onNext:()=>s(i.id),onPrevious:()=>c(i.id),touchHandlers:f(i.id,"flashcard"),nodeRef:m=>{m?o.current.set(i.id,m):o.current.delete(i.id);}},i.id))})});el.displayName="FlashcardLayer";var Nu=e=>{let o=Se(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null);Q(y=>y.toolbar.selectedTool);let l=Q(y=>y.toolbar.penColor),u=Q(y=>y.toolbar.strokeWidth),f=Q(y=>y.canvas.isSketchMode),d=Q(y=>y.canvas.slides.find(C=>C.id===y.canvas.currentSlideId)?.photoFrames.find(C=>C.id===e)),i=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,x=useCallback(y=>{if(!m)return;t.current=true,a.current=false,r.current=[{x:y.x,y:y.y}];let S=y.x/h,C=y.y/p;s({tool:"pen",points:[S,C],color:l,strokeWidth:u/h,isSketch:f});},[m,l,u,f,h,p]),v=useCallback(y=>{if(!t.current||!n)return;a.current=true;let S=r.current[r.current.length-1];if(Math.sqrt(Math.pow(y.x-S.x,2)+Math.pow(y.y-S.y,2))<2)return;r.current.push({x:y.x,y:y.y});let k;if(f)k=Jn(r.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((w,b)=>b%2===0?w/h:w/p);else {let T=y.x/h,w=y.y/p;k=[...n.points,T,w];}s(T=>T?{...T,points:k}:null);},[f,u,n,h,p]),g=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(wi({frameId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:i,activeLine:n,isDrawingMode:m,startDrawing:x,draw:v,stopDrawing:g}};var bg=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onStartCamera:s,onCapture:c,cameraStream:l,nodeRef:u,touchHandlers:f})=>{let[d,i]=useState(null),[m,h]=useState(null),p=useRef(null),x=useRef(null),v=useRef(null),g=useRef(null),y=useRef(0),S=33,C=useSelector(D=>D.toolbar.selectedTool),k=C==="pen"||C==="eraser",{annotations:T,activeLine:w,isDrawingMode:b,startDrawing:I,draw:P,stopDrawing:H}=Nu(e.id);useEffect(()=>{if(!b)return;let D=()=>{H();},q=()=>{H();};return window.addEventListener("mouseup",D),window.addEventListener("touchend",q),()=>{window.removeEventListener("mouseup",D),window.removeEventListener("touchend",q);}},[H,b]),useEffect(()=>{if(e.capturedImageUrl){let D=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(D.crossOrigin="anonymous"),D.src=e.capturedImageUrl,D.onload=()=>{i(D);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&l){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),x.current||(x.current=document.createElement("canvas"));let D=p.current,q=x.current;D.srcObject=l;let j=()=>{q.width=D.videoWidth||640,q.height=D.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",q.width,q.height);let J=re=>{if(re-y.current<S){v.current=requestAnimationFrame(J);return}y.current=re;let $=q.getContext("2d");if($&&D.readyState===D.HAVE_ENOUGH_DATA){$.drawImage(D,0,0,q.width,q.height);let ie=q.toDataURL("image/jpeg",.6),he=new window.Image;he.onload=()=>{h(he);},he.src=ie;}v.current=requestAnimationFrame(J);};v.current=requestAnimationFrame(J);};return D.onloadedmetadata=j,D.readyState>=D.HAVE_METADATA&&j(),D.play().catch(J=>console.error("Error playing video:",J)),()=>{v.current&&(cancelAnimationFrame(v.current),v.current=null);}}return ()=>{h(null),g.current&&(g.current.src="");}},[e.isCapturing,l]);let O=()=>{p.current&&e.isCapturing&&c(p.current);},B=D=>{if(e.capturedImageUrl){if(!b){t();return}let q=D.currentTarget,j=q.getAbsoluteTransform().copy(),re=q.getStage()?.getPointerPosition();if(re){j.invert();let $=j.point(re);I($);}D.cancelBubble=true;}else t();},V=D=>{if(!b||!e.capturedImageUrl)return;let q=D.currentTarget,j=q.getAbsoluteTransform().copy(),re=q.getStage()?.getPointerPosition();if(re){j.invert();let $=j.point(re);P($);}},U=()=>{!b||!e.capturedImageUrl||H();},K=e.isCapturing?m:d,F=Math.min(e.width,e.height)*.12,W=Math.max(25,Math.min(F,50)),te=e.width/2,X=e.height/2;return jsxs(Group,{id:e.id,draggable:!b&&!k,listening:true,onClick:t,onTap:t,x:e.x,y:e.y,...f,...k?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:D=>{if(u(D),D){let q=D.getStage()?.container();if(q){let j=J=>{let re=D.getStage()?.getPointerPosition();if(re){let $={x:e.x,y:e.y,width:e.width,height:e.height};re.x>=$.x&&re.x<=$.x+$.width&&re.y>=$.y&&re.y<=$.y+$.height&&n(J);}};q.addEventListener("contextmenu",j),D._contextMenuCleanup=()=>{q.removeEventListener("contextmenu",j);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:K?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),K&&jsx(Image$1,{image:K,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:B,onTap:B,onMouseDown:B,onTouchStart:B,onMouseMove:V,onTouchMove:V,onMouseUp:U,onTouchEnd:U,...k?{}:{onDragEnd:a,onTransformEnd:r}}),T?.map((D,q)=>{let j=D.points.map((re,$)=>$%2===0?re*e.width:re*e.height),J=D.strokeWidth*e.width;return jsx(Line,{points:j,stroke:D.tool==="eraser"?"white":D.color,strokeWidth:J,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:D.tool==="eraser"?"destination-out":"source-over",fill:D.isSketch?D.color:void 0,closed:D.isSketch,listening:false},q)}),w&&jsx(Line,{points:w.points.map((D,q)=>q%2===0?D*e.width:D*e.height),stroke:w.tool==="eraser"?"white":w.color,strokeWidth:w.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:w.tool==="eraser"?"destination-out":"source-over",fill:w.isSketch?w.color:void 0,closed:w.isSketch,listening:false},"active"),!K&&!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:X-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:te-W+6,y:X-60,width:W*1.6,height:W*1.6,radius:W,fill:"white",cornerRadius:8,listening:true,onClick:D=>{D.cancelBubble=true,e.isCapturing?O():s();},onTap:D=>{D.cancelBubble=true,e.isCapturing?O():s();}}),jsx(Html,{groupProps:{x:te-12,y:X-40,width:W*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:D=>{D.stopPropagation(),e.isCapturing?O():s();}})})]}),jsx(Text,{x:0,y:X,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:X+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:te-24,y:X+104,width:W*1.6,height:W*1.6,radius:W,fill:"#096B76",cornerRadius:W,listening:true,onClick:D=>{D.cancelBubble=true,e.isCapturing?O():s();},onTap:D=>{D.cancelBubble=true,e.isCapturing?O():s();}}),jsx(Html,{groupProps:{x:te-8,y:X+120,width:W*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:D=>{D.stopPropagation(),e.isCapturing?O():s();}})})]}),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:te-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:D=>{D.stopPropagation(),O();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},zu=bg;var sl=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onStartCamera:s,onCapture:c,cameraStreams:l,onContextMenu:u,onLongPress:f})=>{let{createHandlers:d}=Ve({onLongPress:f});return jsx(Fragment,{children:e.map(i=>jsx(zu,{photoFrame:i,isSelected:t===i.id,onClick:()=>n(i.id),onDragEnd:m=>a(m,i.id),onContextMenu:m=>u(m,i.id,"photoFrame"),onStartCamera:()=>s(i.id),onCapture:m=>c(i.id,m),cameraStream:l.get(i.id),touchHandlers:d(i.id,"photoFrame"),nodeRef:m=>{m?o.current.set(i.id,m):o.current.delete(i.id);}},i.id))})});sl.displayName="PhotoFrameLayer";var Gu=({x:e,y:o,onAction:t,onClose:a,type:r,isDrawingMode:n,menuRef:s})=>{useEffect(()=>{let f=i=>{s?.current&&!s.current.contains(i.target)&&a();},d=i=>{i.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",d);}},[a]);let c=useMemo(()=>[{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"border",label:"Toggle Border",icon:jsx(FrameCorners,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{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"}),hideForTypes:["line","video"]},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(d=>!(d.showForTypes&&!d.showForTypes.includes(r)||d.hideForTypes&&d.hideForTypes.includes(r))),[r,n]),l=(f,d)=>{f==="order"||f==="lock"?t(f,d):(t(f),a());},u=jsx("div",{ref:s,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:c.map((f,d)=>jsxs("button",{onClick:i=>l(f.action,i),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${f.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[f.icon,jsx("span",{className:`font-medium ${f.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:f.label})]}),f.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},d))})});return createPortal(u,document.body)};var ju=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let n=s=>{r.current&&!r.current.contains(s.target)&&a();};return document.addEventListener("mousedown",n),()=>{document.removeEventListener("mousedown",n);}},[a]),jsx("div",{ref:r,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((n,s)=>jsx("button",{onClick:()=>{n.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:n.label})},s))})})};var $u=createContext(null),il=()=>useContext($u);function qg({children:e,className:o="",style:t}){let a=useRef(null),[r,n]=useState(null);return useEffect(()=>{a.current&&n(a.current);},[]),jsx($u.Provider,{value:r,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function ze(){let e=il();return typeof document>"u"?null:e||document.body}var Xu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:n})=>{let[s,c]=useState(a),l=useRef(null),u=ze();useEffect(()=>{l.current?.focus();},[]);let f=()=>{r(s),n();},d=m=>{m.key==="Enter"?f():m.key==="Escape"&&n();};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:n,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{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:s,onChange:m=>c(m.target.value),onKeyDown:d,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:n,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:f,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),u):null};var os=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),n=useRef(null),s=ze();useEffect(()=>{let d=i=>{i.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let c=d=>{d.preventDefault(),o(a);},l=(d,i,m)=>{m/=100;let h=i*Math.min(m,1-m)/100,p=x=>{let v=(x+d/30)%12,g=m-h*Math.max(Math.min(v-3,9-v,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},u=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!s)return null;let f=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:n,className:"max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-lg border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:c,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:d=>r(d.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:d=>r(d.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:d=>{let i=parseInt(d.target.value),m=l(i,100,50);r(m);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:u.map(d=>jsx("button",{type:"button",onClick:()=>r(d),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===d.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:d},title:d},d))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(f,s)};var rx=({imageSrc:e,onCrop:o})=>{let[t]=Ju(e),a=useRef(null),r=useRef(null),n=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),c=useMemo(()=>{let i=s.width*.5,m=s.height*.5,h=(s.width-i)/2,p=(s.height-m)/2;return {x:h,y:p,width:i,height:m}},[s]),[l,u]=useState(c);useEffect(()=>{u(c);},[c]),useEffect(()=>{n.current&&r.current&&(n.current.nodes([r.current]),n.current.getLayer()?.batchDraw());},[l]),useEffect(()=>{o(l.x,l.y,l.width,l.height);},[l,o]);let f=()=>{let i=r.current;if(!i)return;let m=i.scaleX(),h=i.scaleY();i.scaleX(1),i.scaleY(1),u({x:i.x(),y:i.y(),width:Math.max(20,i.width()*m),height:Math.max(20,i.height()*h)});},d=()=>{let i=r.current;i&&u({x:i.x(),y:i.y(),width:i.width(),height:i.height()});};return jsx(Stage,{width:s.width,height:s.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:s.width,height:s.height}),jsx(Rect,{x:0,y:0,width:s.width,height:s.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:d,onTransformEnd:f,dragBoundFunc:i=>{let m=Math.max(0,Math.min(i.x,s.width-l.width)),h=Math.max(0,Math.min(i.y,s.height-l.height));return {x:m,y:h}}}),jsx(Transformer,{ref:n,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(i,m)=>m.width<20||m.height<20||m.x<0||m.y<0||m.x+m.width>s.width||m.y+m.height>s.height?i:m})]})})},Qu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,n]=useState({x:0,y:0,width:0,height:0}),[s]=Ju(e),c=ze();useEffect(()=>{let d=i=>{i.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let l=(d,i,m,h)=>{n({x:d,y:i,width:m,height:h});},u=()=>{if(!s)return;let m=Math.min(600/s.width,400/s.height),h=r.x/m,p=r.y/m,x=r.width/m,v=r.height/m,g=document.createElement("canvas");g.width=x,g.height=v;let y=g.getContext("2d");if(!y)return;y.drawImage(s,h,p,x,v,0,0,x,v);let S=g.toDataURL("image/png");o(S);};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-lg border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{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(rx,{imageSrc:e,onCrop:l})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:u,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),c):null};var to=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let r=ze(),[n,s]=useState(false),[c,l]=useState(null),[u,f]=useState(0),[d,i]=useState(true),m=useRef(null),h=useRef([]),p=useRef(null),x=useRef(null),v=useRef(null),g=useRef(null),y=useRef(null),S=useRef(null);useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current),p.current&&clearInterval(p.current),x.current&&x.current.getTracks().forEach(I=>I.stop());},[]);let C=async()=>{try{let I,P=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let U=o.current.getLayers();console.log("Konva layers:",U.length),U.forEach((j,J)=>{let re=j.getChildren();console.log(`Layer ${J} children count:`,re.length);});let K=document.createElement("canvas");K.width=o.current.width(),K.height=o.current.height();let F=K.getContext("2d",{willReadFrequently:!1});if(!F){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",K.width,"x",K.height),y.current=K;let W=()=>{if(F.clearRect(0,0,K.width,K.height),U.forEach(j=>{let J=j.getCanvas()._canvas;J&&F.drawImage(J,0,0);}),a?.current){let j=a.current;F.drawImage(j,0,0);}};S.current=W,o.current.draw(),W(),await new Promise(j=>setTimeout(j,100)),console.log("Creating captureStream..."),I=K.captureStream(30),console.log("Canvas stream created, tracks:",I.getTracks().length);let X=I.getVideoTracks()[0];X&&console.log("Video track:",X.label,"state:",X.readyState);let D=0,q=()=>{W(),o?.current&&(o.current.getLayers().forEach(J=>{J.batchDraw();}),D++,D%60===0&&console.log("Drawing frame:",D)),v.current=requestAnimationFrame(q);};q();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{P=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let H=[...I.getVideoTracks()];P&&H.push(...P.getAudioTracks());let O=new MediaStream(H);x.current=O;let B="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?B="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?B="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?B="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(B="video/webm;codecs=vp8"),console.log("Using mimeType:",B);let V=new MediaRecorder(O,{mimeType:B,videoBitsPerSecond:25e5});m.current=V,h.current=[],V.ondataavailable=U=>{console.log("Data available, size:",U.data.size),U.data.size>0&&h.current.push(U.data);},V.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let U=new Blob(h.current,{type:B});console.log("Final blob size:",U.size),o?.current&&S.current&&y.current&&(o.current.draw(),o.current.getLayers().forEach(F=>{F.batchDraw();}),S.current(),g.current=y.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",g.current.length)),O.getTracks().forEach(K=>K.stop()),p.current&&clearInterval(p.current),v.current&&(cancelAnimationFrame(v.current),v.current=null),l(U);},V.onerror=U=>{console.error("MediaRecorder error:",U);},console.log("Starting recording..."),V.start(1e3),s(!0),f(0),p.current=setInterval(()=>{f(U=>U+1);},1e3);}catch(I){console.error("Error starting screen recording:",I),alert("Failed to start recording. Please ensure you granted permission.");}},k=()=>{m.current&&n&&(console.log("Stopping recording, state:",m.current.state),m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),s(false));},T=()=>{if(c){let I=URL.createObjectURL(c),P=document.createElement("a");P.href=I,P.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(I);}},w=I=>{let P=Math.floor(I/60),H=I%60;return `${P.toString().padStart(2,"0")}:${H.toString().padStart(2,"0")}`};if(!r)return null;if(n){let I=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:w(u)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:k,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(I,r)}let b=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!c&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>i(!d),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${d?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:d?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:C,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),c&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(c),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",w(u)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&c&&g.current&&(t(c,g.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:T,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{l(null),f(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})});return createPortal(b,r)};var oc=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let n=ze(),[s,c]=useState(false),[l,u]=useState(null),[f,d]=useState(false),[i,m]=useState(0),h=useRef(null),p=useRef([]),x=useRef(null),v=useRef(null);useEffect(()=>{o&&!l&&fetch(o).then(I=>I.blob()).then(I=>u(I)).catch(I=>console.error("Error loading audio:",I));},[o,l]);let g=async()=>{try{let I=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),P=new MediaRecorder(I);h.current=P,p.current=[],P.ondataavailable=H=>{H.data.size>0&&p.current.push(H.data);},P.onstop=()=>{let H=new Blob(p.current,{type:"audio/webm"});u(H),I.getTracks().forEach(O=>O.stop()),x.current&&clearInterval(x.current);},P.start(),c(!0),m(0),x.current=setInterval(()=>{m(H=>H+1);},1e3);}catch(I){console.error("Error starting audio recording:",I),alert("Failed to start recording. Please allow microphone access.");}},y=()=>{h.current&&s&&(h.current.stop(),c(false));},S=()=>{if(l){let I=URL.createObjectURL(l),P=new Audio(I);v.current=P,P.onended=()=>{d(false),URL.revokeObjectURL(I);},P.play(),d(true);}},C=()=>{v.current&&(v.current.pause(),v.current.currentTime=0,d(false));},k=async()=>{if(l){let I=new FileReader;I.onloadend=()=>{let P=I.result;t(P),r();},I.readAsDataURL(l);}},T=()=>{u(null),a();},w=I=>{let P=Math.floor(I/60),H=I%60;return `${P.toString().padStart(2,"0")}:${H.toString().padStart(2,"0")}`};if(!n)return null;if(s){let I=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:w(i)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:y,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(I,n)}let b=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!l&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:g,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),l&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:f?C:S,className:"flex w-full cursor-pointer 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"}),f?"Playing...":"Play Audio"]}),jsxs("button",{onClick:T,className:"flex w-full cursor-pointer items-center gap-2 rounded-lg border border-red-300 bg-red-600 px-4 py-3 text-white transition-colors hover:bg-red-700",children:[jsx(Trash,{className:"h-5 w-5",weight:"fill"}),"Delete Audio"]})]}),jsx("button",{onClick:k,className:"w-full cursor-pointer rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:r,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})});return createPortal(b,n)};var qt=({audioData:e,x:o,y:t,width:a,scale:r=1,offsetX:n=0,offsetY:s=0,containerTop:c=90,containerRight:l=320})=>{let[u,f]=useState(false),d=useRef(null),i=p=>{if(p.stopPropagation(),u&&d.current)d.current.pause(),d.current.currentTime=0,f(false);else {let x=new Audio(e);d.current=x,x.onended=()=>{f(false);},x.onerror=()=>{console.error("Error playing audio"),f(false);},x.play(),f(true);}},m=(o+a)*r+n-15,h=t*r+s+c-15;return jsx("button",{onClick:i,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${u?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${m}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:u?"Stop Audio":"Play Audio",children:u?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var rc=({link:e,x:o,y:t,width:a,height:r,scale:n=1,offsetX:s=0,offsetY:c=0,containerTop:l=90})=>{let u=(o+a/2)*n+s,f=(t+r/2)*n+c+l;return jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",onClick:d=>d.stopPropagation(),className:"fixed flex items-center gap-1.5 rounded-full bg-black/60 px-3 py-1.5 text-xs font-medium text-white backdrop-blur-sm transition-colors hover:bg-black/80",style:{left:`${u}px`,top:`${f}px`,transform:"translate(-50%, -50%)",zIndex:99},children:[jsx(ArrowSquareOut,{className:"size-3.5",weight:"bold"}),"Visit Website"]})};var ic=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=Se(),r=Q(ve),n=ze(),s=useMemo(()=>{if(!r)return [];let v=[];return r.images?.forEach(g=>{v.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),r.videos?.forEach(g=>{v.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),r.shapes?.forEach(g=>{v.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),r.texts?.forEach(g=>{v.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),r.flashcards?.forEach(g=>{v.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),r.photoFrames?.forEach(g=>{v.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),r.multipleChoices?.forEach(g=>{v.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),r.trueFalses?.forEach(g=>{v.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),r.shortAnswers?.forEach(g=>{v.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),r.LongAnswer?.forEach(g=>{v.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),r.fillInTheBlanks?.forEach(g=>{v.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),r.lines?.forEach(g=>{g.id&&v.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),v.sort((g,y)=>y.timestamp-g.timestamp)},[r]),[c,l]=useState(s),[u,f]=useState(false);useEffect(()=>{u||l(s);},[s]);let d=v=>{let g="h-5 w-5";switch(v){case "image":return jsx(Image$3,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes$1,{className:g});case "text":return jsx(TextT,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners$1,{className:g});case "line":return jsx(Pen,{className:g});default:return jsx(Question,{className:g})}},h=v=>{f(true),l(v);},p=()=>{f(false);let v=Date.now();c.forEach((g,y)=>{let S=v-y;a(br({id:g.id,type:g.type,newTimestamp:S}));});};if(!n)return null;let x=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-50 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-50 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:c.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:c,onReorder:h,className:"space-y-1",children:c.map(v=>{let g=v.id===e;return jsxs(Reorder.Item,{value:v,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${g?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(v.id,v.type),className:`font-medium ${g?"text-[#096B76]":"text-[#00000099]"}`,children:v.name})}),jsx("div",{className:`${g?"text-[#096B76]":"text-[#00000099]"}`,children:d(v.type)})]},v.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[c.length," Layers"]})]})]})]});return createPortal(x,n)};var ds=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o*1.2;n.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),c=[],l="";return s.forEach(u=>{let f=l?`${l} ${u}`:u;n.measureText(f).width>t&&l!==""?(c.push(l),l=u):l=f;}),l&&c.push(l),c.length*o*1.2},lc=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n,touchHandlers:s,onUpdate:c})=>{let l=useSelector(B=>B.toolbar.selectedTool),u=l==="pen"||l==="eraser",[f,d]=useState(null),i=e.data.responseOptions.attempts||0,m=useRef(null),h=useDispatch(),[p,x]=useState(new Set(e.data.responseOptions.selectedIndices||[])),[v,g]=useState(false);useEffect(()=>{let B=m.current;if(B)return a.current.set(e.id,B),()=>{a.current.delete(e.id);}},[e.id,a]);let y=new Set(e.data.responseOptions.correctIndex),S=y.size>1,C=B=>{if(v)return;let V;S?(V=new Set(p),V.has(B)?V.delete(B):V.add(B)):V=new Set([B]),x(V);let U=Array.from(V),K=U.length===e.data.responseOptions.correctIndex.length&&U.every(F=>e.data.responseOptions.correctIndex.includes(F));h(ht({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:U,isCorrect:K}}})),c?.();},k=()=>{p.size>0&&(g(true),h(ht({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},T=()=>{g(false),x(new Set);},w=p.size===y.size&&Array.from(p).every(B=>y.has(B)),b=Array.from(p).filter(B=>y.has(B)),I=S&&b.length>0&&!w,P=()=>w?"\u2713 Correct! Great job! \u{1F389}":I?`\u26A0 Partially correct (${b.length}/${y.size})`:"\u2717 Try again!",H=()=>w?{bg:"#dcfce7",text:"#166534"}:I?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},O=useMemo(()=>{let X=e.data.feedbackMode==="practice"?48:0,D=12,q=e.width-48,j=q-80,J=Math.max(60,ds(e.data.question,20,q,"bold")+20),re=`Select ${y.size} answers (${p.size}/${y.size} selected)`,$=S&&!v&&e.data.feedbackMode==="practice"?ds(re,14,q)+10:0,ie=v&&e.data.feedbackMode==="practice"?Math.max(60,ds(P(),16,q-40)+30):0,he=e.data.responseOptions.options.map(we=>{let yt=ds(we,16,j);return Math.max(55,yt+20)}),fe=J+$+ie,xe=he.reduce((we,yt)=>we+yt+8,-8),ye=fe+xe+D+X+24;return {padding:24,questionHeight:J,instructionHeight:$,feedbackHeight:ie,optionsStartY:fe,optionHeights:he,totalHeight:ye,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:X,buttonTopMargin:D,availableWidth:q,optionTextWidth:j}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,v,p.size,y.size,S,P]);return jsxs(Group,{ref:m,name:"mcq-element",draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:O.totalHeight,onTransformEnd:B=>o(e.id,B),...s,...u?{}:{onDragEnd:r,onClick:B=>t&&t(e.id),onTap:B=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:O.totalHeight,width:e.width,onContextMenu:B=>{B.cancelBubble=true,n(B.evt,e.id,"mcq");}}),jsx(Text,{x:O.padding+8,y:O.padding,text:e.data.question,fontSize:O.questionFontSize,fontStyle:"bold",fill:"#111827",width:O.availableWidth,height:O.questionHeight-O.padding,wrap:"word",ellipsis:true,listening:false}),O.instructionHeight>0&&jsx(Text,{x:O.padding,y:O.questionHeight,text:`Select ${y.size} answers (${p.size}/${y.size} selected)`,fontSize:O.instructionFontSize,fill:"#6b7280",width:O.availableWidth,wrap:"word",listening:false}),v&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:O.padding+24,y:O.questionHeight+O.instructionHeight+10,width:O.availableWidth-40,height:O.feedbackHeight-20,fill:H().bg,cornerRadius:8}),jsx(Text,{x:O.padding+24,y:O.questionHeight+O.instructionHeight+10,width:O.availableWidth-40,height:O.feedbackHeight-20,text:P()+` (${i} attempts)`,fontSize:O.feedbackFontSize,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((B,V)=>{let U=y.has(V),K=p.has(V),F=O.optionsStartY;for(let q=0;q<V;q++)F+=O.optionHeights[q]+O.optionGap;let W=O.optionHeights[V],te="#e5e7eb",X="#ffffff",D="#111827";return v&&K&&!U?(te="#ef4444",X="#fee2e2",D="#ef4444"):K&&(te="#096B76",X="#ECFFF8",D="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:O.padding+12,y:F+(W-20)/2,width:20,height:20,fill:K?"#096B76":"white",stroke:K?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:S?4:10,onClick:q=>{q.cancelBubble=true,C(V);},onTap:q=>{q.cancelBubble=true,C(V);}}),K&&jsx(Text,{x:O.padding+12,y:F+(W-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:O.padding+44,y:F,width:O.availableWidth-60,height:W,fill:X,stroke:te,strokeWidth:2,cornerRadius:8,onClick:q=>{q.cancelBubble=true,C(V);},onTap:q=>{q.cancelBubble=true,C(V);}}),jsx(Text,{x:O.padding+60,y:F+10,width:O.optionTextWidth,height:W-20,text:B,fontSize:O.optionFontSize,fill:D,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},V)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:O.optionsStartY+O.optionHeights.reduce((B,V)=>B+V+O.optionGap,-O.optionGap)+O.buttonTopMargin,children:[jsxs(Group,{onMouseDown:B=>{B.cancelBubble=true,d("check");},onMouseUp:B=>{B.cancelBubble=true,d(null),k();},onMouseLeave:B=>{B.cancelBubble=true,d(null);},onTouchStart:B=>{B.cancelBubble=true,d("check");},onTouchEnd:B=>{B.cancelBubble=true,d(null),k();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:O.padding+14,width:(O.availableWidth-24)/(v?2:1),height:O.buttonHeight,fill:p.size===0||v?"#9ca3af":"#096B76",cornerRadius:8,onClick:B=>B.cancelBubble=true,onTap:B=>B.cancelBubble=true}),jsx(Text,{x:O.padding+14,width:(O.availableWidth-24)/(v?2:1),height:O.buttonHeight,text:v?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),v&&jsxs(Group,{x:(e.width-O.padding*2)/2+8,onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),T();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),T();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:O.padding,width:(O.availableWidth-8)/2,height:O.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:B=>B.cancelBubble=true,onTap:B=>B.cancelBubble=true}),jsx(Text,{x:O.padding,width:(O.availableWidth-8)/2,height:O.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});lc.displayName="MultipleChoice";var dc=lc;var Jx=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a} ${o}px Arial, sans-serif`;let s=e.split(" "),c=[],l="";return s.forEach(u=>{let f=l?`${l} ${u}`:u;n.measureText(f).width>t&&l!==""?(c.push(l),l=u):l=f;}),l&&c.push(l),c.length*o*1.2},fl=({multipleChoice:e,onContextMenu:o,handleSelect:t,mcqRefs:a,touchHandlers:r,onUpdate:n})=>{let s=useDispatch(),c=useSelector(F=>F.toolbar.selectedTool),l=c==="pen"||c==="eraser",[u,f]=useState(false),d=e.data.responseOptions.selectedIndices??[],i=useMemo(()=>new Set(d),[d]),m=e.data.responseOptions.attempts??0,h=m>0,[p,x]=useState(false),[v,g]=useState(0),y=new Set(e.data.responseOptions.correctIndex),S=Array.from(i).filter(F=>y.has(F)),C=i.size===y.size&&Array.from(i).every(F=>y.has(F)),k=S.length>0&&!C,T=()=>C?"\u2713 Correct! Great job!":k?`\u26A0 Partially correct (${S.length}/${y.size})`:"\u2717 Try again!",w=useCallback(F=>{let W=F.target;s(Li({id:e.id,dragDropPos:{x:W.x(),y:W.y()}})),n?.();},[s,e.id,n]),b=useMemo(()=>{let W=Math.max(window.innerWidth*.3,500),te=20,X=18,D=28,q=40,j=50,J=20,re=60,$=Math.max(W-40,400),ie=Math.max(60,Jx(e.data.question,te,$,"bold")),he=Math.max(W-J*2,400),fe=Math.max(150,window.innerHeight*.2),xe=e.data.feedbackMode==="practice",ye=ie+20+fe+(h?re+18:0)+(xe?q+(h?j:0)+20:0),we=ye+100;return {screenWidth:W,screenHeight:we,dropZoneWidth:he,dropZoneHeight:fe,questionFontSize:te,questionHeight:ie,feedbackFontSize:X,feedbackHeight:re,dropHereFontSize:D,buttonHeight:q,buttonGap:j,padding:J,contentWidth:$,totalContentHeight:ye,isPracticeMode:xe}},[e.data.question,e.data.feedbackMode,h]),I=useRef(null);useEffect(()=>{let F=I.current;if(F)return a.current.set(e.id,F),()=>{a.current.delete(e.id);}},[e.id,a]);let P=F=>{s(Li({id:e.id,dragDropPos:{x:F.target.x(),y:F.target.y()}})),n?.();},H=F=>{let W=F.target,te=W.x(),X=W.y(),D=window.innerWidth*.2,q=50,j=b.padding,J=b.padding+b.dropZoneWidth,re=b.questionHeight+20,$=b.questionHeight+20+b.dropZoneHeight,ie=te+D>j&&te<J&&X+q>re&&X<$;f(ie),n?.();},O=(F,W)=>{let te=W.target,X=te.x(),D=te.y(),q=window.innerWidth*.2,j=50;s(ht({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[F]:{x:X,y:D}}}));let J=b.padding,re=b.padding+b.dropZoneWidth,$=b.questionHeight+20,ie=b.questionHeight+20+b.dropZoneHeight,he=X+q>J&&X<re&&D+j>$&&D<ie,fe;he?fe=new Set(i).add(F):(fe=new Set(i),fe.delete(F)),f(false);let xe=Array.from(fe),ye=xe.length===y.size&&xe.every(we=>y.has(we));s(ht({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:xe,isCorrect:ye}}})),n?.();},B=()=>{s(ht({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},V=()=>{s(ht({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),f(false),g(F=>F+1),n?.();},U=()=>C?{bg:"#dcfce7",text:"#166534"}:k?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},K=()=>h?C?"#4CAF50":k?"#f59e0b":"#ef4444":u?"#4CAF50":"#075560";return jsxs(Group,{ref:I,x:e.dragDropPos?.x,y:e.dragDropPos?.y,name:"mcq-element",width:b.screenWidth,height:b.screenHeight,draggable:!l,listening:!l,onDragMove:w,...r,...l?{}:{onClick:F=>t&&t(e.id),onTap:F=>t&&t(e.id),onContextMenu:F=>{F.evt.preventDefault(),o(F.evt,e.id,"mcq");}},children:[jsxs(Group,{rotation:e.rotation,onDragEnd:P,children:[jsx(Rect,{fill:"white",stroke:u?"#4CAF50":"#e5e7eb",strokeWidth:u?4:2,cornerRadius:12,height:b.totalContentHeight+20,width:b.screenWidth,shadowColor:u?"#4CAF50":"transparent",shadowBlur:u?20:0,shadowOpacity:.5}),jsx(Text,{x:b.padding,y:b.padding,width:b.contentWidth,height:b.questionHeight-b.padding,text:e.data.question,fontSize:b.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:b.padding,y:b.questionHeight+20,width:b.dropZoneWidth,height:b.dropZoneHeight,fill:"#EBF6F7",stroke:K(),strokeWidth:3,dash:[10,10],cornerRadius:8}),h&&jsxs(Fragment,{children:[jsx(Rect,{x:b.padding+3,y:b.questionHeight+20+b.dropZoneHeight+18,width:b.dropZoneWidth-5,height:b.feedbackHeight,fill:U().bg,cornerRadius:8}),jsx(Text,{x:b.padding,y:b.questionHeight+20+b.dropZoneHeight+20,width:b.dropZoneWidth,height:b.feedbackHeight,text:T()+` (${m} attempts)`,fontSize:b.feedbackFontSize,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),i.size===0&&!h&&jsx(Text,{x:b.padding,y:b.questionHeight+20,width:b.dropZoneWidth,height:b.dropZoneHeight,text:y.size>1?`Drop ${y.size} Correct Answers Here`:"Drop Here",fontSize:b.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),b.isPracticeMode?jsxs(Group,{x:b.padding,y:b.questionHeight+20+b.dropZoneHeight+(h?b.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:F=>{F.cancelBubble=true,!(h||i.size===0)&&(x(true),B());},onMouseUp:()=>x(false),onMouseLeave:()=>x(false),onTouchStart:()=>{x(true),B();},onTouchEnd:()=>x(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:h||i.size===0?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:b.buttonHeight,width:b.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:h||i.size===0?"#9ca3af":"white",width:b.dropZoneWidth,height:b.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),h&&jsxs(Group,{y:b.buttonGap,onMouseDown:V,onTouchStart:V,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:b.buttonHeight,width:b.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:b.dropZoneWidth,height:b.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((F,W)=>{let te=W%2,X=Math.floor(W/2),D=b.dropZoneWidth/2+25,q=50,j=10,J=i.has(W),re=y.has(W),$=h&&J,ie="transparent";$?ie=re?"#4CAF50":"#ef4444":J&&(ie="#4CAF50");let he=h&&!J?0:1,fe=e.optionDragDropPos?.[W],xe=fe?.x??te*(D+j),ye=fe?.y??b.totalContentHeight+30+X*(q+j);return jsxs(Group,{x:xe,y:ye,draggable:!h,onDragStart:we=>{we.cancelBubble=true;},onDragMove:we=>{we.cancelBubble=true,H(we);},onDragEnd:we=>{we.cancelBubble=true,O(W,we);},opacity:he,children:[jsx(Rect,{width:D-20,height:q,fill:"white",stroke:ie,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:D-20,height:q,text:F,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${W}-${v}`)})]})};fl.displayName="MultipleChoiceDragAndDrop";var cc=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n,onLongPress:s,onUpdate:c})=>{let{createHandlers:l}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(u=>u.data.responseType==="classic"?jsx(dc,{multipleChoice:u,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:f=>r(f,u.id),onContextMenu:n,touchHandlers:l(u.id,"mcq"),onUpdate:c},u.id):jsx(fl,{multipleChoice:u,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:n,touchHandlers:l(u.id,"mcq"),onUpdate:c},u.id))})};var fc=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o*1.2;n.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),c=[],l="";return s.forEach(u=>{let f=l?`${l} ${u}`:u;n.measureText(f).width>t&&l!==""?(c.push(l),l=u):l=f;}),l&&c.push(l),c.length*o*1.2},mc=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:s,onUpdate:c})=>{let l=useSelector(P=>P.toolbar.selectedTool),u=l==="pen"||l==="eraser",[f,d]=useState(false),i=e.data.responseOptions.attempts||0,[m,h]=useState(null),p=useDispatch(),[x,v]=useState(e.data.responseOptions.selectedResponse??null),g=useRef(null);useEffect(()=>{let P=g.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id]);let y=()=>{x!==null&&d(true),p(tt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},S=()=>{d(false),v(null);},C=e.data.responseOptions.correctAnswer,k=x===C,T=P=>{if(f)return;v(P);let H=P===e.data.responseOptions.correctAnswer;p(tt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:P,isCorrect:H}}})),c?.();},w=()=>k?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",b=()=>k?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},I=useMemo(()=>{let K=e.data.feedbackMode==="practice"?48:0,F=12,W=e.width-48,te=Math.max(60,fc(e.data.question,20,W,"bold")+20),X=f&&e.data.feedbackMode==="practice"?Math.max(60,fc(w(),16,W-40)+30):0,D=te+X,q=164,j=D+q+F+K+24;return {padding:24,questionHeight:te,feedbackHeight:X,optionsStartY:D,optionsHeight:q,totalHeight:j,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:K,buttonTopMargin:F,availableWidth:W}},[e.width,e.data.question,e.data.feedbackMode,f,w]);return jsxs(Group,{ref:g,name:"trueFalse-element",draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:I.totalHeight,...s,...u?{}:{onDragEnd:P=>n(P,e.id),onClick:P=>t&&t(e.id),onTap:P=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:I.totalHeight,width:e.width,onTransformEnd:P=>o(e.id,P),onContextMenu:P=>{P.cancelBubble=true,r(P.evt,e.id,"trueFalse");}}),jsx(Text,{x:I.padding+8,y:I.padding,text:e.data.question,fontSize:I.questionFontSize,fontStyle:"bold",fill:"#111827",width:I.availableWidth,height:I.questionHeight-I.padding,wrap:"word",ellipsis:true,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:I.padding+24,y:I.questionHeight+10,width:I.availableWidth-40,height:I.feedbackHeight-20,fill:b().bg,cornerRadius:8}),jsx(Text,{x:I.padding+24,y:I.questionHeight+10,width:I.availableWidth-40,height:I.feedbackHeight-20,text:w()+` (${i} attempts)`,fontSize:I.feedbackFontSize,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((P,H)=>{let O=C===P.value,B=x===P.value,V=(e.width-I.padding*3)/2,U=I.padding+H*(V+I.padding),K=I.optionsStartY,F=P.value===true,W=F?"#10b981":"#ef4444",te="#ffffff",X="#ffffff",D="#e5e7eb";return f&&B&&(O?(X=F?"#f0fdf4":"#fef2f2",D=F?"#86efac":"#fecaca"):(X="#fee2e2",D="#ef4444")),B&&!f&&(D="#096B76",X="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:U,y:K,width:V,height:I.optionHeight+50,fill:X,stroke:D,strokeWidth:2,cornerRadius:12,onClick:q=>{q.cancelBubble=true,T(P.value);},onTap:q=>{q.cancelBubble=true,T(P.value);}}),jsx(Circle,{x:U+V/2,y:K+40,radius:28,fill:W,listening:false}),F?jsx(Text,{x:U+V/2-14,y:K+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:U+V/2-14,y:K+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:U,y:K+85,width:V,height:30,text:P.label,fontSize:I.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},P.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:I.optionsStartY+2*(I.optionHeight+I.optionGap)+I.buttonTopMargin,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,h("check");},onMouseUp:P=>{P.cancelBubble=true,h(null),y();},onMouseLeave:P=>{P.cancelBubble=true,h(null);},onTouchStart:P=>{P.cancelBubble=true,h("check");},onTouchEnd:P=>{P.cancelBubble=true,h(null),y();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:I.padding+14,width:(I.availableWidth-24)/(f?2:1),height:I.buttonHeight,fill:x===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:I.padding+14,width:(I.availableWidth-24)/(f?2:1),height:I.buttonHeight,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-I.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),S();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),S();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:I.padding,width:(I.availableWidth-8)/2,height:I.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:I.padding,width:(I.availableWidth-8)/2,height:I.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});mc.displayName="TrueFalse";var pc=mc;var pb="#FFFFFF",gl=({trueFalse:e,onContextMenu:o,handleSelect:t,trueFalseRefs:a,touchHandlers:r,onUpdate:n})=>{let s=useDispatch(),c=useSelector(D=>D.toolbar.selectedTool),l=c==="pen"||c==="eraser",[u,f]=useState(false),d=e.data.responseOptions.selectedResponse??null,i=(e.data.responseOptions.attempts??0)>0,[m,h]=useState(false),[p,x]=useState(0),v=e.data.responseOptions.attempts||0,g=340,y=100,S=Math.max(window.innerWidth*.3,400),C=window.innerHeight*.5,k=useRef(null);useEffect(()=>{let D=k.current;if(D)return a.current.set(e.id,D),()=>{a.current.delete(e.id);}},[e.id]);let w=Math.max(60,((D,q,j,J)=>{let $=document.createElement("canvas").getContext("2d");if(!$)return q;$.font=`${J} ${q}px Arial, sans-serif`;let ie=D.split(" "),he=[],fe="";return ie.forEach(xe=>{let ye=fe?`${fe} ${xe}`:xe;$.measureText(ye).width>j&&fe!==""?(he.push(fe),fe=xe):fe=ye;}),fe&&he.push(fe),he.length*q*1.2})(e.data.question,20,S-40,"bold")+20),b=w+10,I=S-40,P=C-w-250,H=useCallback(D=>{let q=D.target;s(tt({id:e.id,dragDropPos:{x:q.x(),y:q.y()}})),n?.();},[s,e.id,n]),O=D=>{s(tt({id:e.id,dragDropPos:{x:D.target.x(),y:D.target.y()}})),n?.();},B=D=>{let q=D.target,j=q.x(),J=q.y(),re=window.innerWidth*.2-40,$=50,ie=20,he=20+I,fe=b,xe=b+P,ye=j+re>ie&&j<he&&J+$>fe&&J<xe;f(ye),n?.();},V=(D,q)=>{let j=D?"true":"false",J=q.target;s(tt({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[j]:{x:J.x(),y:J.y()}}}));let re=J.x(),$=J.y(),ie=window.innerWidth*.2-40,he=50,fe=20,xe=20+I,ye=b,we=b+P;if(!(re+ie>fe&&re<xe&&$+he>ye&&$<we)){f(false);return}f(false);let wt=D===e.data.responseOptions.correctAnswer;s(tt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:D,isCorrect:wt}}}));},U=()=>{s(tt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},K=()=>{s(tt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),f(false),x(D=>D+1),n?.();},F=e.data.responseOptions.correctAnswer,W=d===F,te=()=>W?"\u2713 Correct! Great job!":"\u2717 Try again!",X=()=>W?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:k,name:"trueFalse-element",width:S,height:C,x:e.dragDropPos?.x,y:e.dragDropPos?.y,draggable:!l,listening:!l,onDragMove:H,...r,...l?{}:{onClick:D=>t&&t(e.id),onTap:D=>t&&t(e.id),onContextMenu:D=>{D.evt.preventDefault(),o(D.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:g,y,rotation:e.rotation,onDragEnd:O,children:[jsx(Rect,{fill:"white",stroke:u?"#4CAF50":"#e5e7eb",strokeWidth:u?4:2,cornerRadius:12,height:i?C:e.data.feedbackMode==="practice"?C-50:C-100,width:S,shadowColor:u?"#4CAF50":"transparent",shadowBlur:u?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:S-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:b,width:I,height:P,fill:"transparent",stroke:u?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),i&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:b,width:I,height:60,fill:X().bg,cornerRadius:8}),jsx(Text,{x:20,y:b,width:I,height:60,text:te()+" ("+v+" attempts)",fontSize:18,fontStyle:"bold",fill:X().text,align:"center",verticalAlign:"middle"})]}),d===null&&!i&&jsx(Text,{x:20,y:b,width:I,height:P,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),[{value:true,label:"True"},{value:false,label:"False"}].map((D,q)=>{let j=I/2+20,J=50,re=10,$=d===D.value,ie=F===D.value,he=i&&$,fe=D.value?"true":"false",xe=16+q*(j+re),ye=y+C-300,we=e.optionDragDropPos?.[fe],yt="transparent";return he?yt=ie?"#4CAF50":"#ef4444":$&&(yt="#4CAF50"),jsxs(Group,{x:we?.x??xe,y:we?.y??ye,draggable:!i,onDragStart:wt=>{wt.cancelBubble=true;},onDragMove:wt=>{wt.cancelBubble=true,B(wt);},onDragEnd:wt=>{wt.cancelBubble=true,V(D.value,wt);},opacity:i&&!$?.5:1,children:[jsx(Rect,{width:j-40,height:J,fill:"#075560",stroke:yt,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:j-40,height:J,text:D.label,fontSize:18,fontStyle:"bold",fill:pb,align:"center",verticalAlign:"middle",listening:false})]},`${D.value}-${p}`)}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:C-100,children:[jsxs(Group,{onMouseDown:D=>{D.cancelBubble=true,!(i||d===null)&&d!==null&&(h(true),U());},onMouseUp:()=>h(false),onMouseLeave:()=>h(false),onTouchStart:()=>{d!==null&&(h(true),U());},onTouchEnd:()=>h(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:i||d===null?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:i||d===null?"#9ca3af":"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),i&&jsxs(Group,{y:50,onMouseDown:K,onTouchStart:K,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]})})};gl.displayName="TrueFalseDragAndDrop";var hc=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:n,onLongPress:s,onUpdate:c})=>{let{createHandlers:l}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(u=>u.data.responseType==="classic"?jsx(pc,{trueFalse:u,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:l(u.id,"trueFalse"),onUpdate:c},u.id):jsx(gl,{trueFalse:u,handleSelect:t,trueFalseRefs:a,onContextMenu:n,touchHandlers:l(u.id,"trueFalse"),onUpdate:c},u.id))})};var Da=new WeakMap,Wo=new WeakMap,Fr={current:[]},bl=false,Rr=0,Dr=new Set,us=new Map;function gc(e){let o=Array.from(e).sort((t,a)=>t instanceof $t&&t.options.deps.includes(a)?1:a instanceof $t&&a.options.deps.includes(t)?-1:0);for(let t of o){if(Fr.current.includes(t))continue;Fr.current.push(t),t.recompute();let a=Wo.get(t);if(a)for(let r of a){let n=Da.get(r);n&&gc(n);}}}function xb(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function bb(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function cs(e){if(Rr>0&&!us.has(e)&&us.set(e,e.prevState),Dr.add(e),!(Rr>0)&&!bl)try{for(bl=!0;Dr.size>0;){let o=Array.from(Dr);Dr.clear();for(let t of o){let a=us.get(t)??t.prevState;t.prevState=a,xb(t);}for(let t of o){let a=Da.get(t);a&&(Fr.current.push(t),gc(a));}for(let t of o){let a=Da.get(t);if(a)for(let r of a)bb(r);}}}finally{bl=false,Fr.current=[],us.clear();}}function Mt(e){Rr++;try{e();}finally{if(Rr--,Rr===0){let o=Dr.values().next().value;o&&cs(o);}}}function xc(e){return typeof e=="function"}var aa=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,n;this.listeners.add(a);let s=(n=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:n.call(r,a,this);return ()=>{this.listeners.delete(a),s?.();}},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):xc(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),cs(this);}};var $t=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),r=new Array(t);for(let n=0;n<t;n++){let s=this.options.deps[n];a[n]=s.prevState,r[n]=s.state;}return this.lastSeenDepValues=r,{prevDepVals:a,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let n of this.options.deps)n instanceof e&&n.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let n=0;n<r.length;n++)if(r[n]!==a[n]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,r;this.listeners.add(t);let n=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),n?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof aa){let a=Da.get(t);a||(a=new Set,Da.set(t,a)),a.add(this);let r=Wo.get(this);r||(r=new Set,Wo.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 aa){let a=Da.get(t);a&&a.delete(this);let r=Wo.get(this);r&&r.delete(t);}}};function vb(e){return typeof e=="function"}function vl(e,...o){return vb(e)?e(...o):e}function bc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Ra,xt,ut,Br,Fa,no,ua,Uo,Or,fs,Nr,Ko,so=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Ne(this,Ra,true);Ne(this,xt);Ne(this,ut);Ne(this,Br);Ne(this,Fa);Ne(this,no);Ne(this,ua);Ne(this,Uo);Ne(this,Or,0);Ne(this,fs,5);Ne(this,Nr,()=>{this.debugLog("Connected to event bus"),Re(this,no,true),this.debugLog("Emitting queued events",_(this,Fa)),_(this,Fa).forEach(o=>this.emitEventToBus(o)),Re(this,Fa,[]),this.stopConnectLoop(),_(this,ut).call(this).removeEventListener("tanstack-connect-success",_(this,Nr));});Ne(this,Ko,()=>{if(_(this,ut).call(this).addEventListener("tanstack-connect-success",_(this,Nr)),_(this,Or)<_(this,fs)){zd(this,Or)._++,this.dispatchCustomEvent("tanstack-connect",{});return}_(this,ut).call(this).removeEventListener("tanstack-connect",_(this,Ko)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Re(this,xt,o),Re(this,Ra,a),Re(this,ut,this.getGlobalTarget),Re(this,Br,t),this.debugLog(" Initializing event subscription for plugin",_(this,xt)),Re(this,Fa,[]),Re(this,no,false),Re(this,ua,null),Re(this,Uo,r);}startConnectLoop(){_(this,ua)!==null||_(this,no)||(this.debugLog(`Starting connect loop (every ${_(this,Uo)}ms)`),Re(this,ua,setInterval(_(this,Ko),_(this,Uo))));}stopConnectLoop(){_(this,ua)!==null&&(clearInterval(_(this,ua)),Re(this,ua,null),this.debugLog("Stopped connect loop"));}debugLog(...o){_(this,Br)&&console.log(`\u{1F334} [tanstack-devtools:${_(this,xt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return _(this,xt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});_(this,ut).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{_(this,ut).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!_(this,Ra)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!_(this,no)){this.debugLog("Bus not available, will be pushed as soon as connected"),_(this,Fa).push({type:`${_(this,xt)}:${o}`,payload:t,pluginId:_(this,xt)}),typeof CustomEvent<"u"&&(_(this,Ko).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${_(this,xt)}:${o}`,payload:t,pluginId:_(this,xt)})}on(o,t){let a=`${_(this,xt)}:${o}`;if(!_(this,Ra))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=n=>{this.debugLog("Received event from bus",n.detail),t(n.detail);};return _(this,ut).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{_(this,ut).call(this).removeEventListener(a,r);}}onAll(o){if(!_(this,Ra))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return _(this,ut).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,ut).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!_(this,Ra))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;_(this,xt)&&r.pluginId!==_(this,xt)||o(r);};return _(this,ut).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,ut).call(this).removeEventListener("tanstack-devtools-global",t)}};Ra=new WeakMap,xt=new WeakMap,ut=new WeakMap,Br=new WeakMap,Fa=new WeakMap,no=new WeakMap,ua=new WeakMap,Uo=new WeakMap,Or=new WeakMap,fs=new WeakMap,Nr=new WeakMap,Ko=new WeakMap;var yl=class extends so{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},vc=(e,o)=>{wl.emit(e,o);},wl=new yl;function yc(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var yb={enabled:true,leading:true,trailing:true,wait:0},Ba,Pt,io,lo,uo,Go,ms=class{constructor(o,t){Ne(this,Ba);Ne(this,Pt);Ne(this,io);Ne(this,lo);Ne(this,uo);Ne(this,Go);this.fn=o,this.store=new aa(yc()),this.setOptions=a=>{this.options={...this.options,...a},_(this,io).call(this)||this.cancel();},Re(this,Pt,a=>{this.store.setState(r=>{let n={...r,...a},{isPending:s}=n;return {...n,status:_(this,io).call(this)?s?"pending":"idle":"disabled"}}),vc("Throttler",this);}),Re(this,io,()=>!!vl(this.options.enabled,this)),Re(this,lo,()=>vl(this.options.wait,this)),this.maybeExecute=(...a)=>{_(this,Pt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),n=r-this.store.state.lastExecutionTime,s=_(this,lo).call(this);if(this.options.leading&&n>=s)_(this,uo).call(this,...a);else if(_(this,Pt).call(this,{lastArgs:a}),!_(this,Ba)&&this.options.trailing){let c=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,l=s-c;_(this,Pt).call(this,{isPending:true}),Re(this,Ba,setTimeout(()=>{let{lastArgs:u}=this.store.state;u!==void 0&&_(this,uo).call(this,...u);},l));}},Re(this,uo,(...a)=>{if(!_(this,io).call(this))return;this.fn(...a);let r=Date.now(),n=r+_(this,lo).call(this);_(this,Go).call(this),_(this,Pt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:n,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||_(this,Pt).call(this,{nextExecutionTime:void 0});},_(this,lo).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&_(this,uo).call(this,...this.store.state.lastArgs);},Re(this,Go,()=>{_(this,Ba)&&(clearTimeout(_(this,Ba)),Re(this,Ba,void 0));}),this.cancel=()=>{_(this,Go).call(this),_(this,Pt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{_(this,Pt).call(this,yc());},this.key=bc(t.key),this.options={...yb,...t},_(this,Pt).call(this,this.options.initialState??{}),wl.on("d-Throttler",a=>{a.payload.key===this.key&&(_(this,Pt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Ba=new WeakMap,Pt=new WeakMap,io=new WeakMap,lo=new WeakMap,uo=new WeakMap,Go=new WeakMap;function Sl(e,o){return new ms(e,o).maybeExecute}function Oa(e,o){return typeof e=="function"?e(o):e}function Na(e,o){return xs(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function jo(e,o,t){let a=xs(o);function r(n){if(!a.length)return Oa(t,n);let s=a.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(n))return typeof n=="object"?(n===null&&(n={}),{...n,[s]:r(n[s])}):{[s]:r()};if(Array.isArray(n)&&typeof s=="number"){let c=n.slice(0,s);return [...c.length?c:new Array(s),r(n[s]),...n.slice(s+1)]}return [...new Array(s),r()]}return r(e)}function Il(e,o){let t=xs(o);function a(r){if(!r)return;if(t.length===1){let s=t[0];if(Array.isArray(r)&&typeof s=="number")return r.filter((u,f)=>f!==s);let{[s]:c,...l}=r;return l}let n=t.shift();if(typeof n=="string"&&typeof r=="object")return {...r,[n]:a(r[n])};if(typeof n=="number"&&Array.isArray(r)){if(n>=r.length)return r;let s=r.slice(0,n);return [...s.length?s:new Array(n),a(r[n]),...r.slice(n+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var wb=/^(\d+)$/gm,Sb=/\.(\d+)(?=\.)/gm,Lb=/^(\d+)\./gm,Ib=/\.(\d+$)/gm,Cb=/\.{2,}/gm,Ll="__int__",ps=`${Ll}$1`;function xs(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(wb,ps).replace(Sb,`.${ps}.`).replace(Lb,`${ps}.`).replace(Ib,`.${ps}`).replace(Cb,".").split(".").map(o=>{if(o.startsWith(Ll)){let t=o.substring(Ll.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Cl(e){return !(Array.isArray(e)&&e.length===0)}function _o(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 $o(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:n}=o.validators||{},s=t??0,c=l=>l.validators.filter(Boolean).map(u=>{let f=u?.cause||e,d=s;switch(f){case "change":d=r??s;break;case "blur":d=a??s;break;case "dynamic":d=n??s;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:f,validate:u.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:c})}var Hr=e=>!!e&&typeof e=="object"&&"fields"in e;function Ha(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[r,n]of e)if(!o.has(r)||!Object.is(n,o.get(r)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let r of e)if(!o.has(r))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let r of t)if(!a.includes(r)||!Ha(e[r],o[r]))return false;return true}var bs=({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},vs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Ze(e,o){return e==null?o:{...e,...o}}var co=256,gs=[],hs;for(;co--;)gs[co]=(co+256).toString(16).substring(1);function kl(){let e=0,o,t="";if(!hs||co+16>256){for(hs=new Array(256),e=256;e--;)hs[e]=256*Math.random()|0;e=0,co=0;}for(;e<16;e++)o=hs[co+e],e===6?t+=gs[o&15|64]:e===8?t+=gs[o&63|128]:t+=gs[o],e&1&&e>1&&e<11&&(t+="-");return co++,t}var qa=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},n={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},s=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,r,n,s],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,s],form:e.form});case "change":return e.runValidation({validators:[a,s],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function kb(e,o){let t=new Map;for(let a of e){let r=a.path??[],n=o,s="";for(let c=0;c<r.length;c++){let l=r[c];if(l===void 0)continue;let u=typeof l=="object"?l.key:l,f=Number(u);Array.isArray(n)&&!Number.isNaN(f)?s+=`[${f}]`:s+=(c>0?".":"")+String(u),typeof n=="object"&&n!==null?n=n[u]:n=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var wc=(e,o)=>{let t=kb(e,o);return {form:t,fields:t}},Va={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:wc(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:wc(a.issues,e)}},ys=e=>!!e&&"~standard"in e;var Xo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function qr(e){function o(d,i,m,h){let p=a(d,i,m,h);({insert:()=>c(p,d,i),remove:()=>l(p),swap:()=>h!==void 0&&f(p,d,i,h),move:()=>h!==void 0&&u(p,d,i,h)})[m]();}function t(d,i){return `${d}[${i}]`}function a(d,i,m,h){let p=[t(d,i)];if(m==="swap")p.push(t(d,h));else if(m==="move"){let[x,v]=[Math.min(i,h),Math.max(i,h)];for(let g=x;g<=v;g++)p.push(t(d,g));}else {let x=e.getFieldValue(d),v=Array.isArray(x)?x.length:0;for(let g=i+1;g<v;g++)p.push(t(d,g));}return Object.keys(e.fieldInfo).filter(x=>p.some(v=>x.startsWith(v)))}function r(d,i){return d.replace(/\[(\d+)\]/,(m,h)=>{let p=parseInt(h,10);return `[${i==="up"?p+1:Math.max(0,p-1)}]`})}function n(d,i){(i==="up"?d:[...d].reverse()).forEach(h=>{let p=r(h.toString(),i),x=e.getFieldMeta(p);x?e.setFieldMeta(h,x):e.setFieldMeta(h,s());});}let s=()=>Xo,c=(d,i,m)=>{n(d,"down"),d.forEach(h=>{h.toString().startsWith(t(i,m))&&e.setFieldMeta(h,s());});},l=d=>{n(d,"up");},u=(d,i,m,h)=>{let p=new Map(Object.keys(e.fieldInfo).filter(x=>x.startsWith(t(i,m))).map(x=>[x,e.getFieldMeta(x)]));n(d,m<h?"up":"down"),Object.keys(e.fieldInfo).filter(x=>x.startsWith(t(i,h))).forEach(x=>{let v=x.replace(t(i,h),t(i,m)),g=p.get(v);g&&e.setFieldMeta(x,g);});},f=(d,i,m,h)=>{d.forEach(p=>{if(!p.toString().startsWith(t(i,m)))return;let x=p.toString().replace(t(i,m),t(i,h)),[v,g]=[e.getFieldMeta(p),e.getFieldMeta(x)];v&&e.setFieldMeta(x,v),g&&e.setFieldMeta(p,g);});};return {handleArrayFieldMetaShift:o}}var Tl=class extends so{constructor(){super({pluginId:"form-devtools"});}},At=new Tl;function Ml(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 zr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),n=()=>{a(),r(),At.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return At.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),s&&this.validateSync("mount"),n},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let n=!!a.transform?.deps?.some((l,u)=>l!==this.prevTransformArray[u]),s=a.defaultValues&&!Ha(a.defaultValues,r.defaultValues)&&!this.state.isTouched,c=!Ha(a.defaultState,r.defaultState)&&!this.state.isTouched;!s&&!c&&!n||(Mt(()=>{this.baseStore.setState(()=>Ml(Object.assign({},this.state,c?a.defaultState:{},s?{values:a.defaultValues}:{},n?{_force_re_eval:!this.state._force_re_eval}:{})));}),At.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:n}=this.state,s=this.resetFieldMeta(n);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Ml({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let r=[];return Mt(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;let c=s.instance;r.push(Promise.resolve().then(()=>c.validate(a,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(l=>({...l,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,n)=>{let s=this.getFieldValue(a),c=Array.isArray(s)?Math.max(s.length-1,0):null,l=[`${a}[${r}]`];for(let i=r+1;i<=(c??0);i++)l.push(`${a}[${i}]`);let u=Object.keys(this.fieldInfo).filter(i=>l.some(m=>i.startsWith(m))),f=[];return Mt(()=>{u.forEach(i=>{f.push(Promise.resolve().then(()=>this.validateField(i,n)));});}),(await Promise.all(f)).flat()},this.validateField=(a,r)=>{let n=this.fieldInfo[a]?.instance;return n?(n.state.meta.isTouched||n.setMeta(s=>({...s,isTouched:true})),n.validate(r)):[]},this.validateSync=a=>{let r=_o(a,{...this.options,form:this,validationLogic:this.options.validationLogic||qa}),n=false,s={};return Mt(()=>{for(let u of r){if(!u.validate)continue;let f=this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:i}=ws(f),m=Vr(u.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let p=this.getFieldMeta(h);if(!p)continue;let{errorMap:x,errorSourceMap:v}=p,g=i?.[h],{newErrorValue:y,newSource:S}=bs({newFormValidatorError:g,isPreviousErrorFromFormValidator:v?.[m]==="form",previousErrorValue:x?.[m]});S==="form"&&(s[h]={...s[h],[m]:g}),x?.[m]!==y&&this.setFieldMeta(h,C=>({...C,errorMap:{...C.errorMap,[m]:y},errorSourceMap:{...C.errorSourceMap,[m]:S}}));}this.state.errorMap?.[m]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[m]:d}})),(d||i)&&(n=!0);}let c=Vr("submit");this.state.errorMap?.[c]&&a!=="submit"&&!n&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[c]:void 0}}));let l=Vr("server");this.state.errorMap?.[l]&&a!=="server"&&!n&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[l]:void 0}}));}),{hasErrored:n,fieldsErrorMap:s}},this.validateAsync=async a=>{let r=$o(a,{...this.options,form:this,validationLogic:this.options.validationLogic||qa});this.state.isFormValidating||this.baseStore.setState(u=>({...u,isFormValidating:true}));let n=[],s;for(let u of r){if(!u.validate)continue;let f=Vr(u.cause);this.state.validationMetaMap[f]?.lastAbortController.abort();let i=new AbortController;this.state.validationMetaMap[f]={lastAbortController:i},n.push(new Promise(async m=>{let h;try{h=await new Promise((g,y)=>{setTimeout(async()=>{if(i.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:i.signal},type:"validateAsync"}));}catch(S){y(S);}},u.debounceMs);});}catch(g){h=g;}let{formError:p,fieldErrors:x}=ws(h);x&&(s=s?{...s,...x}:x);let v=Vr(u.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let y=this.getFieldMeta(g);if(!y)continue;let{errorMap:S,errorSourceMap:C}=y,k=s?.[g],{newErrorValue:T,newSource:w}=bs({newFormValidatorError:k,isPreviousErrorFromFormValidator:C?.[v]==="form",previousErrorValue:S?.[v]});S?.[v]!==T&&this.setFieldMeta(g,b=>({...b,errorMap:{...b.errorMap,[v]:T},errorSourceMap:{...b.errorSourceMap,[v]:w}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[v]:p}})),m(s?{fieldErrors:s,errorMapKey:v}:void 0);}));}let c=[],l={};if(n.length){c=await Promise.all(n);for(let u of c)if(u?.fieldErrors){let{errorMapKey:f}=u;for(let[d,i]of Object.entries(u.fieldErrors)){let h={...l[d]||{},[f]:i};l[d]=h;}}}return this.baseStore.setState(u=>({...u,isFormValidating:false})),l},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:n}=this.validateSync(a);return r&&!this.options.asyncAlways?n:this.validateAsync(a)},this.getFieldValue=a=>Na(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var r;return (r=this.fieldInfo)[a]||(r[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,r)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:Oa(r,n.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,n)=>{let s=n;return r[s]=Xo,r},{}),this.setFieldValue=(a,r,n)=>{let s=n?.dontUpdateMeta??false,c=n?.dontRunListeners??false,l=n?.dontValidate??false;Mt(()=>{s||this.setFieldMeta(a,u=>({...u,isTouched:!0,isDirty:!0,errorMap:{...u?.errorMap,onMount:void 0}})),this.baseStore.setState(u=>({...u,values:jo(u.values,a,r)}));}),c||this.getFieldInfo(a).instance?.triggerOnChangeListener(),l||this.validateField(a,"change");},this.deleteField=a=>{let n=[...Object.keys(this.fieldInfo).filter(s=>{let c=a.toString();return s!==c&&s.startsWith(c)}),a];this.baseStore.setState(s=>{let c={...s};return n.forEach(l=>{c.values=Il(c.values,l),delete this.fieldInfo[l],delete c.fieldMetaBase[l];}),c});},this.pushFieldValue=(a,r,n)=>{this.setFieldValue(a,s=>[...Array.isArray(s)?s:[],r],n);},this.insertFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,l=>[...l.slice(0,r),n,...l.slice(r)],Ze(s,{dontValidate:true}));let c=s?.dontValidate??false;c||await this.validateField(a,"change"),qr(this).handleArrayFieldMetaShift(a,r,"insert"),c||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,l=>l.map((u,f)=>f===r?n:u),Ze(s,{dontValidate:true})),(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,n)=>{let s=this.getFieldValue(a),c=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,u=>u.filter((f,d)=>d!==r),Ze(n,{dontValidate:true})),qr(this).handleArrayFieldMetaShift(a,r,"remove"),c!==null){let u=`${a}[${c}]`;this.deleteField(u);}(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,n,s)=>{this.setFieldValue(a,l=>{let u=l[r],f=l[n];return jo(jo(l,`${r}`,f),`${n}`,u)},Ze(s,{dontValidate:true})),qr(this).handleArrayFieldMetaShift(a,r,"swap",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.moveFieldValues=(a,r,n,s)=>{this.setFieldValue(a,l=>{let u=[...l];return u.splice(n,0,u.splice(r,1)[0]),u},Ze(s,{dontValidate:true})),qr(this).handleArrayFieldMetaShift(a,r,"move",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.clearFieldValues=(a,r)=>{let n=this.getFieldValue(a),s=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,[],Ze(r,{dontValidate:true})),s!==null)for(let l=0;l<=s;l++){let u=`${a}[${l}]`;this.deleteField(u);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Xo},values:this.options.defaultValues?jo(r.values,a,Na(this.options.defaultValues,a)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[r,n])=>(Object.keys(n).length&&n.errors.length&&(a[r]={errors:n.errors,errorMap:n.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Va.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Va.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??kl(),this._devtoolsSubmissionOverride=false,this.baseStore=new aa(Ml({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new $t({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,c=a?.[0],l=r[0],u=0,f={};for(let d of Object.keys(l.fieldMetaBase)){let i=l.fieldMetaBase[d],m=c?.fieldMetaBase[d],h=s?.[d],p=Na(l.values,d),x=h?.errors;if(!m||i.errorMap!==m.errorMap){x=Object.values(i.errorMap??{}).filter(C=>C!==void 0);let S=this.getFieldInfo(d)?.instance;S&&!S.options.disableErrorFlat&&(x=x?.flat(1));}let v=!Cl(x??[]),g=!i.isDirty,y=Ha(p,Na(this.options.defaultValues,d))||Ha(p,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===v&&h.isDefaultValue===y&&h.errors===x&&i===m){f[d]=h,u++;continue}f[d]={...i,errors:x,isPristine:g,isValid:v,isDefaultValue:y};}return Object.keys(l.fieldMetaBase).length&&s&&u===Object.keys(l.fieldMetaBase).length?s:f}}),this.store=new $t({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,c=a?.[0],l=r[0],u=r[1],f=Object.values(u).filter(Boolean),d=f.some(B=>B.isValidating),i=f.every(B=>B.isValid),m=f.some(B=>B.isTouched),h=f.some(B=>B.isBlurred),p=f.every(B=>B.isDefaultValue),x=m&&l.errorMap?.onMount,v=f.some(B=>B.isDirty),g=!v,y=!!(l.errorMap?.onMount||f.some(B=>B?.errorMap?.onMount)),S=!!d,C=s?.errors??[];(!c||l.errorMap!==c.errorMap)&&(C=Object.values(l.errorMap).reduce((B,V)=>V===void 0?B:V&&Hr(V)?(B.push(V.form),B):(B.push(V),B),[]));let k=C.length===0,T=i&&k,w=this.options.canSubmitWhenInvalid??false,b=l.submissionAttempts===0&&!m&&!y||!S&&!l.isSubmitting&&T||w,I=l.errorMap;if(x&&(C=C.filter(B=>B!==l.errorMap.onMount),I=Object.assign(I,{onMount:void 0})),s&&c&&s.errorMap===I&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===C&&s.isFieldsValidating===d&&s.isFieldsValid===i&&s.isFormValid===k&&s.isValid===T&&s.canSubmit===b&&s.isTouched===m&&s.isBlurred===h&&s.isPristine===g&&s.isDefaultValue===p&&s.isDirty===v&&Ha(c,l))return s;let P={...l,errorMap:I,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:d,isFieldsValid:i,isFormValid:k,isValid:T,canSubmit:b,isTouched:m,isBlurred:h,isPristine:g,isDefaultValue:p,isDirty:v},H=this.options.transform?.deps??[];if(H.length!==this.prevTransformArray.length||H.some((B,V)=>B!==this.prevTransformArray[V])){let B=Object.assign({},this,{state:P});this.options.transform?.fn(B),P=B.state,this.prevTransformArray=H;}return P}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Sl(a=>At.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),At.on("request-form-state",a=>{a.payload.id===this._formId&&At.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),At.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),At.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return ys(o.validate)?Va[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})),Mt(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(n=>({...n,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(r=>({...r,isSubmitting:true}));let a=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),At.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}),At.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}Mt(()=>{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}),Mt(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),At.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(n=>({...n,isSubmitSuccessful:false})),At.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){Mt(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(Hr(a)){let{formError:n,fieldErrors:s}=ws(a);for(let c of Object.keys(this.fieldInfo))this.getFieldMeta(c)&&this.setFieldMeta(c,u=>({...u,errorMap:{...u.errorMap,[r]:s?.[c]},errorSourceMap:{...u.errorSourceMap,[r]:"form"}}));this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[r]:n}}));}else this.baseStore.setState(n=>({...n,errorMap:{...n.errorMap,[r]:a}}));});});}};function ws(e){if(e){if(Hr(e)){let o=ws(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function Vr(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 Wr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let n=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});n&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:n},errorSourceMap:{...s?.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=Na(t.form.options.defaultValues,t.name),n=t.defaultValue??r;a?this.setValue(s=>s||n,{dontUpdateMeta:true}):n!==void 0&&this.setValue(n,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Ze(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Ze(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,Ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,Ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Ze(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,Ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,Ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Ze(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),r=[];for(let n of a){if(!n.instance)continue;let{onChangeListenTo:s,onBlurListenTo:c}=n.instance.options.validators||{};t==="change"&&s?.includes(this.name)&&r.push(n.instance),t==="blur"&&c?.includes(this.name)&&r.push(n.instance);}return r},this.validateSync=(t,a)=>{let r=_o(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||qa}),s=this.getLinkedFields(t).reduce((u,f)=>{let d=_o(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||qa});return d.forEach(i=>{i.field=f;}),u.concat(d)},[]),c=false;Mt(()=>{let u=(f,d)=>{let i=Ss(d.cause),m=d.validate?Sc(f.runValidator({validate:d.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,h=a[i],{newErrorValue:p,newSource:x}=vs({formLevelError:h,fieldLevelError:m});f.state.meta.errorMap?.[i]!==p&&f.setMeta(v=>({...v,errorMap:{...v.errorMap,[i]:p},errorSourceMap:{...v.errorSourceMap,[i]:x}})),p&&(c=!0);};for(let f of r)u(this,f);for(let f of s)f.validate&&u(f.field,f);});let l=Ss("submit");return this.state.meta.errorMap?.[l]&&t!=="submit"&&!c&&this.setMeta(u=>({...u,errorMap:{...u.errorMap,[l]:void 0},errorSourceMap:{...u.errorSourceMap,[l]:void 0}})),{hasErrored:c}},this.validateAsync=async(t,a)=>{let r=$o(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||qa}),n=await a,s=this.getLinkedFields(t),c=s.reduce((i,m)=>{let h=$o(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||qa});return h.forEach(p=>{p.field=m;}),i.concat(h)},[]);this.state.meta.isValidating||this.setMeta(i=>({...i,isValidating:true}));for(let i of s)i.setMeta(m=>({...m,isValidating:true}));let l=[],u=[],f=(i,m,h)=>{let p=Ss(m.cause);i.getInfo().validationMetaMap[p]?.lastAbortController.abort();let v=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:v},h.push(new Promise(async g=>{let y;try{y=await new Promise((w,b)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(v.signal.aborted)return w(void 0);try{w(await this.runValidator({validate:m.validate,value:{value:i.store.state.value,fieldApi:i,signal:v.signal,validationSource:"field"},type:"validateAsync"}));}catch(I){b(I);}},m.debounceMs);});}catch(w){y=w;}if(v.signal.aborted)return g(void 0);let S=Sc(y),C=n[this.name]?.[p],{newErrorValue:k,newSource:T}=vs({formLevelError:C,fieldLevelError:S});i.setMeta(w=>({...w,errorMap:{...w?.errorMap,[p]:k},errorSourceMap:{...w.errorSourceMap,[p]:T}})),g(k);}));};for(let i of r)i.validate&&f(this,i,l);for(let i of c)i.validate&&f(i.field,i,u);let d=[];(l.length||u.length)&&(d=await Promise.all(l),await Promise.all(u)),this.setMeta(i=>({...i,isValidating:false}));for(let i of s)i.setMeta(m=>({...m,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:n}=this.validateSync(t,r[this.name]??{});if(n&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Ss(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},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=>Va.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Va.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new $t({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Xo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return ys(o.validate)?Va[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 Sc(e){if(e)return e}function Ss(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 Ls(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Mb)}function Mb(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=Lc(e);if(t.length!==Lc(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 Lc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Yo=typeof window<"u"?useLayoutEffect:useEffect;function Bb(e){let[o]=useState(()=>{let a=new Wr({...e,form:e.form,name:e.name});return a.Field=Pl,a});return Yo(o.mount,[o]),Yo(()=>{o.update(e);}),Ls(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Pl=(({children:e,...o})=>{let t=Bb(o),a=useMemo(()=>Oa(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Hb({form:e,selector:o,children:t}){let a=Ls(e.store,o);return Oa(t,a)}function Al(e){let o=useId(),[t]=useState(()=>{let a=new zr({...e,formId:o}),r=a;return r.Field=function(s){return jsx(Pl,{...s,form:a})},r.Subscribe=function(s){return jsx(Hb,{form:a,selector:s.selector,children:s.children})},r});return Yo(t.mount,[]),Yo(()=>{t.update(e);}),t}function El({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 $b=({editElement:e})=>{let o=useDispatch(),t=useSelector(ve),a=useRef(null),r=ze(),n=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[c,l]=useState(s),u=Al({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:i})=>{if(i.questionType==="true-false"){let m={id:n?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctAnswer:i.responseOptions.correctAnswer??false}},x:n?e.x:500,y:n?e.y:200,dragDropPos:{x:n&&"dragDropPos"in e?e.dragDropPos?.x??400:200,y:n&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:n?e.width:400,height:n?e.height:300,rotation:n?e.rotation:0};o(n?tt(m):Ii(m));}else if(i.questionType==="multiple-choice"){let m={id:n?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctIndex:i.responseOptions.correctIndex??[]}},x:n?e.x:500,y:n?e.y:200,dragDropPos:{x:n&&"dragDropPos"in e?e.dragDropPos?.x??400:400,y:n&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:n?e.width:575,height:n?e.height:400,rotation:n?e.rotation:0};o(n?ht(m):Si(m));}else if(i.questionType==="short-answer"){let m={id:n?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctShortAnswer:i.responseOptions.correctShortAnswer??""}},x:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:400,rotation:n?e.rotation:0};o(n?la(m):Ci(m));}else if(i.questionType==="fill-in-the-blank"){let m={id:n?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctShortAnswer:i.responseOptions.correctShortAnswer??""}},x:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:400,rotation:n?e.rotation:0};o(n?Ca(m):Ti(m));}else if(i.questionType==="long-answer"){let m={id:n?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctLongAnswer:i.responseOptions.correctLongAnswer??""}},x:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:400,rotation:n?e.rotation:0};o(n?Qa(m):ki(m));}o(ka(false));}}),f=()=>{o(ka(false));};if(!r)return null;let d=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:i=>{i.preventDefault(),i.stopPropagation(),u.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:n?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{f();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(u.Field,{name:"questionType",children:i=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:i.name,name:i.name,value:i.state.value,onBlur:i.handleBlur,onChange:m=>{i.handleChange(m.target.value),l(m.target.value);},disabled:n,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${n?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),n&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(El,{field:i})]})}),c&&!["short-answer","fill-in-the-blank","long-answer"].includes(c)&&jsx(u.Field,{name:"responseType",children:i=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:i.name,name:i.name,value:i.state.value,onBlur:i.handleBlur,onChange:m=>i.handleChange(m.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(El,{field:i})]})})]}),jsx(u.Field,{name:"feedbackMode",children:i=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${c==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:c==="long-answer",onClick:()=>i.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${i.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:c==="long-answer",onClick:()=>i.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${i.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),c==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(El,{field:i})]})}),jsx(u.Field,{name:"question",validators:{onChange:({value:i})=>i?void 0:"A question is required"},children:i=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:i.state.value,onChange:m=>i.handleChange(m.target.value),onBlur:i.handleBlur,placeholder:"Enter Your Question"})}),i.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:i.state.meta.errors.join(", ")})]})}),c==="true-false"&&jsx(u.Field,{name:"responseOptions.correctAnswer",children:i=>{let m=i.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>i.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-lg border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${m===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"}),m===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>i.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-lg border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${m===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"}),m===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),c==="multiple-choice"&&jsx(u.Field,{name:"responseOptions",validators:{onChange:({value:i})=>{if(i.options.filter(h=>!h.trim()).length>0)return "All options must have text";if(!i.correctIndex||i.correctIndex.length===0)return "Please select at least one correct answer"}},children:i=>{let m=(v,g)=>{let y=[...i.state.value.options];y[v]=g,i.handleChange({...i.state.value,options:y});},h=()=>{if(i.state.value.options.length>=6){alert("Maximum 6 options allowed");return}i.handleChange({...i.state.value,options:[...i.state.value.options,""]});},p=v=>{if(i.state.value.options.length<=2){alert("Minimum 2 options required");return}let g=i.state.value.options.filter((S,C)=>C!==v),y=i.state.value.correctIndex?.filter(S=>S!==v).map(S=>S>v?S-1:S);i.handleChange({...i.state.value,options:g,correctIndex:y});},x=v=>{let g=i.state.value.correctIndex||[];if(g.includes(v))i.handleChange({...i.state.value,correctIndex:g.filter(S=>S!==v)});else {if(g.length>=6){alert("Maximum 6 correct answers allowed");return}i.handleChange({...i.state.value,correctIndex:[...g,v]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:i.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:i.state.value.options.map((v,g)=>{let y=!v.trim(),S=i.state.value.correctIndex?.includes(g),C=i.state.meta.isTouched&&y;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:()=>x(g),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${S?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:S&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${C?"border-red-500 bg-red-50":S?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${g+1}`,value:v,onChange:k=>m(g,k.target.value),onBlur:i.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),i.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>p(g),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},g)})}),jsx("button",{type:"button",onClick:h,disabled:i.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),i.state.value.correctIndex.length===0||i.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:i.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(c==="short-answer"||c==="fill-in-the-blank")&&jsx(u.Field,{name:"responseOptions.correctShortAnswer",children:i=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:i.state.value,onChange:m=>{i.handleChange(m.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),i.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:i.state.meta.errors.join(", ")})]})}),c==="long-answer"&&jsx(u.Field,{name:"responseOptions.correctLongAnswer",children:i=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:i.state.value,onChange:m=>{i.handleChange(m.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),i.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:i.state.meta.errors.join(", ")})]})}),jsx(u.Subscribe,{selector:i=>[i.canSubmit,i.isSubmitting],children:([i,m])=>jsx("button",{type:"submit",disabled:!i,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:m?"Saving...":n?"Update Question":"Save Question"})})]})})});return createPortal(d,r)},kc=$b;var Ac=({text:e,position:o})=>{let t=Se(),a=(f,d,i,m,h)=>{let x=document.createElement("canvas").getContext("2d");if(!x)return {width:e.width,height:e.height};x.font=`${h} ${m} ${d}px ${i}`;let v=f.split(`
4
+ `),g=0;for(let C of v){let k=x.measureText(C||" ");k.width>g&&(g=k.width);}let S=v.length*d*1.2;return {width:Math.max(200,g+40),height:Math.max(50,S+20)}},r=f=>{let d=Math.max(12,Math.min(72,e.fontSize+f)),i=a(e.text,d,e.fontFamily,e.fontWeight,e.fontStyle);t(le()),t(Ot({id:e.id,fontSize:d,width:i.width,height:i.height}));},n=f=>{t(le()),t(Ot({id:e.id,fill:f}));},s=()=>{let f=e.fontWeight==="bold"?"normal":"bold",d=a(e.text,e.fontSize,e.fontFamily,f,e.fontStyle);t(le()),t(Ot({id:e.id,fontWeight:f,width:d.width,height:d.height}));},c=()=>{let f=e.fontStyle==="italic"?"normal":"italic",d=a(e.text,e.fontSize,e.fontFamily,e.fontWeight,f);t(le()),t(Ot({id:e.id,fontStyle:f,width:d.width,height:d.height}));},l=()=>{t(le()),t(Ot({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},u=f=>{let d=a(e.text,e.fontSize,f,e.fontWeight,e.fontStyle);t(le()),t(Ot({id:e.id,fontFamily:f,width:d.width,height:d.height}));};return jsxs("div",{className:"absolute z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:"50%",top:100,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:f=>f.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:f=>u(f.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:()=>r(-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:()=>r(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:c,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:l,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:[jsx(TextUnderline,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextUnderline,{size:16,weight:"bold",className:"hidden sm:block"})]})]}),jsx("div",{className:"border-l border-gray-200 pl-1",children:jsx("input",{type:"color",value:e.fill,onChange:f=>n(f.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 Dc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:n,textareaRef:s})=>{let c=useRef(null),l=useMemo(()=>({fontSize:`${e.fontSize*n}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,n]),u=useCallback(f=>{f.style.height="auto",f.style.height=`${f.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(f).font,d.style.fontSize=f.style.fontSize,d.style.fontFamily=f.style.fontFamily,d.style.fontWeight=f.style.fontWeight,d.style.fontStyle=f.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let i=f.value.split(`
5
+ `),m=0;document.body.appendChild(d);for(let p of i){d.textContent=p||" ";let x=d.offsetWidth;x>m&&(m=x);}document.body.removeChild(d);let h=10;f.style.width=`${Math.max(200,m+h+20)}px`;},[]);return useEffect(()=>{let f=c.current;f&&(f.style.fontSize=`${e.fontSize*n}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,u(f));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,n,u]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:f=>{if(c.current=f,s.current=f,f){f.focus();let d=f.value.length;f.setSelectionRange(d,d),u(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 iv=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a} ${o}px Arial, sans-serif`;let s=e.split(" "),c=[],l="";return s.forEach(u=>{let f=l?`${l} ${u}`:u;n.measureText(f).width>t&&l!==""?(c.push(l),l=u):l=f;}),l&&c.push(l),c.length*o*1.2},Rc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:s})=>{let c=useSelector(I=>I.toolbar.selectedTool),l=c==="pen"||c==="eraser",u=useDispatch(),f=useRef(null),[d,i]=useState(null),m=e.data.responseOptions.attempts||0,[h,p]=useState(e.data.responseOptions.userAnswer||""),[x,v]=useState(false);useEffect(()=>{let I=f.current;if(I)return a.current.set(e.id,I),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",y=x&&h.trim().toLowerCase()===g,S=I=>{p(I);let P=I.trim(),H=P.toLowerCase()===g;u(la({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:P,isCorrect:H}}}));},C=()=>{v(false),p(""),u(la({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:"",isCorrect:false}}}));},k=()=>y?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",T=()=>y?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},w=e.data.feedbackMode==="practice",b=useMemo(()=>{let V=w?48:0,U=12,K=30,F=e.width-48,W=Math.max(60,iv(e.data.question,18,F,"bold")+20),te=x?40:0,X=x?54:20,D=W+te+K+50+12+U+V+24;return {padding:24,questionHeight:W,questionFontSize:18,feedbackHeight:te,feedbackFontSize:12,inputY:X,inputHeight:50,inputMargin:12,buttonHeight:V,buttonTopMargin:U,placeholderHeight:K,contentWidth:F,totalHeight:D}},[e.width,e.data.question,x,y,w,k]);return jsxs(Group,{ref:f,draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:b.totalHeight,name:"sa-element",...s,...l?{}:{onDragEnd:n,onClick:()=>o&&o(e.id),onTap:()=>o&&o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:b.totalHeight,onTransformEnd:I=>t(e.id,I),onContextMenu:I=>{I.cancelBubble=true,r(I.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:b.padding+8,y:b.padding,fontSize:b.questionFontSize,fontStyle:"bold",fill:"#111827",width:b.contentWidth,height:b.questionHeight-b.padding,wrap:"word",listening:false}),jsx(Rect,{x:b.padding,y:b.questionHeight+b.feedbackHeight+b.placeholderHeight-b.inputY,width:b.contentWidth+4,height:b.inputHeight+6,fill:"#ffffff",stroke:y?"#22c55e":x?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:b.padding,y:b.questionHeight+b.feedbackHeight+b.placeholderHeight-b.inputY},divProps:{style:{width:`${b.contentWidth-4}px`,height:`${b.inputHeight}px`,pointerEvents:x?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:I=>S(I.target.value),disabled:x,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:x?"none":"auto"}})}),x&&jsxs(Fragment,{children:[jsx(Rect,{x:b.padding,y:b.questionHeight+80,width:b.contentWidth,height:b.feedbackHeight,fill:T().bg,cornerRadius:8}),jsx(Text,{x:36,y:b.questionHeight+80,width:b.contentWidth,height:b.feedbackHeight,text:k()+` (${m} attempts)`,fontSize:b.feedbackFontSize,fontStyle:"bold",fill:T().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:b.questionHeight+b.feedbackHeight+b.placeholderHeight+b.inputHeight+b.inputMargin+b.buttonTopMargin,children:[jsxs(Group,{onMouseDown:I=>{I.cancelBubble=true,i("check");},onMouseUp:I=>{I.cancelBubble=true,i(null),h.length>0&&(v(true),u(la({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},onMouseLeave:I=>{I.cancelBubble=true,i(null);},onTouchStart:I=>{I.cancelBubble=true,i("check");},onTouchEnd:I=>{I.cancelBubble=true,i(null),h.length>0&&v(true);},scaleX:d==="check"?.95:1,scaleY:d==="check"?.95:1,children:[jsx(Rect,{x:b.padding+14,width:(b.contentWidth-24)/(x?2:1),height:b.buttonHeight,fill:h.length===0||x?"#9ca3af":"#096B76",cornerRadius:8,onClick:I=>I.cancelBubble=true,onTap:I=>I.cancelBubble=true}),jsx(Text,{x:b.padding+14,width:(b.contentWidth-24)/(x?2:1),height:b.buttonHeight,text:x?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),x&&jsxs(Group,{x:(e.width-b.padding*2)/2+8,onMouseDown:()=>i("reset"),onMouseUp:()=>{i(null),C();},onMouseLeave:()=>i(null),onTouchStart:()=>i("reset"),onTouchEnd:()=>{i(null),C();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:b.padding,width:(b.contentWidth-8)/2,height:b.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:I=>I.cancelBubble=true,onTap:I=>I.cancelBubble=true}),jsx(Text,{x:b.padding,width:(b.contentWidth-8)/2,height:b.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Rc.displayName="ShortAnswer";var Fc=Rc;var Oc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,onLongPress:s})=>{let{createHandlers:c}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(l=>jsx(Fc,{shortAnswer:l,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:u=>n(u,l.id),touchHandlers:c(l.id,"shortAnswer")},l.id))})};var Nc=e=>{let o=useDispatch(),a=useSelector(ve)?.fillInTheBlanks||[],r=useRef(new Map),n=useCallback((s,c)=>{let l=s.target;o(Ca({id:c,x:l.x(),y:l.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:n}};var Fl=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),c=[],l="";return s.forEach(u=>{let f=l?`${l} ${u}`:u;n.measureText(f).width>t&&l!==""?(c.push(l),l=u):l=f;}),l&&c.push(l),c.length*o*1.2},Hc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:n,touchHandlers:s})=>{let c=useSelector(I=>I.toolbar.selectedTool),l=c==="pen"||c==="eraser",u=useRef(null),f=useDispatch(),[d,i]=useState(null),m=e.data.responseOptions.attempts||0,[h,p]=useState(e.data.responseOptions.userAnswer||""),[x,v]=useState(false);useEffect(()=>{let I=u.current;if(I)return n.current.set(e.id,I),()=>{n.current.delete(e.id);}},[e.id,n]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",y=x&&h.trim().toLowerCase()===g,S=I=>{p(I);let P=I.trim(),H=P.toLowerCase()===g;f(Ca({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:P,isCorrect:H}}}));},C=()=>{v(false),p("");},k=()=>{h.length>0&&(v(true),f(Ca({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},T=e.data.feedbackMode==="practice",w=useMemo(()=>{let K=e.width-48,F=(K-15)/2,W=24,te=W,X=Math.max(60,Fl(e.data.question.replace("_____","________"),24,K,"bold")+20);W+=X;let D=W,q=Math.max(35,Fl("Enter your answer in the blank.",16,K)+10);W+=q;let j=W;W+=67;let J=W,re=x?Math.max(32,Fl(y?"Right Answer, Great Job!":"Wrong Answer",14,K-40)+16):0;x&&(W+=re+16);let $=W;return T&&(W+=64),W+=24,{padding:24,questionY:te,questionHeight:X,questionFontSize:24,helperTextY:D,helperTextHeight:q,helperTextFontSize:16,inputY:j,inputHeight:51,feedbackY:J,feedbackHeight:re,feedbackFontSize:14,buttonsY:$,buttonHeight:64,buttonGap:15,buttonWidth:F,contentWidth:K,totalHeight:W}},[e.width,e.data.question,x,y,T]),b=()=>x?y?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:u,draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...s,...l?{}:{onDragEnd:I=>a(I,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:w.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:I=>t(e.id,I),onContextMenu:I=>{I.cancelBubble=true,r?.(I.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:w.padding,y:w.questionY,fontSize:w.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:w.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:w.padding,y:w.helperTextY,fontSize:w.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:w.contentWidth,height:w.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:w.padding,y:w.inputY,width:w.contentWidth,height:w.inputHeight,fill:"#ffffff",stroke:b(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:w.padding,y:w.inputY},divProps:{style:{width:`${w.contentWidth}px`,height:`${w.inputHeight}px`,pointerEvents:x?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:I=>S(I.target.value),disabled:x,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"}})}),x&&jsxs(Group,{y:w.feedbackY,children:[jsx(Rect,{x:w.padding,width:w.contentWidth,height:w.feedbackHeight,fill:y?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:y?"\u2713":"\u2717",x:w.padding+10,y:0,width:16,height:w.feedbackHeight,fontSize:w.feedbackFontSize,fill:y?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:y?`Right Answer, Great Job! (${m} attempts)`:`Wrong Answer (${m} attempts)`,x:w.padding+30,y:0,height:w.feedbackHeight,fontSize:w.feedbackFontSize,fontStyle:"600",fill:y?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),T&&jsxs(Group,{y:w.buttonsY,children:[jsxs(Group,{x:w.padding,onClick:I=>I.cancelBubble=true,onTap:I=>I.cancelBubble=true,onMouseDown:I=>{I.cancelBubble=true,i("reset");},onMouseUp:I=>{I.cancelBubble=true,i(null),C();},onMouseLeave:I=>{I.cancelBubble=true,i(null);},onTouchStart:I=>{I.cancelBubble=true,i("reset");},onTouchEnd:I=>{I.cancelBubble=true,i(null),C();},scaleX:d==="reset"?.98:1,scaleY:d==="reset"?.98:1,children:[jsx(Rect,{width:w.buttonWidth,height:w.buttonHeight,fill:x?"#096b76":"#9ca3af",cornerRadius:8}),jsx(Text,{width:w.buttonWidth,height:w.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:w.padding+w.buttonWidth+w.buttonGap,onClick:I=>I.cancelBubble=true,onTap:I=>I.cancelBubble=true,onMouseDown:I=>{I.cancelBubble=true,!x&&i("submit");},onMouseUp:I=>{I.cancelBubble=true,!x&&(i(null),k());},onMouseLeave:I=>{I.cancelBubble=true,i(null);},onTouchStart:I=>{I.cancelBubble=true,!x&&i("submit");},onTouchEnd:I=>{I.cancelBubble=true,!x&&(i(null),k());},scaleX:d==="submit"?.98:1,scaleY:d==="submit"?.98:1,children:[jsx(Rect,{width:w.buttonWidth,height:w.buttonHeight,fill:h.length===0||x?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:w.buttonWidth,height:w.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Hc.displayName="FillInTheBlanks";var qc=Hc;var zc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,onLongPress:n,fibRefs:s})=>{let{createHandlers:c}=Ve({onLongPress:n});return jsx(Fragment,{children:e.map(l=>jsx(qc,{fillInTheBlank:l,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:s,touchHandlers:c(l.id,"fillInTheBlanks")},l.id))})};var Nl=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),c=[],l="";return s.forEach(u=>{let f=l?`${l} ${u}`:u;n.measureText(f).width>t&&l!==""?(c.push(l),l=u):l=f;}),l&&c.push(l),c.length*o*1.2},ql=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,touchHandlers:n,handleDragEnd:s})=>{let c=useSelector(w=>w.toolbar.selectedTool),l=c==="pen"||c==="eraser",u=useRef(null),f=useDispatch(),[d,i]=useState(null),[m,h]=useState(e.data.responseOptions.userAnswer||""),[p,x]=useState(false);useEffect(()=>{let w=u.current;if(w)return a.current.set(e.id,w),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",g=p&&m.trim().toLowerCase()===v,y=w=>{h(w);let b=w.trim();b.toLowerCase()===v;f(Qa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:b}}}));},S=()=>{x(false),h("");},C=()=>g?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",k=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},T=useMemo(()=>{let U=e.width-48,K=Math.max(60,Nl(e.data.question,20,U,"bold")+20),F=p?Math.max(60,Nl(C(),14,U)+30):0,te=Math.max(30,Nl("Answer (Extended response):",14,U)+10),X=K+F+te+120+12+12+48+24;return {padding:24,questionHeight:K,questionFontSize:20,feedbackHeight:F,feedbackFontSize:14,placeholderHeight:te,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:U,totalHeight:X}},[e.width,e.data.question,p,g,C]);return jsxs(Group,{ref:u,draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:T.totalHeight,...n,name:"la-element",...l?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:w=>{let b=u.current?.getStage()?.getPointerPosition();if(!b||!r)return;let I={x:e.x,y:e.y,width:e.width,height:T.totalHeight};b.x>=I.x&&b.x<=I.x+I.width&&b.y>=I.y&&b.y<=I.y+I.height&&r(w.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:T.totalHeight-50,onTransformEnd:w=>t(e.id,w)}),jsx(Text,{text:e.data.question,x:T.padding+8,y:T.padding,fontSize:T.questionFontSize,fontStyle:"bold",fill:"#111827",width:T.contentWidth,wrap:"word",listening:false}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:T.padding,y:T.questionHeight,width:T.contentWidth,height:T.feedbackHeight,fill:k().bg,cornerRadius:8}),jsx(Text,{x:T.padding,y:T.questionHeight,width:T.contentWidth,height:T.feedbackHeight,text:C(),fontSize:T.feedbackFontSize,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),jsx(Text,{text:"Answer:",x:T.padding,y:T.questionHeight+T.feedbackHeight+T.textareaMargin,fontSize:T.placeholderFontSize,fill:"#6b7280",width:T.contentWidth,wrap:"word",listening:false}),jsx(Rect,{x:T.padding,y:T.questionHeight+T.feedbackHeight+T.placeholderHeight,width:T.contentWidth,height:T.textareaHeight,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:T.padding,y:T.questionHeight+T.feedbackHeight+T.placeholderHeight},divProps:{style:{width:`${T.contentWidth}px`,height:`${T.textareaHeight}px`,pointerEvents:p?"none":"auto"}},children:jsx("textarea",{value:m,onChange:w=>y(w.target.value),disabled:p,placeholder:"Type your extended answer here...",className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"18px",pointerEvents:p?"none":"auto"}})}),jsx(Group,{y:T.questionHeight+T.feedbackHeight+T.placeholderHeight+T.textareaHeight+T.textareaMargin+T.buttonTopMargin,children:p&&jsxs(Group,{onMouseDown:()=>i("reset"),onMouseUp:()=>{i(null),S();},onMouseLeave:()=>i(null),onTouchStart:()=>i("reset"),onTouchEnd:()=>{i(null),S();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:T.padding,width:T.contentWidth,height:T.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:T.padding,width:T.contentWidth,height:T.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});ql.displayName="LongAnswer";var Uc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,onLongPress:s})=>{let{createHandlers:c}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(l=>jsx(ql,{longAnswer:l,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:u=>n(u,l.id),touchHandlers:c(l.id,"longAnswer")},l.id))})};var mo=1600,po=900,_c=3200,$c=1800,Ov=e=>{let o=0,t=0,a=mo,r=po;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:mo,height:po};let n=(l,u,f,d)=>{o=Math.min(o,l),t=Math.min(t,u),a=Math.max(a,l+f),r=Math.max(r,u+d);};e.lines?.forEach(l=>{if(l.points&&l.points.length>=2){let u=l.x||0,f=l.y||0,d=l.scaleX||1,i=l.scaleY||1;for(let m=0;m<l.points.length;m+=2){let h=u+l.points[m]*d,p=f+l.points[m+1]*i;o=Math.min(o,h),t=Math.min(t,p),a=Math.max(a,h),r=Math.max(r,p);}}}),e.images?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.videos?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.shapes?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.texts?.forEach(l=>n(l.x,l.y,l.width||200,l.height||l.fontSize||24)),e.flashcards?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.photoFrames?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.multipleChoices?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.trueFalses?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.shortAnswers?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.LongAnswer?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.fillInTheBlanks?.forEach(l=>n(l.x,l.y,l.width,l.height));let s=Math.min(a-o,_c),c=Math.min(r-t,$c);return o=Math.max(o,a-_c),t=Math.max(t,r-$c),{minX:o,minY:t,maxX:a,maxY:r,width:s,height:c}},Nv=(e,o,t={minX:0,minY:0,maxX:mo,maxY:po,width:mo,height:po})=>{let a=Math.max(t.width,mo),r=Math.max(t.height,po),n=e/o,s=a/r,c,l,u,f=0;if(n>s)l=r,c=Math.round(l*n),u=o/l;else {c=a,l=Math.round(c/n),u=e/c;let d=r*u;f=(o-d)/2;}return {scale:u,scaleX:u,scaleY:u,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:c,baseHeight:l,contentOffsetX:t.minX,contentOffsetY:t.minY}},Xc=(e,o,t=1)=>{let a=o.contentOffsetX||0,r=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/(o.scale*t)+a,y:(e.y-o.offsetY)/(o.scale*t)+r}},Hv=({onStageReady:e,onImagesLoaded:o,onSelectionChange:t,onTextEditingReady:a,onDirectDrawingCanvasReady:r,contextMenuConfig:n={enabled:true}}={})=>{let s=_e(),c=ze(),l=Q(L=>L.toolbar.selectedTool),u=Q(ve),f=Q(Ta),d=Q(Yn),i=Q(L=>L.canvas.zoomLevel),h=(u?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),p=!!h,x=useCallback(()=>{h&&s(Ya(h.id));},[s,h]),v=u?.editingActivity,g=u?.showMcqForm,y=u?.lines||[],S=useRef(null),C=useRef(null),[k,T]=useState(null),w=useRef(null),[b,I]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:mo,stageHeight:po,offsetX:0,offsetY:0,baseWidth:mo,baseHeight:po,contentOffsetX:0,contentOffsetY:0}),P=useMemo(()=>Ov(u||null),[f]),[H,O]=useState(null),[B,V]=useState(null),[U,K]=useState(null),[F,W]=useState(null),[te,X$1]=useState(null),[D,q]=useState(null),[j,J]=useState(null),[re,$]=useState(false),[ie,he]=useState(null),[fe,xe]=useState(false),[ye,we]=useState({}),yt=useRef(null),wt=useRef(null),wo=useRef(null),{debouncedGenerateThumbnail:So}=yu(f,S);useEffect(()=>{let L=()=>{if(C.current){let E=C.current.getBoundingClientRect(),N=Nv(E.width,E.height,P);I(N);}};L();let M=new ResizeObserver(L);return C.current&&M.observe(C.current),window.addEventListener("resize",L),()=>{M.disconnect(),window.removeEventListener("resize",L);}},[P]),useEffect(()=>{if(S.current){let L=S.current.container();L&&(L.style.cursor="");}},[l]);let ne=useCallback(()=>{S.current&&requestAnimationFrame(()=>{if(!S.current)return;if(S.current.getLayers().forEach(M=>M.batchDraw()),!d)try{So();}catch(M){console.warn("Preview generation failed (CORS):",M);}});},[So,d]),nn=useRef(f);useEffect(()=>{nn.current!==f&&(nn.current=f,ne());},[f,ne]);let sn=useRef(null),ln=useRef(true);useEffect(()=>{if(!u)return;let L=(u.lines?.length||0)+(u.images?.length||0)+(u.videos?.length||0)+(u.shapes?.length||0)+(u.texts?.length||0)+(u.flashcards?.length||0)+(u.photoFrames?.length||0)+(u.multipleChoices?.length||0)+(u.trueFalses?.length||0)+(u.shortAnswers?.length||0)+(u.LongAnswer?.length||0)+(u.fillInTheBlanks?.length||0),M=sn.current?.count!==L;!ln.current&&M&&setTimeout(()=>{ne();},100),sn.current={slideId:f,count:L},ln.current=false;},[u,f,ne]),useEffect(()=>{S.current&&e&&e(S);},[e]),useEffect(()=>{wo.current&&r&&r(wo);},[r]);let{startDrawing:dn,draw:un,stopDrawing:wa,setCanvasRef:_s,tool:$s,color:Xs,strokeWidth:Ys,isSketchMode:cn}=_d(ne),Sa=useRef(new Map),{images:Zs,getLoadedImage:Js,imageRefs:Lo,handleDragEnd:fn,handleImageTransformEnd:Qs,allImagesLoaded:mn}=eu(ne);useEffect(()=>{mn&&o?.();},[mn,o]);let{videos:lr,videoRefs:A,handleVideoClick:ae,handleVideoDragEnd:Ee,handleVideoTransformEnd:Ie}=ou(ne),{multipleChoice:ue,handleMcqTransform:se,mcqRefs:De,handleDragEnd:nt}=tu(ne),{trueFalse:sa,handleTrueFalseTransform:St,trueFalseRefs:Pe,handleTrueFalseDragEnd:st}=au(ne),{shortAnswers:ia,saRefs:Ft,handleShortAnswerDragEnd:ei}=du(ne),{longAnswers:ti,handleLongAnswerDragEnd:pn}=uu(ne),{fillInTheBlanks:jt,handleFillInTheBlanksDragEnd:La,fibRefs:ea}=Nc(ne),{transformerRef:me,boundBoxFunc:$a}=gu(),{shapes:Qm,shapeRefs:hn,isDragging:Md,handleShapeDragEnd:ep,handleShapeResizeEnd:tp}=su(ne),{texts:dr,textRefs:Ia,handleDragEnd:ap,handleTransformEnd:op,handleDoubleClick:rp,startEditing:gn,editingTextId:be,editingValue:Pd,handleEditingChange:Ad,finishEditing:ai}=lu(ne,yt);useEffect(()=>{a&&a(gn);},[a,gn]);let xn=Q(L=>L.canvas.editingTextId);useEffect(()=>{xn&&xn!==be&&gn(xn);},[xn,be,gn]);let{flashcards:np,flashcardRefs:bn,handleDragEnd:sp,handleFlashcardTransformEnd:ip,handleNext:lp,handlePrevious:dp}=fu(ne),{photoFrames:Ed,photoFrameRefs:vn,handleDragEnd:up,handlePhotoFrameTransformEnd:cp,startCamera:fp,capturePhoto:mp,cameraStreams:pp}=hu(ne);useEffect(()=>{if(me.current){if(be){me.current.nodes([]),me.current.getLayer()?.batchDraw();return}if(k&&!lr.find(E=>E.id===k)?.isPlaying){let E=Sa.current.get(k)||Lo.current.get(k)||A.current.get(k)||hn.current.get(k)||Ia.current.get(k)||De.current.get(k)||bn.current.get(k)||vn.current.get(k)||Ft.current.get(k)||Pe.current.get(k)||ea.current.get(k);if(E){let N=E.attrs?.locked;if(E.visible()&&N!==true){me.current.nodes([E]),me.current.getLayer()?.batchDraw();return}}}me.current.nodes([]),me.current.getLayer()?.batchDraw();}},[k,be,lr,Sa,Lo,A,hn,Ia,bn,vn,Ed,De,Pe,ea,me]);let We=useCallback(L=>{T(L),t?.(L);},[t]),Io=useCallback(()=>{T(null),t?.(null),me.current&&(me.current.nodes([]),me.current.getLayer()?.batchDraw());},[me,t]),Dd=useCallback(L=>u?u.lines?.some(M=>M.id===L)?"line":u.images?.some(M=>M.id===L)?"image":u.videos?.some(M=>M.id===L)?"video":u.shapes?.some(M=>M.id===L)?"shape":u.texts?.some(M=>M.id===L)?"text":u.flashcards?.some(M=>M.id===L)?"flashcard":u.photoFrames?.some(M=>M.id===L)?"photoFrame":u.multipleChoices?.some(M=>M.id===L)?"mcq":u.trueFalses?.some(M=>M.id===L)?"trueFalse":u.shortAnswers?.some(M=>M.id===L)?"shortAnswer":u.LongAnswer?.some(M=>M.id===L)?"longAnswer":u.fillInTheBlanks?.some(M=>M.id===L)?"fillInTheBlanks":null:null,[u]),Rd=useCallback((L,M)=>{switch(s(le()),M){case "line":s($n(L));break;case "image":s(wn(L));break;case "video":s(In(L));break;case "shape":s(Tn(L));break;case "text":s(Mn(L));break;case "flashcard":s(An(L));break;case "photoFrame":s(Dn(L));break;case "mcq":s(Fn(L));break;case "trueFalse":s(On(L));break;case "shortAnswer":s(Hn(L));break;case "longAnswer":s(Vn(L));break;case "fillInTheBlanks":s(Wn(L));break}Io(),ne();},[s,Io,ne]);useEffect(()=>{let L=M=>{if(M.key!=="Delete"&&M.key!=="Backspace"||!k||be)return;let E=document.activeElement;if(E instanceof HTMLInputElement||E instanceof HTMLTextAreaElement||E?.getAttribute("contenteditable")==="true")return;M.preventDefault();let Ce=Dd(k);Ce&&Rd(k,Ce);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[k,be,Dd,Rd]),useEffect(()=>{let L=me.current;return ()=>{L&&L.nodes([]);}},[f]),useEffect(()=>{let L=M=>{be&&M.target.tagName!=="TEXTAREA"&&ai();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[be,ai]),useEffect(()=>{let L=be||k;if(!L||k&&be){V(null);return}let M=Ia.current.get(L),E=S.current;if(!M||!E){V(null);return}let N=E.container().getBoundingClientRect(),Ce=M.absolutePosition(),ge=E.scaleX();V({x:N.left+(Ce.x+M.width()*ge/2)*ge+b.offsetX,y:N.top+Ce.y*ge+b.offsetY-70});},[k,be,dr,Ia,b.offsetX,b.offsetY]),useEffect(()=>{if(!be){K(null);return}let L=Ia.current.get(be),M=S.current;if(!L||!M){K(null);return}let E=L.getClientRect({relativeTo:M}),N=M.container().getBoundingClientRect(),Ce=M.scaleX(),ge=M.position(),oe={top:N.top+ge.y+E.y*Ce,left:N.left+ge.x+E.x*Ce,scale:Ce};K(oe),s(Ud(oe));},[be,dr,Ia,b.offsetY,b.offsetX]);let Fd=useCallback(L=>{let M=L.target.getClassName(),E=L.target===L.target.getStage(),N=M==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",Ce=M==="Image",ge=M==="Text",oe=M==="Group"||L.target.getParent()?.getClassName()==="Group",mt=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&L.target.attrs.id,pt=M==="Group";if(E&&!N&&!Ce&&!ge&&!oe&&!mt&&!pt&&Io(),!(l==="pen"||l==="eraser")&&(Ce||ge||N||oe||mt||pt))return;let Ue=L.target.getStage()?.getPointerPosition();if(!Ue)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(l)){let z=Xc(Ue,b,i);dn(z);}},[l,dn,Io,b,i]),Bd=useCallback(L=>{if(Md)return;let M=L.target.getStage()?.getPointerPosition();if(!M)return;let E=Xc(M,b,i);un(E);},[un,Md,b,i]),Od=useCallback(()=>{wa();},[wa]),hp=useCallback(L=>{let M=L.target.id();we(E=>{let N={...E};return delete N[M],N}),fn(L,ne);},[fn,ne]),gp=useCallback((L,M,E)=>{we(N=>({...N,[L]:{x:M,y:E}}));},[]),xp=useCallback(L=>{ae(L),We(L);},[ae,We]),Bt=useCallback((L,M,E)=>{if(L.preventDefault(),!n.enabled)return;let N=L.clientX,Ce=L.clientY,ge=w.current?.offsetHeight||250,oe=w.current?.offsetWidth||200,mt=window.innerHeight,pt=window.innerWidth,Qe=N,Ue=Ce;Ce+ge>mt&&(Ue=Ce-ge),N+oe>pt&&(Qe=N-oe),We(M),O({x:Qe,y:Ue,elementId:M,elementType:E});},[We,n.enabled]),Xa=useRef(null),ur=useRef(null),Lt=useCallback((L,M)=>E=>{if(!n.enabled)return;E.preventDefault();let N=E.changedTouches[0];if(!N)return;let Ce=N.clientX,ge=N.clientY,oe=w.current?.offsetHeight||200,mt=w.current?.offsetWidth||200,pt=window.innerHeight,Qe=window.innerWidth,Ue=Ce,et=ge;ge+oe>pt&&(et=ge-oe),Ce+mt>Qe&&(Ue=Ce-mt),We(L),O({x:Ue,y:et,elementId:L,elementType:M});},[We,n.enabled]),bp=useCallback((L,M)=>({onTouchStart:E=>{let N=E.evt.touches[0];ur.current={x:N.clientX,y:N.clientY},Xa.current=setTimeout(()=>{Lt(L,M)(E.evt);},500);},onTouchMove:E=>{if(!ur.current)return;let N=E.evt.touches[0],Ce=Math.abs(N.clientX-ur.current.x),ge=Math.abs(N.clientY-ur.current.y);(Ce>10||ge>10)&&Xa.current&&(clearTimeout(Xa.current),Xa.current=null);},onTouchEnd:()=>{Xa.current&&(clearTimeout(Xa.current),Xa.current=null),ur.current=null;}}),[Lt]),Nd=useCallback(L=>{s(xr(L)),s(ka(true));},[s]),Hd=useCallback(L=>{s(gr(L)),s(eo(true));},[s]),vp=useCallback((L,M)=>{if(!H)return;let{elementId:E,elementType:N}=H;switch(L){case "order":if(M){let R=M.target.getBoundingClientRect();W({x:R.right+5,y:R.top,type:"order"});}break;case "lock":if(M){let R=M.target.getBoundingClientRect();W({x:R.right+5,y:R.top,type:"lock"});}break;case "link":if(O(null),N==="line")break;let Ce=u?N==="image"?u.images.find(R=>R.id===E):u.videos.find(R=>R.id===E):null;X$1({type:"link",defaultValue:Ce?.link||""});break;case "voice":if(O(null),N==="line")break;let ge=u?N==="image"?u.images.find(R=>R.id===E):N==="video"?u.videos.find(R=>R.id===E):N==="text"?u.texts.find(R=>R.id===E):N==="flashcard"?u.flashcards.find(R=>R.id===E):N==="photoFrame"?u.photoFrames.find(R=>R.id===E):N==="mcq"?u.multipleChoices.find(R=>R.id===E):N==="fillInTheBlanks"?u.fillInTheBlanks.find(R=>R.id===E):N==="longAnswer"?u.LongAnswer.find(R=>R.id===E):N==="shortAnswer"?u.shortAnswers.find(R=>R.id===E):N==="trueFalse"?u.trueFalses.find(R=>R.id===E):N==="shape"?u.shapes.find(R=>R.id===E):null:null;he({elementId:E,elementType:N,existingAudio:ge?.audioData});break;case "edit":O(null);let oe=null;N==="mcq"?oe=u?.multipleChoices.find(R=>R.id===E):N==="trueFalse"?oe=u?.trueFalses.find(R=>R.id===E):N==="shortAnswer"?oe=u?.shortAnswers.find(R=>R.id===E):N==="longAnswer"?oe=u?.LongAnswer.find(R=>R.id===E):N==="fillInTheBlanks"&&(oe=u?.fillInTheBlanks.find(R=>R.id===E)),oe&&Nd(oe);break;case "editFlashcard":O(null);let mt=u?.flashcards.find(R=>R.id===E);mt&&Hd(mt);break;case "color":O(null);let pt=u?.shapes.find(R=>R.id===E);q({elementId:E,elementType:"shape",defaultColor:pt?.color||"#096B76"});break;case "border":if(O(null),N==="shape"){s(le());let R=u?.shapes.find(ri=>ri.id===E);R&&s(Za({id:E,hasBorder:!R.hasBorder})),ne();}break;case "crop":if(O(null),N==="image"){let R=u?.images.find(ri=>ri.id===E);R&&J({elementId:E,imageSrc:R.src});}break;case "draw":O(null),N==="image"?s(bi(E)):N==="photoFrame"&&s(yi(E));break;case "duplicate":s(le()),N==="line"?s(Ri(E)):N==="image"?s(Sn(E)):N==="video"?s(Cn(E)):N==="shape"?s(kn(E)):N==="text"?s(Pn(E)):N==="flashcard"?s(En(E)):N==="photoFrame"?s(Rn(E)):N==="mcq"?s(Bn(E)):N==="trueFalse"?s(Nn(E)):N==="shortAnswer"?s(qn(E)):N==="fillInTheBlanks"?s(Un(E)):N==="longAnswer"&&s(zn(E)),ne();break;case "infinite-clone":s(le());let Qe=5;for(let R=0;R<Qe;R++)N==="image"?s(Sn(E)):N==="video"?s(Cn(E)):N==="shape"?s(kn(E)):N==="text"?s(Pn(E)):N==="flashcard"?s(En(E)):N==="photoFrame"?s(Rn(E)):N==="mcq"?s(Bn(E)):N==="trueFalse"?s(Nn(E)):N==="shortAnswer"?s(qn(E)):N==="fillInTheBlanks"?s(Un(E)):N==="longAnswer"&&s(zn(E));ne();break;case "make-response":if(O(null),N==="line")break;let Ue=`#response-${E}`;s(le()),s(Kn({id:E,type:N,link:Ue})),(u?N==="image"?u.images.find(R=>R.id===E):N==="video"?u.videos.find(R=>R.id===E):N==="shape"?u.shapes.find(R=>R.id===E):N==="flashcard"?u.flashcards.find(R=>R.id===E):N==="photoFrame"?u.photoFrames.find(R=>R.id===E):u.multipleChoices.find(R=>R.id===E):null)?.altText||s(Gn({id:E,type:N,altText:"Interactive response area"})),ne(),console.log(`Element ${E} marked as interactive response area`);break;case "accessibility":if(O(null),N==="line")break;let z=u?N==="image"?u.images.find(R=>R.id===E):N==="video"?u.videos.find(R=>R.id===E):N==="shape"?u.shapes.find(R=>R.id===E):null:null;X$1({type:"altText",defaultValue:z?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),O(null),xe(true),console.log("showLayersPanel state set to:",true);break;case "delete":s(le()),N==="line"?s($n(E)):N==="image"?s(wn(E)):N==="video"?s(In(E)):N==="shape"?s(Tn(E)):N==="text"?s(Mn(E)):N==="flashcard"?s(An(E)):N==="photoFrame"?s(Dn(E)):N==="mcq"?s(Fn(E)):N==="trueFalse"?s(On(E)):N==="shortAnswer"?s(Hn(E)):N==="longAnswer"?s(Vn(E)):N==="fillInTheBlanks"&&s(Wn(E)),Io(),ne();break}},[H,s,ne,Io,u,Nd,Hd]),yp=useCallback(()=>{O(null),W(null);},[]),oi=useCallback(L=>{if(!H)return;let{elementId:M,elementType:E}=H;switch(s(le()),L){case "bring-to-front":E!=="line"&&s(Pi({id:M,type:E}));break;case "send-to-back":E!=="line"&&s(Ai({id:M,type:E}));break;case "lock":case "unlock":E!=="line"&&s(Ei({id:M,type:E}));break}ne(),O(null),W(null);},[H,s,ne]),wp=useCallback(L=>{if(!H||!te)return;let{elementId:M,elementType:E}=H;s(le()),te.type==="link"&&E!=="line"?s(Kn({id:M,type:E,link:L})):te.type==="altText"&&E!=="line"&&s(Gn({id:M,type:E,altText:L})),ne(),X$1(null);},[H,te,s,ne]),Sp=useCallback(L=>{if(!ie)return;let{elementId:M,elementType:E}=ie;s(le()),s(jn({id:M,type:E,audioData:L})),ne(),he(null);},[ie,s,ne]),Lp=useCallback(()=>{if(!ie)return;let{elementId:L,elementType:M}=ie;s(le()),s(jn({id:L,type:M,audioData:""})),ne();},[ie,s,ne]),Ip=useCallback(L=>{if(!D)return;let{elementId:M}=D;s(le()),s(Za({id:M,color:L})),ne(),q(null);},[D,s,ne]),Cp=useCallback(L=>{if(!j)return;let{elementId:M}=j;s(le()),s(ko({id:M,src:L})),ne(),J(null);},[j,s,ne]);return jsxs("div",{ref:C,className:"fixed inset-0",style:{cursor:l==="pen"?"crosshair":l==="eraser"?"":"default"},children:[l==="pen"&&jsx(Jd,{ref:L=>{if(wt.current=L,_s(L),L){let M=L.getCanvasElement();M&&(wo.current=M,r&&r(wo));}},width:b.baseWidth,height:b.baseHeight,tool:$s,color:Xs,strokeWidth:Ys/(b.scale*i),isSketchMode:cn,xOffset:b.contentOffsetX,yOffset:b.contentOffsetY-b.offsetY/b.scale,style:{width:b.stageWidth,height:b.stageHeight}}),jsxs(Stage,{ref:S,width:b.stageWidth,height:b.stageHeight,scaleX:b.scaleX*i,scaleY:b.scaleY*i,x:b.offsetX,y:0,onMouseDown:Fd,onMouseMove:Bd,onMouseUp:Od,onTouchStart:Fd,onTouchMove:Bd,onTouchEnd:Od,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:b.baseWidth,height:b.stageHeight/b.scale,fill:u?.backgroundColor||"white"})}),jsx(Layer,{x:-b.contentOffsetX,y:b.offsetY/b.scale-b.contentOffsetY,children:(()=>{let L=[];return y.forEach((M,E)=>{L.push({type:"line",timestamp:M.timestamp||E,element:{...M,id:M.id??`line-${E}`},index:E});}),Qm.forEach(M=>{L.push({type:"shape",timestamp:M.timestamp||0,element:M});}),Zs.forEach(M=>{L.push({type:"image",timestamp:M.timestamp||0,element:M});}),lr.forEach(M=>{L.push({type:"video",timestamp:M.timestamp||0,element:M});}),dr.forEach(M=>{L.push({type:"text",timestamp:M.timestamp||0,element:M});}),np.forEach(M=>{L.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Ed.forEach(M=>{L.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),ue.forEach(M=>{L.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),sa.forEach(M=>{L.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),ia.forEach(M=>{L.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),ti.forEach(M=>{L.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),jt.forEach(M=>{L.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),L.sort((M,E)=>M.timestamp-E.timestamp),L.map((M,E)=>{let N=`${M.type}-${"id"in M.element&&M.element.id||M.index||E}`,Ce="id"in M.element?M.element.id:void 0,ge=Ce&&k===Ce;switch(M.type){case "line":let oe=M.element,mt=M.index||0,pt=oe.tool==="eraser",Qe=oe.isSketch&&oe.tool==="pen",Ue=oe.isSketch&&pt,et=oe.id||`line-${mt}`;return oe.x===void 0&&(oe.x=0),oe.y===void 0&&(oe.y=0),oe.scaleX===void 0&&(oe.scaleX=1),oe.scaleY===void 0&&(oe.scaleY=1),oe.rotation===void 0&&(oe.rotation=0),l==="eraser"?jsx(Group,{x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,children:jsx(Line,{points:oe.points||[],stroke:Qe||Ue?void 0:oe.color,strokeWidth:Qe||Ue?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Qe||Ue?pt?"black":oe.color:void 0,closed:Qe||Ue,tension:0,globalCompositeOperation:pt?"destination-out":"source-over",listening:true,onClick:()=>{s(le()),s(yn(mt));},onTap:()=>{s(le()),s(yn(mt));},hitStrokeWidth:Math.max(20,(oe.strokeWidth??0)*2),onMouseEnter:z=>{let R=z.target.getStage();R&&(R.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:z=>{let R=z.target.getStage();R&&(R.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},N):jsxs(Le__default.Fragment,{children:[jsx(Group,{id:et,ref:z=>{z?Sa.current.set(et,z):Sa.current.delete(et);},x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,draggable:l==="select",listening:l==="select",onClick:()=>{l==="select"&&(console.log("Line clicked:",et),We(et));},onTap:()=>{l==="select"&&(console.log("Line tapped:",et),We(et));},onDragEnd:z=>{s(le()),s(_n({id:et,x:z.target.x(),y:z.target.y(),scaleX:z.target.scaleX(),scaleY:z.target.scaleY(),rotation:z.target.rotation()})),ne();},onTransformEnd:z=>{s(le()),s(_n({id:et,x:z.target.x(),y:z.target.y(),scaleX:z.target.scaleX(),scaleY:z.target.scaleY(),rotation:z.target.rotation()})),ne();},onMouseEnter:z=>{if(l==="select"){let R=z.target.getStage();R&&(R.container().style.cursor="move");}},onMouseLeave:z=>{if(l==="select"){let R=z.target.getStage();R&&(R.container().style.cursor="default");}},onContextMenu:z=>{let R=z.evt;R.preventDefault(),Bt(R,et,"line");},...bp(et,"line"),children:jsx(Line,{points:oe.points||[],stroke:Qe||Ue?void 0:oe.color,strokeWidth:Qe||Ue?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Qe||Ue?pt?"black":oe.color:void 0,closed:Qe||Ue,tension:0,globalCompositeOperation:pt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=Sa.current.get(k);console.log("Line Transformer - selectedId:",k,"node found:",!!R),R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:$a,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"]})]},N);case "shape":return jsxs(Le__default.Fragment,{children:[jsx(Yi,{onSelect:We,shapes:[M.element],shapeRefs:hn,handleShapeDragEnd:ep,handleShapeResizeEnd:tp,onContextMenu:Bt,onLongPress:Lt}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=hn.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},boundBoxFunc:$a,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"]})]},N);case "image":return jsxs(Le__default.Fragment,{children:[jsx(ji,{images:[M.element],getLoadedImage:Js,imageRefs:Lo,onDragEnd:hp,onDragMove:gp,onTransform:Qs,onSelect:We,onContextMenu:Bt,onLongPress:Lt}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=Lo.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},boundBoxFunc:$a,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"]})]},N);case "video":return jsxs(Le__default.Fragment,{children:[jsx(Xi,{videos:[M.element],selectedId:k,videoRefs:A,onVideoClick:xp,onDragEnd:Ee,onTransformEnd:Ie,onContextMenu:Bt,onLongPress:Lt}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=A.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},boundBoxFunc:$a,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"]})]},N);case "text":return jsxs(Le__default.Fragment,{children:[jsx(Du,{texts:[M.element],textRefs:Ia,onDragEnd:ap,onTransformEnd:op,onSelect:We,onContextMenu:Bt,onLongPress:Lt,onDoubleClick:rp,editingTextId:be,editingValue:Pd,onEditingChange:Ad}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=Ia.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},boundBoxFunc:$a,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"]})]},N);case "flashcard":return jsxs(Le__default.Fragment,{children:[jsx(el,{flashcards:[M.element],flashcardRefs:bn,selectedId:k,onDragEnd:sp,onTransform:ip,onSelect:We,onNext:lp,onPrevious:dp,onContextMenu:Bt,onLongPress:Lt}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=bn.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},boundBoxFunc:$a,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"]})]},N);case "photoFrame":return jsxs(Le__default.Fragment,{children:[jsx(sl,{photoFrames:[M.element],photoFrameRefs:vn,selectedId:k,onDragEnd:up,onTransform:cp,onSelect:We,onStartCamera:fp,onCapture:mp,cameraStreams:pp,onContextMenu:Bt,onLongPress:Lt}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=vn.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},boundBoxFunc:$a,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"]})]},N);case "mcq":return jsxs(Le__default.Fragment,{children:[jsx(cc,{handleMcqTransform:se,multipleChoice:[M.element],handleSelect:We,mcqRefs:De,handleDragEnd:nt,onContextMenu:Bt,onLongPress:Lt,onUpdate:ne}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=De.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},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"]})]},N);case "trueFalse":return jsxs(Le__default.Fragment,{children:[jsx(hc,{trueFalses:[M.element],handleTrueFalseTransform:St,handleSelect:We,trueFalseRefs:Pe,onContextMenu:Bt,onLongPress:Lt,handleDragEnd:st,onUpdate:ne}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=Pe.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},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"]})]},N);case "shortAnswer":return jsxs(Le__default.Fragment,{children:[jsx(Oc,{shortAnswers:[M.element],handleSelect:We,handleTransform:se,saRefs:Ft,onContextMenu:Bt,onLongPress:Lt,handleDragEnd:ei}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=Ft.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},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"]})]},N);case "longAnswer":return jsxs(Le__default.Fragment,{children:[jsx(Uc,{longAnswer:[M.element],handleSelect:We,handleTransform:se,saRefs:Ft,onContextMenu:Bt,onLongPress:Lt,handleDragEnd:pn}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=Ft.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},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"]})]},N);case "fillInTheBlanks":return jsxs(Le__default.Fragment,{children:[jsx(zc,{fillInTheBlanks:[M.element],handleSelect:We,handleTransform:se,onContextMenu:Bt,onLongPress:Lt,handleDragEnd:La,fibRefs:ea}),ge&&!be&&k&&jsx(Transformer,{ref:z=>{if(z&&me.current!==z){me.current=z;let R=ea.current.get(k);R&&R.visible()&&(z.nodes([R]),z.getLayer()?.batchDraw());}},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"]})]},N);default:return null}})})()})]}),H&&jsx(Gu,{menuRef:w,x:H.x,y:H.y,type:H.elementType,onAction:vp,onClose:yp,isDrawingMode:H.elementType==="image"?u?.images.find(L=>L.id===H.elementId)?.isDrawingMode:H.elementType==="photoFrame"?u?.photoFrames.find(L=>L.id===H.elementId)?.isDrawingMode:false}),F&&H&&jsx(ju,{x:F.x,y:F.y,items:F.type==="order"?[{label:"Bring to Front",onClick:()=>oi("bring-to-front")},{label:"Send to Back",onClick:()=>oi("send-to-back")}]:[{label:u&&(H.elementType==="image"?u.images.find(L=>L.id===H.elementId)?.locked:u.videos.find(L=>L.id===H.elementId)?.locked)?"Unlock":"Lock",onClick:()=>oi(u&&(H.elementType==="image"?u.images.find(L=>L.id===H.elementId)?.locked:u.videos.find(L=>L.id===H.elementId)?.locked)?"unlock":"lock")}],onClose:()=>W(null)}),te&&jsx(Xu,{title:te.type==="link"?"Add Link":"Add Alt Text",label:te.type==="link"?"URL":"Alternative Text",placeholder:te.type==="link"?"https://example.com":"Describe this image/video",defaultValue:te.defaultValue,onSave:wp,onClose:()=>X$1(null)}),D&&jsx(os,{defaultColor:D.defaultColor,onConfirm:Ip,onCancel:()=>q(null)}),j&&jsx(Qu,{imageSrc:j.imageSrc,onConfirm:Cp,onCancel:()=>J(null)}),re&&jsx(to,{onClose:()=>$(false),stageRef:S}),ie&&jsx(oc,{elementId:ie.elementId,elementType:ie.elementType,existingAudio:ie.existingAudio,onSave:Sp,onDelete:Lp,onClose:()=>he(null)}),fe&&jsx(ic,{selectedElementId:k||void 0,onClose:()=>xe(false),onSelectElement:L=>{We(L),xe(false);}}),u?.images.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.videos.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.shapes?.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.texts?.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.flashcards?.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(qt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${L.id}`)),u?.images.filter(L=>L.link).map(L=>{let M=ye[L.id];return jsx(rc,{link:L.link,x:M?.x??L.x,y:M?.y??L.y,width:L.width,height:L.height,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`link-${L.id}`)}),g&&jsx(kc,{editElement:v}),B&&(()=>{let L=be||k;if(!L)return null;let M=dr.find(E=>E.id===L);return M?jsx(Ac,{text:M,position:B}):null})(),U&&be&&(()=>{let L=dr.find(M=>M.id===be);return L?jsx(Dc,{text:L,editingValue:Pd,onEditingChange:Ad,onFinish:ai,position:{top:U.top,left:U.left},scale:U.scale,textareaRef:yt},be):null})(),p&&c&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:h?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:x})}),jsx("button",{onClick:x,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),c)]})},qv=Hv;var zv="SchooplaVideoStorage";var oa="videos",Ms=()=>new Promise((e,o)=>{let t=indexedDB.open(zv,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(oa)||r.createObjectStore(oa,{keyPath:"id"});};}),ca=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Ms(),n=a.transaction([oa],"readwrite").objectStore(oa),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((c,l)=>{let u=n.put(s);u.onsuccess=()=>c(!0),u.onerror=()=>l(u.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var Yc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Ms(),t=e.transaction([oa],"readonly").objectStore(oa);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result,c=new Map;s.forEach(l=>{c.set(l.id,{blob:l.blob,thumbnailDataUrl:l.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${c.size} video blobs from IndexedDB`),a(c);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Vl=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Ms(),a=o.transaction([oa],"readwrite").objectStore(oa);await new Promise((r,n)=>{let s=a.delete(e);s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Zc=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Ms(),t=e.transaction([oa],"readwrite").objectStore(oa);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Jc=e=>URL.createObjectURL(e);function za(e,o=[]){let t=[];function a(n,s){let c=Le.createContext(s),l=t.length;t=[...t,s];let u=d=>{let{scope:i,children:m,...h}=d,p=i?.[e]?.[l]||c,x=Le.useMemo(()=>h,Object.values(h));return jsx(p.Provider,{value:x,children:m})};u.displayName=n+"Provider";function f(d,i){let m=i?.[e]?.[l]||c,h=Le.useContext(m);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${n}\``)}return [u,f]}let r=()=>{let n=t.map(s=>Le.createContext(s));return function(c){let l=c?.[e]||n;return Le.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return r.scopeName=e,[a,Uv(r,...o)]}function Uv(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(n){let s=a.reduce((c,{useScope:l,scopeName:u})=>{let d=l(n)[`__scope${u}`];return {...c,...d}},{});return Le.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function Qc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Xr(...e){return o=>{let t=false,a=e.map(r=>{let n=Qc(r,o);return !t&&typeof n=="function"&&(t=true),n});if(t)return ()=>{for(let r=0;r<a.length;r++){let n=a[r];typeof n=="function"?n():Qc(e[r],null);}}}}function Kt(...e){return Le.useCallback(Xr(...e),e)}function af(e){let o=Kv(e),t=Le.forwardRef((a,r)=>{let{children:n,...s}=a,c=Le.Children.toArray(n),l=c.find(jv);if(l){let u=l.props.children,f=c.map(d=>d===l?Le.Children.count(u)>1?Le.Children.only(null):Le.isValidElement(u)?u.props.children:null:d);return jsx(o,{...s,ref:r,children:Le.isValidElement(u)?Le.cloneElement(u,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function Kv(e){let o=Le.forwardRef((t,a)=>{let{children:r,...n}=t;if(Le.isValidElement(r)){let s=$v(r),c=_v(n,r.props);return r.type!==Le.Fragment&&(c.ref=a?Xr(a,s):s),Le.cloneElement(r,c)}return Le.Children.count(r)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Gv=Symbol("radix.slottable");function jv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Gv}function _v(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let l=n(...c);return r(...c),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function $v(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 Zv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],bt=Zv.reduce((e,o)=>{let t=af(`Primitive.${o}`),a=Le.forwardRef((r,n)=>{let{asChild:s,...c}=r,l=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(l,{...c,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function ot(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function zl(e){let o=Jv(e),t=Le.forwardRef((a,r)=>{let{children:n,...s}=a,c=Le.Children.toArray(n),l=c.find(ey);if(l){let u=l.props.children,f=c.map(d=>d===l?Le.Children.count(u)>1?Le.Children.only(null):Le.isValidElement(u)?u.props.children:null:d);return jsx(o,{...s,ref:r,children:Le.isValidElement(u)?Le.cloneElement(u,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function Jv(e){let o=Le.forwardRef((t,a)=>{let{children:r,...n}=t;if(Le.isValidElement(r)){let s=ay(r),c=ty(n,r.props);return r.type!==Le.Fragment&&(c.ref=a?Xr(a,s):s),Le.cloneElement(r,c)}return Le.Children.count(r)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Qv=Symbol("radix.slottable");function ey(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Qv}function ty(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let l=n(...c);return r(...c),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function ay(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function Ps(e){let o=e+"CollectionProvider",[t,a]=za(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=p=>{let{scope:x,children:v}=p,g=Le__default.useRef(null),y=Le__default.useRef(new Map).current;return jsx(r,{scope:x,itemMap:y,collectionRef:g,children:v})};s.displayName=o;let c=e+"CollectionSlot",l=zl(c),u=Le__default.forwardRef((p,x)=>{let{scope:v,children:g}=p,y=n(c,v),S=Kt(x,y.collectionRef);return jsx(l,{ref:S,children:g})});u.displayName=c;let f=e+"CollectionItemSlot",d="data-radix-collection-item",i=zl(f),m=Le__default.forwardRef((p,x)=>{let{scope:v,children:g,...y}=p,S=Le__default.useRef(null),C=Kt(x,S),k=n(f,v);return Le__default.useEffect(()=>(k.itemMap.set(S,{ref:S,...y}),()=>void k.itemMap.delete(S))),jsx(i,{[d]:"",ref:C,children:g})});m.displayName=f;function h(p){let x=n(e+"CollectionConsumer",p);return Le__default.useCallback(()=>{let g=x.collectionRef.current;if(!g)return [];let y=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(x.itemMap.values()).sort((k,T)=>y.indexOf(k.ref.current)-y.indexOf(T.ref.current))},[x.collectionRef,x.itemMap])}return [{Provider:s,Slot:u,ItemSlot:m},h,a]}var Jo=globalThis?.document?Le.useLayoutEffect:()=>{};var oy=Le[" useId ".trim().toString()]||(()=>{}),ry=0;function sf(e){let[o,t]=Le.useState(oy());return Jo(()=>{t(a=>a??String(ry++));},[e]),(o?`radix-${o}`:"")}function lf(e){let o=Le.useRef(e);return Le.useEffect(()=>{o.current=e;}),Le.useMemo(()=>(...t)=>o.current?.(...t),[])}var ny=Le[" useInsertionEffect ".trim().toString()]||Jo;function ma({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,s]=sy({defaultProp:o,onChange:t}),c=e!==void 0,l=c?e:r;{let f=Le.useRef(e!==void 0);Le.useEffect(()=>{let d=f.current;d!==c&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=c;},[c,a]);}let u=Le.useCallback(f=>{if(c){let d=iy(f)?f(e):f;d!==e&&s.current?.(d);}else n(f);},[c,e,n,s]);return [l,u]}function sy({defaultProp:e,onChange:o}){let[t,a]=Le.useState(e),r=Le.useRef(t),n=Le.useRef(o);return ny(()=>{n.current=o;},[o]),Le.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function iy(e){return typeof e=="function"}var ly=Le.createContext(void 0);function er(e){let o=Le.useContext(ly);return e||o||"ltr"}var Kl="rovingFocusGroup.onEntryFocus",dy={bubbles:false,cancelable:true},Yr="RovingFocusGroup",[Gl,df,uy]=Ps(Yr),[cy,jl]=za(Yr,[uy]),[fy,my]=cy(Yr),uf=Le.forwardRef((e,o)=>jsx(Gl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Gl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(py,{...e,ref:o})})}));uf.displayName=Yr;var py=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:u,preventScrollOnEntryFocus:f=false,...d}=e,i=Le.useRef(null),m=Kt(o,i),h=er(n),[p,x]=ma({prop:s,defaultProp:c??null,onChange:l,caller:Yr}),[v,g]=Le.useState(false),y=lf(u),S=df(t),C=Le.useRef(false),[k,T]=Le.useState(0);return Le.useEffect(()=>{let w=i.current;if(w)return w.addEventListener(Kl,y),()=>w.removeEventListener(Kl,y)},[y]),jsx(fy,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:p,onItemFocus:Le.useCallback(w=>x(w),[x]),onItemShiftTab:Le.useCallback(()=>g(true),[]),onFocusableItemAdd:Le.useCallback(()=>T(w=>w+1),[]),onFocusableItemRemove:Le.useCallback(()=>T(w=>w-1),[]),children:jsx(bt.div,{tabIndex:v||k===0?-1:0,"data-orientation":a,...d,ref:m,style:{outline:"none",...e.style},onMouseDown:ot(e.onMouseDown,()=>{C.current=true;}),onFocus:ot(e.onFocus,w=>{let b=!C.current;if(w.target===w.currentTarget&&b&&!v){let I=new CustomEvent(Kl,dy);if(w.currentTarget.dispatchEvent(I),!I.defaultPrevented){let P=S().filter(U=>U.focusable),H=P.find(U=>U.active),O=P.find(U=>U.id===p),V=[H,O,...P].filter(Boolean).map(U=>U.ref.current);mf(V,f);}}C.current=false;}),onBlur:ot(e.onBlur,()=>g(false))})})}),cf="RovingFocusGroupItem",ff=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:s,...c}=e,l=sf(),u=n||l,f=my(cf,t),d=f.currentTabStopId===u,i=df(t),{onFocusableItemAdd:m,onFocusableItemRemove:h,currentTabStopId:p}=f;return Le.useEffect(()=>{if(a)return m(),()=>h()},[a,m,h]),jsx(Gl.ItemSlot,{scope:t,id:u,focusable:a,active:r,children:jsx(bt.span,{tabIndex:d?0:-1,"data-orientation":f.orientation,...c,ref:o,onMouseDown:ot(e.onMouseDown,x=>{a?f.onItemFocus(u):x.preventDefault();}),onFocus:ot(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:ot(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;let v=xy(x,f.orientation,f.dir);if(v!==void 0){if(x.metaKey||x.ctrlKey||x.altKey||x.shiftKey)return;x.preventDefault();let y=i().filter(S=>S.focusable).map(S=>S.ref.current);if(v==="last")y.reverse();else if(v==="prev"||v==="next"){v==="prev"&&y.reverse();let S=y.indexOf(x.currentTarget);y=f.loop?by(y,S+1):y.slice(S+1);}setTimeout(()=>mf(y));}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:p!=null}):s})})});ff.displayName=cf;var hy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function gy(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function xy(e,o,t){let a=gy(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return hy[a]}function mf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function by(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var pf=uf,hf=ff;var xf="Toggle",_l=Le.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[s,c]=ma({prop:t,onChange:r,defaultProp:a??false,caller:xf});return jsx(bt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:ot(e.onClick,()=>{e.disabled||c(!s);})})});_l.displayName=xf;var Wa="ToggleGroup",[vf]=za(Wa,[jl]),yf=jl(),$l=Le__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(wy,{...a,ref:o});if(t==="multiple")return jsx(Sy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Wa}\``)});$l.displayName=Wa;var[wf,Sf]=vf(Wa),wy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=ma({prop:t,defaultProp:a??"",onChange:r,caller:Wa});return jsx(wf,{scope:e.__scopeToggleGroup,type:"single",value:Le__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:c,onItemDeactivate:Le__default.useCallback(()=>c(""),[c]),children:jsx(Lf,{...n,ref:o})})}),Sy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=ma({prop:t,defaultProp:a??[],onChange:r,caller:Wa}),l=Le__default.useCallback(f=>c((d=[])=>[...d,f]),[c]),u=Le__default.useCallback(f=>c((d=[])=>d.filter(i=>i!==f)),[c]);return jsx(wf,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:l,onItemDeactivate:u,children:jsx(Lf,{...n,ref:o})})});$l.displayName=Wa;var[Ly,Iy]=vf(Wa),Lf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:s,loop:c=true,...l}=e,u=yf(t),f=er(s),d={role:"group",dir:f,...l};return jsx(Ly,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(pf,{asChild:true,...u,orientation:n,dir:f,loop:c,children:jsx(bt.div,{...d,ref:o})}):jsx(bt.div,{...d,ref:o})})}),Ds="ToggleGroupItem",Cy=Le__default.forwardRef((e,o)=>{let t=Sf(Ds,e.__scopeToggleGroup),a=Iy(Ds,e.__scopeToggleGroup),r=yf(e.__scopeToggleGroup),n=t.value.includes(e.value),s=a.disabled||e.disabled,c={...e,pressed:n,disabled:s},l=Le__default.useRef(null);return a.rovingFocus?jsx(hf,{asChild:true,...r,focusable:!s,active:n,ref:l,children:jsx(bf,{...c,ref:o})}):jsx(bf,{...c,ref:o})});Cy.displayName=Ds;var bf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=Sf(Ds,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=n.type==="single"?s:void 0;return jsx(_l,{...c,...r,ref:o,onPressedChange:l=>{l?n.onItemActivate(a):n.onItemDeactivate(a);}})}),If=$l;function Cf(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=Cf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Rs(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=Cf(e))&&(a&&(a+=" "),a+=o);return a}var Ty=(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},My=(e,o)=>({classGroupId:e,validator:o}),Af=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var kf=[],Py="arbitrary..",Ay=e=>{let o=Dy(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return Ey(s);let c=s.split("-"),l=c[0]===""&&c.length>1?1:0;return Ef(c,l,o)},getConflictingClassGroupIds:(s,c)=>{if(c){let l=a[s],u=t[s];return l?u?Ty(u,l):l:u||kf}return t[s]||kf}}},Ef=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let u=Ef(e,o+1,n);if(u)return u}let s=t.validators;if(s===null)return;let c=o===0?e.join("-"):e.slice(o).join("-"),l=s.length;for(let u=0;u<l;u++){let f=s[u];if(f.validator(c))return f.classGroupId}},Ey=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?Py+a:void 0})(),Dy=e=>{let{theme:o,classGroups:t}=e;return Ry(t,o)},Ry=(e,o)=>{let t=Af();for(let a in e){let r=e[a];Zl(r,t,a,o);}return t},Zl=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let s=e[n];Fy(s,o,t,a);}},Fy=(e,o,t,a)=>{if(typeof e=="string"){By(e,o,t);return}if(typeof e=="function"){Oy(e,o,t,a);return}Ny(e,o,t,a);},By=(e,o,t)=>{let a=e===""?o:Df(o,e);a.classGroupId=t;},Oy=(e,o,t,a)=>{if(Hy(e)){Zl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(My(t,e));},Ny=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let s=0;s<n;s++){let[c,l]=r[s];Zl(l,Df(o,c),t,a);}},Df=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let n=0;n<r;n++){let s=a[n],c=t.nextPart.get(s);c||(c=Af(),t.nextPart.set(s,c)),t=c;}return t},Hy=e=>"isThemeGetter"in e&&e.isThemeGetter===true,qy=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(n,s)=>{t[n]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(n){let s=t[n];if(s!==void 0)return s;if((s=a[n])!==void 0)return r(n,s),s},set(n,s){n in t?t[n]=s:r(n,s);}}};var Vy=[],Tf=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),zy=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],s=0,c=0,l=0,u,f=r.length;for(let p=0;p<f;p++){let x=r[p];if(s===0&&c===0){if(x===":"){n.push(r.slice(l,p)),l=p+1;continue}if(x==="/"){u=p;continue}}x==="["?s++:x==="]"?s--:x==="("?c++:x===")"&&c--;}let d=n.length===0?r:r.slice(l),i=d,m=false;d.endsWith("!")?(i=d.slice(0,-1),m=true):d.startsWith("!")&&(i=d.slice(1),m=true);let h=u&&u>l?u-l:void 0;return Tf(n,m,i,h)};if(o){let r=o+":",n=a;a=s=>s.startsWith(r)?n(s.slice(r.length)):Tf(Vy,false,s,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},Wy=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let n=0;n<t.length;n++){let s=t[n],c=s[0]==="[",l=o.has(s);c||l?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(s)):r.push(s);}return r.length>0&&(r.sort(),a.push(...r)),a}},Uy=e=>({cache:qy(e.cacheSize),parseClassName:zy(e),sortModifiers:Wy(e),...Ay(e)}),Ky=/\s+/,Gy=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,s=[],c=e.trim().split(Ky),l="";for(let u=c.length-1;u>=0;u-=1){let f=c[u],{isExternal:d,modifiers:i,hasImportantModifier:m,baseClassName:h,maybePostfixModifierPosition:p}=t(f);if(d){l=f+(l.length>0?" "+l:l);continue}let x=!!p,v=a(x?h.substring(0,p):h);if(!v){if(!x){l=f+(l.length>0?" "+l:l);continue}if(v=a(h),!v){l=f+(l.length>0?" "+l:l);continue}x=false;}let g=i.length===0?"":i.length===1?i[0]:n(i).join(":"),y=m?g+"!":g,S=y+v;if(s.indexOf(S)>-1)continue;s.push(S);let C=r(v,x);for(let k=0;k<C.length;++k){let T=C[k];s.push(y+T);}l=f+(l.length>0?" "+l:l);}return l},jy=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=Rf(t))&&(r&&(r+=" "),r+=a);return r},Rf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Rf(e[a]))&&(t&&(t+=" "),t+=o);return t},_y=(e,...o)=>{let t,a,r,n,s=l=>{let u=o.reduce((f,d)=>d(f),e());return t=Uy(u),a=t.cache.get,r=t.cache.set,n=c,c(l)},c=l=>{let u=a(l);if(u)return u;let f=Gy(l,t);return r(l,f),f};return n=s,(...l)=>n(jy(...l))},$y=[],je=e=>{let o=t=>t[e]||$y;return o.isThemeGetter=true,o},Ff=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Bf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Xy=/^\d+\/\d+$/,Yy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Zy=/\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$/,Jy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Qy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ew=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,tr=e=>Xy.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ua=e=>!!e&&Number.isInteger(Number(e)),Xl=e=>e.endsWith("%")&&de(e.slice(0,-1)),pa=e=>Yy.test(e),tw=()=>true,aw=e=>Zy.test(e)&&!Jy.test(e),Of=()=>false,ow=e=>Qy.test(e),rw=e=>ew.test(e),nw=e=>!Y(e)&&!Z(e),sw=e=>ar(e,qf,Of),Y=e=>Ff.test(e),xo=e=>ar(e,Vf,aw),Yl=e=>ar(e,cw,de),Mf=e=>ar(e,Nf,Of),iw=e=>ar(e,Hf,rw),Fs=e=>ar(e,zf,ow),Z=e=>Bf.test(e),Zr=e=>or(e,Vf),lw=e=>or(e,fw),Pf=e=>or(e,Nf),dw=e=>or(e,qf),uw=e=>or(e,Hf),Bs=e=>or(e,zf,true),ar=(e,o,t)=>{let a=Ff.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},or=(e,o,t=false)=>{let a=Bf.exec(e);return a?a[1]?o(a[1]):t:false},Nf=e=>e==="position"||e==="percentage",Hf=e=>e==="image"||e==="url",qf=e=>e==="length"||e==="size"||e==="bg-size",Vf=e=>e==="length",cw=e=>e==="number",fw=e=>e==="family-name",zf=e=>e==="shadow";var mw=()=>{let e=je("color"),o=je("font"),t=je("text"),a=je("font-weight"),r=je("tracking"),n=je("leading"),s=je("breakpoint"),c=je("container"),l=je("spacing"),u=je("radius"),f=je("shadow"),d=je("inset-shadow"),i=je("text-shadow"),m=je("drop-shadow"),h=je("blur"),p=je("perspective"),x=je("aspect"),v=je("ease"),g=je("animate"),y=()=>["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"],C=()=>[...S(),Z,Y],k=()=>["auto","hidden","clip","visible","scroll"],T=()=>["auto","contain","none"],w=()=>[Z,Y,l],b=()=>[tr,"full","auto",...w()],I=()=>[Ua,"none","subgrid",Z,Y],P=()=>["auto",{span:["full",Ua,Z,Y]},Ua,Z,Y],H=()=>[Ua,"auto",Z,Y],O=()=>["auto","min","max","fr",Z,Y],B=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],V=()=>["start","end","center","stretch","center-safe","end-safe"],U=()=>["auto",...w()],K=()=>[tr,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...w()],F=()=>[e,Z,Y],W=()=>[...S(),Pf,Mf,{position:[Z,Y]}],te=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",dw,sw,{size:[Z,Y]}],D=()=>[Xl,Zr,xo],q=()=>["","none","full",u,Z,Y],j=()=>["",de,Zr,xo],J=()=>["solid","dashed","dotted","double"],re=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],$=()=>[de,Xl,Pf,Mf],ie=()=>["","none",h,Z,Y],he=()=>["none",de,Z,Y],fe=()=>["none",de,Z,Y],xe=()=>[de,Z,Y],ye=()=>[tr,"full",...w()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[pa],breakpoint:[pa],color:[tw],container:[pa],"drop-shadow":[pa],ease:["in","out","in-out"],font:[nw],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[pa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[pa],shadow:[pa],spacing:["px",de],text:[pa],"text-shadow":[pa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",tr,Y,Z,x]}],container:["container"],columns:[{columns:[de,Y,Z,c]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:C()}],overflow:[{overflow:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:b()}],"inset-x":[{"inset-x":b()}],"inset-y":[{"inset-y":b()}],start:[{start:b()}],end:[{end:b()}],top:[{top:b()}],right:[{right:b()}],bottom:[{bottom:b()}],left:[{left:b()}],visibility:["visible","invisible","collapse"],z:[{z:[Ua,"auto",Z,Y]}],basis:[{basis:[tr,"full","auto",c,...w()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,tr,"auto","initial","none",Y]}],grow:[{grow:["",de,Z,Y]}],shrink:[{shrink:["",de,Z,Y]}],order:[{order:[Ua,"first","last","none",Z,Y]}],"grid-cols":[{"grid-cols":I()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":I()}],"row-start-end":[{row:P()}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":O()}],"auto-rows":[{"auto-rows":O()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...B(),"normal"]}],"justify-items":[{"justify-items":[...V(),"normal"]}],"justify-self":[{"justify-self":["auto",...V()]}],"align-content":[{content:["normal",...B()]}],"align-items":[{items:[...V(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...V(),{baseline:["","last"]}]}],"place-content":[{"place-content":B()}],"place-items":[{"place-items":[...V(),"baseline"]}],"place-self":[{"place-self":["auto",...V()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:U()}],mx:[{mx:U()}],my:[{my:U()}],ms:[{ms:U()}],me:[{me:U()}],mt:[{mt:U()}],mr:[{mr:U()}],mb:[{mb:U()}],ml:[{ml:U()}],"space-x":[{"space-x":w()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":w()}],"space-y-reverse":["space-y-reverse"],size:[{size:K()}],w:[{w:[c,"screen",...K()]}],"min-w":[{"min-w":[c,"screen","none",...K()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[s]},...K()]}],h:[{h:["screen","lh",...K()]}],"min-h":[{"min-h":["screen","lh","none",...K()]}],"max-h":[{"max-h":["screen","lh",...K()]}],"font-size":[{text:["base",t,Zr,xo]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,Z,Yl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Xl,Y]}],"font-family":[{font:[lw,Y,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,Z,Y]}],"line-clamp":[{"line-clamp":[de,"none",Z,Yl]}],leading:[{leading:[n,...w()]}],"list-image":[{"list-image":["none",Z,Y]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Z,Y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",Z,xo]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[de,"auto",Z,Y]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:w()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Z,Y]}],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",Z,Y]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:W()}],"bg-repeat":[{bg:te()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ua,Z,Y],radial:["",Z,Y],conic:[Ua,Z,Y]},uw,iw]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:D()}],"gradient-via-pos":[{via:D()}],"gradient-to-pos":[{to:D()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:q()}],"rounded-s":[{"rounded-s":q()}],"rounded-e":[{"rounded-e":q()}],"rounded-t":[{"rounded-t":q()}],"rounded-r":[{"rounded-r":q()}],"rounded-b":[{"rounded-b":q()}],"rounded-l":[{"rounded-l":q()}],"rounded-ss":[{"rounded-ss":q()}],"rounded-se":[{"rounded-se":q()}],"rounded-ee":[{"rounded-ee":q()}],"rounded-es":[{"rounded-es":q()}],"rounded-tl":[{"rounded-tl":q()}],"rounded-tr":[{"rounded-tr":q()}],"rounded-br":[{"rounded-br":q()}],"rounded-bl":[{"rounded-bl":q()}],"border-w":[{border:j()}],"border-w-x":[{"border-x":j()}],"border-w-y":[{"border-y":j()}],"border-w-s":[{"border-s":j()}],"border-w-e":[{"border-e":j()}],"border-w-t":[{"border-t":j()}],"border-w-r":[{"border-r":j()}],"border-w-b":[{"border-b":j()}],"border-w-l":[{"border-l":j()}],"divide-x":[{"divide-x":j()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":j()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,Z,Y]}],"outline-w":[{outline:["",de,Zr,xo]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",f,Bs,Fs]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",d,Bs,Fs]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:j()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[de,xo]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":j()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",i,Bs,Fs]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[de,Z,Y]}],"mix-blend":[{"mix-blend":[...re(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":re()}],"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":$()}],"mask-image-linear-to-pos":[{"mask-linear-to":$()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":$()}],"mask-image-t-to-pos":[{"mask-t-to":$()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":$()}],"mask-image-r-to-pos":[{"mask-r-to":$()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":$()}],"mask-image-b-to-pos":[{"mask-b-to":$()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":$()}],"mask-image-l-to-pos":[{"mask-l-to":$()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":$()}],"mask-image-x-to-pos":[{"mask-x-to":$()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":$()}],"mask-image-y-to-pos":[{"mask-y-to":$()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[Z,Y]}],"mask-image-radial-from-pos":[{"mask-radial-from":$()}],"mask-image-radial-to-pos":[{"mask-radial-to":$()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":S()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":$()}],"mask-image-conic-to-pos":[{"mask-conic-to":$()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:W()}],"mask-repeat":[{mask:te()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Z,Y]}],filter:[{filter:["","none",Z,Y]}],blur:[{blur:ie()}],brightness:[{brightness:[de,Z,Y]}],contrast:[{contrast:[de,Z,Y]}],"drop-shadow":[{"drop-shadow":["","none",m,Bs,Fs]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",de,Z,Y]}],"hue-rotate":[{"hue-rotate":[de,Z,Y]}],invert:[{invert:["",de,Z,Y]}],saturate:[{saturate:[de,Z,Y]}],sepia:[{sepia:["",de,Z,Y]}],"backdrop-filter":[{"backdrop-filter":["","none",Z,Y]}],"backdrop-blur":[{"backdrop-blur":ie()}],"backdrop-brightness":[{"backdrop-brightness":[de,Z,Y]}],"backdrop-contrast":[{"backdrop-contrast":[de,Z,Y]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,Z,Y]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,Z,Y]}],"backdrop-invert":[{"backdrop-invert":["",de,Z,Y]}],"backdrop-opacity":[{"backdrop-opacity":[de,Z,Y]}],"backdrop-saturate":[{"backdrop-saturate":[de,Z,Y]}],"backdrop-sepia":[{"backdrop-sepia":["",de,Z,Y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Z,Y]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",Z,Y]}],ease:[{ease:["linear","initial",v,Z,Y]}],delay:[{delay:[de,Z,Y]}],animate:[{animate:["none",g,Z,Y]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,Z,Y]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:he()}],"rotate-x":[{"rotate-x":he()}],"rotate-y":[{"rotate-y":he()}],"rotate-z":[{"rotate-z":he()}],scale:[{scale:fe()}],"scale-x":[{"scale-x":fe()}],"scale-y":[{"scale-y":fe()}],"scale-z":[{"scale-z":fe()}],"scale-3d":["scale-3d"],skew:[{skew:xe()}],"skew-x":[{"skew-x":xe()}],"skew-y":[{"skew-y":xe()}],transform:[{transform:[Z,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ye()}],"translate-x":[{"translate-x":ye()}],"translate-y":[{"translate-y":ye()}],"translate-z":[{"translate-z":ye()}],"translate-none":["translate-none"],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Z,Y]}],"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":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"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",Z,Y]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[de,Zr,xo,Yl]}],stroke:[{stroke:["none",...F()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var Wf=_y(mw);function Ka(...e){return Wf(Rs(e))}var hw=Le.createContext({size:"default",variant:"default",spacing:0});function Ga({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(If,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Ka("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(hw.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var xw={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},_f=createSlice({name:"toolbar",initialState:xw,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:ra,setPenColor:ha,setStrokeWidth:Jr,setFontSize:aR,setFontFamily:oR,setFontStyle:rR,setFontWeight:nR,setTextDecoration:sR,setTextColor:iR}=_f.actions,Ql=_f.reducer;var Xf=e=>jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",...e,children:jsx("ellipse",{cx:"12",cy:"12",rx:"10.5",ry:"7.5"})});var Zf=e=>jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",...e,children:[jsx("circle",{cx:"12",cy:"12",r:"10",fill:"currentColor"}),jsx("circle",{cx:"12",cy:"12",r:"6",fill:"white"})]});var Os=({onClose:e,onRecordingComplete:o})=>{let t=ze(),[a,r]=useState(false),[n,s]=useState(null),[c,l]=useState(0),[u,f]=useState(null),[d,i]=useState(false),m=useRef(null),h=useRef([]),p=useRef(null),x=useRef(null),v=useRef(null);useEffect(()=>((async()=>{try{let b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});f(b),i(!0),v.current&&(v.current.srcObject=b);}catch(b){console.error("Error accessing camera:",b),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),u&&u.getTracks().forEach(b=>b.stop());}),[]);let g=()=>{u&&(u.getTracks().forEach(w=>w.stop()),f(null),i(false));},y=async()=>{try{let w=null,b=null;try{w=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(B){console.error("Error accessing camera for recording:",B),alert("Failed to access camera for recording.");return}try{b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(B){console.warn("Microphone access denied:",B);}let I=[...w.getVideoTracks()];b&&I.push(...b.getAudioTracks());let P=new MediaStream(I),H="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?H="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?H="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?H="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(H="video/webm;codecs=vp8");let O=new MediaRecorder(P,{mimeType:H,videoBitsPerSecond:25e5});m.current=O,h.current=[],O.ondataavailable=B=>{B.data.size>0&&h.current.push(B.data);},O.onstop=()=>{let B=new Blob(h.current,{type:H}),V=document.createElement("video");V.src=URL.createObjectURL(B),V.muted=!0,V.currentTime=.1,V.onseeked=()=>{let U=document.createElement("canvas");U.width=V.videoWidth,U.height=V.videoHeight;let K=U.getContext("2d");K&&(K.drawImage(V,0,0),x.current=U.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(V.src);},P.getTracks().forEach(U=>U.stop()),w&&w.getTracks().forEach(U=>U.stop()),b&&b.getTracks().forEach(U=>U.stop()),p.current&&clearInterval(p.current),s(B),g();},O.onerror=B=>{console.error("MediaRecorder error:",B);},O.start(1e3),r(!0),l(0),p.current=setInterval(()=>{l(B=>B+1);},1e3);}catch(w){console.error("Error starting camera recording:",w),alert("Failed to start recording. Please check permissions.");}},S=()=>{m.current&&a&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),r(false));},C=()=>{if(n){let w=URL.createObjectURL(n),b=document.createElement("a");b.href=w,b.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(w);}},k=w=>{let b=Math.floor(w/60),I=w%60;return `${b.toString().padStart(2,"0")}:${I.toString().padStart(2,"0")}`};if(!t)return null;let T=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:w=>{w.target===w.currentTarget&&e(),w.stopPropagation();},onMouseUp:w=>w.stopPropagation(),onMouseMove:w=>w.stopPropagation(),onTouchStart:w=>w.stopPropagation(),onTouchMove:w=>w.stopPropagation(),onTouchEnd:w=>w.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:w=>w.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,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!n&&jsxs(Fragment,{children:[jsx("video",{ref:v,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:y,disabled:!d,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!d&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:S,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(c)})]})]})]}),n&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(n),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",k(c)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{s(null),l(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:C,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&n&&x.current&&(o(n,x.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(T,t)};var ga=40,Qf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,s]=useState(t?.order||"sequential"),[c,l]=useState(false),u=useRef(null),f=ze(),d=useRef(null);useEffect(()=>{let y=S=>{S.key==="Escape"&&o();};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[o]);let i=y=>{let S=y.target.files;if(!S||S.length===0)return;let C=ga-a.length;if(C<=0){alert(`You can only upload a maximum of ${ga} images`);return}let k=Array.from(S).slice(0,C);k.length<S.length&&alert(`Only ${C} more images can be added (max ${ga} total)`);let T=k.map(w=>new Promise((b,I)=>{let P=new FileReader;P.onload=H=>{H.target?.result?b(H.target.result):I(new Error("Failed to read file"));},P.onerror=I,P.readAsDataURL(w);}));Promise.all(T).then(w=>{r(b=>[...b,...w]),d.current&&(d.current.value="");});},m=y=>{y.preventDefault(),l(false);let S=Array.from(y.dataTransfer.files).filter(w=>w.type.startsWith("image/"));if(S.length===0)return;let C=ga-a.length;if(C<=0){alert(`You can only upload a maximum of ${ga} images`);return}let k=S.slice(0,C);k.length<S.length&&alert(`Only ${C} more images can be added (max ${ga} total)`);let T=k.map(w=>new Promise((b,I)=>{let P=new FileReader;P.onload=H=>{H.target?.result?b(H.target.result):I(new Error("Failed to read file"));},P.onerror=I,P.readAsDataURL(w);}));Promise.all(T).then(w=>{r(b=>[...b,...w]);});},h=y=>{y.preventDefault(),l(true);},p=()=>{l(false);},x=y=>{r(S=>S.filter((C,k)=>k!==y));},v=y=>{if(y.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,n,t?.id);};if(!f)return null;let g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:y=>{y.target===y.currentTarget&&o(),y.stopPropagation();},onMouseUp:y=>y.stopPropagation(),onMouseMove:y=>y.stopPropagation(),onTouchStart:y=>y.stopPropagation(),onTouchMove:y=>y.stopPropagation(),onTouchEnd:y=>y.stopPropagation(),children:jsxs("div",{ref:u,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:y=>y.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,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:v,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=ga?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ga," images"]}):jsxs("span",{children:[a.length,"/",ga," images"]})})]}),jsx("input",{ref:d,type:"file",accept:"image/*",multiple:true,onChange:i,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:h,onDragLeave:p,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${c?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:c?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>s("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>s("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((y,S)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:y,alt:`Flashcard ${S+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>x(S),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:S+1})]},S))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(g,f)};var Ns={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},Fw={enabled:true};function ad(e){return e?{tools:{...Ns.tools,...e.tools},actions:{...Ns.actions,...e.actions}}:Ns}var Bw={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Ow={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};function od(e,[o,t]){return Math.min(t,Math.max(o,e))}function em(e){let o=Le.useRef({value:e,previous:e});return Le.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function am(e){let[o,t]=Le.useState(void 0);return Jo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let n=r[0],s,c;if("borderBoxSize"in n){let l=n.borderBoxSize,u=Array.isArray(l)?l[0]:l;s=u.inlineSize,c=u.blockSize;}else s=e.offsetWidth,c=e.offsetHeight;t({width:s,height:c});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var om=["PageUp","PageDown"],rm=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],nm={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},rr="Slider",[rd,Hw,qw]=Ps(rr),[sm]=za(rr,[qw]),[Vw,qs]=sm(rr),im=Le.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:s="horizontal",disabled:c=false,minStepsBetweenThumbs:l=0,defaultValue:u=[a],value:f,onValueChange:d=()=>{},onValueCommit:i=()=>{},inverted:m=false,form:h,...p}=e,x=Le.useRef(new Set),v=Le.useRef(0),y=s==="horizontal"?zw:Ww,[S=[],C]=ma({prop:f,defaultProp:u,onChange:P=>{[...x.current][v.current]?.focus(),d(P);}}),k=Le.useRef(S);function T(P){let H=_w(S,P);I(P,H);}function w(P){I(P,v.current);}function b(){let P=k.current[v.current];S[v.current]!==P&&i(S);}function I(P,H,{commit:O}={commit:false}){let B=Zw(n),V=Jw(Math.round((P-a)/n)*n+a,B),U=od(V,[a,r]);C((K=[])=>{let F=Gw(K,U,H);if(Yw(F,l*n)){v.current=F.indexOf(U);let W=String(F)!==String(K);return W&&O&&i(F),W?F:K}else return K});}return jsx(Vw,{scope:e.__scopeSlider,name:t,disabled:c,min:a,max:r,valueIndexToChangeRef:v,thumbs:x.current,values:S,orientation:s,form:h,children:jsx(rd.Provider,{scope:e.__scopeSlider,children:jsx(rd.Slot,{scope:e.__scopeSlider,children:jsx(y,{"aria-disabled":c,"data-disabled":c?"":void 0,...p,ref:o,onPointerDown:ot(p.onPointerDown,()=>{c||(k.current=S);}),min:a,max:r,inverted:m,onSlideStart:c?void 0:T,onSlideMove:c?void 0:w,onSlideEnd:c?void 0:b,onHomeKeyDown:()=>!c&&I(a,0,{commit:true}),onEndKeyDown:()=>!c&&I(r,S.length-1,{commit:true}),onStepKeyDown:({event:P,direction:H})=>{if(!c){let V=om.includes(P.key)||P.shiftKey&&rm.includes(P.key)?10:1,U=v.current,K=S[U],F=n*V*H;I(K+F,U,{commit:true});}}})})})})});im.displayName=rr;var[lm,dm]=sm(rr,{startEdge:"left",endEdge:"right",size:"width",direction:1}),zw=Le.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:s,onSlideMove:c,onSlideEnd:l,onStepKeyDown:u,...f}=e,[d,i]=Le.useState(null),m=Kt(o,y=>i(y)),h=Le.useRef(void 0),p=er(r),x=p==="ltr",v=x&&!n||!x&&n;function g(y){let S=h.current||d.getBoundingClientRect(),C=[0,S.width],T=id(C,v?[t,a]:[a,t]);return h.current=S,T(y-S.left)}return jsx(lm,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:jsx(um,{dir:p,"data-orientation":"horizontal",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:y=>{let S=g(y.clientX);s?.(S);},onSlideMove:y=>{let S=g(y.clientX);c?.(S);},onSlideEnd:()=>{h.current=void 0,l?.();},onStepKeyDown:y=>{let C=nm[v?"from-left":"from-right"].includes(y.key);u?.({event:y,direction:C?-1:1});}})})}),Ww=Le.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:s,onSlideEnd:c,onStepKeyDown:l,...u}=e,f=Le.useRef(null),d=Kt(o,f),i=Le.useRef(void 0),m=!r;function h(p){let x=i.current||f.current.getBoundingClientRect(),v=[0,x.height],y=id(v,m?[a,t]:[t,a]);return i.current=x,y(p-x.top)}return jsx(lm,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:jsx(um,{"data-orientation":"vertical",...u,ref:d,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:p=>{let x=h(p.clientY);n?.(x);},onSlideMove:p=>{let x=h(p.clientY);s?.(x);},onSlideEnd:()=>{i.current=void 0,c?.();},onStepKeyDown:p=>{let v=nm[m?"from-bottom":"from-top"].includes(p.key);l?.({event:p,direction:v?-1:1});}})})}),um=Le.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:s,onEndKeyDown:c,onStepKeyDown:l,...u}=e,f=qs(rr,t);return jsx(bt.span,{...u,ref:o,onKeyDown:ot(e.onKeyDown,d=>{d.key==="Home"?(s(d),d.preventDefault()):d.key==="End"?(c(d),d.preventDefault()):om.concat(rm).includes(d.key)&&(l(d),d.preventDefault());}),onPointerDown:ot(e.onPointerDown,d=>{let i=d.target;i.setPointerCapture(d.pointerId),d.preventDefault(),f.thumbs.has(i)?i.focus():a(d);}),onPointerMove:ot(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d);}),onPointerUp:ot(e.onPointerUp,d=>{let i=d.target;i.hasPointerCapture(d.pointerId)&&(i.releasePointerCapture(d.pointerId),n(d));})})}),cm="SliderTrack",fm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=qs(cm,t);return jsx(bt.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});fm.displayName=cm;var nd="SliderRange",mm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=qs(nd,t),n=dm(nd,t),s=Le.useRef(null),c=Kt(o,s),l=r.values.length,u=r.values.map(i=>gm(i,r.min,r.max)),f=l>1?Math.min(...u):0,d=100-Math.max(...u);return jsx(bt.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:c,style:{...e.style,[n.startEdge]:f+"%",[n.endEdge]:d+"%"}})});mm.displayName=nd;var sd="SliderThumb",pm=Le.forwardRef((e,o)=>{let t=Hw(e.__scopeSlider),[a,r]=Le.useState(null),n=Kt(o,c=>r(c)),s=Le.useMemo(()=>a?t().findIndex(c=>c.ref.current===a):-1,[t,a]);return jsx(Uw,{...e,ref:n,index:s})}),Uw=Le.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,s=qs(sd,t),c=dm(sd,t),[l,u]=Le.useState(null),f=Kt(o,g=>u(g)),d=l?s.form||!!l.closest("form"):true,i=am(l),m=s.values[a],h=m===void 0?0:gm(m,s.min,s.max),p=jw(a,s.values.length),x=i?.[c.size],v=x?$w(x,h,c.direction):0;return Le.useEffect(()=>{if(l)return s.thumbs.add(l),()=>{s.thumbs.delete(l);}},[l,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[c.startEdge]:`calc(${h}% + ${v}px)`},children:[jsx(rd.ItemSlot,{scope:e.__scopeSlider,children:jsx(bt.span,{role:"slider","aria-label":e["aria-label"]||p,"aria-valuemin":s.min,"aria-valuenow":m,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...n,ref:f,style:m===void 0?{display:"none"}:e.style,onFocus:ot(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),d&&jsx(hm,{name:r??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:m},a)]})});pm.displayName=sd;var Kw="RadioBubbleInput",hm=Le.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=Le.useRef(null),n=Kt(r,a),s=em(o);return Le.useEffect(()=>{let c=r.current;if(!c)return;let l=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==o&&f){let d=new Event("input",{bubbles:true});f.call(c,o),c.dispatchEvent(d);}},[s,o]),jsx(bt.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});hm.displayName=Kw;function Gw(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function gm(e,o,t){let n=100/(t-o)*(e-o);return od(n,[0,100])}function jw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function _w(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 $w(e,o,t){let a=e/2,n=id([0,50],[0,a]);return (a-n(o)*t)*t}function Xw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Yw(e,o){if(o>0){let t=Xw(e);return Math.min(...t)>=o}return true}function id(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 Zw(e){return (String(e).split(".")[1]||"").length}function Jw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var xm=im,bm=fm,vm=mm,ym=pm;function Vs({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:s,thumbClassName:c,...l}){let u=Le.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(xm,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Ka("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(bm,{"data-slot":"slider-track",className:Ka("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",s),children:jsx(vm,{"data-slot":"slider-range",className:Ka("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:u.length},(f,d)=>jsx(ym,{"data-slot":"slider-thumb",className:Ka("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",c)},d))]})}var MS=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a,onVisibilityChange:r}={})=>{let n=Se(),s=Q(A=>A.canvas.slides.find(ae=>ae.id===A.canvas.currentSlideId)),c=s?.videos||[],l=s?.editingFlashcard,u=Q(A=>A.toolbar.selectedTool),f=Q(A=>A.toolbar.penColor),d=Q(A=>A.toolbar.strokeWidth),i=Q(A=>A.canvas.editingOverlayPosition),m=s?.showMcqForm,h=s?.showFlashcardForm,p=useRef(null);useEffect(()=>{let A=ae=>{(ae.ctrlKey||ae.metaKey)&&ae.key==="z"&&!ae.shiftKey&&(ae.preventDefault(),n(Po())),(ae.ctrlKey&&ae.shiftKey&&ae.key==="Z"||ae.ctrlKey&&ae.key==="y")&&(ae.preventDefault(),n(Ao()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[n]);let x=useMemo(()=>ad(a),[a]),{tools:v,actions:g}=x,y=c.some(A=>A.isRecorded&&A.isPlaying),S=Q(A=>A.toolbar.fontSize),C=Q(A=>A.toolbar.fontFamily),k=Q(A=>A.toolbar.fontStyle),T=Q(A=>A.toolbar.fontWeight),w=Q(A=>A.toolbar.textDecoration),b=Q(A=>A.toolbar.textColor),[I,P]=useState(false),[H,O]=useState(false),[B,V]=useState(false),[U,K]=useState(false),[F,W]=useState(false),[te,X]=useState(false),[D,q]=useState(false),[j,J]=useState(false),[re,$]=useState(true),ie=useRef(null),he=useRef(null),fe=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],xe=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"style",icon:Palette,label:"Style",configKey:"style"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),ye=useMemo(()=>[{name:"rectangle",icon:Square,label:"Square"},{name:"rectangle",icon:Rectangle,label:"Rectangle"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Xf,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Zf,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"}],[]),we=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),yt=useMemo(()=>xe.filter(A=>{let ae=v[A.configKey];return typeof ae=="boolean"?ae:Array.isArray(ae)?ae.length>0:true}),[v,xe]),wt=useMemo(()=>{let A=v.shapes;return A===false?[]:A===true?ye:Array.isArray(A)?ye.filter(ae=>A.includes(ae.name)):ye},[v.shapes,ye]),wo=useMemo(()=>{let A=v.activities;return A===false?[]:A===true?we:Array.isArray(A)?we.filter(ae=>A.includes(ae.name)):we},[v.activities,we]),So=useMemo(()=>{let A=v.media;return A===false?{photoFrame:false,image:false,video:false}:A===true?{photoFrame:true,image:true,video:true}:Array.isArray(A)?{photoFrame:A.includes("photo-frame"),image:A.includes("image"),video:A.includes("video")}:{photoFrame:true,image:true,video:true}},[v.media]),ne=useMemo(()=>{let A=v.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[v.activities]),nn=A=>{let ae=A.target.files;!ae||ae.length===0||(n(ra("select")),n(It(false)),K(false),Array.from(ae).forEach(Ee=>{let Ie=new FileReader;Ie.onload=ue=>{let se=new window.Image;se.src=ue.target?.result,se.onload=()=>{let De=se.width/se.height,nt=300,sa=300,St=se.width,Pe=se.height;St>nt&&(St=nt,Pe=St/De),Pe>sa&&(Pe=sa,St=Pe*De),n(le());let st=i?.left||800-St/2,ia=i?.top||450-Pe/2;n(ci({id:v4(),src:se.src,x:st,y:ia,width:St,height:Pe,draggable:true,rotation:0}));};},Ie.readAsDataURL(Ee);}),A.target.value="");},sn=async A=>{let ae=A.target.files;if(!(!ae||ae.length===0)){console.log("files",A),n(ra("select")),n(It(false)),K(false);for(let Ee of Array.from(ae))try{let Ie=URL.createObjectURL(Ee),ue=document.createElement("video");console.log("video",ue),ue.src=Ie,ue.muted=!0,ue.playsInline=!0,ue.preload="auto",ue.load(),await new Promise((jt,La)=>{let ea=setTimeout(()=>La(new Error("Metadata load timeout")),1e4);ue.onloadedmetadata=()=>{clearTimeout(ea),jt();},ue.onerror=()=>{clearTimeout(ea),La(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ue.duration,width:ue.videoWidth,height:ue.videoHeight}),await new Promise((jt,La)=>{let ea=setTimeout(()=>La(new Error("Video load timeout")),1e4);ue.readyState>=2?(clearTimeout(ea),jt()):ue.onloadeddata=()=>{clearTimeout(ea),jt();};});let se=Math.min(.8,ue.duration/2);console.log("Seeking to:",se),ue.currentTime=se,await new Promise(jt=>{let La=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),jt();},5e3);ue.onseeked=()=>{clearTimeout(La),console.log("Seek completed"),jt();};});let De=document.createElement("canvas"),nt=ue.videoWidth/ue.videoHeight,sa=400,St=400,Pe=ue.videoWidth,st=ue.videoHeight;Pe>sa&&(Pe=sa,st=Pe/nt),st>St&&(st=St,Pe=st*nt),De.width=Pe,De.height=st;let ia=De.getContext("2d",{willReadFrequently:!1});if(!ia)throw new Error("Failed to get canvas context");if(await new Promise(jt=>setTimeout(jt,100)),ue.videoWidth===0||ue.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Pe,height:st}),ia.drawImage(ue,0,0,Pe,st);let Ft=De.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Ft.length),n(le());let ei=800-Pe/2,ti=450-st/2,pn=v4();await ca(pn,Ee,Ft),n(To({id:pn,objectUrl:Ie,thumbnailDataUrl:Ft,videoBlob:Ee,x:ei,y:ti,width:Pe,height:st,draggable:!0,isPlaying:!1,rotation:0})),ue.src="",ue.load(),console.log(`Video uploaded: ${Ee.name}`);}catch(Ie){console.error("Error processing video:",Ie),alert(`Failed to process video: ${Ee.name}`);}A.target.value="";}},ln=(A,ae,Ee)=>{n(le()),n(ra("select")),n(It(false));let Ie=300,ue=300,se=800-Ie/2,De=450-ue/2;n(Ee?Mo({id:Ee,images:A,order:ae,x:se,y:De,width:Ie,height:ue,rotation:0,draggable:true}):pi({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:ae,x:se,y:De,width:Ie,height:ue,rotation:0,draggable:true})),n(eo(false));},dn=()=>{n(le()),n(ra("select")),n(It(false));let A=400,ae=300,Ee=800-A/2,Ie=450-ae/2;n(xi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ee,y:Ie,width:A,height:ae,rotation:0,draggable:true,isCapturing:false})),K(false);},un=A=>{let se={};switch(A.name){case "rectangle":A.label==="Rectangle"?(se.width=120,se.height=80):(se.width=100,se.height=100);break;case "circle":case "ring":case "wedge":case "arc":se.radius=50,(A.name==="ring"||A.name==="arc")&&(se.innerRadius=25,se.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(se.angle=A.name==="wedge"?60:90);break;case "ellipse":se.radiusX=60,se.radiusY=40;break;case "triangle":se.radius=50,se.sides=3;break;case "polygon":se.radius=50,se.sides=6;break;case "star":se.innerRadius=25,se.outerRadius=50,se.numPoints=5;break;case "arrow":case "line":se.points=[0,0,100,0],A.name==="arrow"&&(se.pointerLength=10,se.pointerWidth=10);break}let De={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:f,...se};n(le()),n(It(false)),n(ra(A.name)),n(fi(De)),V(false);},wa=A=>{if(n(ra(A)),A==="select")n(It(false));else if(A==="text"){n(It(false)),n(le());let ae=200,Ee=50,Ie=800-ae/2,ue=450-Ee/2,De=window.innerWidth<768?Math.max(S,32):S,nt=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;n(mi({id:nt,text:"",x:Ie,y:ue,width:ae,height:Ee,rotation:0,draggable:true,fontSize:De,fontFamily:C,fontStyle:k,fontWeight:T,textDecoration:w,fill:b,align:"left"})),setTimeout(()=>{n(yr(nt));},100),t&&t(nt);}else n(It(true));},_s=()=>{n(vr()),n(It(false));},$s=()=>{e?e():o?P(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Xs=()=>{O(true);},Ys=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:dn,enabled:So.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>ie.current?.click(),enabled:So.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>he.current?.click(),enabled:So.video}],cn=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>n(Po()),enabled:g.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>n(Ao()),enabled:g.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:$s,enabled:g.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:Xs,enabled:g.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:_s,enabled:g.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],Sa=async(A,ae)=>{try{n(ra("select")),n(It(!1));let Ee=URL.createObjectURL(A),Ie=document.createElement("video");Ie.src=Ee,Ie.muted=!0,Ie.playsInline=!0,Ie.preload="auto",await new Promise((st,ia)=>{let Ft=setTimeout(()=>ia(new Error("Metadata load timeout")),1e4);Ie.onloadedmetadata=()=>{clearTimeout(Ft),st();},Ie.onerror=()=>{clearTimeout(Ft),ia(new Error("Failed to load video"));};});let ue=640,se=Ie.videoWidth/Ie.videoHeight,De=ue,nt=De/se;n(le());let sa=800-De/2,St=450-nt/2,Pe=v4();await ca(Pe,A,ae),n(To({id:Pe,objectUrl:Ee,thumbnailDataUrl:ae,videoBlob:A,x:sa,y:St,width:De,height:nt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),P(!1),O(!1);}catch(Ee){console.error("Error adding recorded video to canvas:",Ee),alert("Failed to add video to canvas. Please try again.");}},Zs=A=>{n(ra("select")),n(It(false)),n(xr(null)),A&&n(Mi(A)),n(ka(!m)),W(false);},Js=()=>{n(gr(null)),n(eo(true)),W(false);},Lo=()=>{V(!B);},fn=()=>{K(!U);},Qs=()=>{W(!F);},mn=()=>{X(!te);},lr=()=>{let A=!re;A||(V(false),K(false),W(false),X(false),J(false),q(false)),$(A),r?.(A);};return useEffect(()=>{if(!j)return;let A=ae=>{p.current&&!p.current.contains(ae.target)&&J(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[j]),y?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:lr,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:re?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),re&&jsxs("div",{className:"scrollbar-hide fixed top-[168px] bottom-4 left-4 z-50 flex flex-col gap-4 overflow-y-auto",children:[jsxs("div",{className:"flex items-center",children:[jsx(Ga,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:yt.map((A,ae)=>jsx("div",{title:A.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.name===u?"bg-primary/10":A.name==="style"?"md:hidden":""}`,onClick:()=>{A.name==="image"?(fn(),V(false),W(false),X(false),wa(A.name)):A.name==="shapes"?(Lo(),K(false),W(false),X(false),wa(A.name)):A.name==="activities"?(wa(A.name),Qs(),V(false),K(false),X(false)):A.name==="style"?(mn(),V(false),K(false),W(false),wa(A.name)):(wa(A.name),V(false),K(false),W(false),X(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ae))}),B&&jsx(Ga,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:wt.map((A,ae)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>un(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ae))}),U&&jsx(Ga,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:Ys.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),F&&jsxs(Ga,{type:"single",className:"mx-1 mt-auto mb-10 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl lg:mb-11",children:[ne&&jsx("div",{title:"Flashcard",onClick:()=>Js(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),wo.map((A,ae)=>jsx("div",{title:A.label,onClick:()=>Zs(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},ae))]}),te&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Vs,{value:[d],onValueChange:A=>{n(Jr(A[0]));},max:28,min:6,step:1,className:"w-28",rangeClassName:"bg-gray-300",thumbClassName:"bg-gray-600 border-none h-4 w-4"}),jsx("div",{className:"h-5 w-5 rounded-full bg-gray-800"})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"COLOR"}),jsxs("div",{className:"flex flex-wrap gap-1",children:[fe.map(A=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${f===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{n(ha(A.value)),X(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:f,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>n(ha(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:f,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{n(hr(A.target.value)),X(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),cn.some(A=>A.enabled)&&jsx(Ga,{type:"single",className:"hidden flex-col border bg-white p-1 shadow-xl md:flex",children:cn.filter(A=>A.enabled).map(A=>jsx("button",{onClick:A.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.colorClass}`,title:A.title,children:jsx(A.icon,{weight:A.iconWeight,className:"text-lg md:text-xl"})},A.key))})]}),jsx("input",{ref:ie,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:nn}),jsx("input",{ref:he,type:"file",accept:"video/*",className:"hidden",onChange:sn}),!e&&I&&o&&jsx(to,{onClose:()=>P(false),stageRef:o,onRecordingComplete:Sa}),H&&jsx(Os,{onClose:()=>O(false),onRecordingComplete:Sa}),h&&jsx(Qf,{editingFlashcard:l,onConfirm:ln,onCancel:()=>n(eo(false))}),D&&jsx(os,{defaultColor:f,onConfirm:A=>{n(ha(A)),q(false);},onCancel:()=>q(false)})]})},PS=MS;var fd=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let r=Fe(Ma),n=Fe(Ni),s=a?n:r,c=Fe(Sr),f=(Fe(g=>g.canvas.slides.find(y=>y.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[d,i]=useState(false),[m,h]=useState(null),[p,x]=useState(null),v=async()=>{if(r.length===0){x({type:"error",message:"No slides to publish"});return}if(!e){x({type:"error",message:"No publish handler provided"});return}i(true),x(null);try{let g=await e(s,c,y=>{h(y);});g.success?x({type:"success",message:g.message}):x({type:"error",message:g.message});}catch(g){x({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{i(false),setTimeout(()=>{h(null),x(null);},3e3);}console.log("For checking>>>>>>>>>>>",s,"<<<<<<<<<<<<<");};return f?null:jsxs("button",{onClick:v,disabled:d||r.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var FS=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:r,onDescriptionChange:n,showPublishButton:s=true,showBackButton:c=true,editableTitle:l=true,editableDescription:u=true,className:f="",rightContent:d,leftContent:i,includeInactiveSlides:m=false})=>{let h=_e(),p=Fe(Sr),x=Fe(Hi),v=e??(x?p.title:"")??"Untitled",g=o??(x?p.description:"")??"Add a description...",[y,S]=useState(false),[C,k]=useState(false),[T,w]=useState(v),[b,I]=useState(g),P=useRef(null),H=useRef(null);useEffect(()=>{w(v);},[v]),useEffect(()=>{I(g);},[g]),useEffect(()=>{y&&P.current&&(P.current.focus(),P.current.select());},[y]),useEffect(()=>{C&&H.current&&(H.current.focus(),H.current.select());},[C]);let O=()=>{l&&S(true);},B=()=>{u&&k(true);},V=()=>{S(false),T.trim()&&T!==v?r?r(T.trim()):h(Fi(T.trim())):T.trim()||w(v);},U=()=>{k(false),b.trim()&&b!==g?n?n(b.trim()):h(Bi(b.trim())):b.trim()||I(g);},K=W=>{W.key==="Enter"?V():W.key==="Escape"&&(w(v),S(false));},F=W=>{W.key==="Enter"?U():W.key==="Escape"&&(I(g),k(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${f}`,children:[i||jsxs("div",{className:"flex items-center gap-4",children:[c&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[y?jsx("input",{ref:P,type:"text",value:T,onChange:W=>w(W.target.value),onBlur:V,onKeyDown:K,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:O,title:T,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:T}),C?jsx("input",{ref:H,type:"text",value:b,onChange:W=>I(W.target.value),onBlur:U,onKeyDown:F,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:B,title:b,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${u?"hover:border-primary cursor-text":""}`,children:b})]})]}),d||s&&a&&jsx(fd,{onPublish:a,includeInactiveSlides:m})]})};var VS=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],zS=({colors:e=VS,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let[n,s]=useState(true),c=Q(ve),l=Q(i=>i.toolbar.penColor),u=Q(i=>i.toolbar.strokeWidth),f=c?.backgroundColor,d=Se();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:n?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-16 left-1/2 z-50 hidden w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-3 shadow-2xl md:bottom-6 md:flex md:p-5 2xl:px-8 2xl:py-6 ${r}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-black md:h-3 md:w-3"}),jsx(Vs,{defaultValue:[20],max:36,min:8,step:2,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[u],onValueChange:i=>d(Jr(i[0]))}),jsx("div",{className:"h-5 w-5 rounded-full bg-black md:h-7 md:w-7 lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"COLOR"}),jsxs(Ga,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(i=>jsx("button",{value:i.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${l===i.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:i.value},onClick:()=>d(ha(i.value))},i.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>d(ha("#2D2F50"))}),jsxs("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] md:h-10 md:w-10 lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>d(ha(i.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:f},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>d(hr(i.target.value))})})]})}),jsx("div",{className:"absolute -top-6 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2 md:-top-4",children:jsx("button",{onClick:()=>s(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{weight:"bold",className:"text-gray-600 md:text-xl"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>s(true),className:"fixed bottom-20 left-1/2 z-50 hidden -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl md:bottom-3 md:flex","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var Tm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),WS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),pd=e=>{let o=WS(e);return o.charAt(0).toUpperCase()+o.slice(1)},Ks=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Mm=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Pm={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var Em=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:s,...c},l)=>createElement("svg",{ref:l,...Pm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Ks("lucide",r),...!n&&!Mm(c)&&{"aria-hidden":"true"},...c},[...s.map(([u,f])=>createElement(u,f)),...Array.isArray(n)?n:[n]]));var Gs=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(Em,{ref:n,iconNode:o,className:Ks(`lucide-${Tm(pd(e))}`,`lucide-${e}`,a),...r}));return t.displayName=pd(e),t};var jS=[["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"}]],tn=Gs("copy",jS);var _S=[["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"}]],an=Gs("trash-2",_S);var Rm=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:s})=>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:c=>{c.stopPropagation(),n();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(tn,{size:14})}),!a&&jsx("button",{onClick:c=>{c.stopPropagation(),s();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(an,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-white",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 ZS=({softDelete:e=false})=>{let o=_e(),t=Fe(Ma),a=Fe(Ta),r=Fe(wr),[n,s]=useState(true),u=(Fe(h=>h.canvas.slides.find(p=>p.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),f=()=>{r&&o(cr());},d=h=>{o(pr(h));},i=h=>{o(mr(h));},m=h=>{t.length>1&&o(fr({id:h,softDelete:e}));};return u?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:n?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>s(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((h,p)=>jsx(Rm,{slide:h,index:p,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>i(h.id),onDelete:()=>m(h.id)},h.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:!n&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>s(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 nr=20,sL=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:s})=>jsxs("div",{className:`relative h-[122px] w-[166px] shrink-0 cursor-pointer rounded-lg border bg-[#fafafa] transition-all ${t?"border-[#096b76]":"border-black/10"}`,onClick:r,children:[jsx("div",{className:"absolute top-1 right-1 bottom-1 left-1 overflow-hidden rounded bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"size-full object-contain"}):jsx("div",{className:"flex size-full items-center justify-center",children:jsx("span",{className:"text-xs text-black/20",children:"No preview"})})}),jsx("div",{className:"absolute top-3 left-3 flex h-5 w-5 items-center justify-center rounded-full bg-[#333c48]",children:jsx("span",{className:"text-xs font-bold text-white",children:o+1})}),jsx("button",{onClick:c=>{c.stopPropagation(),n();},className:"absolute top-3 right-3 flex cursor-pointer items-center justify-center rounded-md bg-[#3B75E0] p-1.5 text-white transition-colors hover:bg-[#2d5fc0]",title:"Duplicate Page",children:jsx(Copy,{size:18,weight:"bold"})}),!a&&jsx("button",{onClick:c=>{c.stopPropagation(),s();},className:"absolute right-3 bottom-6 flex cursor-pointer items-center justify-center rounded-md bg-[#E53935] p-1.5 text-white transition-colors hover:bg-[#c62828]",title:"Delete Page",children:jsx(Trash,{size:18,weight:"bold"})}),jsxs("p",{className:"absolute bottom-2 left-3 text-sm text-black/40",children:["Page ",o+1]})]}),iL=({softDelete:e=false})=>{let o=_e(),t=Fe(Ma),a=Fe(Ta),r=Fe(wr),[n,s]=useState(false),[c,l]=useState(false),[u,f]=useState(false),d=useRef(null),h=(Fe(C=>C.canvas.slides.find(k=>k.id===C.canvas.currentSlideId))?.videos||[]).some(C=>C.isRecorded&&C.isPlaying),p=()=>{r&&t.length<nr&&o(cr());},x=C=>{o(pr(C));},v=C=>{t.length<nr&&o(mr(C));},g=C=>{t.length>1&&o(fr({id:C,softDelete:e}));},y=()=>{if(!d.current)return;let{scrollLeft:C,scrollWidth:k,clientWidth:T}=d.current,w=k>T+5;l(w&&C>5),f(w&&C<k-T-5);},S=C=>{if(!d.current)return;let k=177,T=C==="left"?d.current.scrollLeft-k:d.current.scrollLeft+k;d.current.scrollTo({left:T,behavior:"smooth"});};return useEffect(()=>{if(n){let C=setTimeout(()=>{requestAnimationFrame(()=>{y();});},350);return ()=>clearTimeout(C)}},[t,n]),useEffect(()=>{let C=d.current;if(!(!C||!n))return C.addEventListener("scroll",y),window.addEventListener("resize",y),()=>{C.removeEventListener("scroll",y),window.removeEventListener("resize",y);}},[n]),h?null:jsx("div",{className:"fixed bottom-0 left-1/2 z-50 flex w-full -translate-x-1/2 flex-col gap-4 md:hidden",children:jsxs(AnimatePresence,{mode:"wait",children:[n&&jsxs(motion.div,{initial:{y:230,opacity:0},animate:{y:0,opacity:1},exit:{y:230,opacity:0},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},onAnimationComplete:()=>y(),className:"border bg-white md:hidden",children:[jsxs("div",{className:"flex w-full items-center justify-between px-4 py-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Cards,{size:24,weight:"fill",className:"text-[#096b76]"}),jsx("span",{className:"text-base font-bold text-black/80",children:"Pages"}),jsxs("span",{className:"text-base font-bold text-black/80",children:["(",t.length,"/",nr,")"]})]}),jsx("button",{onClick:()=>s(false),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretDown,{size:16,weight:"bold",className:"text-black/60"})})]}),jsxs("div",{className:"relative",children:[c&&jsx("button",{onClick:()=>S("left"),className:"absolute top-1/2 left-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll left",children:jsx(CaretLeft,{size:20,weight:"bold",className:"text-black/80"})}),u&&jsx("button",{onClick:()=>S("right"),className:"absolute top-1/2 right-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll right",children:jsx(CaretRight,{size:20,weight:"bold",className:"text-black/80"})}),jsx("div",{ref:d,className:"scrollbar-hide flex gap-[11px] overflow-x-auto px-4 pb-4",children:t.map((C,k)=>jsx(sL,{slide:C,index:k,isSelected:C.id===a,isSingleSlide:t.length===1,onSelect:()=>x(C.id),onDuplicate:()=>v(C.id),onDelete:()=>g(C.id)},C.id))})]}),jsx("button",{onClick:p,disabled:!r||t.length>=nr,className:`px-4 pb-4 text-base font-bold ${r&&t.length<nr?"cursor-pointer text-[#096b76]":"cursor-not-allowed text-black/30"}`,children:"+ Add Page"})]},"open"),!n&&jsxs(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{type:"tween",duration:.2},className:"flex cursor-pointer items-center justify-between gap-2 border border-black/10 bg-white px-4 py-3 shadow-lg md:hidden",children:[jsxs("div",{className:"flex gap-2",children:[jsx(Cards,{size:20,weight:"fill",className:"text-[#096b76]"}),jsxs("span",{className:"text-sm font-bold text-black/80",children:["Pages (",t.length,"/",nr,")"]})]}),jsx("button",{onClick:()=>s(true),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretUp,{size:16,weight:"bold",className:"text-black/60"})})]},"close")]})})},gd=iL;var hL=({stageRef:e,onScreenRecord:o,visible:t=true,config:a={}})=>{let r=_e(),[n,s]=useState(false),[c,l]=useState(false),u=Fe(S=>S.canvas.slides.find(C=>C.id===S.canvas.currentSlideId)),f=Fe(S=>S.canvas.zoomLevel),i=(u?.videos||[]).some(S=>S.isRecorded&&S.isPlaying),m={undo:a.undo??true,redo:a.redo??true,screenRecord:a.screenRecord??true,cameraRecord:a.cameraRecord??true,clear:a.clear??true,zoomOut:a.zoomOut??true,zoomIn:a.zoomIn??true,resetZoom:a.resetZoom??true},h=()=>{o?o():s(true);},p=()=>{l(true);},x=()=>{r(vr());},v=async(S,C)=>{let k=v4(),T=URL.createObjectURL(S),w=document.createElement("video");w.src=T,w.muted=true,w.playsInline=true,w.preload="auto",await new Promise((O,B)=>{let V=setTimeout(()=>B(new Error("Metadata load timeout")),1e4);w.onloadedmetadata=()=>{clearTimeout(V),O();},w.onerror=()=>{clearTimeout(V),B(new Error("Failed to load video"));};});let b=640,I=w.videoWidth/w.videoHeight,P=b,H=P/I;await ca(k,S,C),r(To({id:k,objectUrl:T,thumbnailDataUrl:C,videoBlob:S,x:100,y:100,width:P,height:H,draggable:true,isPlaying:false,rotation:0,isRecorded:true}));},y=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Po()),enabled:m.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(Ao()),enabled:m.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:h,enabled:m.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:p,enabled:m.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:x,enabled:m.clear,iconWeight:"fill",colorClass:"text-[#E92222]"},{key:"resetZoom",title:"Reset Zoom",icon:ArrowsOut,onClick:()=>r(Kd()),enabled:m.resetZoom&&f!==1,iconWeight:"bold",colorClass:"text-primary"}].filter(S=>S.enabled);return !t||i||y.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fixed bottom-[74px] left-1/2 z-50 flex w-11/12 -translate-x-1/2 items-center justify-between rounded-md border bg-white px-4 py-1 shadow-lg md:hidden",children:y.map(S=>jsx("button",{onClick:S.onClick,className:`flex size-10 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-black/5 ${S.colorClass}`,title:S.title,children:jsx(S.icon,{weight:S.iconWeight,className:"text-xl"})},S.key))}),!o&&n&&e&&jsx(to,{onClose:()=>s(false),stageRef:e,onRecordingComplete:v}),c&&jsx(Os,{onClose:()=>l(false),onRecordingComplete:v})]})},xd=hL;var bL=({stageRef:e,onScreenRecord:o,softDelete:t=false,actionButtonsVisible:a=true,actionButtonsConfig:r})=>jsxs(Fragment,{children:[jsx(xd,{stageRef:e,onScreenRecord:o,visible:a,config:r}),jsx(gd,{softDelete:t})]}),vL=bL;var SL="SchooplaEditorDB",LL=1,ja="slides",_a="metadata",bd="schoopla_current_slide_id",zm="presentation_metadata",rn=()=>new Promise((e,o)=>{let t=indexedDB.open(SL,LL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(ja)||r.createObjectStore(ja,{keyPath:"id"}),r.objectStoreNames.contains(_a)||r.createObjectStore(_a,{keyPath:"id"});};}),vd=async e=>{try{let o=await rn(),t=o.transaction([ja],"readwrite"),a=t.objectStore(ja);a.clear();for(let r of e)a.put(r);await new Promise((r,n)=>{t.oncomplete=()=>{o.close(),r();},t.onerror=()=>{o.close(),n(t.error);};});}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);}}},yd=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await rn(),t=e.transaction([ja],"readonly").objectStore(ja);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result;console.log("\u2705 Loaded from IndexedDB:",s.length,"slides"),s.length>0&&s[0].images&&console.log("First slide images:",s[0].images.map(c=>({id:c.id,width:c.width,height:c.height,x:c.x,y:c.y}))),a(s.length>0?s:null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},js=async()=>{try{let e=await rn(),o=e.transaction([ja,_a],"readwrite"),t=o.objectStore(ja),a=o.objectStore(_a);await new Promise((r,n)=>{let s=t.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),await new Promise((r,n)=>{let s=a.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(bd),localStorage.removeItem("schoopla_presentation_metadata"),await Zc(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},wd=e=>{try{localStorage.setItem(bd,e);}catch(o){console.error("Error saving current slide ID:",o);}},Sd=()=>{try{return localStorage.getItem(bd)}catch(e){return console.error("Error loading current slide ID:",e),null}},Ld=(e,o)=>{let t=null,a=null,r=(...n)=>{a=n,t&&clearTimeout(t),t=setTimeout(()=>{a=null,t=null,e(...n);},o);};return r.flush=()=>{if(t&&a){clearTimeout(t);let n=a;a=null,t=null,e(...n);}},r},Id=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await rn(),a=o.transaction([_a],"readwrite").objectStore(_a);await new Promise((r,n)=>{let s=a.put({id:zm,...e});s.onsuccess=()=>r(!0),s.onerror=()=>n(s.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);}}},Cd=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await rn(),t=e.transaction([_a],"readonly").objectStore(_a);return new Promise((a,r)=>{let n=t.get(zm);n.onsuccess=()=>{e.close();let s=n.result;if(s){let{id:c,...l}=s;console.log("\u2705 Loaded presentation metadata:",l),a(l);}else console.log("No presentation metadata found"),a(null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var IL=["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"],CL=["canvas/clearCanvas"],kL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],Wm=Ld((e,o)=>{vd(e),wd(o);},500),Um=Ld(e=>{Id(e);},500),TL=(e,o)=>{vd(e),wd(o);},kd=false,Km=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let n=t.payload;Vl(n).catch(s=>{console.error("Error deleting video blob:",s);});}if(t.type==="canvas/deleteSlide"&&t.payload){let n=t.payload,c=e.getState().canvas.slides.find(l=>l.id===n);c&&c.videos&&c.videos.length>0&&c.videos.forEach(l=>{Vl(l.id).catch(u=>{console.error("Error deleting video blob:",u);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let n=t.payload,s=e.getState(),l=s.canvas.slides.find(u=>u.id===s.canvas.currentSlideId)?.videos.find(u=>u.id===n);l&&l.videoBlob&&setTimeout(()=>{let u=e.getState(),d=u.canvas.slides.find(i=>i.id===u.canvas.currentSlideId)?.videos.find(i=>i.id!==n&&i.x===l.x+20&&i.y===l.y+20);d&&l.videoBlob&&ca(d.id,l.videoBlob,d.thumbnailDataUrl).catch(i=>{console.error("Error saving duplicated video blob:",i);});},0);}let a=o(t),r=e.getState();if(r.canvas.viewerMode)return a;if(t.type&&CL.includes(t.type)){if(!kd){kd=true;try{let{slides:n,currentSlideId:s}=r.canvas;TL(n,s);}finally{setTimeout(()=>{kd=false;},0);}}}else if(t.type&&IL.includes(t.type)){let{slides:n,currentSlideId:s}=r.canvas;Wm(n,s);}else if(t.type&&kL.includes(t.type)){let{presentationMetadata:n}=r.canvas;Um(n);}return a}),ML=()=>{Wm.flush(),Um.flush();};new QueryClient;var AL=configureStore({reducer:{toolbar:Ql,canvas:qi},middleware:e=>e({serializableCheck:false}).concat(Km)}),EL=()=>configureStore({reducer:{toolbar:Ql,canvas:qi},middleware:e=>e({serializableCheck:false})});var DL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:n=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",c=e.toDataURL({mimeType:s,quality:a,pixelRatio:r}),l=document.createElement("a");l.download=`${n}.${t}`,l.href=c,document.body.appendChild(l),l.click(),document.body.removeChild(l);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},RL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((n,s)=>{try{let c=t==="png"?"image/png":"image/jpeg",l=e.toDataURL({mimeType:c,quality:a,pixelRatio:r});fetch(l).then(u=>u.blob()).then(u=>n(u)).catch(u=>s(u));}catch(c){s(c);}})},FL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,n=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:n,quality:a,pixelRatio:r})};var BL=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let n=a*a+r*r,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/n)),c=o.x+s*a,l=o.y+s*r;return Math.sqrt(Math.pow(e.x-c,2)+Math.pow(e.y-l,2))},Td=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],n=e[e.length-1];for(let s=1;s<e.length-1;s++){let c=BL(e[s],r,n);c>t&&(t=c,a=s);}if(t>o){let s=Td(e.slice(0,a+1),o),c=Td(e.slice(a),o);return [...s.slice(0,-1),...c]}return [r,n]},OL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},NL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},jm=(e,o=1.5)=>{if(e.length<=4)return e;let t=OL(e),a=Td(t,o);return NL(a)},_m=(e,o=1.5)=>({...e,points:jm(e.points,o)}),HL=(e,o=1.5)=>e.map(t=>_m(t,o)),qL=(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 VL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var $m=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((n,s)=>{let c=new Image;c.onload=()=>{let{width:l,height:u}=c;if(l>t||u>a){let h=l/u;l>u?(l=Math.min(l,t),u=l/h):(u=Math.min(u,a),l=u*h);}let f=document.createElement("canvas");f.width=l,f.height=u;let d=f.getContext("2d");if(!d){s(new Error("Failed to get canvas context"));return}d.drawImage(c,0,0,l,u);let i=VL(e),m=f.toDataURL(i,r);n(m);},c.onerror=s,c.src=e;})};var yo=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},sr=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",ir=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",zL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,s=[],c=0;for(let l of e){let u=[],f=[],d=[];for(let i of l.images){let m=i.src;if(t&&m.startsWith("data:"))try{m=await $m(m,{maxWidth:a,maxHeight:r,quality:n});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(m.startsWith("data:")){let h=yo(m),p=sr(m);c+=h.byteLength;let x={id:i.id,x:i.x,y:i.y,width:i.width,height:i.height,draggable:i.draggable,rotation:i.rotation,locked:i.locked,link:i.link,altText:i.altText,zIndex:i.zIndex,buffer:h,mimeType:p};if(i.audioData&&i.audioData.startsWith("data:")){let v=yo(i.audioData),g=sr(i.audioData);c+=v.byteLength,x.audioBuffer=v,x.audioMimeType=g;}u.push(x);}}for(let i of l.videos){let m,h;if(i.videoBlob)m=await i.videoBlob.arrayBuffer(),h=i.videoBlob.type;else if(i.videoData&&i.videoData.startsWith("data:"))m=yo(i.videoData),h=sr(i.videoData);else {console.warn(`Video ${i.id} has no blob or videoData, skipping`);continue}c+=m.byteLength;let p={id:i.id,thumbnailDataUrl:i.thumbnailDataUrl,x:i.x,y:i.y,width:i.width,height:i.height,draggable:i.draggable,isPlaying:i.isPlaying,rotation:i.rotation,locked:i.locked,link:i.link,altText:i.altText,zIndex:i.zIndex,isRecorded:i.isRecorded,buffer:m,mimeType:h};if(i.audioData&&i.audioData.startsWith("data:")){let x=yo(i.audioData),v=sr(i.audioData);c+=x.byteLength,p.audioBuffer=x,p.audioMimeType=v;}f.push(p);}for(let i of l.photoFrames){let m={id:i.id,x:i.x,y:i.y,width:i.width,height:i.height,rotation:i.rotation,draggable:i.draggable,locked:i.locked,link:i.link,altText:i.altText,zIndex:i.zIndex,isCapturing:i.isCapturing};if(i.capturedImageUrl&&i.capturedImageUrl.startsWith("data:")){let h=yo(i.capturedImageUrl),p=sr(i.capturedImageUrl);c+=h.byteLength,m.buffer=h,m.mimeType=p;}if(i.audioData&&i.audioData.startsWith("data:")){let h=yo(i.audioData),p=sr(i.audioData);c+=h.byteLength,m.audioBuffer=h,m.audioMimeType=p;}d.push(m);}s.push({...l,images:u,videos:f,photoFrames:d});}return {slides:s,totalSize:c}},WL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},UL=e=>{let o=new FormData,t=e.slides.map((a,r)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,mimeType:n.mimeType,fileKey:`slide_${r}_image_${s}`,audioFileKey:n.audioBuffer?`slide_${r}_image_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),videos:a.videos.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,isPlaying:n.isPlaying,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isRecorded:n.isRecorded,mimeType:n.mimeType,fileKey:`slide_${r}_video_${s}`,thumbnailFileKey:`slide_${r}_video_${s}_thumbnail`,audioFileKey:n.audioBuffer?`slide_${r}_video_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),photoFrames:a.photoFrames.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,draggable:n.draggable,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isCapturing:n.isCapturing,mimeType:n.mimeType,fileKey:n.buffer?`slide_${r}_photoframe_${s}`:void 0,audioFileKey:n.audioBuffer?`slide_${r}_photoframe_${s}_audio`:void 0,audioMimeType:n.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${ir(n.mimeType)}`;if(o.append(`slide_${r}_image_${s}`,c,l),n.audioBuffer&&n.audioMimeType){let u=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${ir(n.audioMimeType)}`;o.append(`slide_${r}_image_${s}_audio`,u,f);}}),a.videos.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${ir(n.mimeType)}`;if(o.append(`slide_${r}_video_${s}`,c,l),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let u=yo(n.thumbnailDataUrl),f=new Blob([u],{type:"image/jpeg"}),d=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${s}_thumbnail`,f,d);}if(n.audioBuffer&&n.audioMimeType){let u=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${ir(n.audioMimeType)}`;o.append(`slide_${r}_video_${s}_audio`,u,f);}}),a.photoFrames.forEach((n,s)=>{if(n.buffer&&n.mimeType){let c=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${ir(n.mimeType)}`;o.append(`slide_${r}_photoframe_${s}`,c,l);}if(n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),l=`${n.id}_audio.${ir(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${s}_audio`,c,l);}});}),o};var jL=()=>{let e=_e(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let r=await yd(),n=Sd(),s=await Cd();if(r&&r.length>0){let c=await Yc(),l=r.map(f=>{if(f.videos&&f.videos.length>0){let d=f.videos.map(i=>{let m=c.get(i.id);if(m){let h=Jc(m.blob);return {...i,objectUrl:h,thumbnailDataUrl:m.thumbnailDataUrl,videoBlob:m.blob}}else return i});return {...f,videos:d}}return f}),u=n&&l.find(f=>f.id===n)?n:l[0].id;e(Co({slides:l,currentSlideId:u}));}e(s?Oi({title:s.title,description:s.description}):Xn(!0));}catch(r){console.error("Error loading persisted slides:",r),e(Xn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var Ym=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||""})),Zm=new WeakSet,Jm=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 ca(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},_L=()=>{let e=_e(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Zm.has(a))return;Zm.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await js(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(u){console.error("Error clearing local data:",u);}let c=n&&r.find(u=>u.id===n)?n:r[0].id,l=Ym(r);e(Co({slides:l,currentSlideId:c})),await Jm(l);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await js(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(u){console.error("Error clearing local data:",u);}let c=n&&r.find(u=>u.id===n)?n:r[0].id,l=Ym(r);e(Co({slides:l,currentSlideId:c})),await Jm(l);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
6
6
 
7
7
  lucide-react/dist/esm/shared/src/utils.js:
8
8
  lucide-react/dist/esm/defaultAttributes.js:
@@ -17,5 +17,5 @@ lucide-react/dist/esm/lucide-react.js:
17
17
  * This source code is licensed under the ISC license.
18
18
  * See the LICENSE file in the root directory of this source tree.
19
19
  *)
20
- */export{Iw as BASIC_EDITOR_TOOLBAR_CONFIG,AS as BottomToolbar,Tv as Canvas,Sw as DEFAULT_CONTEXT_MENU_CONFIG,Fs as DEFAULT_TOOLBAR_CONFIG,Pg as EditorRoot,pd as MobileActionButtons,iL as MobileBottomSection,md as MobilePrevPanel,dd as PublishButton,eo as ScreenRecorder,qS as SlideNavigation,xS as Toolbar,SS as TopNavBar,Lw as VIEWER_TOOLBAR_CONFIG,Ii as addFillInTheBlanks,ci as addFlashcard,li as addImage,gi as addImageAnnotation,ii as addLine,Li as addLongAnswer,vi as addMultipleChoice,pi as addPhotoFrame,bi as addPhotoFrameAnnotation,di as addShape,Si as addShortAnswer,ur as addSlide,ui as addText,wi as addTrueFalse,ko as addVideo,EL as arrayBufferToBase64,ki as bringToFront,br as clearCanvas,kp as clearImageAnnotations,Us as clearLocalData,Mp as clearPhotoFrameAnnotations,ni as createEmptySlide,yL as createViewerStore,qn as deleteFillInTheBlanks,Tn as deleteFlashcard,bn as deleteImage,Gn as deleteLineById,Nn as deleteLongAnswer,En as deleteMultipleChoice,An as deletePhotoFrame,In as deleteShape,Bn as deleteShortAnswer,cr as deleteSlide,Cn as deleteText,Rn as deleteTrueFalse,wn as deleteVideo,Vn as duplicateFillInTheBlanks,Mn as duplicateFlashcard,vn as duplicateImage,Pi as duplicateLine,Hn as duplicateLongAnswer,Dn as duplicateMultipleChoice,Pn as duplicatePhotoFrame,Ln as duplicateShape,On as duplicateShortAnswer,fr as duplicateSlide,kn as duplicateText,Fn as duplicateTrueFalse,Sn as duplicateVideo,hr as editFlashcard,Ap as editMultipleChoice,SL as exportSlideAsBlob,wL as exportSlideAsImage,Ai as finalizeDrawing,ML as getCompressionStats,LL as getSlideDataURL,vd as loadCurrentSlideId,xd as loadFromIndexedDB,Ri as loadPresentationMetadata,Sd as loadPresentationMetadataFromDB,Io as loadSlides,Ql as mergeToolbarConfig,fi as nextFlashcard,DL as prepareFormData,PL as prepareSlidesForPublishing,mi as previousFlashcard,Ao as redo,xn as removeLine,Ip as reorderSlides,wd as savePresentationMetadata,de as saveToHistory,Ca as selectAllSlides,Fi as selectAllSlidesIncludingInactive,yr as selectCanAddSlide,ve as selectCurrentSlide,Ia as selectCurrentSlideId,Bi as selectMetadataLoaded,wr as selectPresentationMetadata,Fp as selectSlideById,Ti as sendToBack,Ci as setActivityType,Wn as setAltText,Un as setAudioData,pr as setBackgroundColor,mr as setCurrentSlide,gr as setEditingActivity,vr as setEditingTextId,Ep as setLines,zn as setLink,jn as setMetadataLoaded,ma as setPenColor,Di as setPresentationDescription,Ei as setPresentationTitle,Qa as setShowFlashcardForm,La as setShowMcqForm,It as setSketchMode,Zr as setStrokeWidth,aa as setTool,Lp as setViewerMode,Vm as simplifyFlatPoints,zm as simplifyLine,TL as simplifyLines,vL as store,hi as toggleImageDrawingMode,Mi as toggleLock,xi as togglePhotoFrameDrawingMode,Rp as toggleSketchMode,Xa as toggleVideoPlaying,Mo as undo,xr as updateElementOrder,Sa as updateFillInTheBlanks,To as updateFlashcard,Co as updateImage,Cp as updateImageAnnotation,Pp as updateLastLine,Dp as updateLinePosition,Kn as updateLineTransform,Ja as updateLongAnswer,gt as updateMultipleChoice,Za as updatePhotoFrame,Tp as updatePhotoFrameAnnotation,Ya as updateShape,sa as updateShortAnswer,si as updateSlideThumbnail,Ft as updateText,ot as updateTrueFalse,yn as updateVideo,Se as useDispatch,OL as useInitialSlides,rl as useModalPortal,J as useSelector,BL as useSlidesPersistence};//# sourceMappingURL=index.js.map
20
+ */export{Ow as BASIC_EDITOR_TOOLBAR_CONFIG,zS as BottomToolbar,qv as Canvas,Fw as DEFAULT_CONTEXT_MENU_CONFIG,Ns as DEFAULT_TOOLBAR_CONFIG,qg as EditorRoot,xd as MobileActionButtons,vL as MobileBottomSection,gd as MobilePrevPanel,fd as PublishButton,to as ScreenRecorder,ZS as SlideNavigation,PS as Toolbar,FS as TopNavBar,Bw as VIEWER_TOOLBAR_CONFIG,Ti as addFillInTheBlanks,pi as addFlashcard,ci as addImage,vi as addImageAnnotation,ui as addLine,ki as addLongAnswer,Si as addMultipleChoice,xi as addPhotoFrame,wi as addPhotoFrameAnnotation,fi as addShape,Ci as addShortAnswer,cr as addSlide,mi as addText,Ii as addTrueFalse,To as addVideo,WL as arrayBufferToBase64,Pi as bringToFront,vr as clearCanvas,Fp as clearImageAnnotations,js as clearLocalData,Op as clearPhotoFrameAnnotations,li as createEmptySlide,EL as createViewerStore,Wn as deleteFillInTheBlanks,An as deleteFlashcard,wn as deleteImage,$n as deleteLineById,Vn as deleteLongAnswer,Fn as deleteMultipleChoice,Dn as deletePhotoFrame,Tn as deleteShape,Hn as deleteShortAnswer,fr as deleteSlide,Mn as deleteText,On as deleteTrueFalse,In as deleteVideo,Un as duplicateFillInTheBlanks,En as duplicateFlashcard,Sn as duplicateImage,Ri as duplicateLine,zn as duplicateLongAnswer,Bn as duplicateMultipleChoice,Rn as duplicatePhotoFrame,kn as duplicateShape,qn as duplicateShortAnswer,mr as duplicateSlide,Pn as duplicateText,Nn as duplicateTrueFalse,Cn as duplicateVideo,gr as editFlashcard,Np as editMultipleChoice,RL as exportSlideAsBlob,DL as exportSlideAsImage,Di as finalizeDrawing,ML as flushPendingSave,qL as getCompressionStats,FL as getSlideDataURL,Sd as loadCurrentSlideId,yd as loadFromIndexedDB,Oi as loadPresentationMetadata,Cd as loadPresentationMetadataFromDB,Co as loadSlides,ad as mergeToolbarConfig,hi as nextFlashcard,UL as prepareFormData,zL as prepareSlidesForPublishing,gi as previousFlashcard,Ao as redo,yn as removeLine,Dp as reorderSlides,Id as savePresentationMetadata,le as saveToHistory,Ma as selectAllSlides,Ni as selectAllSlidesIncludingInactive,wr as selectCanAddSlide,ve as selectCurrentSlide,Ta as selectCurrentSlideId,Hi as selectMetadataLoaded,Sr as selectPresentationMetadata,Wp as selectSlideById,Ai as sendToBack,Mi as setActivityType,Gn as setAltText,jn as setAudioData,hr as setBackgroundColor,pr as setCurrentSlide,xr as setEditingActivity,yr as setEditingTextId,qp as setLines,Kn as setLink,Xn as setMetadataLoaded,ha as setPenColor,Bi as setPresentationDescription,Fi as setPresentationTitle,eo as setShowFlashcardForm,ka as setShowMcqForm,It as setSketchMode,Jr as setStrokeWidth,ra as setTool,Ep as setViewerMode,jm as simplifyFlatPoints,_m as simplifyLine,HL as simplifyLines,AL as store,bi as toggleImageDrawingMode,Ei as toggleLock,yi as togglePhotoFrameDrawingMode,zp as toggleSketchMode,Ya as toggleVideoPlaying,Po as undo,br as updateElementOrder,Ca as updateFillInTheBlanks,Mo as updateFlashcard,ko as updateImage,Rp as updateImageAnnotation,Hp as updateLastLine,Vp as updateLinePosition,_n as updateLineTransform,Qa as updateLongAnswer,ht as updateMultipleChoice,Ja as updatePhotoFrame,Bp as updatePhotoFrameAnnotation,Za as updateShape,la as updateShortAnswer,di as updateSlideThumbnail,Ot as updateText,tt as updateTrueFalse,Ln as updateVideo,Se as useDispatch,_L as useInitialSlides,il as useModalPortal,Q as useSelector,jL as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
21
  //# sourceMappingURL=index.js.map