@turnix-co/konva-editor 4.0.1 → 4.0.2

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 Se from'react';import Se__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 Qu 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 Hd=e=>{throw TypeError(e)};var qd=(e,o,t)=>o.has(e)||Hd("Cannot "+t);var $=(e,o,t)=>(qd(e,o,"read from private field"),t?t.call(e):o.get(e)),He=(e,o,t)=>o.has(e)?Hd("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Re=(e,o,t,a)=>(qd(e,o,"write to private field"),o.set(e,t),t);var Vd=(e,o,t,a)=>({set _(n){Re(e,o,n);},get _(){return $(e,o,a)}});var we=()=>useDispatch(),te=e=>useSelector(e),$e=we,Fe=te;var ni=20,ut=(()=>{let e=0;return o=>`${o}-${Date.now()}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`})();function Tp(e){let o=JSON.parse(JSON.stringify(e));return o.id=ut("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:ut("line")})),o.shapes=o.shapes.map(t=>({...t,id:ut("shape")})),o.images=o.images.map(t=>({...t,id:ut("img"),annotations:t.annotations?.map(a=>({...a,id:ut("line")}))??[]})),o.videos=o.videos.map(t=>({...t,id:ut("vid"),isPlaying:false,videoBlob:void 0})),o.flashcards=o.flashcards.map(t=>({...t,id:ut("flashcard")})),o.photoFrames=o.photoFrames.map(t=>({...t,id:ut("photoframe"),isCapturing:false,annotations:t.annotations?.map(a=>({...a,id:ut("line")}))??[]})),o.texts=o.texts.map(t=>({...t,id:ut("text")})),o.multipleChoices=o.multipleChoices.map(t=>({...t,id:ut("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:ut("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:ut("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:ut("longAnswer"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0}}})),o.fillInTheBlanks=o.fillInTheBlanks.map(t=>({...t,id:ut("fillInTheBlank"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0,isCorrect:void 0,attempts:void 0}}})),o}var ii=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now(),isActive:true}),ri=ii("Page 1"),Mp={slides:[ri],currentSlideId:ri.id,history:{[ri.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false,editingOverlayPosition:null,zoomLevel:1},zd=createSlice({name:"canvas",initialState:Mp,reducers:{addSlide:e=>{if(e.slides.length>=ni)return;let o=ii(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(u=>u.isActive).length<=1)return;let r=e.slides.findIndex(u=>u.id===t);if(r===-1)return;let 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>=ni)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],n=Tp(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(g=>g.id===a);s&&(s.timestamp=r);break;case "video":let u=t.videos.find(g=>g.id===a);u&&(u.timestamp=r);break;case "shape":let i=t.shapes.find(g=>g.id===a);i&&(i.timestamp=r);break;case "text":let c=t.texts.find(g=>g.id===a);c&&(c.timestamp=r);break;case "flashcard":let f=t.flashcards.find(g=>g.id===a);f&&(f.timestamp=r);break;case "photoFrame":let d=t.photoFrames.find(g=>g.id===a);d&&(d.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(g=>g.id===a);l&&(l.timestamp=r);break;case "trueFalse":let m=t.trueFalses.find(g=>g.id===a);m&&(m.timestamp=r);break;case "shortAnswer":let h=t.shortAnswers.find(g=>g.id===a);h&&(h.timestamp=r);break;case "longAnswer":let p=t.LongAnswer.find(g=>g.id===a);p&&(p.timestamp=r);break;case "fillInTheBlanks":let v=t.fillInTheBlanks.find(g=>g.id===a);v&&(v.timestamp=r);break;case "line":let y=t.lines.find(g=>g.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:Ap,updateSlideThumbnail:li,setBackgroundColor:pr,reorderSlides:Pp,loadSlides:Io,addLine:di,removeLine:bn,addImage:ui,updateImage:Co,deleteImage:vn,duplicateImage:yn,addVideo:ko,updateVideo:wn,deleteVideo:Sn,duplicateVideo:Ln,toggleVideoPlaying:Za,addShape:ci,updateShape:Ja,duplicateShape:In,deleteShape:Cn,addText:fi,editingOverlayPosition:Wd,updateText:Ft,deleteText:kn,duplicateText:Tn,addFlashcard:mi,updateFlashcard:To,deleteFlashcard:Mn,duplicateFlashcard:An,editFlashcard:hr,nextFlashcard:pi,previousFlashcard:hi,addPhotoFrame:gi,updatePhotoFrame:Qa,deletePhotoFrame:Pn,duplicatePhotoFrame:En,toggleImageDrawingMode:xi,addImageAnnotation:bi,updateImageAnnotation:Ep,clearImageAnnotations:Dp,togglePhotoFrameDrawingMode:vi,addPhotoFrameAnnotation:yi,updatePhotoFrameAnnotation:Rp,clearPhotoFrameAnnotations:Fp,addMultipleChoice:wi,updateMultipleChoice:xt,updateMultipleChoiceDragAndDrop:Si,editMultipleChoice:Bp,deleteMultipleChoice:Dn,duplicateMultipleChoice:Rn,addTrueFalse:Li,updateTrueFalse:Qe,deleteTrueFalse:Fn,duplicateTrueFalse:Bn,addShortAnswer:Ii,updateShortAnswer:ea,deleteShortAnswer:On,duplicateShortAnswer:Nn,addLongAnswer:Ci,updateLongAnswer:La,deleteLongAnswer:Hn,duplicateLongAnswer:qn,addFillInTheBlanks:ki,updateFillInTheBlanks:la,deleteFillInTheBlanks:Vn,duplicateFillInTheBlanks:zn,setShowMcqForm:Ia,setShowFlashcardForm:eo,setActivityType:Ti,setEditingActivity:gr,bringToFront:Mi,sendToBack:Ai,toggleLock:Pi,setLink:Wn,setAltText:Un,setAudioData:Kn,updateLastLine:Op,finalizeDrawing:Ei,setLines:Np,updateLinePosition:Hp,updateLineTransform:Gn,deleteLineById:jn,duplicateLine:Di,updateElementOrder:xr,clearCanvas:br,undo:Mo,redo:Ao,saveToHistory:de,toggleSketchMode:qp,setSketchMode:It,setEditingTextId:vr,setPresentationTitle:Ri,setPresentationDescription:Fi,loadPresentationMetadata:Bi,setMetadataLoaded:_n,setZoomLevel:GL,zoomIn:jL,zoomOut:_L,resetZoom:Ud}=zd.actions;var Kd=e=>e.canvas.slides,Ca=e=>e.canvas.currentSlideId,ve=createSelector([Kd,Ca],(e,o)=>e.find(t=>t.id===o)),ka=createSelector([Kd],e=>e.filter(o=>o.isActive!==false)),Oi=e=>e.canvas.slides,yr=createSelector([ka],e=>e.length<ni),Vp=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,Ni=e=>e.canvas.metadataLoaded,Xn=e=>e.canvas.viewerMode,Hi=zd.reducer;var jd=e=>{let o=we(),t=useRef(null),a=useRef(false),n=te(m=>m.toolbar.selectedTool),r=te(m=>m.toolbar.penColor),s=te(m=>m.toolbar.strokeWidth),u=te(m=>m.canvas.isSketchMode),i=te(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(di(m)),o(Ei()),e?.();},[o,e]);return {lines:i,tool:n,color:r,strokeWidth:s,isSketchMode:u,setCanvasRef:c,startDrawing:f,draw:d,stopDrawing:l}};var Yd=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),g=useRef(r),x=useRef(u),L=useRef(i);useEffect(()=>{p.current=t,v.current=a,y.current=n,g.current=r,x.current=u,L.current=i;},[t,a,n,r,u,i]);let I=useCallback(()=>{let C=f.current;if(!C)return;let b=C.getContext("2d");b&&b.clearRect(0,0,C.width,C.height);},[]),F=useCallback(()=>{let C=f.current,b=m.current;if(!C||b.length<1)return;let k=C.getContext("2d");if(!k)return;if(k.clearRect(0,0,C.width,C.height),p.current==="eraser"?(k.globalCompositeOperation="destination-out",k.fillStyle="rgba(0,0,0,1)"):(k.globalCompositeOperation="source-over",k.fillStyle=v.current),b.length===1){k.beginPath(),k.arc(b[0].x,b[0].y,y.current/2,0,Math.PI*2),k.fill();return}let E=$d(b,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:M=>M,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(E.length<2)){k.beginPath(),k.moveTo(E[0][0],E[0][1]);for(let M=1;M<E.length;M++)k.lineTo(E[M][0],E[M][1]);k.closePath(),k.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:C=>{d.current=true;let b={x:C.x-x.current,y:C.y-L.current};l.current=[{x:C.x,y:C.y}],m.current=[b],h.current=C,F();},draw:C=>{if(!d.current||!h.current)return;let b=C.x-h.current.x,k=C.y-h.current.y;if(Math.sqrt(b*b+k*k)<2)return;let E={x:C.x-x.current,y:C.y-L.current};l.current.push({x:C.x,y:C.y}),m.current.push(E),h.current=C,F();},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 b=$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]]),k={tool:p.current,points:b,color:v.current,strokeWidth:y.current,isSketch:true};return l.current=[],m.current=[],h.current=null,I(),k},clear:()=>{I(),l.current=[],m.current=[],h.current=null,d.current=false;},isDrawing:()=>d.current,getCanvasElement:()=>f.current}),[I,F]),useEffect(()=>{let C=f.current;C&&(C.width=e,C.height=o);},[e,o]),jsx("canvas",{ref:f,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});Yd.displayName="DirectDrawingCanvas";var Zd=Yd;var Qd=e=>{let o=we(),a=te(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(),g=m.height(),x=Math.max(5,y*h),L=Math.max(5,g*p);l.scaleX(1),l.scaleY(1),m.width(x),m.height(L),o(Co({id:f,width:x,height:L,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 eu=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();c.scaleX(1),c.scaleY(1),o(xt({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(xt({id:i,x:u.target.x(),y:u.target.y()})),e?.();}}};var tu=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(),h=n.find(p=>p.id===u)?.data.responseType!=="classic";c.scaleX(1),c.scaleY(1),o(h?Qe({id:u,scaleX:f,scaleY:d,dragDropPos:{x:c.x(),y:c.y()},rotation:l}):Qe({id:u,scaleX:f,scaleY:d,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e,n]);return {trueFalse:n,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(u,i)=>{o(Qe({id:i,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var au=e=>{let o=we(),a=te(ve)?.videos||[],n=useRef(new Map),r=useCallback(i=>{o(Za(i));},[o]),s=useCallback((i,c)=>{let f=c.target;o(wn({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(wn({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 nu=e=>{let o=we(),a=te(ve)?.shapes||[],n=useRef(new Map),r=useRef(new Map),[s,u]=useState(false),i=useCallback((f,d)=>{let l=d.target;o(Ja({id:f,x:l.x(),y:l.y()})),e?.();},[o,e]),c=useCallback((f,d)=>{let l=d.target,m=a.find(x=>x.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 g={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":g.radius=l.width()*h/2;break;case "star":g.innerRadius=l.width()*h/4,g.outerRadius=l.width()*h/2;break;case "triangle":g.radius=l.width()*h/2;break;case "ellipse":g.radiusX=l.width()*h/2,g.radiusY=l.height()*p/2;break;case "polygon":g.radius=l.width()*h/2;break;case "ring":let x=h;g.innerRadius=m.innerRadius&&m.innerRadius*x,g.outerRadius=m.outerRadius&&m.outerRadius*x;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(Ja(g)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:n,isDragging:s,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:c}};var iu=(e,o)=>{let t=$e(),n=te(ve)?.texts||[],r=useRef(new Map),[s,u]=useState(null),[i,c]=useState("");return {texts:n,textRefs:r,handleDragEnd:(v,y)=>{let g=v.target;t(de()),t(Ft({id:y,x:g.x(),y:g.y()})),e();},handleTransformEnd:v=>{let y=r.current.get(v);if(!y)return;let g=y.scaleX(),x=y.scaleY(),L=n.find(F=>F.id===v);if(!L)return;let I=(g+x)/2;y.scaleX(1),y.scaleY(1),t(de()),t(Ft({id:v,x:y.x(),y:y.y(),width:Math.max(5,(L.width||100)*g),height:Math.max(5,(L.height||50)*x),fontSize:Math.round(Math.max(8,L.fontSize*I)),rotation:y.rotation()})),e();},handleDoubleClick:v=>{let y=n.find(g=>g.id===v);y&&!y.locked&&(u(v),c(y.text));},startEditing:v=>{let y=n.find(g=>g.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(x=>x.id===s);t(de());let g={id:s,text:i};if(y&&(y.fontWeight!==void 0&&(g.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(g.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(g.textDecoration=y.textDecoration)),o?.current&&i.trim()){let x=o.current,L=x.offsetWidth,I=x.offsetHeight,F=1;if(v){let G=v.getStage();G&&(F=G.scaleX());}let C=14,b=(L-C)/F,k=(I-C)/F,w=i.split(`
3
+ `).length,M=n.find(G=>G.id===s)?.fontSize||24,U=w*M*1.2+10;g.width=Math.max(200,b),g.height=Math.max(50,k,U);}else if(v&&i.trim()){let x=v.text(),L=v.width();v.text(i),v.width(void 0);let I=v.width(),F=v.height();v.text(x),v.width(L),g.width=Math.max(200,I+20),g.height=Math.max(50,F+20);}t(Ft(g)),u(null),c(""),t(vr(null)),e();}}}};var du=e=>{let o=useDispatch(),a=useSelector(ve)?.shortAnswers||[],n=useRef(new Map),r=useCallback((u,i)=>{let c=u.target;o(ea({id:i,x:c.x(),y:c.y()})),e?.();},[o,e]),s=useCallback((u,i)=>{let c=i.target,f=c.scaleX(),d=c.scaleY(),l=c.rotation();c.scaleX(1),c.scaleY(1),o(ea({id:u,scaleX:f,scaleY:d,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {shortAnswers:a,saRefs:n,handleShortAnswerDragEnd:r,handleShortAnswerTransform:s}};var cu=e=>{let o=useDispatch(),t=useSelector(ve),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),n=useCallback((s,u)=>{let i=s.target;o(La({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]),r=useCallback((s,u)=>{let i=u.target,c=i.scaleX(),f=i.scaleY(),d=i.rotation();i.scaleX(1),i.scaleY(1),o(La({id:s,scaleX:c,scaleY:f,x:i.x(),y:i.y(),rotation:d})),i.getLayer()?.batchDraw(),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:n,handleLongAnswerTransform:r}};var mu=e=>{let o=we(),a=te(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),g=Math.max(50,m.height()*p);m.scaleX(1),m.scaleY(1),m.width(y),m.height(g),o(To({id:d,width:y,height:g,x:m.x(),y:m.y(),rotation:v})),m.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(d=>{o(pi(d)),e?.();},[o,e]),f=useCallback(d=>{o(hi(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:n,handleDragEnd:u,handleFlashcardTransformEnd:i,handleNext:c,handlePrevious:f}};var gu=e=>{let o=we(),a=te(ve)?.photoFrames||[],n=useRef(new Map),[r,s]=useState(new Map),u=useCallback((m,h)=>{o(Qa({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(),g=p.rotation();p.scaleX(1),p.scaleY(1),o(Qa({id:m,scaleX:v,scaleY:y,x:p.x(),y:p.y(),rotation:g})),p.getLayer()?.batchDraw(),e?.();},[o,e]),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(Qa({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(Qa({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(Qa({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 xu=()=>{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 fh=(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])},wu=(e,o)=>{let t=$e(),a=Fe(Xn),n=useRef(e);useEffect(()=>{n.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(li({id:n.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),s=fh(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var ph=e=>e.flatMap(o=>[o[0],o[1]]),Yn=(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 ph(t)};var Su=e=>{let o=we(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null),u=te(x=>x.toolbar.selectedTool),i=te(x=>x.toolbar.penColor),c=te(x=>x.toolbar.strokeWidth),f=te(x=>x.canvas.isSketchMode),d=te(x=>x.canvas.slides.find(I=>I.id===x.canvas.currentSlideId)?.images.find(I=>I.id===e)),l=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(x=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,n.current=[{x:x.x,y:x.y}];let L=x.x/h,I=x.y/p;s({tool:u,points:[L,I],color:i,strokeWidth:c/h,isSketch:f});},[u,i,c,f,h,p]),y=useCallback(x=>{if(!t.current||!r)return;a.current=true;let L=n.current[n.current.length-1];if(Math.sqrt(Math.pow(x.x-L.x,2)+Math.pow(x.y-L.y,2))<2)return;n.current.push({x:x.x,y:x.y});let F;if(f)F=Yn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,k)=>k%2===0?b/h:b/p);else {let C=x.x/h,b=x.y/p;F=[...r.points,C,b];}s(C=>C?{...C,points:F}:null);},[f,c,r,h,p]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(bi({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:g,tool:u}};function ze({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 Tu=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}=Su(e.id),{createHandlers:h}=ze({onLongPress:u});useEffect(()=>{let x=t.current.get(e.id);x&&(x.width()!==e.width||x.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:x.width(),konvaHeight:x.height()}),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[l,p]);let v=x=>{{r(e.id);return}},y=x=>{return;},g=x=>{};return jsxs(Group,{listening:m!=="pen"&&m!=="eraser",children:[jsx(Image$1,{id:e.id,ref:x=>{if(x)t.current.set(e.id,x),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw();else {let L=t.current.get(e.id);L?._contextMenuCleanup&&L._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:m!=="pen"&&m!=="eraser",onDragEnd:a,onTransformEnd:x=>n(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:x=>{x.evt.preventDefault();let L=x.evt;s(L,e.id,"image");},...m!=="pen"&&m!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onMouseMove:y,onMouseUp:g,...h(e.id,"image")}:{}}),i?.map((x,L)=>{let I=x.points.map((C,b)=>b%2===0?C*e.width+e.x:C*e.height+e.y),F=x.strokeWidth*e.width;return jsx(Line,{points:I,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:F,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},L)}),c&&jsx(Line,{points:c.points.map((x,L)=>L%2===0?x*e.width+e.x:x*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});Tu.displayName="ImageWithDrawing";var Gi=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(Tu,{img:i,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u},i.id):null})}));Gi.displayName="ImageLayer";var Ch=({src:e,x:o,id:t,y:a,width:n,height:r,isSelected:s,rotation:u=0,onTransformEnd:i,onDragEnd:c})=>{let f=we(),d=useRef(null),l=m=>{f(Za(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"}})})]})},Mu=Ch;var Rh=({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=g=>{let x=p.getStage()?.getPointerPosition();if(x){let L={x:e.x,y:e.y,width:e.width,height:e.height};x.x>=L.x&&x.x<=L.x+L.width&&x.y>=L.y&&x.y<=L.y+L.height&&r(g);}};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}})]})},Pu=Rh;var Xi=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:n,onTransformEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(u=>jsxs(Se__default.Fragment,{children:[jsx(Pu,{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(Mu,{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))}));Xi.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}=ze({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 Ru=({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}=ze({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 ng=({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 g=new window.Image,x=e.images[e.currentIndex];(x.startsWith("http://")||x.startsWith("https://"))&&(g.crossOrigin="anonymous"),g.src=x,g.onload=()=>{l(g);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let 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:g=>{if(i(g),g){let x=g.getStage()?.container();if(x){let L=I=>{let F=g.getStage()?.getPointerPosition();if(F){let C={x:e.x,y:e.y,width:e.width,height:e.height};F.x>=C.x&&F.x<=C.x+C.width&&F.y>=C.y&&F.y<=C.y+C.height&&r(I);}};x.addEventListener("contextmenu",L),g._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",L);};}}},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:g=>{g.cancelBubble=true,u();},onTap:g=>{g.cancelBubble=true,u();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-y-v,y:e.height/2,onClick:g=>{g.cancelBubble=true,s();},onTap:g=>{g.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"})]})},Ou=ng;var Qi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onNext:s,onPrevious:u,onContextMenu:i,onLongPress:c})=>{let{createHandlers:f}=ze({onLongPress:c}),d=te(l=>l.toolbar.selectedTool);return jsx(Fragment,{children:e.map(l=>jsx(Ou,{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))})});Qi.displayName="FlashcardLayer";var Hu=e=>{let o=we(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null);te(x=>x.toolbar.selectedTool);let i=te(x=>x.toolbar.penColor),c=te(x=>x.toolbar.strokeWidth),f=te(x=>x.canvas.isSketchMode),d=te(x=>x.canvas.slides.find(I=>I.id===x.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),l=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(x=>{if(!m)return;t.current=true,a.current=false,n.current=[{x:x.x,y:x.y}];let L=x.x/h,I=x.y/p;s({tool:"pen",points:[L,I],color:i,strokeWidth:c/h,isSketch:f});},[m,i,c,f,h,p]),y=useCallback(x=>{if(!t.current||!r)return;a.current=true;let L=n.current[n.current.length-1];if(Math.sqrt(Math.pow(x.x-L.x,2)+Math.pow(x.y-L.y,2))<2)return;n.current.push({x:x.x,y:x.y});let F;if(f)F=Yn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,k)=>k%2===0?b/h:b/p);else {let C=x.x/h,b=x.y/p;F=[...r.points,C,b];}s(C=>C?{...C,points:F}:null);},[f,c,r,h,p]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(yi({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:g}};var mg=({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),g=useRef(null),x=useRef(0),L=33,I=useSelector(V=>V.toolbar.selectedTool),F=I==="pen"||I==="eraser",{annotations:C,activeLine:b,isDrawingMode:k,startDrawing:w,draw:E,stopDrawing:M}=Hu(e.id);useEffect(()=>{if(!k)return;let V=()=>{M();},O=()=>{M();};return window.addEventListener("mouseup",V),window.addEventListener("touchend",O),()=>{window.removeEventListener("mouseup",V),window.removeEventListener("touchend",O);}},[M,k]),useEffect(()=>{if(e.capturedImageUrl){let V=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(V.crossOrigin="anonymous"),V.src=e.capturedImageUrl,V.onload=()=>{l(V);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),v.current||(v.current=document.createElement("canvas"));let V=p.current,O=v.current;V.srcObject=i;let K=()=>{O.width=V.videoWidth||640,O.height=V.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",O.width,O.height);let j=ee=>{if(ee-x.current<L){y.current=requestAnimationFrame(j);return}x.current=ee;let Y=O.getContext("2d");if(Y&&V.readyState===V.HAVE_ENOUGH_DATA){Y.drawImage(V,0,0,O.width,O.height);let le=O.toDataURL("image/jpeg",.6),pe=new window.Image;pe.onload=()=>{h(pe);},pe.src=le;}y.current=requestAnimationFrame(j);};y.current=requestAnimationFrame(j);};return V.onloadedmetadata=K,V.readyState>=V.HAVE_METADATA&&K(),V.play().catch(j=>console.error("Error playing video:",j)),()=>{y.current&&(cancelAnimationFrame(y.current),y.current=null);}}return ()=>{h(null),g.current&&(g.current.src="");}},[e.isCapturing,i]);let A=()=>{p.current&&e.isCapturing&&u(p.current);},U=V=>{if(e.capturedImageUrl){if(!k){t();return}let O=V.currentTarget,K=O.getAbsoluteTransform().copy(),ee=O.getStage()?.getPointerPosition();if(ee){K.invert();let Y=K.point(ee);w(Y);}V.cancelBubble=true;}else t();},G=V=>{if(!k||!e.capturedImageUrl)return;let O=V.currentTarget,K=O.getAbsoluteTransform().copy(),ee=O.getStage()?.getPointerPosition();if(ee){K.invert();let Y=K.point(ee);E(Y);}},B=()=>{!k||!e.capturedImageUrl||M();},W=e.isCapturing?m:d,q=Math.min(e.width,e.height)*.12,N=Math.max(25,Math.min(q,50)),Z=e.width/2,X=e.height/2;return jsxs(Group,{id:e.id,draggable:!k&&!F,listening:true,onClick:t,onTap:t,x:e.x,y:e.y,scaleX:e.scaleX||1,scaleY:e.scaleY||1,...f,...F?{}:{onDragEnd:a,onTransformEnd:n},rotation:e.rotation,width:e.width,height:e.height,ref:V=>{if(c(V),V){let O=V.getStage()?.container();if(O){let K=j=>{let ee=V.getStage()?.getPointerPosition();if(ee){let Y={x:e.x,y:e.y,width:e.width,height:e.height};ee.x>=Y.x&&ee.x<=Y.x+Y.width&&ee.y>=Y.y&&ee.y<=Y.y+Y.height&&r(j);}};O.addEventListener("contextmenu",K),V._contextMenuCleanup=()=>{O.removeEventListener("contextmenu",K);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:W?"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}}),W&&jsx(Image$1,{image:W,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:U,onTap:U,onMouseDown:U,onTouchStart:U,onMouseMove:G,onTouchMove:G,onMouseUp:B,onTouchEnd:B,...F?{}:{onDragEnd:a,onTransformEnd:n}}),C?.map((V,O)=>{let K=V.points.map((ee,Y)=>Y%2===0?ee*e.width:ee*e.height),j=V.strokeWidth*e.width;return jsx(Line,{points:K,stroke:V.tool==="eraser"?"white":V.color,strokeWidth:j,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:V.tool==="eraser"?"destination-out":"source-over",fill:V.isSketch?V.color:void 0,closed:V.isSketch,listening:false},O)}),b&&jsx(Line,{points:b.points.map((V,O)=>O%2===0?V*e.width:V*e.height),stroke:b.tool==="eraser"?"white":b.color,strokeWidth:b.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},"active"),!W&&!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:Z-N+6,y:X-60,width:N*1.6,height:N*1.6,radius:N,fill:"white",cornerRadius:8,listening:true,onClick:V=>{V.cancelBubble=true,e.isCapturing?A():s();},onTap:V=>{V.cancelBubble=true,e.isCapturing?A():s();}}),jsx(Html,{groupProps:{x:Z-12,y:X-40,width:N*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:V=>{V.stopPropagation(),e.isCapturing?A():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:Z-24,y:X+104,width:N*1.6,height:N*1.6,radius:N,fill:"#096B76",cornerRadius:N,listening:true,onClick:V=>{V.cancelBubble=true,e.isCapturing?A():s();},onTap:V=>{V.cancelBubble=true,e.isCapturing?A():s();}}),jsx(Html,{groupProps:{x:Z-8,y:X+120,width:N*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:V=>{V.stopPropagation(),e.isCapturing?A():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:Z-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:V=>{V.stopPropagation(),A();},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})})})})]})]})},Wu=mg;var nl=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}=ze({onLongPress:f});return jsx(Fragment,{children:e.map(l=>jsx(Wu,{photoFrame:l,isSelected:t===l.id,onClick:()=>r(l.id),onDragEnd:m=>a(m,l.id),onTransformEnd:m=>n(l.id,m),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))})});nl.displayName="PhotoFrameLayer";var ju=({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 _u=({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 $u=createContext(null),sl=()=>useContext($u);function Fg({children:e,className:o="",style:t}){let a=useRef(null),[n,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx($u.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 We(){let e=sl();return typeof document>"u"?null:e||document.body}var Yu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:n,onClose:r})=>{let[s,u]=useState(a),i=useRef(null),c=We();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 ts=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,n]=useState(e),r=useRef(null),s=We();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,g=m-h*Math.max(Math.min(y-3,9-y,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!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 Qg=({imageSrc:e,onCrop:o})=>{let[t]=Qu(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})]})})},ec=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[n,r]=useState({x:0,y:0,width:0,height:0}),[s]=Qu(e),u=We();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,g=document.createElement("canvas");g.width=v,g.height=y;let x=g.getContext("2d");if(!x)return;x.drawImage(s,h,p,v,y,0,0,v,y);let L=g.toDataURL("image/png");o(L);};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{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(Qg,{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 to=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let n=We(),[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),g=useRef(null),x=useRef(null),L=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,E=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let B=o.current.getLayers();console.log("Konva layers:",B.length),B.forEach((K,j)=>{let ee=K.getChildren();console.log(`Layer ${j} children count:`,ee.length);});let W=document.createElement("canvas");W.width=o.current.width(),W.height=o.current.height();let q=W.getContext("2d",{willReadFrequently:!1});if(!q){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",W.width,"x",W.height),x.current=W;let N=()=>{if(q.clearRect(0,0,W.width,W.height),B.forEach(K=>{let j=K.getCanvas()._canvas;j&&q.drawImage(j,0,0);}),a?.current){let K=a.current;q.drawImage(K,0,0);}};L.current=N,o.current.draw(),N(),await new Promise(K=>setTimeout(K,100)),console.log("Creating captureStream..."),w=W.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 V=0,O=()=>{N(),o?.current&&(o.current.getLayers().forEach(j=>{j.batchDraw();}),V++,V%60===0&&console.log("Drawing frame:",V)),y.current=requestAnimationFrame(O);};O();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{E=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(B){console.warn("Microphone access denied:",B);}let M=[...w.getVideoTracks()];E&&M.push(...E.getAudioTracks());let A=new MediaStream(M);v.current=A;let U="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?U="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?U="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?U="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(U="video/webm;codecs=vp8"),console.log("Using mimeType:",U);let G=new MediaRecorder(A,{mimeType:U,videoBitsPerSecond:25e5});m.current=G,h.current=[],G.ondataavailable=B=>{console.log("Data available, size:",B.data.size),B.data.size>0&&h.current.push(B.data);},G.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let B=new Blob(h.current,{type:U});console.log("Final blob size:",B.size),o?.current&&L.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(q=>{q.batchDraw();}),L.current(),g.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",g.current.length)),A.getTracks().forEach(W=>W.stop()),p.current&&clearInterval(p.current),y.current&&(cancelAnimationFrame(y.current),y.current=null),i(B);},G.onerror=B=>{console.error("MediaRecorder error:",B);},console.log("Starting recording..."),G.start(1e3),s(!0),f(0),p.current=setInterval(()=>{f(B=>B+1);},1e3);}catch(w){console.error("Error starting screen recording:",w),alert("Failed to start recording. Please ensure you granted permission.");}},F=()=>{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));},C=()=>{if(u){let w=URL.createObjectURL(u),E=document.createElement("a");E.href=w,E.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(w);}},b=w=>{let E=Math.floor(w/60),M=w%60;return `${E.toString().padStart(2,"0")}:${M.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:b(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:F,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 k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!u&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>l(!d),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${d?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:d?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:I,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),u&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(u),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",b(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&g.current&&(t(u,g.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:C,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),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(k,n)};var rc=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:n})=>{let r=We(),[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 g=async()=>{try{let w=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),E=new MediaRecorder(w);h.current=E,p.current=[],E.ondataavailable=M=>{M.data.size>0&&p.current.push(M.data);},E.onstop=()=>{let M=new Blob(p.current,{type:"audio/webm"});c(M),w.getTracks().forEach(A=>A.stop()),v.current&&clearInterval(v.current);},E.start(),u(!0),m(0),v.current=setInterval(()=>{m(M=>M+1);},1e3);}catch(w){console.error("Error starting audio recording:",w),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{h.current&&s&&(h.current.stop(),u(false));},L=()=>{if(i){let w=URL.createObjectURL(i),E=new Audio(w);y.current=E,E.onended=()=>{d(false),URL.revokeObjectURL(w);},E.play(),d(true);}},I=()=>{y.current&&(y.current.pause(),y.current.currentTime=0,d(false));},F=async()=>{if(i){let w=new FileReader;w.onloadend=()=>{let E=w.result;t(E),n();},w.readAsDataURL(i);}},C=()=>{c(null),a();},b=w=>{let E=Math.floor(w/60),M=w%60;return `${E.toString().padStart(2,"0")}:${M.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:b(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:x,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(w,r)}let k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&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"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:f?I:L,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:C,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:F,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(k,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 ic=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=we(),n=te(ve),r=We(),s=useMemo(()=>{if(!n)return [];let y=[];return n.images?.forEach(g=>{y.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),n.videos?.forEach(g=>{y.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),n.shapes?.forEach(g=>{y.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),n.texts?.forEach(g=>{y.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),n.flashcards?.forEach(g=>{y.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),n.photoFrames?.forEach(g=>{y.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),n.multipleChoices?.forEach(g=>{y.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),n.trueFalses?.forEach(g=>{y.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),n.shortAnswers?.forEach(g=>{y.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),n.LongAnswer?.forEach(g=>{y.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),n.fillInTheBlanks?.forEach(g=>{y.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),n.lines?.forEach(g=>{g.id&&y.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),y.sort((g,x)=>x.timestamp-g.timestamp)},[n]),[u,i]=useState(s),[c,f]=useState(false);useEffect(()=>{c||i(s);},[s]);let d=y=>{let g="h-5 w-5";switch(y){case "image":return jsx(Image$3,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes$1,{className:g});case "text":return jsx(TextT,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners$1,{className:g});case "line":return jsx(Pen,{className:g});default:return jsx(Question,{className:g})}},h=y=>{f(true),i(y);},p=()=>{f(false);let y=Date.now();u.forEach((g,x)=>{let L=y-x;a(xr({id:g.id,type:g.type,newTimestamp:L}));});};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 g=y.id===e;return jsxs(Reorder.Item,{value:y,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${g?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(y.id,y.type),className:`font-medium ${g?"text-[#096B76]":"text-[#00000099]"}`,children:y.name})}),jsx("div",{className:`${g?"text-[#096B76]":"text-[#00000099]"}`,children:d(y.type)})]},y.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[u.length," Layers"]})]})]})]});return createPortal(v,r)};var is=(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},lc=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,touchHandlers:s,onUpdate:u})=>{let i=useSelector(B=>B.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,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 x=new Set(e.data.responseOptions.correctIndex),L=x.size>1,I=B=>{if(y)return;let W;L?(W=new Set(p),W.has(B)?W.delete(B):W.add(B)):W=new Set([B]),v(W);let q=Array.from(W),N=q.length===e.data.responseOptions.correctIndex.length&&q.every(Z=>e.data.responseOptions.correctIndex.includes(Z));h(xt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:q,isCorrect:N}}})),u?.();},F=()=>{p.size>0&&(g(true),h(xt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},C=()=>{g(false),v(new Set);},b=p.size===x.size&&Array.from(p).every(B=>x.has(B)),k=Array.from(p).filter(B=>x.has(B)),w=L&&k.length>0&&!b,E=()=>b?"\u2713 Correct! Great job! \u{1F389}":w?`\u26A0 Partially correct (${k.length}/${x.size})`:"\u2717 Try again!",M=()=>b?{bg:"#dcfce7",text:"#166534"}:w?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},A=useMemo(()=>{let O=e.data.feedbackMode==="practice"?48:0,K=12,j=e.width-48,ee=j-80,Y=Math.max(60,is(e.data.question,20,j,"bold")+20),le=`Select ${x.size} answers (${p.size}/${x.size} selected)`,pe=L&&!y&&e.data.feedbackMode==="practice"?is(le,14,j)+10:0,ye=y&&e.data.feedbackMode==="practice"?Math.max(60,is(E(),16,j-40)+30):0,ce=e.data.responseOptions.options.map(re=>{let Xe=is(re,16,ee);return Math.max(55,Xe+20)}),ge=Y+pe+ye,Le=ce.reduce((re,Xe)=>re+Xe+8,-8),Ae=ge+Le+K+O+24;return {padding:24,questionHeight:Y,instructionHeight:pe,feedbackHeight:ye,optionsStartY:ge,optionHeights:ce,totalHeight:Ae,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:O,buttonTopMargin:K,availableWidth:j,optionTextWidth:ee}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,y,p.size,x.size,L,E]),U=e.scaleX||1,G=e.scaleY||1;return jsxs(Group,{ref:m,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,scaleX:U,scaleY:G,rotation:e.rotation,width:e.width,height:A.totalHeight,onTransformEnd:B=>o(e.id,B),...s,...c?{}:{onDragEnd:n,onClick:B=>t&&t(e.id),onTap:B=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:A.totalHeight,width:e.width,onContextMenu:B=>{B.cancelBubble=true,r(B.evt,e.id,"mcq");}}),jsx(Text,{x:A.padding+8,y:A.padding,text:e.data.question,fontSize:A.questionFontSize,fontStyle:"bold",fill:"#111827",width:A.availableWidth,height:A.questionHeight-A.padding,wrap:"word",ellipsis:true,listening:false}),A.instructionHeight>0&&jsx(Text,{x:A.padding,y:A.questionHeight,text:`Select ${x.size} answers (${p.size}/${x.size} selected)`,fontSize:A.instructionFontSize,fill:"#6b7280",width:A.availableWidth,wrap:"word",listening:false}),y&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:A.padding+24,y:A.questionHeight+A.instructionHeight+10,width:A.availableWidth-40,height:A.feedbackHeight-20,fill:M().bg,cornerRadius:8}),jsx(Text,{x:A.padding+24,y:A.questionHeight+A.instructionHeight+10,width:A.availableWidth-40,height:A.feedbackHeight-20,text:E()+` (${l} attempts)`,fontSize:A.feedbackFontSize,fontStyle:"bold",fill:M().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((B,W)=>{let q=x.has(W),N=p.has(W),Z=A.optionsStartY;for(let j=0;j<W;j++)Z+=A.optionHeights[j]+A.optionGap;let X=A.optionHeights[W],V="#e5e7eb",O="#ffffff",K="#111827";return y&&N&&!q?(V="#ef4444",O="#fee2e2",K="#ef4444"):N&&(V="#096B76",O="#ECFFF8",K="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:A.padding+12,y:Z+(X-20)/2,width:20,height:20,fill:N?"#096B76":"white",stroke:N?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:L?4:10,onClick:j=>{j.cancelBubble=true,I(W);},onTap:j=>{j.cancelBubble=true,I(W);}}),N&&jsx(Text,{x:A.padding+12,y:Z+(X-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:A.padding+44,y:Z,width:A.availableWidth-60,height:X,fill:O,stroke:V,strokeWidth:2,cornerRadius:8,onClick:j=>{j.cancelBubble=true,I(W);},onTap:j=>{j.cancelBubble=true,I(W);}}),jsx(Text,{x:A.padding+60,y:Z+10,width:A.optionTextWidth,height:X-20,text:B,fontSize:A.optionFontSize,fill:K,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},W)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:A.optionsStartY+A.optionHeights.reduce((B,W)=>B+W+A.optionGap,-A.optionGap)+A.buttonTopMargin,children:[jsxs(Group,{onMouseDown:B=>{B.cancelBubble=true,d("check");},onMouseUp:B=>{B.cancelBubble=true,d(null),F();},onMouseLeave:B=>{B.cancelBubble=true,d(null);},onTouchStart:B=>{B.cancelBubble=true,d("check");},onTouchEnd:B=>{B.cancelBubble=true,d(null),F();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:A.padding+14,width:(A.availableWidth-24)/(y?2:1),height:A.buttonHeight,fill:p.size===0||y?"#9ca3af":"#096B76",cornerRadius:8,onClick:B=>B.cancelBubble=true,onTap:B=>B.cancelBubble=true}),jsx(Text,{x:A.padding+14,width:(A.availableWidth-24)/(y?2:1),height:A.buttonHeight,text:y?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),y&&jsxs(Group,{x:(e.width-A.padding*2)/2+8,onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),C();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),C();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:A.padding,width:(A.availableWidth-8)/2,height:A.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:B=>B.cancelBubble=true,onTap:B=>B.cancelBubble=true}),jsx(Text,{x:A.padding,width:(A.availableWidth-8)/2,height:A.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});lc.displayName="MultipleChoice";var dc=lc;var Kx=(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},cl=({multipleChoice:e,handleMcqTransform:o,onContextMenu:t,handleSelect:a,mcqRefs:n,touchHandlers:r,onUpdate:s})=>{let u=useDispatch(),i=useSelector(N=>N.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(false),l=e.data.responseOptions.selectedIndices??[],m=useMemo(()=>new Set(l),[l]),h=e.data.responseOptions.attempts??0,p=h>0,[v,y]=useState(false),[g,x]=useState(0),L=new Set(e.data.responseOptions.correctIndex),I=Array.from(m).filter(N=>L.has(N)),F=m.size===L.size&&Array.from(m).every(N=>L.has(N)),C=I.length>0&&!F,b=()=>F?"\u2713 Correct! Great job!":C?`\u26A0 Partially correct (${I.length}/${L.size})`:"\u2717 Try again!",k=useCallback(N=>{let Z=N.target;u(Si({id:e.id,dragDropPos:{x:Z.x(),y:Z.y()}})),s?.();},[u,e.id,s]),w=useMemo(()=>{let Z=Math.max(window.innerWidth*.3,500),X=20,V=18,O=28,K=40,j=50,ee=20,Y=60,le=Math.max(Z-40,400),pe=Math.max(60,Kx(e.data.question,X,le,"bold")),ye=Math.max(Z-ee*2,400),ce=Math.max(150,window.innerHeight*.2),ge=e.data.feedbackMode==="practice",Le=pe+20+ce+(p?Y+18:0)+(ge?K+(p?j:0)+20:0),Ae=Le+100;return {screenWidth:Z,screenHeight:Ae,dropZoneWidth:ye,dropZoneHeight:ce,questionFontSize:X,questionHeight:pe,feedbackFontSize:V,feedbackHeight:Y,dropHereFontSize:O,buttonHeight:K,buttonGap:j,padding:ee,contentWidth:le,totalContentHeight:Le,isPracticeMode:ge}},[e.data.question,e.data.feedbackMode,p]),E=useRef(null);useEffect(()=>{let N=E.current;if(N)return n.current.set(e.id,N),()=>{n.current.delete(e.id);}},[e.id,n]);let M=N=>{u(Si({id:e.id,dragDropPos:{x:N.target.x(),y:N.target.y()}})),s?.();},A=N=>{let Z=N.target,X=Z.x(),V=Z.y(),O=window.innerWidth*.2,K=50,j=w.padding,ee=w.padding+w.dropZoneWidth,Y=w.questionHeight+20,le=w.questionHeight+20+w.dropZoneHeight,pe=X+O>j&&X<ee&&V+K>Y&&V<le;d(pe),s?.();},U=(N,Z)=>{let X=Z.target,V=X.x(),O=X.y(),K=window.innerWidth*.2,j=50;u(xt({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[N]:{x:V,y:O}}}));let ee=w.padding,Y=w.padding+w.dropZoneWidth,le=w.questionHeight+20,pe=w.questionHeight+20+w.dropZoneHeight,ye=V+K>ee&&V<Y&&O+j>le&&O<pe,ce;ye?ce=new Set(m).add(N):(ce=new Set(m),ce.delete(N)),d(false);let ge=Array.from(ce),Le=ge.length===L.size&&ge.every(Ae=>L.has(Ae));u(xt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:ge,isCorrect:Le}}})),s?.();},G=()=>{u(xt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},B=()=>{u(xt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),d(false),x(N=>N+1),s?.();},W=()=>F?{bg:"#dcfce7",text:"#166534"}:C?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},q=()=>p?F?"#4CAF50":C?"#f59e0b":"#ef4444":f?"#4CAF50":"#075560";return jsxs(Group,{ref:E,x:e.dragDropPos?.x,y:e.dragDropPos?.y,name:"mcq-element",width:w.screenWidth,height:w.screenHeight,scaleX:e.scaleX||1,scaleY:e.scaleY||1,draggable:!c,listening:!c,onDragMove:k,onTransformEnd:N=>o(e.id,N),...r,...c?{}:{onClick:N=>a&&a(e.id),onTap:N=>a&&a(e.id),onContextMenu:N=>{N.evt.preventDefault(),t(N.evt,e.id,"mcq");}},children:[jsxs(Group,{rotation:e.rotation,onDragEnd:M,children:[jsx(Rect,{fill:"white",stroke:f?"#4CAF50":"#e5e7eb",strokeWidth:f?4:2,cornerRadius:12,height:w.totalContentHeight+20,width:w.screenWidth,shadowColor:f?"#4CAF50":"transparent",shadowBlur:f?20:0,shadowOpacity:.5}),jsx(Text,{x:w.padding,y:w.padding,width:w.contentWidth,height:w.questionHeight-w.padding,text:e.data.question,fontSize:w.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:w.padding,y:w.questionHeight+20,width:w.dropZoneWidth,height:w.dropZoneHeight,fill:"#EBF6F7",stroke:q(),strokeWidth:3,dash:[10,10],cornerRadius:8}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:w.padding+3,y:w.questionHeight+20+w.dropZoneHeight+18,width:w.dropZoneWidth-5,height:w.feedbackHeight,fill:W().bg,cornerRadius:8}),jsx(Text,{x:w.padding,y:w.questionHeight+20+w.dropZoneHeight+20,width:w.dropZoneWidth,height:w.feedbackHeight,text:b()+` (${h} attempts)`,fontSize:w.feedbackFontSize,fontStyle:"bold",fill:W().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),m.size===0&&!p&&jsx(Text,{x:w.padding,y:w.questionHeight+20,width:w.dropZoneWidth,height:w.dropZoneHeight,text:L.size>1?`Drop ${L.size} Correct Answers Here`:"Drop Here",fontSize:w.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),w.isPracticeMode?jsxs(Group,{x:w.padding,y:w.questionHeight+20+w.dropZoneHeight+(p?w.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:N=>{N.cancelBubble=true,!(p||m.size===0)&&(y(true),G());},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{y(true),G();},onTouchEnd:()=>y(false),scaleX:v?.95:1,scaleY:v?.95:1,children:[jsx(Rect,{fill:p||m.size===0?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:w.buttonHeight,width:w.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:p||m.size===0?"#9ca3af":"white",width:w.dropZoneWidth,height:w.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),p&&jsxs(Group,{y:w.buttonGap,onMouseDown:B,onTouchStart:B,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:w.buttonHeight,width:w.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:w.dropZoneWidth,height:w.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((N,Z)=>{let X=Z%2,V=Math.floor(Z/2),O=w.dropZoneWidth/2+25,K=50,j=10,ee=m.has(Z),Y=L.has(Z),le=p&&ee,pe="transparent";le?pe=Y?"#4CAF50":"#ef4444":ee&&(pe="#4CAF50");let ye=p&&!ee?0:1,ce=e.optionDragDropPos?.[Z],ge=ce?.x??X*(O+j),Le=ce?.y??w.totalContentHeight+30+V*(K+j);return jsxs(Group,{x:ge,y:Le,draggable:!p,onDragStart:Ae=>{Ae.cancelBubble=true;},onDragMove:Ae=>{Ae.cancelBubble=true,A(Ae);},onDragEnd:Ae=>{Ae.cancelBubble=true,U(Z,Ae);},opacity:ye,children:[jsx(Rect,{width:O-20,height:K,fill:"white",stroke:pe,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:O-20,height:K,text:N,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${Z}-${g}`)})]})};cl.displayName="MultipleChoiceDragAndDrop";var cc=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=ze({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(dc,{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(cl,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id))})};var fc=(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},mc=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s,onUpdate:u})=>{let i=useSelector(A=>A.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),g=useRef(null);useEffect(()=>{let A=g.current;if(A)return a.current.set(e.id,A),()=>{a.current.delete(e.id);}},[e.id]);let x=()=>{v!==null&&d(true),p(Qe({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},L=()=>{d(false),y(null);},I=e.data.responseOptions.correctAnswer,F=v===I,C=A=>{if(f)return;y(A);let U=A===e.data.responseOptions.correctAnswer;p(Qe({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:A,isCorrect:U}}})),u?.();},b=()=>F?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",k=()=>F?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},w=useMemo(()=>{let N=e.data.feedbackMode==="practice"?48:0,Z=12,X=e.width-48,V=Math.max(60,fc(e.data.question,20,X,"bold")+20),O=f&&e.data.feedbackMode==="practice"?Math.max(60,fc(b(),16,X-40)+30):0,K=V+O,j=164,ee=K+j+Z+N+24;return {padding:24,questionHeight:V,feedbackHeight:O,optionsStartY:K,optionsHeight:j,totalHeight:ee,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:N,buttonTopMargin:Z,availableWidth:X}},[e.width,e.data.question,e.data.feedbackMode,f,b]),E=e.scaleX||1,M=e.scaleY||1;return jsxs(Group,{ref:g,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,scaleX:E,scaleY:M,rotation:e.rotation,width:e.width,height:w.totalHeight,onTransformEnd:A=>o(e.id,A),...s,...c?{}:{onDragEnd:A=>r(A,e.id),onClick:A=>t&&t(e.id),onTap:A=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:w.totalHeight,width:e.width,onContextMenu:A=>{A.cancelBubble=true,n(A.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:k().bg,cornerRadius:8}),jsx(Text,{x:w.padding+24,y:w.questionHeight+10,width:w.availableWidth-40,height:w.feedbackHeight-20,text:b()+` (${l} attempts)`,fontSize:w.feedbackFontSize,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((A,U)=>{let G=I===A.value,B=v===A.value,W=(e.width-w.padding*3)/2,q=w.padding+U*(W+w.padding),N=w.optionsStartY,Z=A.value===true,X=Z?"#10b981":"#ef4444",V="#ffffff",O="#ffffff",K="#e5e7eb";return f&&B&&(G?(O=Z?"#f0fdf4":"#fef2f2",K=Z?"#86efac":"#fecaca"):(O="#fee2e2",K="#ef4444")),B&&!f&&(K="#096B76",O="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:q,y:N,width:W,height:w.optionHeight+50,fill:O,stroke:K,strokeWidth:2,cornerRadius:12,onClick:j=>{j.cancelBubble=true,C(A.value);},onTap:j=>{j.cancelBubble=true,C(A.value);}}),jsx(Circle,{x:q+W/2,y:N+40,radius:28,fill:X,listening:false}),Z?jsx(Text,{x:q+W/2-14,y:N+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:V,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:q+W/2-14,y:N+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:V,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:q,y:N+85,width:W,height:30,text:A.label,fontSize:w.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},A.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:w.optionsStartY+2*(w.optionHeight+w.optionGap)+w.buttonTopMargin,children:[jsxs(Group,{onMouseDown:A=>{A.cancelBubble=true,h("check");},onMouseUp:A=>{A.cancelBubble=true,h(null),x();},onMouseLeave:A=>{A.cancelBubble=true,h(null);},onTouchStart:A=>{A.cancelBubble=true,h("check");},onTouchEnd:A=>{A.cancelBubble=true,h(null),x();},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:A=>A.cancelBubble=true,onTap:A=>A.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),L();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),L();},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:A=>A.cancelBubble=true,onTap:A=>A.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})]})]})]})});mc.displayName="TrueFalse";var pc=mc;var sb="#FFFFFF",hl=({trueFalse:e,handleTrueFalseTransform:o,onContextMenu:t,handleSelect:a,trueFalseRefs:n,touchHandlers:r,onUpdate:s})=>{let u=useDispatch(),i=useSelector(O=>O.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(false),l=e.data.responseOptions.selectedResponse??null,m=(e.data.responseOptions.attempts??0)>0,[h,p]=useState(false),[v,y]=useState(0),g=e.data.responseOptions.attempts||0,x=340,L=100,I=Math.max(window.innerWidth*.3,400),F=window.innerHeight*.5,C=useRef(null);useEffect(()=>{let O=C.current;if(O)return n.current.set(e.id,O),()=>{n.current.delete(e.id);}},[e.id]);let k=Math.max(60,((O,K,j,ee)=>{let le=document.createElement("canvas").getContext("2d");if(!le)return K;le.font=`${ee} ${K}px Arial, sans-serif`;let pe=O.split(" "),ye=[],ce="";return pe.forEach(ge=>{let Le=ce?`${ce} ${ge}`:ge;le.measureText(Le).width>j&&ce!==""?(ye.push(ce),ce=ge):ce=Le;}),ce&&ye.push(ce),ye.length*K*1.2})(e.data.question,20,I-40,"bold")+20),w=k+10,E=I-40,M=F-k-250,A=useCallback(O=>{let K=O.target;u(Qe({id:e.id,dragDropPos:{x:K.x(),y:K.y()}})),s?.();},[u,e.id,s]),U=O=>{u(Qe({id:e.id,dragDropPos:{x:O.target.x(),y:O.target.y()}})),s?.();},G=O=>{let K=O.target,j=K.x(),ee=K.y(),Y=window.innerWidth*.2-40,le=50,pe=20,ye=20+E,ce=w,ge=w+M,Le=j+Y>pe&&j<ye&&ee+le>ce&&ee<ge;d(Le),s?.();},B=(O,K)=>{let j=O?"true":"false",ee=K.target;u(Qe({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[j]:{x:ee.x(),y:ee.y()}}}));let Y=ee.x(),le=ee.y(),pe=window.innerWidth*.2-40,ye=50,ce=20,ge=20+E,Le=w,Ae=w+M;if(!(Y+pe>ce&&Y<ge&&le+ye>Le&&le<Ae)){d(false);return}d(false);let Xe=O===e.data.responseOptions.correctAnswer;u(Qe({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:O,isCorrect:Xe}}}));},W=()=>{u(Qe({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},q=()=>{u(Qe({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),d(false),y(O=>O+1),s?.();},N=e.data.responseOptions.correctAnswer,Z=l===N,X=()=>Z?"\u2713 Correct! Great job!":"\u2717 Try again!",V=()=>Z?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:C,name:"trueFalse-element",width:I,height:F,x:e.dragDropPos?.x,y:e.dragDropPos?.y,scaleX:e.scaleX||1,scaleY:e.scaleY||1,draggable:!c,listening:!c,onDragMove:A,onTransformEnd:O=>o(e.id,O),...r,...c?{}:{onClick:O=>a&&a(e.id),onTap:O=>a&&a(e.id),onContextMenu:O=>{O.evt.preventDefault(),t(O.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:L,rotation:e.rotation,onDragEnd:U,children:[jsx(Rect,{fill:"white",stroke:f?"#4CAF50":"#e5e7eb",strokeWidth:f?4:2,cornerRadius:12,height:m?F:e.data.feedbackMode==="practice"?F-50:F-100,width:I,shadowColor:f?"#4CAF50":"transparent",shadowBlur:f?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:I-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:w,width:E,height:M,fill:"transparent",stroke:f?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:w,width:E,height:60,fill:V().bg,cornerRadius:8}),jsx(Text,{x:20,y:w,width:E,height:60,text:X()+" ("+g+" attempts)",fontSize:18,fontStyle:"bold",fill:V().text,align:"center",verticalAlign:"middle"})]}),l===null&&!m&&jsx(Text,{x:20,y:w,width:E,height:M,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),[{value:true,label:"True"},{value:false,label:"False"}].map((O,K)=>{let j=E/2+20,ee=50,Y=10,le=l===O.value,pe=N===O.value,ye=m&&le,ce=O.value?"true":"false",ge=16+K*(j+Y),Le=L+F-300,Ae=e.optionDragDropPos?.[ce],re="transparent";return ye?re=pe?"#4CAF50":"#ef4444":le&&(re="#4CAF50"),jsxs(Group,{x:Ae?.x??ge,y:Ae?.y??Le,draggable:!m,onDragStart:Xe=>{Xe.cancelBubble=true;},onDragMove:Xe=>{Xe.cancelBubble=true,G(Xe);},onDragEnd:Xe=>{Xe.cancelBubble=true,B(O.value,Xe);},opacity:m&&!le?.5:1,children:[jsx(Rect,{width:j-40,height:ee,fill:"#075560",stroke:re,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:j-40,height:ee,text:O.label,fontSize:18,fontStyle:"bold",fill:sb,align:"center",verticalAlign:"middle",listening:false})]},`${O.value}-${v}`)}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:F-100,children:[jsxs(Group,{onMouseDown:O=>{O.cancelBubble=true,!(m||l===null)&&l!==null&&(p(true),W());},onMouseUp:()=>p(false),onMouseLeave:()=>p(false),onTouchStart:()=>{l!==null&&(p(true),W());},onTouchEnd:()=>p(false),scaleX:h?.95:1,scaleY:h?.95:1,children:[jsx(Rect,{fill:m||l===null?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:E}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:m||l===null?"#9ca3af":"white",width:E,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:q,onTouchStart:q,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:E}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:E,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]})})};hl.displayName="TrueFalseDragAndDrop";var hc=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=ze({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(pc,{trueFalse:c,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id):jsx(hl,{trueFalse:c,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id))})};var Pa=new WeakMap,zo=new WeakMap,Rr={current:[]},xl=false,Dr=0,Er=new Set,ls=new Map;function gc(e){let o=Array.from(e).sort((t,a)=>t instanceof Xt&&t.options.deps.includes(a)?1:a instanceof Xt&&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=Pa.get(n);r&&gc(r);}}}function db(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function ub(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function ds(e){if(Dr>0&&!ls.has(e)&&ls.set(e,e.prevState),Er.add(e),!(Dr>0)&&!xl)try{for(xl=!0;Er.size>0;){let o=Array.from(Er);Er.clear();for(let t of o){let a=ls.get(t)??t.prevState;t.prevState=a,db(t);}for(let t of o){let a=Pa.get(t);a&&(Rr.current.push(t),gc(a));}for(let t of o){let a=Pa.get(t);if(a)for(let n of a)ub(n);}}}finally{xl=false,Rr.current=[],ls.clear();}}function Mt(e){Dr++;try{e();}finally{if(Dr--,Dr===0){let o=Er.values().next().value;o&&ds(o);}}}function xc(e){return typeof e=="function"}var aa=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):xc(o)?this.state=o(this.prevState):this.state=o,(n=(a=this.options)==null?void 0:a.onUpdate)==null||n.call(a),ds(this);}};var Xt=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 aa){let a=Pa.get(t);a||(a=new Set,Pa.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 aa){let a=Pa.get(t);a&&a.delete(this);let n=zo.get(this);n&&n.delete(t);}}};function cb(e){return typeof e=="function"}function bl(e,...o){return cb(e)?e(...o):e}function bc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Ea,vt,mt,Fr,Da,no,ua,Wo,Br,us,Or,Uo,so=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:n=1e3}){He(this,Ea,true);He(this,vt);He(this,mt);He(this,Fr);He(this,Da);He(this,no);He(this,ua);He(this,Wo);He(this,Br,0);He(this,us,5);He(this,Or,()=>{this.debugLog("Connected to event bus"),Re(this,no,true),this.debugLog("Emitting queued events",$(this,Da)),$(this,Da).forEach(o=>this.emitEventToBus(o)),Re(this,Da,[]),this.stopConnectLoop(),$(this,mt).call(this).removeEventListener("tanstack-connect-success",$(this,Or));});He(this,Uo,()=>{if($(this,mt).call(this).addEventListener("tanstack-connect-success",$(this,Or)),$(this,Br)<$(this,us)){Vd(this,Br)._++,this.dispatchCustomEvent("tanstack-connect",{});return}$(this,mt).call(this).removeEventListener("tanstack-connect",$(this,Uo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Re(this,vt,o),Re(this,Ea,a),Re(this,mt,this.getGlobalTarget),Re(this,Fr,t),this.debugLog(" Initializing event subscription for plugin",$(this,vt)),Re(this,Da,[]),Re(this,no,false),Re(this,ua,null),Re(this,Wo,n);}startConnectLoop(){$(this,ua)!==null||$(this,no)||(this.debugLog(`Starting connect loop (every ${$(this,Wo)}ms)`),Re(this,ua,setInterval($(this,Uo),$(this,Wo))));}stopConnectLoop(){$(this,ua)!==null&&(clearInterval($(this,ua)),Re(this,ua,null),this.debugLog("Stopped connect loop"));}debugLog(...o){$(this,Fr)&&console.log(`\u{1F334} [tanstack-devtools:${$(this,vt)}-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,vt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});$(this,mt).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{$(this,mt).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,Ea)){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,Da).push({type:`${$(this,vt)}:${o}`,payload:t,pluginId:$(this,vt)}),typeof CustomEvent<"u"&&($(this,Uo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${$(this,vt)}:${o}`,payload:t,pluginId:$(this,vt)})}on(o,t){let a=`${$(this,vt)}:${o}`;if(!$(this,Ea))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,mt).call(this).addEventListener(a,n),this.debugLog("Registered event to bus",a),()=>{$(this,mt).call(this).removeEventListener(a,n);}}onAll(o){if(!$(this,Ea))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;o(n);};return $(this,mt).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,mt).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!$(this,Ea))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;$(this,vt)&&n.pluginId!==$(this,vt)||o(n);};return $(this,mt).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,mt).call(this).removeEventListener("tanstack-devtools-global",t)}};Ea=new WeakMap,vt=new WeakMap,mt=new WeakMap,Fr=new WeakMap,Da=new WeakMap,no=new WeakMap,ua=new WeakMap,Wo=new WeakMap,Br=new WeakMap,us=new WeakMap,Or=new WeakMap,Uo=new WeakMap;var vl=class extends so{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},vc=(e,o)=>{yl.emit(e,o);},yl=new vl;function yc(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var fb={enabled:true,leading:true,trailing:true,wait:0},Ra,At,io,lo,uo,Ko,cs=class{constructor(o,t){He(this,Ra);He(this,At);He(this,io);He(this,lo);He(this,uo);He(this,Ko);this.fn=o,this.store=new aa(yc()),this.setOptions=a=>{this.options={...this.options,...a},$(this,io).call(this)||this.cancel();},Re(this,At,a=>{this.store.setState(n=>{let r={...n,...a},{isPending:s}=r;return {...r,status:$(this,io).call(this)?s?"pending":"idle":"disabled"}}),vc("Throttler",this);}),Re(this,io,()=>!!bl(this.options.enabled,this)),Re(this,lo,()=>bl(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,lo).call(this);if(this.options.leading&&r>=s)$(this,uo).call(this,...a);else if($(this,At).call(this,{lastArgs:a}),!$(this,Ra)&&this.options.trailing){let u=this.store.state.lastExecutionTime?n-this.store.state.lastExecutionTime:0,i=s-u;$(this,At).call(this,{isPending:true}),Re(this,Ra,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&$(this,uo).call(this,...c);},i));}},Re(this,uo,(...a)=>{if(!$(this,io).call(this))return;this.fn(...a);let n=Date.now(),r=n+$(this,lo).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,lo).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&$(this,uo).call(this,...this.store.state.lastArgs);},Re(this,Ko,()=>{$(this,Ra)&&(clearTimeout($(this,Ra)),Re(this,Ra,void 0));}),this.cancel=()=>{$(this,Ko).call(this),$(this,At).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{$(this,At).call(this,yc());},this.key=bc(t.key),this.options={...fb,...t},$(this,At).call(this,this.options.initialState??{}),yl.on("d-Throttler",a=>{a.payload.key===this.key&&($(this,At).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Ra=new WeakMap,At=new WeakMap,io=new WeakMap,lo=new WeakMap,uo=new WeakMap,Ko=new WeakMap;function wl(e,o){return new cs(e,o).maybeExecute}function Fa(e,o){return typeof e=="function"?e(o):e}function Ba(e,o){return hs(o).reduce((a,n)=>{if(a===null)return null;if(typeof a<"u")return a[n]},e)}function Go(e,o,t){let a=hs(o);function n(r){if(!a.length)return Fa(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 Ll(e,o){let t=hs(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 mb=/^(\d+)$/gm,pb=/\.(\d+)(?=\.)/gm,hb=/^(\d+)\./gm,gb=/\.(\d+$)/gm,xb=/\.{2,}/gm,Sl="__int__",fs=`${Sl}$1`;function hs(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(mb,fs).replace(pb,`.${fs}.`).replace(hb,`${fs}.`).replace(gb,`.${fs}`).replace(xb,".").split(".").map(o=>{if(o.startsWith(Sl)){let t=o.substring(Sl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Il(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 Oa(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)||!Oa(e[n],o[n]))return false;return true}var gs=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},xs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function tt(e,o){return e==null?o:{...e,...o}}var co=256,ps=[],ms;for(;co--;)ps[co]=(co+256).toString(16).substring(1);function Cl(){let e=0,o,t="";if(!ms||co+16>256){for(ms=new Array(256),e=256;e--;)ms[e]=256*Math.random()|0;e=0,co=0;}for(;e<16;e++)o=ms[co+e],e===6?t+=ps[o&15|64]:e===8?t+=ps[o&63|128]:t+=ps[o],e&1&&e>1&&e<11&&(t+="-");return co++,t}var Na=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 bb(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 wc=(e,o)=>{let t=bb(e,o);return {form:t,fields:t}},Ha={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)}},bs=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 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 g=v;g<=y;g++)p.push(t(d,g));}else {let v=e.getFieldValue(d),y=Array.isArray(v)?v.length:0;for(let g=l+1;g<y;g++)p.push(t(d,g));}return Object.keys(e.fieldInfo).filter(v=>p.some(y=>v.startsWith(y)))}function 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=()=>Xo,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)),g=p.get(y);g&&e.setFieldMeta(v,g);});},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,g]=[e.getFieldMeta(p),e.getFieldMeta(v)];y&&e.setFieldMeta(v,y),g&&e.setFieldMeta(p,g);});};return {handleArrayFieldMetaShift:o}}var kl=class extends so{constructor(){super({pluginId:"form-devtools"});}},Pt=new kl;function Tl(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&&!Oa(a.defaultValues,n.defaultValues)&&!this.state.isTouched,u=!Oa(a.defaultState,n.defaultState)&&!this.state.isTouched;!s&&!u&&!r||(Mt(()=>{this.baseStore.setState(()=>Tl(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(()=>Tl({...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||Na}),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}=vs(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,g=l?.[h],{newErrorValue:x,newSource:L}=gs({newFormValidatorError:g,isPreviousErrorFromFormValidator:y?.[m]==="form",previousErrorValue:v?.[m]});L==="form"&&(s[h]={...s[h],[m]:g}),v?.[m]!==x&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[m]:x},errorSourceMap:{...I.errorSourceMap,[m]:L}}));}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||Na});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((g,x)=>{setTimeout(async()=>{if(l.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(L){x(L);}},c.debounceMs);});}catch(g){h=g;}let{formError:p,fieldErrors:v}=vs(h);v&&(s=s?{...s,...v}:v);let y=qr(c.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let x=this.getFieldMeta(g);if(!x)continue;let{errorMap:L,errorSourceMap:I}=x,F=s?.[g],{newErrorValue:C,newSource:b}=gs({newFormValidatorError:F,isPreviousErrorFromFormValidator:I?.[y]==="form",previousErrorValue:L?.[y]});L?.[y]!==C&&this.setFieldMeta(g,k=>({...k,errorMap:{...k.errorMap,[y]:C},errorSourceMap:{...k.errorSourceMap,[y]:b}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.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=>Ba(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]:Fa(n,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((n,r)=>{let s=r;return n[s]=Xo,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=Ll(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)],tt(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),tt(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),tt(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)},tt(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},tt(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,[],tt(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]:Xo},values:this.options.defaultValues?Go(n.values,a,Ba(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=>Ha.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ha.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Cl(),this._devtoolsSubmissionOverride=false,this.baseStore=new aa(Tl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Xt({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=Ba(i.values,d),v=h?.errors;if(!m||l.errorMap!==m.errorMap){v=Object.values(l.errorMap??{}).filter(I=>I!==void 0);let L=this.getFieldInfo(d)?.instance;L&&!L.options.disableErrorFlat&&(v=v?.flat(1));}let y=!Il(v??[]),g=!l.isDirty,x=Oa(p,Ba(this.options.defaultValues,d))||Oa(p,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===y&&h.isDefaultValue===x&&h.errors===v&&l===m){f[d]=h,c++;continue}f[d]={...l,errors:v,isPristine:g,isValid:y,isDefaultValue:x};}return Object.keys(i.fieldMetaBase).length&&s&&c===Object.keys(i.fieldMetaBase).length?s:f}}),this.store=new Xt({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(U=>U.isValidating),l=f.every(U=>U.isValid),m=f.some(U=>U.isTouched),h=f.some(U=>U.isBlurred),p=f.every(U=>U.isDefaultValue),v=m&&i.errorMap?.onMount,y=f.some(U=>U.isDirty),g=!y,x=!!(i.errorMap?.onMount||f.some(U=>U?.errorMap?.onMount)),L=!!d,I=s?.errors??[];(!u||i.errorMap!==u.errorMap)&&(I=Object.values(i.errorMap).reduce((U,G)=>G===void 0?U:G&&Nr(G)?(U.push(G.form),U):(U.push(G),U),[]));let F=I.length===0,C=l&&F,b=this.options.canSubmitWhenInvalid??false,k=i.submissionAttempts===0&&!m&&!x||!L&&!i.isSubmitting&&C||b,w=i.errorMap;if(v&&(I=I.filter(U=>U!==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===F&&s.isValid===C&&s.canSubmit===k&&s.isTouched===m&&s.isBlurred===h&&s.isPristine===g&&s.isDefaultValue===p&&s.isDirty===y&&Oa(u,i))return s;let E={...i,errorMap:w,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:l,isFormValid:F,isValid:C,canSubmit:k,isTouched:m,isBlurred:h,isPristine:g,isDefaultValue:p,isDirty:y},M=this.options.transform?.deps??[];if(M.length!==this.prevTransformArray.length||M.some((U,G)=>U!==this.prevTransformArray[G])){let U=Object.assign({},this,{state:E});this.options.transform?.fn(U),E=U.state,this.prevTransformArray=M;}return E}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=wl(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 bs(o.validate)?Ha[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}=vs(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 vs(e){if(e){if(Nr(e)){let o=vs(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=Ba(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,tt(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,tt(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,n)=>{this.form.insertFieldValue(this.name,t,a,tt(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,n)=>{this.form.replaceFieldValue(this.name,t,a,tt(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,tt(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,n)=>{this.form.swapFieldValues(this.name,t,a,tt(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,n)=>{this.form.moveFieldValues(this.name,t,a,tt(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,tt(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||Na}),s=this.getLinkedFields(t).reduce((c,f)=>{let d=jo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Na});return d.forEach(l=>{l.field=f;}),c.concat(d)},[]),u=false;Mt(()=>{let c=(f,d)=>{let l=ys(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[l],{newErrorValue:p,newSource:v}=xs({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=ys("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||Na}),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||Na});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=ys(m.cause);l.getInfo().validationMetaMap[p]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:y},h.push(new Promise(async g=>{let x;try{x=await new Promise((b,k)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(y.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:m.validate,value:{value:l.store.state.value,fieldApi:l,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(w){k(w);}},m.debounceMs);});}catch(b){x=b;}if(y.signal.aborted)return g(void 0);let L=Sc(x),I=r[this.name]?.[p],{newErrorValue:F,newSource:C}=xs({formLevelError:I,fieldLevelError:L});l.setMeta(b=>({...b,errorMap:{...b?.errorMap,[p]:F},errorSourceMap:{...b.errorSourceMap,[p]:C}})),g(F);}));};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[ys(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=>Ha.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ha.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Xt({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 bs(o.validate)?Ha[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 ys(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function ws(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,yb)}function yb(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=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 $o=typeof window<"u"?useLayoutEffect:useEffect;function Tb(e){let[o]=useState(()=>{let a=new zr({...e,form:e.form,name:e.name});return a.Field=Ml,a});return $o(o.mount,[o]),$o(()=>{o.update(e);}),ws(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Ml=(({children:e,...o})=>{let t=Tb(o),a=useMemo(()=>Fa(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Pb({form:e,selector:o,children:t}){let a=ws(e.store,o);return Fa(t,a)}function Al(e){let o=useId(),[t]=useState(()=>{let a=new Vr({...e,formId:o}),n=a;return n.Field=function(s){return jsx(Ml,{...s,form:a})},n.Subscribe=function(s){return jsx(Pb,{form:a,selector:s.selector,children:s.children})},n});return $o(t.mount,[]),$o(()=>{t.update(e);}),t}function Pl({field:e}){return jsxs(Fragment,{children:[e.state.meta.isTouched&&!e.state.meta.isValid?jsx("em",{children:e.state.meta.errors.join(", ")}):null,e.state.meta.isValidating?"Validating...":null]})}var Vb=({editElement:e})=>{let o=useDispatch(),t=useSelector(ve),a=useRef(null),n=We(),r=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[u,i]=useState(s),c=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: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?Qe(m):Li(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?xt(m):wi(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?ea(m):Ii(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?la(m):ki(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?La(m):Ci(m));}o(Ia(false));}}),f=()=>{o(Ia(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(Pl,{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(Pl,{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(Pl,{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,g)=>{let x=[...l.state.value.options];x[y]=g,l.handleChange({...l.state.value,options:x});},h=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},p=y=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let g=l.state.value.options.filter((L,I)=>I!==y),x=l.state.value.correctIndex?.filter(L=>L!==y).map(L=>L>y?L-1:L);l.handleChange({...l.state.value,options:g,correctIndex:x});},v=y=>{let g=l.state.value.correctIndex||[];if(g.includes(y))l.handleChange({...l.state.value,correctIndex:g.filter(L=>L!==y)});else {if(g.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...g,y]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:l.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:l.state.value.options.map((y,g)=>{let x=!y.trim(),L=l.state.value.correctIndex?.includes(g),I=l.state.meta.isTouched&&x;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>v(g),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${L?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:L&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${I?"border-red-500 bg-red-50":L?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${g+1}`,value:y,onChange:F=>m(g,F.target.value),onBlur:l.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),l.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>p(g),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},g)})}),jsx("button",{type:"button",onClick:h,disabled:l.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),l.state.value.correctIndex.length===0||l.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:l.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.Field,{name:"responseOptions.correctShortAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:l.state.value,onChange: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)},kc=Vb;var Pc=({text:e,position:o})=>{let t=we(),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
+ `),g=0;for(let I of y){let F=v.measureText(I||" ");F.width>g&&(g=F.width);}let L=y.length*d*1.2;return {width:Math.max(200,g+40),height:Math.max(50,L+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 Dc=({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 Qb=(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},Rc=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 g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",x=v&&h.trim().toLowerCase()===g,L=w=>{p(w);let E=w.trim(),M=E.toLowerCase()===g;c(ea({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:E,isCorrect:M}}}));},I=()=>{y(false),p(""),c(ea({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:"",isCorrect:false}}}));},F=()=>x?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",C=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},b=e.data.feedbackMode==="practice",k=useMemo(()=>{let G=b?48:0,B=12,W=30,q=e.width-48,N=Math.max(60,Qb(e.data.question,18,q,"bold")+20),Z=v?40:0,X=v?54:20,V=N+Z+W+50+12+B+G+24;return {padding:24,questionHeight:N,questionFontSize:18,feedbackHeight:Z,feedbackFontSize:12,inputY:X,inputHeight:50,inputMargin:12,buttonHeight:G,buttonTopMargin:B,placeholderHeight:W,contentWidth:q,totalHeight:V}},[e.width,e.data.question,v,x,b,F]);return jsxs(Group,{ref:f,draggable:!i,listening:!i,x:e.x,y:e.y,scaleX:e.scaleX||1,scaleY:e.scaleY||1,rotation:e.rotation,width:e.width,height:k.totalHeight,name:"sa-element",onTransformEnd:w=>t(e.id,w),...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:k.totalHeight,onContextMenu:w=>{w.cancelBubble=true,n(w.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:k.padding+8,y:k.padding,fontSize:k.questionFontSize,fontStyle:"bold",fill:"#111827",width:k.contentWidth,height:k.questionHeight-k.padding,wrap:"word",listening:false}),jsx(Rect,{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight-k.inputY,width:k.contentWidth+4,height:k.inputHeight+6,fill:"#ffffff",stroke:x?"#22c55e":v?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight-k.inputY},divProps:{style:{width:`${k.contentWidth-4}px`,height:`${k.inputHeight}px`,pointerEvents:v?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:w=>L(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:k.padding,y:k.questionHeight+80,width:k.contentWidth,height:k.feedbackHeight,fill:C().bg,cornerRadius:8}),jsx(Text,{x:36,y:k.questionHeight+80,width:k.contentWidth,height:k.feedbackHeight,text:F()+` (${m} attempts)`,fontSize:k.feedbackFontSize,fontStyle:"bold",fill:C().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:k.questionHeight+k.feedbackHeight+k.placeholderHeight+k.inputHeight+k.inputMargin+k.buttonTopMargin,children:[jsxs(Group,{onMouseDown:w=>{w.cancelBubble=true,l("check");},onMouseUp:w=>{w.cancelBubble=true,l(null),h.length>0&&(y(true),c(ea({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:k.padding+14,width:(k.contentWidth-24)/(v?2:1),height:k.buttonHeight,fill:h.length===0||v?"#9ca3af":"#096B76",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:k.padding+14,width:(k.contentWidth-24)/(v?2:1),height:k.buttonHeight,text:v?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),v&&jsxs(Group,{x:(e.width-k.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:k.padding,width:(k.contentWidth-8)/2,height:k.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:k.padding,width:(k.contentWidth-8)/2,height:k.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Rc.displayName="ShortAnswer";var Fc=Rc;var Oc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=ze({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Fc,{shortAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"shortAnswer")},i.id))})};var Hc=e=>{let o=useDispatch(),a=useSelector(ve)?.fillInTheBlanks||[],n=useRef(new Map),r=useCallback((u,i)=>{let c=u.target;o(la({id:i,x:c.x(),y:c.y()})),e?.();},[o,e]),s=useCallback((u,i)=>{let c=i.target,f=c.scaleX(),d=c.scaleY(),l=c.rotation();c.scaleX(1),c.scaleY(1),o(la({id:u,scaleX:f,scaleY:d,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:n,handleFillInTheBlanksDragEnd:r,handleFillInTheBlanksTransform:s}};var Rl=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let 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},qc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:n,fibRefs:r,touchHandlers:s})=>{let u=useSelector(M=>M.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 M=c.current;if(M)return r.current.set(e.id,M),()=>{r.current.delete(e.id);}},[e.id,r]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",x=v&&h.trim().toLowerCase()===g,L=M=>{p(M);let A=M.trim(),U=A.toLowerCase()===g;f(la({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:A,isCorrect:U}}}));},I=()=>{y(false),p("");},F=()=>{h.length>0&&(y(true),f(la({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},C=e.data.feedbackMode==="practice",b=useMemo(()=>{let N=e.width-48,Z=(N-15)/2,X=24,V=X,O=Math.max(60,Rl(e.data.question.replace("_____","________"),24,N,"bold")+20);X+=O;let K=X,j=Math.max(35,Rl("Enter your answer in the blank.",16,N)+10);X+=j;let ee=X;X+=67;let Y=X,le=v?Math.max(32,Rl(x?"Right Answer, Great Job!":"Wrong Answer",14,N-40)+16):0;v&&(X+=le+16);let pe=X;return C&&(X+=64),X+=24,{padding:24,questionY:V,questionHeight:O,questionFontSize:24,helperTextY:K,helperTextHeight:j,helperTextFontSize:16,inputY:ee,inputHeight:51,feedbackY:Y,feedbackHeight:le,feedbackFontSize:14,buttonsY:pe,buttonHeight:64,buttonGap:15,buttonWidth:Z,contentWidth:N,totalHeight:X}},[e.width,e.data.question,v,x,C]),k=()=>v?x?"#1b9d2c":"#ef4444":"#d1d5db",w=e.scaleX||1,E=e.scaleY||1;return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,scaleX:w,scaleY:E,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...s,...i?{}:{onDragEnd:M=>a(M,e.id),onTransformEnd:M=>t(e.id,M),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:b.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onContextMenu:M=>{M.cancelBubble=true,n?.(M.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:b.padding,y:b.questionY,fontSize:b.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:b.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:b.padding,y:b.helperTextY,fontSize:b.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:b.contentWidth,height:b.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:b.padding,y:b.inputY,width:b.contentWidth,height:b.inputHeight,fill:"#ffffff",stroke:k(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:b.padding,y:b.inputY},divProps:{style:{width:`${b.contentWidth}px`,height:`${b.inputHeight}px`,pointerEvents:v?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:M=>L(M.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:b.feedbackY,children:[jsx(Rect,{x:b.padding,width:b.contentWidth,height:b.feedbackHeight,fill:x?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:x?"\u2713":"\u2717",x:b.padding+10,y:0,width:16,height:b.feedbackHeight,fontSize:b.feedbackFontSize,fill:x?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:x?`Right Answer, Great Job! (${m} attempts)`:`Wrong Answer (${m} attempts)`,x:b.padding+30,y:0,height:b.feedbackHeight,fontSize:b.feedbackFontSize,fontStyle:"600",fill:x?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),C&&jsxs(Group,{y:b.buttonsY,children:[jsxs(Group,{x:b.padding,onClick:M=>M.cancelBubble=true,onTap:M=>M.cancelBubble=true,onMouseDown:M=>{M.cancelBubble=true,l("reset");},onMouseUp:M=>{M.cancelBubble=true,l(null),I();},onMouseLeave:M=>{M.cancelBubble=true,l(null);},onTouchStart:M=>{M.cancelBubble=true,l("reset");},onTouchEnd:M=>{M.cancelBubble=true,l(null),I();},scaleX:d==="reset"?.98:1,scaleY:d==="reset"?.98:1,children:[jsx(Rect,{width:b.buttonWidth,height:b.buttonHeight,fill:v?"#096b76":"#9ca3af",cornerRadius:8}),jsx(Text,{width:b.buttonWidth,height:b.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:b.padding+b.buttonWidth+b.buttonGap,onClick:M=>M.cancelBubble=true,onTap:M=>M.cancelBubble=true,onMouseDown:M=>{M.cancelBubble=true,!v&&l("submit");},onMouseUp:M=>{M.cancelBubble=true,!v&&(l(null),F());},onMouseLeave:M=>{M.cancelBubble=true,l(null);},onTouchStart:M=>{M.cancelBubble=true,!v&&l("submit");},onTouchEnd:M=>{M.cancelBubble=true,!v&&(l(null),F());},scaleX:d==="submit"?.98:1,scaleY:d==="submit"?.98:1,children:[jsx(Rect,{width:b.buttonWidth,height:b.buttonHeight,fill:h.length===0||v?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:b.buttonWidth,height:b.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});qc.displayName="FillInTheBlanks";var Vc=qc;var Wc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,onLongPress:r,fibRefs:s})=>{let{createHandlers:u}=ze({onLongPress:r});return jsx(Fragment,{children:e.map(i=>jsx(Vc,{fillInTheBlank:i,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,fibRefs:s,touchHandlers:u(i.id,"fillInTheBlanks")},i.id))})};var Ol=(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},Hl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,touchHandlers:r,handleDragEnd:s})=>{let u=useSelector(w=>w.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 w=c.current;if(w)return a.current.set(e.id,w),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",g=p&&m.trim().toLowerCase()===y,x=w=>{h(w);let E=w.trim();E.toLowerCase()===y;f(La({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:E}}}));},L=()=>{v(false),h("");},I=()=>g?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",F=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},C=useMemo(()=>{let q=e.width-48,N=Math.max(60,Ol(e.data.question,20,q,"bold")+20),Z=p?Math.max(60,Ol(I(),14,q)+30):0,V=Math.max(30,Ol("Answer (Extended response):",14,q)+10),O=N+Z+V+120+12+12+48+24;return {padding:24,questionHeight:N,questionFontSize:20,feedbackHeight:Z,feedbackFontSize:14,placeholderHeight:V,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:q,totalHeight:O}},[e.width,e.data.question,p,g,I]),b=e.scaleX||1,k=e.scaleY||1;return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,scaleX:b,scaleY:k,rotation:e.rotation,width:e.width,height:C.totalHeight,...r,name:"la-element",...i?{}:{onDragEnd:s,onTransformEnd:w=>t(e.id,w),onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:w=>{let E=c.current?.getStage()?.getPointerPosition();if(!E||!n)return;let M={x:e.x,y:e.y,width:e.width,height:C.totalHeight};E.x>=M.x&&E.x<=M.x+M.width&&E.y>=M.y&&E.y<=M.y+M.height&&n(w.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:C.totalHeight-50}),jsx(Text,{text:e.data.question,x:C.padding+8,y:C.padding,fontSize:C.questionFontSize,fontStyle:"bold",fill:"#111827",width:C.contentWidth,wrap:"word",listening:false}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:C.padding,y:C.questionHeight,width:C.contentWidth,height:C.feedbackHeight,fill:F().bg,cornerRadius:8}),jsx(Text,{x:C.padding,y:C.questionHeight,width:C.contentWidth,height:C.feedbackHeight,text:I(),fontSize:C.feedbackFontSize,fontStyle:"bold",fill:F().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),jsx(Text,{text:"Answer:",x:C.padding,y:C.questionHeight+C.feedbackHeight+C.textareaMargin,fontSize:C.placeholderFontSize,fill:"#6b7280",width:C.contentWidth,wrap:"word",listening:false}),jsx(Rect,{x:C.padding,y:C.questionHeight+C.feedbackHeight+C.placeholderHeight,width:C.contentWidth,height:C.textareaHeight,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:C.padding,y:C.questionHeight+C.feedbackHeight+C.placeholderHeight},divProps:{style:{width:`${C.contentWidth}px`,height:`${C.textareaHeight}px`,pointerEvents:p?"none":"auto"}},children:jsx("textarea",{value:m,onChange:w=>x(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:C.questionHeight+C.feedbackHeight+C.placeholderHeight+C.textareaHeight+C.textareaMargin+C.buttonTopMargin,children:p&&jsxs(Group,{onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),L();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),L();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:C.padding,width:C.contentWidth,height:C.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:C.padding,width:C.contentWidth,height:C.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Hl.displayName="LongAnswer";var Kc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=ze({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Hl,{longAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"longAnswer")},i.id))})};var mo=1600,po=900,Xc=3200,$c=1800,Tv=e=>{let o=0,t=0,a=mo,n=po;if(!e)return {minX:o,minY:t,maxX:a,maxY:n,width:mo,height:po};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,Xc),u=Math.min(n-t,$c);return o=Math.max(o,a-Xc),t=Math.max(t,n-$c),{minX:o,minY:t,maxX:a,maxY:n,width:s,height:u}},Mv=(e,o,t={minX:0,minY:0,maxX:mo,maxY:po,width:mo,height:po})=>{let a=Math.max(t.width,mo),n=Math.max(t.height,po),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}},Yc=(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}},Av=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:n={enabled:true}}={})=>{let r=$e(),s=We(),u=te(S=>S.toolbar.selectedTool),i=te(ve),c=te(Ca),f=te(Xn),d=te(S=>S.canvas.zoomLevel),m=(i?.videos||[]).find(S=>S.isRecorded&&S.isPlaying),h=!!m,p=useCallback(()=>{m&&r(Za(m.id));},[r,m]),v=i?.editingActivity,y=i?.showMcqForm,g=i?.lines||[],x=useRef(null),L=useRef(null),[I,F]=useState(null),C=useRef(null),[b,k]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:mo,stageHeight:po,offsetX:0,offsetY:0,baseWidth:mo,baseHeight:po,contentOffsetX:0,contentOffsetY:0}),w=useMemo(()=>Tv(i||null),[c]),[E,M]=useState(null),[A,U]=useState(null),[G,B]=useState(null),[W,q]=useState(null),[N,Z]=useState(null),[X$1,V]=useState(null),[O,K]=useState(null),[j,ee]=useState(false),[Y,le]=useState(null),[pe,ye]=useState(false),ce=useRef(null),ge=useRef(null),Le=useRef(null),{debouncedGenerateThumbnail:Ae}=wu(c,x);useEffect(()=>{let S=()=>{if(L.current){let D=L.current.getBoundingClientRect(),H=Mv(D.width,D.height,w);k(H);}};S();let T=new ResizeObserver(S);return L.current&&T.observe(L.current),window.addEventListener("resize",S),()=>{T.disconnect(),window.removeEventListener("resize",S);}},[w]),useEffect(()=>{if(x.current){let S=x.current.container();S&&(S.style.cursor="");}},[u]);let re=useCallback(()=>{x.current&&requestAnimationFrame(()=>{if(!x.current)return;if(x.current.getLayers().forEach(T=>T.batchDraw()),!f)try{Ae();}catch(T){console.warn("Preview generation failed (CORS):",T);}});},[Ae,f]),Xe=useRef(c);useEffect(()=>{Xe.current!==c&&(Xe.current=c,re());},[c,re]);let wo=useRef(null),rn=useRef(true);useEffect(()=>{if(!i)return;let S=(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),T=wo.current?.count!==S;!rn.current&&T&&setTimeout(()=>{re();},100),wo.current={slideId:c,count:S},rn.current=false;},[i,c,re]),useEffect(()=>{x.current&&e&&e(x);},[e]),useEffect(()=>{Le.current&&a&&a(Le);},[a]);let{startDrawing:nn,draw:sn,stopDrawing:ln,setCanvasRef:Gs,tool:js,color:ja,strokeWidth:_s,isSketchMode:Xs}=jd(re),_a=useRef(new Map),{images:$s,getLoadedImage:dn,imageRefs:Xa,handleDragEnd:un,handleImageTransformEnd:Ys}=Qd(re),{videos:ir,videoRefs:So,handleVideoClick:cn,handleVideoDragEnd:Zs,handleVideoTransformEnd:Js}=au(re),{multipleChoice:P,handleMcqTransform:ne,mcqRefs:ke,handleDragEnd:Ie}=eu(re),{trueFalse:fe,handleTrueFalseTransform:ie,trueFalseRefs:De,handleTrueFalseDragEnd:lt}=tu(re),{shortAnswers:sa,saRefs:Je,handleShortAnswerDragEnd:Ne,handleShortAnswerTransform:dt}=du(re),{longAnswers:ia,handleLongAnswerDragEnd:wa,handleLongAnswerTransform:Qs}=cu(re),{fillInTheBlanks:ei,handleFillInTheBlanksDragEnd:fn,handleFillInTheBlanksTransform:Gt,fibRefs:jt}=Hc(re),{transformerRef:se,boundBoxFunc:$a}=xu(),{shapes:Jm,shapeRefs:mn,isDragging:Td,handleShapeDragEnd:Qm,handleShapeResizeEnd:ep}=nu(re),{texts:lr,textRefs:Sa,handleDragEnd:tp,handleTransformEnd:ap,handleDoubleClick:op,startEditing:pn,editingTextId:be,editingValue:Md,handleEditingChange:Ad,finishEditing:ti}=iu(re,ce);useEffect(()=>{t&&t(pn);},[t,pn]);let hn=te(S=>S.canvas.editingTextId);useEffect(()=>{hn&&hn!==be&&pn(hn);},[hn,be,pn]);let{flashcards:rp,flashcardRefs:gn,handleDragEnd:np,handleFlashcardTransformEnd:sp,handleNext:ip,handlePrevious:lp}=mu(re),{photoFrames:Pd,photoFrameRefs:xn,handleDragEnd:dp,handlePhotoFrameTransformEnd:up,startCamera:cp,capturePhoto:fp,cameraStreams:mp}=gu(re);useEffect(()=>{if(se.current){if(be){se.current.nodes([]),se.current.getLayer()?.batchDraw();return}if(I&&!ir.find(D=>D.id===I)?.isPlaying){let D=_a.current.get(I)||Xa.current.get(I)||So.current.get(I)||mn.current.get(I)||Sa.current.get(I)||ke.current.get(I)||gn.current.get(I)||xn.current.get(I)||Je.current.get(I)||De.current.get(I)||jt.current.get(I);if(D){let H=D.attrs?.locked;if(D.visible()&&H!==true){se.current.nodes([D]),se.current.getLayer()?.batchDraw();return}}}se.current.nodes([]),se.current.getLayer()?.batchDraw();}},[I,be,ir,_a,Xa,So,mn,Sa,gn,xn,Pd,ke,De,jt,se]);let Ue=useCallback(S=>{F(S),o?.(S);},[o]),Lo=useCallback(()=>{F(null),o?.(null),se.current&&(se.current.nodes([]),se.current.getLayer()?.batchDraw());},[se,o]),Ed=useCallback(S=>i?i.lines?.some(T=>T.id===S)?"line":i.images?.some(T=>T.id===S)?"image":i.videos?.some(T=>T.id===S)?"video":i.shapes?.some(T=>T.id===S)?"shape":i.texts?.some(T=>T.id===S)?"text":i.flashcards?.some(T=>T.id===S)?"flashcard":i.photoFrames?.some(T=>T.id===S)?"photoFrame":i.multipleChoices?.some(T=>T.id===S)?"mcq":i.trueFalses?.some(T=>T.id===S)?"trueFalse":i.shortAnswers?.some(T=>T.id===S)?"shortAnswer":i.LongAnswer?.some(T=>T.id===S)?"longAnswer":i.fillInTheBlanks?.some(T=>T.id===S)?"fillInTheBlanks":null:null,[i]),Dd=useCallback((S,T)=>{switch(r(de()),T){case "line":r(jn(S));break;case "image":r(vn(S));break;case "video":r(Sn(S));break;case "shape":r(Cn(S));break;case "text":r(kn(S));break;case "flashcard":r(Mn(S));break;case "photoFrame":r(Pn(S));break;case "mcq":r(Dn(S));break;case "trueFalse":r(Fn(S));break;case "shortAnswer":r(On(S));break;case "longAnswer":r(Hn(S));break;case "fillInTheBlanks":r(Vn(S));break}Lo(),re();},[r,Lo,re]);useEffect(()=>{let S=T=>{if(T.key!=="Delete"&&T.key!=="Backspace"||!I||be)return;let D=document.activeElement;if(D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement||D?.getAttribute("contenteditable")==="true")return;T.preventDefault();let Ce=Ed(I);Ce&&Dd(I,Ce);};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[I,be,Ed,Dd]),useEffect(()=>{let S=se.current;return ()=>{S&&S.nodes([]);}},[c]),useEffect(()=>{let S=T=>{be&&T.target.tagName!=="TEXTAREA"&&ti();};return document.addEventListener("mousedown",S),()=>{document.removeEventListener("mousedown",S);}},[be,ti]),useEffect(()=>{let S=be||I;if(!S||I&&be){U(null);return}let T=Sa.current.get(S),D=x.current;if(!T||!D){U(null);return}let H=D.container().getBoundingClientRect(),Ce=T.absolutePosition(),xe=D.scaleX();U({x:H.left+(Ce.x+T.width()*xe/2)*xe+b.offsetX,y:H.top+Ce.y*xe+b.offsetY-70});},[I,be,lr,Sa,b.offsetX,b.offsetY]),useEffect(()=>{if(!be){B(null);return}let S=Sa.current.get(be),T=x.current;if(!S||!T){B(null);return}let D=S.getClientRect({relativeTo:T}),H=T.container().getBoundingClientRect(),Ce=T.scaleX(),xe=T.position(),oe={top:H.top+xe.y+D.y*Ce,left:H.left+xe.x+D.x*Ce,scale:Ce};B(oe),r(Wd(oe));},[be,lr,Sa,b.offsetY,b.offsetX]);let Rd=useCallback(S=>{let T=S.target.getClassName(),D=S.target===S.target.getStage(),H=T==="Transformer"||S.target.getParent()?.getClassName()==="Transformer",Ce=T==="Image",xe=T==="Text",oe=T==="Group"||S.target.getParent()?.getClassName()==="Group",ht=T==="Circle"||T==="Star"||T==="RegularPolygon"||T==="Ellipse"||T==="Ring"||T==="Wedge"||T==="Arrow"||T==="Line"||T==="Arc"||T==="Rect"&&S.target.attrs.id,gt=T==="Group";if(D&&!H&&!Ce&&!xe&&!oe&&!ht&&!gt&&Lo(),!(u==="pen"||u==="eraser")&&(Ce||xe||H||oe||ht||gt))return;let Ke=S.target.getStage()?.getPointerPosition();if(!Ke)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let z=Yc(Ke,b,d);nn(z);}},[u,nn,Lo,b,d]),Fd=useCallback(S=>{if(Td)return;let T=S.target.getStage()?.getPointerPosition();if(!T)return;let D=Yc(T,b,d);sn(D);},[sn,Td,b,d]),Bd=useCallback(()=>{ln();},[ln]),pp=useCallback(S=>{un(S,re);},[un,re]),hp=useCallback(S=>{cn(S),Ue(S);},[cn,Ue]),Rt=useCallback((S,T,D)=>{if(S.preventDefault(),!n.enabled)return;let H=S.clientX,Ce=S.clientY,xe=C.current?.offsetHeight||250,oe=C.current?.offsetWidth||200,ht=window.innerHeight,gt=window.innerWidth,ot=H,Ke=Ce;Ce+xe>ht&&(Ke=Ce-xe),H+oe>gt&&(ot=H-oe),Ue(T),M({x:ot,y:Ke,elementId:T,elementType:D});},[Ue,n.enabled]),Ya=useRef(null),dr=useRef(null),Lt=useCallback((S,T)=>D=>{if(!n.enabled)return;D.preventDefault();let H=D.changedTouches[0];if(!H)return;let Ce=H.clientX,xe=H.clientY,oe=C.current?.offsetHeight||200,ht=C.current?.offsetWidth||200,gt=window.innerHeight,ot=window.innerWidth,Ke=Ce,rt=xe;xe+oe>gt&&(rt=xe-oe),Ce+ht>ot&&(Ke=Ce-ht),Ue(S),M({x:Ke,y:rt,elementId:S,elementType:T});},[Ue,n.enabled]),gp=useCallback((S,T)=>({onTouchStart:D=>{let H=D.evt.touches[0];dr.current={x:H.clientX,y:H.clientY},Ya.current=setTimeout(()=>{Lt(S,T)(D.evt);},500);},onTouchMove:D=>{if(!dr.current)return;let H=D.evt.touches[0],Ce=Math.abs(H.clientX-dr.current.x),xe=Math.abs(H.clientY-dr.current.y);(Ce>10||xe>10)&&Ya.current&&(clearTimeout(Ya.current),Ya.current=null);},onTouchEnd:()=>{Ya.current&&(clearTimeout(Ya.current),Ya.current=null),dr.current=null;}}),[Lt]),Od=useCallback(S=>{r(gr(S)),r(Ia(true));},[r]),Nd=useCallback(S=>{r(hr(S)),r(eo(true));},[r]),xp=useCallback((S,T)=>{if(!E)return;let{elementId:D,elementType:H}=E;switch(S){case "order":if(T){let R=T.target.getBoundingClientRect();q({x:R.right+5,y:R.top,type:"order"});}break;case "lock":if(T){let R=T.target.getBoundingClientRect();q({x:R.right+5,y:R.top,type:"lock"});}break;case "link":if(M(null),H==="line")break;let Ce=i?H==="image"?i.images.find(R=>R.id===D):i.videos.find(R=>R.id===D):null;Z({type:"link",defaultValue:Ce?.link||""});break;case "voice":if(M(null),H==="line")break;let xe=i?H==="image"?i.images.find(R=>R.id===D):H==="video"?i.videos.find(R=>R.id===D):H==="text"?i.texts.find(R=>R.id===D):H==="flashcard"?i.flashcards.find(R=>R.id===D):H==="photoFrame"?i.photoFrames.find(R=>R.id===D):H==="mcq"?i.multipleChoices.find(R=>R.id===D):H==="fillInTheBlanks"?i.fillInTheBlanks.find(R=>R.id===D):H==="longAnswer"?i.LongAnswer.find(R=>R.id===D):H==="shortAnswer"?i.shortAnswers.find(R=>R.id===D):H==="trueFalse"?i.trueFalses.find(R=>R.id===D):H==="shape"?i.shapes.find(R=>R.id===D):null:null;le({elementId:D,elementType:H,existingAudio:xe?.audioData});break;case "edit":M(null);let oe=null;H==="mcq"?oe=i?.multipleChoices.find(R=>R.id===D):H==="trueFalse"?oe=i?.trueFalses.find(R=>R.id===D):H==="shortAnswer"?oe=i?.shortAnswers.find(R=>R.id===D):H==="longAnswer"?oe=i?.LongAnswer.find(R=>R.id===D):H==="fillInTheBlanks"&&(oe=i?.fillInTheBlanks.find(R=>R.id===D)),oe&&Od(oe);break;case "editFlashcard":M(null);let ht=i?.flashcards.find(R=>R.id===D);ht&&Nd(ht);break;case "color":M(null);let gt=i?.shapes.find(R=>R.id===D);V({elementId:D,elementType:"shape",defaultColor:gt?.color||"#096B76"});break;case "border":if(M(null),H==="shape"){r(de());let R=i?.shapes.find(oi=>oi.id===D);R&&r(Ja({id:D,hasBorder:!R.hasBorder})),re();}break;case "crop":if(M(null),H==="image"){let R=i?.images.find(oi=>oi.id===D);R&&K({elementId:D,imageSrc:R.src});}break;case "draw":M(null),H==="image"?r(xi(D)):H==="photoFrame"&&r(vi(D));break;case "duplicate":r(de()),H==="line"?r(Di(D)):H==="image"?r(yn(D)):H==="video"?r(Ln(D)):H==="shape"?r(In(D)):H==="text"?r(Tn(D)):H==="flashcard"?r(An(D)):H==="photoFrame"?r(En(D)):H==="mcq"?r(Rn(D)):H==="trueFalse"?r(Bn(D)):H==="shortAnswer"?r(Nn(D)):H==="fillInTheBlanks"?r(zn(D)):H==="longAnswer"&&r(qn(D)),re();break;case "infinite-clone":r(de());let ot=5;for(let R=0;R<ot;R++)H==="image"?r(yn(D)):H==="video"?r(Ln(D)):H==="shape"?r(In(D)):H==="text"?r(Tn(D)):H==="flashcard"?r(An(D)):H==="photoFrame"?r(En(D)):H==="mcq"?r(Rn(D)):H==="trueFalse"?r(Bn(D)):H==="shortAnswer"?r(Nn(D)):H==="fillInTheBlanks"?r(zn(D)):H==="longAnswer"&&r(qn(D));re();break;case "make-response":if(M(null),H==="line")break;let Ke=`#response-${D}`;r(de()),r(Wn({id:D,type:H,link:Ke})),(i?H==="image"?i.images.find(R=>R.id===D):H==="video"?i.videos.find(R=>R.id===D):H==="shape"?i.shapes.find(R=>R.id===D):H==="flashcard"?i.flashcards.find(R=>R.id===D):H==="photoFrame"?i.photoFrames.find(R=>R.id===D):i.multipleChoices.find(R=>R.id===D):null)?.altText||r(Un({id:D,type:H,altText:"Interactive response area"})),re(),console.log(`Element ${D} marked as interactive response area`);break;case "accessibility":if(M(null),H==="line")break;let z=i?H==="image"?i.images.find(R=>R.id===D):H==="video"?i.videos.find(R=>R.id===D):H==="shape"?i.shapes.find(R=>R.id===D):null:null;Z({type:"altText",defaultValue:z?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),M(null),ye(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(de()),H==="line"?r(jn(D)):H==="image"?r(vn(D)):H==="video"?r(Sn(D)):H==="shape"?r(Cn(D)):H==="text"?r(kn(D)):H==="flashcard"?r(Mn(D)):H==="photoFrame"?r(Pn(D)):H==="mcq"?r(Dn(D)):H==="trueFalse"?r(Fn(D)):H==="shortAnswer"?r(On(D)):H==="longAnswer"?r(Hn(D)):H==="fillInTheBlanks"&&r(Vn(D)),Lo(),re();break}},[E,r,re,Lo,i,Od,Nd]),bp=useCallback(()=>{M(null),q(null);},[]),ai=useCallback(S=>{if(!E)return;let{elementId:T,elementType:D}=E;switch(r(de()),S){case "bring-to-front":D!=="line"&&r(Mi({id:T,type:D}));break;case "send-to-back":D!=="line"&&r(Ai({id:T,type:D}));break;case "lock":case "unlock":D!=="line"&&r(Pi({id:T,type:D}));break}re(),M(null),q(null);},[E,r,re]),vp=useCallback(S=>{if(!E||!N)return;let{elementId:T,elementType:D}=E;r(de()),N.type==="link"&&D!=="line"?r(Wn({id:T,type:D,link:S})):N.type==="altText"&&D!=="line"&&r(Un({id:T,type:D,altText:S})),re(),Z(null);},[E,N,r,re]),yp=useCallback(S=>{if(!Y)return;let{elementId:T,elementType:D}=Y;r(de()),r(Kn({id:T,type:D,audioData:S})),re(),le(null);},[Y,r,re]),wp=useCallback(()=>{if(!Y)return;let{elementId:S,elementType:T}=Y;r(de()),r(Kn({id:S,type:T,audioData:""})),re();},[Y,r,re]),Sp=useCallback(S=>{if(!X$1)return;let{elementId:T}=X$1;r(de()),r(Ja({id:T,color:S})),re(),V(null);},[X$1,r,re]),Lp=useCallback(S=>{if(!O)return;let{elementId:T}=O;r(de()),r(Co({id:T,src:S})),re(),K(null);},[O,r,re]);return jsxs("div",{ref:L,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Zd,{ref:S=>{if(ge.current=S,Gs(S),S){let T=S.getCanvasElement();T&&(Le.current=T,a&&a(Le));}},width:b.baseWidth,height:b.baseHeight,tool:js,color:ja,strokeWidth:_s/(b.scale*d),isSketchMode:Xs,xOffset:b.contentOffsetX,yOffset:b.contentOffsetY-b.offsetY/b.scale,style:{width:b.stageWidth,height:b.stageHeight}}),jsxs(Stage,{ref:x,width:b.stageWidth,height:b.stageHeight,scaleX:b.scaleX*d,scaleY:b.scaleY*d,x:b.offsetX,y:0,onMouseDown:Rd,onMouseMove:Fd,onMouseUp:Bd,onTouchStart:Rd,onTouchMove:Fd,onTouchEnd:Bd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:b.baseWidth,height:b.stageHeight/b.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-b.contentOffsetX,y:b.offsetY/b.scale-b.contentOffsetY,children:(()=>{let S=[];return g.forEach((T,D)=>{S.push({type:"line",timestamp:T.timestamp||D,element:{...T,id:T.id??`line-${D}`},index:D});}),Jm.forEach(T=>{S.push({type:"shape",timestamp:T.timestamp||0,element:T});}),$s.forEach(T=>{S.push({type:"image",timestamp:T.timestamp||0,element:T});}),ir.forEach(T=>{S.push({type:"video",timestamp:T.timestamp||0,element:T});}),lr.forEach(T=>{S.push({type:"text",timestamp:T.timestamp||0,element:T});}),rp.forEach(T=>{S.push({type:"flashcard",timestamp:T.timestamp||0,element:T});}),Pd.forEach(T=>{S.push({type:"photoFrame",timestamp:T.timestamp||0,element:T});}),P.forEach(T=>{S.push({type:"mcq",timestamp:T.timestamp||0,element:T});}),fe.forEach(T=>{S.push({type:"trueFalse",timestamp:T.timestamp||0,element:T});}),sa.forEach(T=>{S.push({type:"shortAnswer",timestamp:T.timestamp||0,element:T});}),ia.forEach(T=>{S.push({type:"longAnswer",timestamp:T.timestamp||0,element:T});}),ei.forEach(T=>{S.push({type:"fillInTheBlanks",timestamp:T.timestamp||0,element:T});}),S.sort((T,D)=>T.timestamp-D.timestamp),S.map((T,D)=>{let H=`${T.type}-${"id"in T.element&&T.element.id||T.index||D}`,Ce="id"in T.element?T.element.id:void 0,xe=Ce&&I===Ce;switch(T.type){case "line":let oe=T.element,ht=T.index||0,gt=oe.tool==="eraser",ot=oe.isSketch&&oe.tool==="pen",Ke=oe.isSketch&&gt,rt=oe.id||`line-${ht}`;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:ot||Ke?void 0:oe.color,strokeWidth:ot||Ke?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:ot||Ke?gt?"black":oe.color:void 0,closed:ot||Ke,tension:0,globalCompositeOperation:gt?"destination-out":"source-over",listening:true,onClick:()=>{r(de()),r(bn(ht));},onTap:()=>{r(de()),r(bn(ht));},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`);}})},H):jsxs(Se__default.Fragment,{children:[jsx(Group,{id:rt,ref:z=>{z?_a.current.set(rt,z):_a.current.delete(rt);},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:",rt),Ue(rt));},onTap:()=>{u==="select"&&(console.log("Line tapped:",rt),Ue(rt));},onDragEnd:z=>{r(de()),r(Gn({id:rt,x:z.target.x(),y:z.target.y(),scaleX:z.target.scaleX(),scaleY:z.target.scaleY(),rotation:z.target.rotation()})),re();},onTransformEnd:z=>{r(de()),r(Gn({id:rt,x:z.target.x(),y:z.target.y(),scaleX:z.target.scaleX(),scaleY:z.target.scaleY(),rotation:z.target.rotation()})),re();},onMouseEnter:z=>{if(u==="select"){let R=z.target.getStage();R&&(R.container().style.cursor="move");}},onMouseLeave:z=>{if(u==="select"){let R=z.target.getStage();R&&(R.container().style.cursor="default");}},onContextMenu:z=>{let R=z.evt;R.preventDefault(),Rt(R,rt,"line");},...gp(rt,"line"),children:jsx(Line,{points:oe.points||[],stroke:ot||Ke?void 0:oe.color,strokeWidth:ot||Ke?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:ot||Ke?gt?"black":oe.color:void 0,closed:ot||Ke,tension:0,globalCompositeOperation:gt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=_a.current.get(I);console.log("Line Transformer - selectedId:",I,"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"]})]},H);case "shape":return jsxs(Se__default.Fragment,{children:[jsx($i,{onSelect:Ue,shapes:[T.element],shapeRefs:mn,handleShapeDragEnd:Qm,handleShapeResizeEnd:ep,onContextMenu:Rt,onLongPress:Lt}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=mn.current.get(I);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"]})]},H);case "image":return jsxs(Se__default.Fragment,{children:[jsx(Gi,{images:[T.element],getLoadedImage:dn,imageRefs:Xa,onDragEnd:pp,onTransform:Ys,onSelect:Ue,onContextMenu:Rt,onLongPress:Lt}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=Xa.current.get(I);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"]})]},H);case "video":return jsxs(Se__default.Fragment,{children:[jsx(Xi,{videos:[T.element],selectedId:I,videoRefs:So,onVideoClick:hp,onDragEnd:Zs,onTransformEnd:Js,onContextMenu:Rt,onLongPress:Lt}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=So.current.get(I);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"]})]},H);case "text":return jsxs(Se__default.Fragment,{children:[jsx(Ru,{texts:[T.element],textRefs:Sa,onDragEnd:tp,onTransformEnd:ap,onSelect:Ue,onContextMenu:Rt,onLongPress:Lt,onDoubleClick:op,editingTextId:be,editingValue:Md,onEditingChange:Ad}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=Sa.current.get(I);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"]})]},H);case "flashcard":return jsxs(Se__default.Fragment,{children:[jsx(Qi,{flashcards:[T.element],flashcardRefs:gn,selectedId:I,onDragEnd:np,onTransform:sp,onSelect:Ue,onNext:ip,onPrevious:lp,onContextMenu:Rt,onLongPress:Lt}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=gn.current.get(I);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"]})]},H);case "photoFrame":return jsxs(Se__default.Fragment,{children:[jsx(nl,{photoFrames:[T.element],photoFrameRefs:xn,selectedId:I,onDragEnd:dp,onTransform:up,onSelect:Ue,onStartCamera:cp,onCapture:fp,cameraStreams:mp,onContextMenu:Rt,onLongPress:Lt}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=xn.current.get(I);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"]})]},H);case "mcq":return jsxs(Se__default.Fragment,{children:[jsx(cc,{handleMcqTransform:ne,multipleChoice:[T.element],handleSelect:Ue,mcqRefs:ke,handleDragEnd:Ie,onContextMenu:Rt,onLongPress:Lt,onUpdate:re}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=ke.current.get(I);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"]})]},H);case "trueFalse":return jsxs(Se__default.Fragment,{children:[jsx(hc,{trueFalses:[T.element],handleTrueFalseTransform:ie,handleSelect:Ue,trueFalseRefs:De,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:lt,onUpdate:re}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=De.current.get(I);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"]})]},H);case "shortAnswer":return jsxs(Se__default.Fragment,{children:[jsx(Oc,{shortAnswers:[T.element],handleSelect:Ue,handleTransform:dt,saRefs:Je,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:Ne}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=Je.current.get(I);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"]})]},H);case "longAnswer":return jsxs(Se__default.Fragment,{children:[jsx(Kc,{longAnswer:[T.element],handleSelect:Ue,handleTransform:Qs,saRefs:Je,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:wa}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=Je.current.get(I);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"]})]},H);case "fillInTheBlanks":return jsxs(Se__default.Fragment,{children:[jsx(Wc,{fillInTheBlanks:[T.element],handleSelect:Ue,handleTransform:Gt,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:fn,fibRefs:jt}),xe&&!be&&I&&jsx(Transformer,{ref:z=>{if(z&&se.current!==z){se.current=z;let R=jt.current.get(I);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"]})]},H);default:return null}})})()})]}),E&&jsx(ju,{menuRef:C,x:E.x,y:E.y,type:E.elementType,onAction:xp,onClose:bp,isDrawingMode:E.elementType==="image"?i?.images.find(S=>S.id===E.elementId)?.isDrawingMode:E.elementType==="photoFrame"?i?.photoFrames.find(S=>S.id===E.elementId)?.isDrawingMode:false}),W&&E&&jsx(_u,{x:W.x,y:W.y,items:W.type==="order"?[{label:"Bring to Front",onClick:()=>ai("bring-to-front")},{label:"Send to Back",onClick:()=>ai("send-to-back")}]:[{label:i&&(E.elementType==="image"?i.images.find(S=>S.id===E.elementId)?.locked:i.videos.find(S=>S.id===E.elementId)?.locked)?"Unlock":"Lock",onClick:()=>ai(i&&(E.elementType==="image"?i.images.find(S=>S.id===E.elementId)?.locked:i.videos.find(S=>S.id===E.elementId)?.locked)?"unlock":"lock")}],onClose:()=>q(null)}),N&&jsx(Yu,{title:N.type==="link"?"Add Link":"Add Alt Text",label:N.type==="link"?"URL":"Alternative Text",placeholder:N.type==="link"?"https://example.com":"Describe this image/video",defaultValue:N.defaultValue,onSave:vp,onClose:()=>Z(null)}),X$1&&jsx(ts,{defaultColor:X$1.defaultColor,onConfirm:Sp,onCancel:()=>V(null)}),O&&jsx(ec,{imageSrc:O.imageSrc,onConfirm:Lp,onCancel:()=>K(null)}),j&&jsx(to,{onClose:()=>ee(false),stageRef:x}),Y&&jsx(rc,{elementId:Y.elementId,elementType:Y.elementType,existingAudio:Y.existingAudio,onSave:yp,onDelete:wp,onClose:()=>le(null)}),pe&&jsx(ic,{selectedElementId:I||void 0,onClose:()=>ye(false),onSelectElement:S=>{Ue(S),ye(false);}}),i?.images.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.videos.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.shapes?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.texts?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.flashcards?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.photoFrames?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.multipleChoices?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.trueFalses?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.shortAnswers?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.LongAnswer?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),i?.fillInTheBlanks?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:b.scale,offsetX:b.offsetX,offsetY:b.offsetY},`audio-${S.id}`)),y&&jsx(kc,{editElement:v}),A&&(()=>{let S=be||I;if(!S)return null;let T=lr.find(D=>D.id===S);return T?jsx(Pc,{text:T,position:A}):null})(),G&&be&&(()=>{let S=lr.find(T=>T.id===be);return S?jsx(Dc,{text:S,editingValue:Md,onEditingChange:Ad,onFinish:ti,position:{top:G.top,left:G.left},scale:G.scale,textareaRef:ce},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)]})},Pv=Av;var Dv="SchooplaVideoStorage";var oa="videos",ks=()=>new Promise((e,o)=>{let t=indexedDB.open(Dv,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(oa)||n.createObjectStore(oa,{keyPath:"id"});};}),ca=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await ks(),r=a.transaction([oa],"readwrite").objectStore(oa),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 Zc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await ks(),t=e.transaction([oa],"readonly").objectStore(oa);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}},ql=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await ks(),a=o.transaction([oa],"readwrite").objectStore(oa);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}},Jc=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await ks(),t=e.transaction([oa],"readwrite").objectStore(oa);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}},Qc=e=>URL.createObjectURL(e);function qa(e,o=[]){let t=[];function a(r,s){let u=Se.createContext(s),i=t.length;t=[...t,s];let c=d=>{let{scope:l,children:m,...h}=d,p=l?.[e]?.[i]||u,v=Se.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=Se.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=>Se.createContext(s));return function(u){let i=u?.[e]||r;return Se.useMemo(()=>({[`__scope${e}`]:{...u,[e]:i}}),[u,i])}};return n.scopeName=e,[a,Fv(n,...o)]}function Fv(...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 Se.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function ef(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(n=>{let r=ef(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():ef(e[n],null);}}}}function Ut(...e){return Se.useCallback(Xr(...e),e)}function of(e){let o=Bv(e),t=Se.forwardRef((a,n)=>{let{children:r,...s}=a,u=Se.Children.toArray(r),i=u.find(Nv);if(i){let c=i.props.children,f=u.map(d=>d===i?Se.Children.count(c)>1?Se.Children.only(null):Se.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Se.isValidElement(c)?Se.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Bv(e){let o=Se.forwardRef((t,a)=>{let{children:n,...r}=t;if(Se.isValidElement(n)){let s=qv(n),u=Hv(r,n.props);return n.type!==Se.Fragment&&(u.ref=a?Xr(a,s):s),Se.cloneElement(n,u)}return Se.Children.count(n)>1?Se.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Ov=Symbol("radix.slottable");function Nv(e){return Se.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ov}function Hv(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 qv(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 Wv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],wt=Wv.reduce((e,o)=>{let t=of(`Primitive.${o}`),a=Se.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 st(e,o,{checkForDefaultPrevented:t=true}={}){return function(n){if(e?.(n),t===false||!n.defaultPrevented)return o?.(n)}}function Vl(e){let o=Uv(e),t=Se.forwardRef((a,n)=>{let{children:r,...s}=a,u=Se.Children.toArray(r),i=u.find(Gv);if(i){let c=i.props.children,f=u.map(d=>d===i?Se.Children.count(c)>1?Se.Children.only(null):Se.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Se.isValidElement(c)?Se.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Uv(e){let o=Se.forwardRef((t,a)=>{let{children:n,...r}=t;if(Se.isValidElement(n)){let s=_v(n),u=jv(r,n.props);return n.type!==Se.Fragment&&(u.ref=a?Xr(a,s):s),Se.cloneElement(n,u)}return Se.Children.count(n)>1?Se.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Kv=Symbol("radix.slottable");function Gv(e){return Se.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Kv}function jv(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 _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)}function Ts(e){let o=e+"CollectionProvider",[t,a]=qa(o),[n,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=p=>{let{scope:v,children:y}=p,g=Se__default.useRef(null),x=Se__default.useRef(new Map).current;return jsx(n,{scope:v,itemMap:x,collectionRef:g,children:y})};s.displayName=o;let u=e+"CollectionSlot",i=Vl(u),c=Se__default.forwardRef((p,v)=>{let{scope:y,children:g}=p,x=r(u,y),L=Ut(v,x.collectionRef);return jsx(i,{ref:L,children:g})});c.displayName=u;let f=e+"CollectionItemSlot",d="data-radix-collection-item",l=Vl(f),m=Se__default.forwardRef((p,v)=>{let{scope:y,children:g,...x}=p,L=Se__default.useRef(null),I=Ut(v,L),F=r(f,y);return Se__default.useEffect(()=>(F.itemMap.set(L,{ref:L,...x}),()=>void F.itemMap.delete(L))),jsx(l,{[d]:"",ref:I,children:g})});m.displayName=f;function h(p){let v=r(e+"CollectionConsumer",p);return Se__default.useCallback(()=>{let g=v.collectionRef.current;if(!g)return [];let x=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(v.itemMap.values()).sort((F,C)=>x.indexOf(F.ref.current)-x.indexOf(C.ref.current))},[v.collectionRef,v.itemMap])}return [{Provider:s,Slot:c,ItemSlot:m},h,a]}var Zo=globalThis?.document?Se.useLayoutEffect:()=>{};var Xv=Se[" useId ".trim().toString()]||(()=>{}),$v=0;function lf(e){let[o,t]=Se.useState(Xv());return Zo(()=>{t(a=>a??String($v++));},[e]),(o?`radix-${o}`:"")}function df(e){let o=Se.useRef(e);return Se.useEffect(()=>{o.current=e;}),Se.useMemo(()=>(...t)=>o.current?.(...t),[])}var Yv=Se[" useInsertionEffect ".trim().toString()]||Zo;function ma({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[n,r,s]=Zv({defaultProp:o,onChange:t}),u=e!==void 0,i=u?e:n;{let f=Se.useRef(e!==void 0);Se.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=Se.useCallback(f=>{if(u){let d=Jv(f)?f(e):f;d!==e&&s.current?.(d);}else r(f);},[u,e,r,s]);return [i,c]}function Zv({defaultProp:e,onChange:o}){let[t,a]=Se.useState(e),n=Se.useRef(t),r=Se.useRef(o);return Yv(()=>{r.current=o;},[o]),Se.useEffect(()=>{n.current!==t&&(r.current?.(t),n.current=t);},[t,n]),[t,a,r]}function Jv(e){return typeof e=="function"}var Qv=Se.createContext(void 0);function Qo(e){let o=Se.useContext(Qv);return e||o||"ltr"}var Ul="rovingFocusGroup.onEntryFocus",ey={bubbles:false,cancelable:true},$r="RovingFocusGroup",[Kl,uf,ty]=Ts($r),[ay,Gl]=qa($r,[ty]),[oy,ry]=ay($r),cf=Se.forwardRef((e,o)=>jsx(Kl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Kl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(ny,{...e,ref:o})})}));cf.displayName=$r;var ny=Se.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=Se.useRef(null),m=Ut(o,l),h=Qo(r),[p,v]=ma({prop:s,defaultProp:u??null,onChange:i,caller:$r}),[y,g]=Se.useState(false),x=df(c),L=uf(t),I=Se.useRef(false),[F,C]=Se.useState(0);return Se.useEffect(()=>{let b=l.current;if(b)return b.addEventListener(Ul,x),()=>b.removeEventListener(Ul,x)},[x]),jsx(oy,{scope:t,orientation:a,dir:h,loop:n,currentTabStopId:p,onItemFocus:Se.useCallback(b=>v(b),[v]),onItemShiftTab:Se.useCallback(()=>g(true),[]),onFocusableItemAdd:Se.useCallback(()=>C(b=>b+1),[]),onFocusableItemRemove:Se.useCallback(()=>C(b=>b-1),[]),children:jsx(wt.div,{tabIndex:y||F===0?-1:0,"data-orientation":a,...d,ref:m,style:{outline:"none",...e.style},onMouseDown:st(e.onMouseDown,()=>{I.current=true;}),onFocus:st(e.onFocus,b=>{let k=!I.current;if(b.target===b.currentTarget&&k&&!y){let w=new CustomEvent(Ul,ey);if(b.currentTarget.dispatchEvent(w),!w.defaultPrevented){let E=L().filter(B=>B.focusable),M=E.find(B=>B.active),A=E.find(B=>B.id===p),G=[M,A,...E].filter(Boolean).map(B=>B.ref.current);pf(G,f);}}I.current=false;}),onBlur:st(e.onBlur,()=>g(false))})})}),ff="RovingFocusGroupItem",mf=Se.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:n=false,tabStopId:r,children:s,...u}=e,i=lf(),c=r||i,f=ry(ff,t),d=f.currentTabStopId===c,l=uf(t),{onFocusableItemAdd:m,onFocusableItemRemove:h,currentTabStopId:p}=f;return Se.useEffect(()=>{if(a)return m(),()=>h()},[a,m,h]),jsx(Kl.ItemSlot,{scope:t,id:c,focusable:a,active:n,children:jsx(wt.span,{tabIndex:d?0:-1,"data-orientation":f.orientation,...u,ref:o,onMouseDown:st(e.onMouseDown,v=>{a?f.onItemFocus(c):v.preventDefault();}),onFocus:st(e.onFocus,()=>f.onItemFocus(c)),onKeyDown:st(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){f.onItemShiftTab();return}if(v.target!==v.currentTarget)return;let y=ly(v,f.orientation,f.dir);if(y!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let x=l().filter(L=>L.focusable).map(L=>L.ref.current);if(y==="last")x.reverse();else if(y==="prev"||y==="next"){y==="prev"&&x.reverse();let L=x.indexOf(v.currentTarget);x=f.loop?dy(x,L+1):x.slice(L+1);}setTimeout(()=>pf(x));}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:p!=null}):s})})});mf.displayName=ff;var sy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function iy(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ly(e,o,t){let a=iy(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return sy[a]}function pf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function dy(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var hf=cf,gf=mf;var bf="Toggle",jl=Se.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:n,...r}=e,[s,u]=ma({prop:t,onChange:n,defaultProp:a??false,caller:bf});return jsx(wt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:st(e.onClick,()=>{e.disabled||u(!s);})})});jl.displayName=bf;var Va="ToggleGroup",[yf]=qa(Va,[Gl]),wf=Gl(),_l=Se__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(fy,{...a,ref:o});if(t==="multiple")return jsx(my,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Va}\``)});_l.displayName=Va;var[Sf,Lf]=yf(Va),fy=Se__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=ma({prop:t,defaultProp:a??"",onChange:n,caller:Va});return jsx(Sf,{scope:e.__scopeToggleGroup,type:"single",value:Se__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:u,onItemDeactivate:Se__default.useCallback(()=>u(""),[u]),children:jsx(If,{...r,ref:o})})}),my=Se__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=ma({prop:t,defaultProp:a??[],onChange:n,caller:Va}),i=Se__default.useCallback(f=>u((d=[])=>[...d,f]),[u]),c=Se__default.useCallback(f=>u((d=[])=>d.filter(l=>l!==f)),[u]);return jsx(Sf,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:c,children:jsx(If,{...r,ref:o})})});_l.displayName=Va;var[py,hy]=yf(Va),If=Se__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:n=true,orientation:r,dir:s,loop:u=true,...i}=e,c=wf(t),f=Qo(s),d={role:"group",dir:f,...i};return jsx(py,{scope:t,rovingFocus:n,disabled:a,children:n?jsx(hf,{asChild:true,...c,orientation:r,dir:f,loop:u,children:jsx(wt.div,{...d,ref:o})}):jsx(wt.div,{...d,ref:o})})}),Ps="ToggleGroupItem",gy=Se__default.forwardRef((e,o)=>{let t=Lf(Ps,e.__scopeToggleGroup),a=hy(Ps,e.__scopeToggleGroup),n=wf(e.__scopeToggleGroup),r=t.value.includes(e.value),s=a.disabled||e.disabled,u={...e,pressed:r,disabled:s},i=Se__default.useRef(null);return a.rovingFocus?jsx(gf,{asChild:true,...n,focusable:!s,active:r,ref:i,children:jsx(vf,{...u,ref:o})}):jsx(vf,{...u,ref:o})});gy.displayName=Ps;var vf=Se__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...n}=e,r=Lf(Ps,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=r.type==="single"?s:void 0;return jsx(jl,{...u,...n,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Cf=_l;function kf(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=kf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Es(){for(var e,o,t=0,a="",n=arguments.length;t<n;t++)(e=arguments[t])&&(o=kf(e))&&(a&&(a+=" "),a+=o);return a}var by=(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},vy=(e,o)=>({classGroupId:e,validator:o}),Ef=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Tf=[],yy="arbitrary..",wy=e=>{let o=Ly(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return Sy(s);let u=s.split("-"),i=u[0]===""&&u.length>1?1:0;return Df(u,i,o)},getConflictingClassGroupIds:(s,u)=>{if(u){let i=a[s],c=t[s];return i?c?by(c,i):i:c||Tf}return t[s]||Tf}}},Df=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let n=e[o],r=t.nextPart.get(n);if(r){let c=Df(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}},Sy=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?yy+a:void 0})(),Ly=e=>{let{theme:o,classGroups:t}=e;return Iy(t,o)},Iy=(e,o)=>{let t=Ef();for(let a in e){let n=e[a];Yl(n,t,a,o);}return t},Yl=(e,o,t,a)=>{let n=e.length;for(let r=0;r<n;r++){let s=e[r];Cy(s,o,t,a);}},Cy=(e,o,t,a)=>{if(typeof e=="string"){ky(e,o,t);return}if(typeof e=="function"){Ty(e,o,t,a);return}My(e,o,t,a);},ky=(e,o,t)=>{let a=e===""?o:Rf(o,e);a.classGroupId=t;},Ty=(e,o,t,a)=>{if(Ay(e)){Yl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(vy(t,e));},My=(e,o,t,a)=>{let n=Object.entries(e),r=n.length;for(let s=0;s<r;s++){let[u,i]=n[s];Yl(i,Rf(o,u),t,a);}},Rf=(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=Ef(),t.nextPart.set(s,u)),t=u;}return t},Ay=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Py=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 Ey=[],Mf=(e,o,t,a,n)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:n}),Dy=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 Mf(r,m,l,h)};if(o){let n=o+":",r=a;a=s=>s.startsWith(n)?r(s.slice(n.length)):Mf(Ey,false,s,void 0,true);}if(t){let n=a;a=r=>t({className:r,parseClassName:n});}return a},Ry=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}},Fy=e=>({cache:Py(e.cacheSize),parseClassName:Dy(e),sortModifiers:Ry(e),...wy(e)}),By=/\s+/,Oy=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:n,sortModifiers:r}=o,s=[],u=e.trim().split(By),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 g=l.length===0?"":l.length===1?l[0]:r(l).join(":"),x=m?g+"!":g,L=x+y;if(s.indexOf(L)>-1)continue;s.push(L);let I=n(y,v);for(let F=0;F<I.length;++F){let C=I[F];s.push(x+C);}i=f+(i.length>0?" "+i:i);}return i},Ny=(...e)=>{let o=0,t,a,n="";for(;o<e.length;)(t=e[o++])&&(a=Ff(t))&&(n&&(n+=" "),n+=a);return n},Ff=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Ff(e[a]))&&(t&&(t+=" "),t+=o);return t},Hy=(e,...o)=>{let t,a,n,r,s=i=>{let c=o.reduce((f,d)=>d(f),e());return t=Fy(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=Oy(i,t);return n(i,f),f};return r=s,(...i)=>r(Ny(...i))},qy=[],_e=e=>{let o=t=>t[e]||qy;return o.isThemeGetter=true,o},Bf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Of=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Vy=/^\d+\/\d+$/,zy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Wy=/\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$/,Uy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Ky=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Gy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,er=e=>Vy.test(e),ue=e=>!!e&&!Number.isNaN(Number(e)),za=e=>!!e&&Number.isInteger(Number(e)),Xl=e=>e.endsWith("%")&&ue(e.slice(0,-1)),pa=e=>zy.test(e),jy=()=>true,_y=e=>Wy.test(e)&&!Uy.test(e),Nf=()=>false,Xy=e=>Ky.test(e),$y=e=>Gy.test(e),Yy=e=>!J(e)&&!Q(e),Zy=e=>tr(e,Vf,Nf),J=e=>Bf.test(e),xo=e=>tr(e,zf,_y),$l=e=>tr(e,aw,ue),Af=e=>tr(e,Hf,Nf),Jy=e=>tr(e,qf,$y),Ds=e=>tr(e,Wf,Xy),Q=e=>Of.test(e),Yr=e=>ar(e,zf),Qy=e=>ar(e,ow),Pf=e=>ar(e,Hf),ew=e=>ar(e,Vf),tw=e=>ar(e,qf),Rs=e=>ar(e,Wf,true),tr=(e,o,t)=>{let a=Bf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},ar=(e,o,t=false)=>{let a=Of.exec(e);return a?a[1]?o(a[1]):t:false},Hf=e=>e==="position"||e==="percentage",qf=e=>e==="image"||e==="url",Vf=e=>e==="length"||e==="size"||e==="bg-size",zf=e=>e==="length",aw=e=>e==="number",ow=e=>e==="family-name",Wf=e=>e==="shadow";var rw=()=>{let e=_e("color"),o=_e("font"),t=_e("text"),a=_e("font-weight"),n=_e("tracking"),r=_e("leading"),s=_e("breakpoint"),u=_e("container"),i=_e("spacing"),c=_e("radius"),f=_e("shadow"),d=_e("inset-shadow"),l=_e("text-shadow"),m=_e("drop-shadow"),h=_e("blur"),p=_e("perspective"),v=_e("aspect"),y=_e("ease"),g=_e("animate"),x=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...L(),Q,J],F=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],b=()=>[Q,J,i],k=()=>[er,"full","auto",...b()],w=()=>[za,"none","subgrid",Q,J],E=()=>["auto",{span:["full",za,Q,J]},za,Q,J],M=()=>[za,"auto",Q,J],A=()=>["auto","min","max","fr",Q,J],U=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],G=()=>["start","end","center","stretch","center-safe","end-safe"],B=()=>["auto",...b()],W=()=>[er,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],q=()=>[e,Q,J],N=()=>[...L(),Pf,Af,{position:[Q,J]}],Z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",ew,Zy,{size:[Q,J]}],V=()=>[Xl,Yr,xo],O=()=>["","none","full",c,Q,J],K=()=>["",ue,Yr,xo],j=()=>["solid","dashed","dotted","double"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Y=()=>[ue,Xl,Pf,Af],le=()=>["","none",h,Q,J],pe=()=>["none",ue,Q,J],ye=()=>["none",ue,Q,J],ce=()=>[ue,Q,J],ge=()=>[er,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[pa],breakpoint:[pa],color:[jy],container:[pa],"drop-shadow":[pa],ease:["in","out","in-out"],font:[Yy],"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",ue],text:[pa],"text-shadow":[pa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",er,J,Q,v]}],container:["container"],columns:[{columns:[ue,J,Q,u]}],"break-after":[{"break-after":x()}],"break-before":[{"break-before":x()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:I()}],overflow:[{overflow:F()}],"overflow-x":[{"overflow-x":F()}],"overflow-y":[{"overflow-y":F()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:k()}],"inset-x":[{"inset-x":k()}],"inset-y":[{"inset-y":k()}],start:[{start:k()}],end:[{end:k()}],top:[{top:k()}],right:[{right:k()}],bottom:[{bottom:k()}],left:[{left:k()}],visibility:["visible","invisible","collapse"],z:[{z:[za,"auto",Q,J]}],basis:[{basis:[er,"full","auto",u,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ue,er,"auto","initial","none",J]}],grow:[{grow:["",ue,Q,J]}],shrink:[{shrink:["",ue,Q,J]}],order:[{order:[za,"first","last","none",Q,J]}],"grid-cols":[{"grid-cols":w()}],"col-start-end":[{col:E()}],"col-start":[{"col-start":M()}],"col-end":[{"col-end":M()}],"grid-rows":[{"grid-rows":w()}],"row-start-end":[{row:E()}],"row-start":[{"row-start":M()}],"row-end":[{"row-end":M()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":A()}],"auto-rows":[{"auto-rows":A()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...U(),"normal"]}],"justify-items":[{"justify-items":[...G(),"normal"]}],"justify-self":[{"justify-self":["auto",...G()]}],"align-content":[{content:["normal",...U()]}],"align-items":[{items:[...G(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...G(),{baseline:["","last"]}]}],"place-content":[{"place-content":U()}],"place-items":[{"place-items":[...G(),"baseline"]}],"place-self":[{"place-self":["auto",...G()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:B()}],mx:[{mx:B()}],my:[{my:B()}],ms:[{ms:B()}],me:[{me:B()}],mt:[{mt:B()}],mr:[{mr:B()}],mb:[{mb:B()}],ml:[{ml:B()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:W()}],w:[{w:[u,"screen",...W()]}],"min-w":[{"min-w":[u,"screen","none",...W()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[s]},...W()]}],h:[{h:["screen","lh",...W()]}],"min-h":[{"min-h":["screen","lh","none",...W()]}],"max-h":[{"max-h":["screen","lh",...W()]}],"font-size":[{text:["base",t,Yr,xo]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,Q,$l]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Xl,J]}],"font-family":[{font:[Qy,J,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[n,Q,J]}],"line-clamp":[{"line-clamp":[ue,"none",Q,$l]}],leading:[{leading:[r,...b()]}],"list-image":[{"list-image":["none",Q,J]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Q,J]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:q()}],"text-color":[{text:q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...j(),"wavy"]}],"text-decoration-thickness":[{decoration:[ue,"from-font","auto",Q,xo]}],"text-decoration-color":[{decoration:q()}],"underline-offset":[{"underline-offset":[ue,"auto",Q,J]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Q,J]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Q,J]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:N()}],"bg-repeat":[{bg:Z()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},za,Q,J],radial:["",Q,J],conic:[za,Q,J]},tw,Jy]}],"bg-color":[{bg:q()}],"gradient-from-pos":[{from:V()}],"gradient-via-pos":[{via:V()}],"gradient-to-pos":[{to:V()}],"gradient-from":[{from:q()}],"gradient-via":[{via:q()}],"gradient-to":[{to:q()}],rounded:[{rounded:O()}],"rounded-s":[{"rounded-s":O()}],"rounded-e":[{"rounded-e":O()}],"rounded-t":[{"rounded-t":O()}],"rounded-r":[{"rounded-r":O()}],"rounded-b":[{"rounded-b":O()}],"rounded-l":[{"rounded-l":O()}],"rounded-ss":[{"rounded-ss":O()}],"rounded-se":[{"rounded-se":O()}],"rounded-ee":[{"rounded-ee":O()}],"rounded-es":[{"rounded-es":O()}],"rounded-tl":[{"rounded-tl":O()}],"rounded-tr":[{"rounded-tr":O()}],"rounded-br":[{"rounded-br":O()}],"rounded-bl":[{"rounded-bl":O()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...j(),"hidden","none"]}],"divide-style":[{divide:[...j(),"hidden","none"]}],"border-color":[{border:q()}],"border-color-x":[{"border-x":q()}],"border-color-y":[{"border-y":q()}],"border-color-s":[{"border-s":q()}],"border-color-e":[{"border-e":q()}],"border-color-t":[{"border-t":q()}],"border-color-r":[{"border-r":q()}],"border-color-b":[{"border-b":q()}],"border-color-l":[{"border-l":q()}],"divide-color":[{divide:q()}],"outline-style":[{outline:[...j(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ue,Q,J]}],"outline-w":[{outline:["",ue,Yr,xo]}],"outline-color":[{outline:q()}],shadow:[{shadow:["","none",f,Rs,Ds]}],"shadow-color":[{shadow:q()}],"inset-shadow":[{"inset-shadow":["none",d,Rs,Ds]}],"inset-shadow-color":[{"inset-shadow":q()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:q()}],"ring-offset-w":[{"ring-offset":[ue,xo]}],"ring-offset-color":[{"ring-offset":q()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":q()}],"text-shadow":[{"text-shadow":["none",l,Rs,Ds]}],"text-shadow-color":[{"text-shadow":q()}],opacity:[{opacity:[ue,Q,J]}],"mix-blend":[{"mix-blend":[...ee(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ee()}],"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":Y()}],"mask-image-linear-to-pos":[{"mask-linear-to":Y()}],"mask-image-linear-from-color":[{"mask-linear-from":q()}],"mask-image-linear-to-color":[{"mask-linear-to":q()}],"mask-image-t-from-pos":[{"mask-t-from":Y()}],"mask-image-t-to-pos":[{"mask-t-to":Y()}],"mask-image-t-from-color":[{"mask-t-from":q()}],"mask-image-t-to-color":[{"mask-t-to":q()}],"mask-image-r-from-pos":[{"mask-r-from":Y()}],"mask-image-r-to-pos":[{"mask-r-to":Y()}],"mask-image-r-from-color":[{"mask-r-from":q()}],"mask-image-r-to-color":[{"mask-r-to":q()}],"mask-image-b-from-pos":[{"mask-b-from":Y()}],"mask-image-b-to-pos":[{"mask-b-to":Y()}],"mask-image-b-from-color":[{"mask-b-from":q()}],"mask-image-b-to-color":[{"mask-b-to":q()}],"mask-image-l-from-pos":[{"mask-l-from":Y()}],"mask-image-l-to-pos":[{"mask-l-to":Y()}],"mask-image-l-from-color":[{"mask-l-from":q()}],"mask-image-l-to-color":[{"mask-l-to":q()}],"mask-image-x-from-pos":[{"mask-x-from":Y()}],"mask-image-x-to-pos":[{"mask-x-to":Y()}],"mask-image-x-from-color":[{"mask-x-from":q()}],"mask-image-x-to-color":[{"mask-x-to":q()}],"mask-image-y-from-pos":[{"mask-y-from":Y()}],"mask-image-y-to-pos":[{"mask-y-to":Y()}],"mask-image-y-from-color":[{"mask-y-from":q()}],"mask-image-y-to-color":[{"mask-y-to":q()}],"mask-image-radial":[{"mask-radial":[Q,J]}],"mask-image-radial-from-pos":[{"mask-radial-from":Y()}],"mask-image-radial-to-pos":[{"mask-radial-to":Y()}],"mask-image-radial-from-color":[{"mask-radial-from":q()}],"mask-image-radial-to-color":[{"mask-radial-to":q()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[ue]}],"mask-image-conic-from-pos":[{"mask-conic-from":Y()}],"mask-image-conic-to-pos":[{"mask-conic-to":Y()}],"mask-image-conic-from-color":[{"mask-conic-from":q()}],"mask-image-conic-to-color":[{"mask-conic-to":q()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:N()}],"mask-repeat":[{mask:Z()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Q,J]}],filter:[{filter:["","none",Q,J]}],blur:[{blur:le()}],brightness:[{brightness:[ue,Q,J]}],contrast:[{contrast:[ue,Q,J]}],"drop-shadow":[{"drop-shadow":["","none",m,Rs,Ds]}],"drop-shadow-color":[{"drop-shadow":q()}],grayscale:[{grayscale:["",ue,Q,J]}],"hue-rotate":[{"hue-rotate":[ue,Q,J]}],invert:[{invert:["",ue,Q,J]}],saturate:[{saturate:[ue,Q,J]}],sepia:[{sepia:["",ue,Q,J]}],"backdrop-filter":[{"backdrop-filter":["","none",Q,J]}],"backdrop-blur":[{"backdrop-blur":le()}],"backdrop-brightness":[{"backdrop-brightness":[ue,Q,J]}],"backdrop-contrast":[{"backdrop-contrast":[ue,Q,J]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ue,Q,J]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ue,Q,J]}],"backdrop-invert":[{"backdrop-invert":["",ue,Q,J]}],"backdrop-opacity":[{"backdrop-opacity":[ue,Q,J]}],"backdrop-saturate":[{"backdrop-saturate":[ue,Q,J]}],"backdrop-sepia":[{"backdrop-sepia":["",ue,Q,J]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Q,J]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ue,"initial",Q,J]}],ease:[{ease:["linear","initial",y,Q,J]}],delay:[{delay:[ue,Q,J]}],animate:[{animate:["none",g,Q,J]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,Q,J]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:pe()}],"rotate-x":[{"rotate-x":pe()}],"rotate-y":[{"rotate-y":pe()}],"rotate-z":[{"rotate-z":pe()}],scale:[{scale:ye()}],"scale-x":[{"scale-x":ye()}],"scale-y":[{"scale-y":ye()}],"scale-z":[{"scale-z":ye()}],"scale-3d":["scale-3d"],skew:[{skew:ce()}],"skew-x":[{"skew-x":ce()}],"skew-y":[{"skew-y":ce()}],transform:[{transform:[Q,J,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ge()}],"translate-x":[{"translate-x":ge()}],"translate-y":[{"translate-y":ge()}],"translate-z":[{"translate-z":ge()}],"translate-none":["translate-none"],accent:[{accent:q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:q()}],"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",Q,J]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Q,J]}],fill:[{fill:["none",...q()]}],"stroke-w":[{stroke:[ue,Yr,xo,$l]}],stroke:[{stroke:["none",...q()]}],"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 Uf=Hy(rw);function Wa(...e){return Uf(Es(e))}var sw=Se.createContext({size:"default",variant:"default",spacing:0});function Ua({className:e,variant:o,size:t,spacing:a=1,children:n,...r}){return jsx(Cf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Wa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(sw.Provider,{value:{variant:o,size:t,spacing:a},children:n})})}var lw={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Xf=createSlice({name:"toolbar",initialState:lw,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:Zr,setFontSize:KD,setFontFamily:GD,setFontStyle:jD,setFontWeight:_D,setTextDecoration:XD,setTextColor:$D}=Xf.actions,Jl=Xf.reducer;var Yf=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 Jf=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 Fs=({onClose:e,onRecordingComplete:o})=>{let t=We(),[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 k=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});f(k),l(!0),y.current&&(y.current.srcObject=k);}catch(k){console.error("Error accessing camera:",k),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),c&&c.getTracks().forEach(k=>k.stop());}),[]);let g=()=>{c&&(c.getTracks().forEach(b=>b.stop()),f(null),l(false));},x=async()=>{try{let b=null,k=null;try{b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(U){console.error("Error accessing camera for recording:",U),alert("Failed to access camera for recording.");return}try{k=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let w=[...b.getVideoTracks()];k&&w.push(...k.getAudioTracks());let E=new MediaStream(w),M="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?M="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?M="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?M="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(M="video/webm;codecs=vp8");let A=new MediaRecorder(E,{mimeType:M,videoBitsPerSecond:25e5});m.current=A,h.current=[],A.ondataavailable=U=>{U.data.size>0&&h.current.push(U.data);},A.onstop=()=>{let U=new Blob(h.current,{type:M}),G=document.createElement("video");G.src=URL.createObjectURL(U),G.muted=!0,G.currentTime=.1,G.onseeked=()=>{let B=document.createElement("canvas");B.width=G.videoWidth,B.height=G.videoHeight;let W=B.getContext("2d");W&&(W.drawImage(G,0,0),v.current=B.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(G.src);},E.getTracks().forEach(B=>B.stop()),b&&b.getTracks().forEach(B=>B.stop()),k&&k.getTracks().forEach(B=>B.stop()),p.current&&clearInterval(p.current),s(U),g();},A.onerror=U=>{console.error("MediaRecorder error:",U);},A.start(1e3),n(!0),i(0),p.current=setInterval(()=>{i(U=>U+1);},1e3);}catch(b){console.error("Error starting camera recording:",b),alert("Failed to start recording. Please check permissions.");}},L=()=>{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 b=URL.createObjectURL(r),k=document.createElement("a");k.href=b,k.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(k),k.click(),document.body.removeChild(k),URL.revokeObjectURL(b);}},F=b=>{let k=Math.floor(b/60),w=b%60;return `${k.toString().padStart(2,"0")}:${w.toString().padStart(2,"0")}`};if(!t)return null;let C=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:b=>{b.target===b.currentTarget&&e(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:b=>b.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{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:x,disabled:!d,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!d&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:L,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:F(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: ",F(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(C,t)};var ga=40,em=({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=We(),d=useRef(null);useEffect(()=>{let x=L=>{L.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let l=x=>{let L=x.target.files;if(!L||L.length===0)return;let I=ga-a.length;if(I<=0){alert(`You can only upload a maximum of ${ga} images`);return}let F=Array.from(L).slice(0,I);F.length<L.length&&alert(`Only ${I} more images can be added (max ${ga} total)`);let C=F.map(b=>new Promise((k,w)=>{let E=new FileReader;E.onload=M=>{M.target?.result?k(M.target.result):w(new Error("Failed to read file"));},E.onerror=w,E.readAsDataURL(b);}));Promise.all(C).then(b=>{n(k=>[...k,...b]),d.current&&(d.current.value="");});},m=x=>{x.preventDefault(),i(false);let L=Array.from(x.dataTransfer.files).filter(b=>b.type.startsWith("image/"));if(L.length===0)return;let I=ga-a.length;if(I<=0){alert(`You can only upload a maximum of ${ga} images`);return}let F=L.slice(0,I);F.length<L.length&&alert(`Only ${I} more images can be added (max ${ga} total)`);let C=F.map(b=>new Promise((k,w)=>{let E=new FileReader;E.onload=M=>{M.target?.result?k(M.target.result):w(new Error("Failed to read file"));},E.onerror=w,E.readAsDataURL(b);}));Promise.all(C).then(b=>{n(k=>[...k,...b]);});},h=x=>{x.preventDefault(),i(true);},p=()=>{i(false);},v=x=>{n(L=>L.filter((I,F)=>F!==x));},y=x=>{if(x.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 g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{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>=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: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((x,L)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${L+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(L),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:L+1})]},L))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(g,f)};var Bs={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}},Cw={enabled:true};function td(e){return e?{tools:{...Bs.tools,...e.tools},actions:{...Bs.actions,...e.actions}}:Bs}var kw={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}},Tw={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 ad(e,[o,t]){return Math.min(t,Math.max(o,e))}function tm(e){let o=Se.useRef({value:e,previous:e});return Se.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function om(e){let[o,t]=Se.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 rm=["PageUp","PageDown"],nm=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],sm={"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",[od,Aw,Pw]=Ts(or),[im]=qa(or,[Pw]),[Ew,Ns]=im(or),lm=Se.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=Se.useRef(new Set),y=Se.useRef(0),x=s==="horizontal"?Dw:Rw,[L=[],I]=ma({prop:f,defaultProp:c,onChange:E=>{[...v.current][y.current]?.focus(),d(E);}}),F=Se.useRef(L);function C(E){let M=Hw(L,E);w(E,M);}function b(E){w(E,y.current);}function k(){let E=F.current[y.current];L[y.current]!==E&&l(L);}function w(E,M,{commit:A}={commit:false}){let U=Ww(r),G=Uw(Math.round((E-a)/r)*r+a,U),B=ad(G,[a,n]);I((W=[])=>{let q=Ow(W,B,M);if(zw(q,i*r)){y.current=q.indexOf(B);let N=String(q)!==String(W);return N&&A&&l(q),N?q:W}else return W});}return jsx(Ew,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:n,valueIndexToChangeRef:y,thumbs:v.current,values:L,orientation:s,form:h,children:jsx(od.Provider,{scope:e.__scopeSlider,children:jsx(od.Slot,{scope:e.__scopeSlider,children:jsx(x,{"aria-disabled":u,"data-disabled":u?"":void 0,...p,ref:o,onPointerDown:st(p.onPointerDown,()=>{u||(F.current=L);}),min:a,max:n,inverted:m,onSlideStart:u?void 0:C,onSlideMove:u?void 0:b,onSlideEnd:u?void 0:k,onHomeKeyDown:()=>!u&&w(a,0,{commit:true}),onEndKeyDown:()=>!u&&w(n,L.length-1,{commit:true}),onStepKeyDown:({event:E,direction:M})=>{if(!u){let G=rm.includes(E.key)||E.shiftKey&&nm.includes(E.key)?10:1,B=y.current,W=L[B],q=r*G*M;w(W+q,B,{commit:true});}}})})})})});lm.displayName=or;var[dm,um]=im(or,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Dw=Se.forwardRef((e,o)=>{let{min:t,max:a,dir:n,inverted:r,onSlideStart:s,onSlideMove:u,onSlideEnd:i,onStepKeyDown:c,...f}=e,[d,l]=Se.useState(null),m=Ut(o,x=>l(x)),h=Se.useRef(void 0),p=Qo(n),v=p==="ltr",y=v&&!r||!v&&r;function g(x){let L=h.current||d.getBoundingClientRect(),I=[0,L.width],C=sd(I,y?[t,a]:[a,t]);return h.current=L,C(x-L.left)}return jsx(dm,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx(cm,{dir:p,"data-orientation":"horizontal",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:x=>{let L=g(x.clientX);s?.(L);},onSlideMove:x=>{let L=g(x.clientX);u?.(L);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:x=>{let I=sm[y?"from-left":"from-right"].includes(x.key);c?.({event:x,direction:I?-1:1});}})})}),Rw=Se.forwardRef((e,o)=>{let{min:t,max:a,inverted:n,onSlideStart:r,onSlideMove:s,onSlideEnd:u,onStepKeyDown:i,...c}=e,f=Se.useRef(null),d=Ut(o,f),l=Se.useRef(void 0),m=!n;function h(p){let v=l.current||f.current.getBoundingClientRect(),y=[0,v.height],x=sd(y,m?[a,t]:[t,a]);return l.current=v,x(p-v.top)}return jsx(dm,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:jsx(cm,{"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=sm[m?"from-bottom":"from-top"].includes(p.key);i?.({event:p,direction:y?-1:1});}})})}),cm=Se.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:n,onSlideEnd:r,onHomeKeyDown:s,onEndKeyDown:u,onStepKeyDown:i,...c}=e,f=Ns(or,t);return jsx(wt.span,{...c,ref:o,onKeyDown:st(e.onKeyDown,d=>{d.key==="Home"?(s(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):rm.concat(nm).includes(d.key)&&(i(d),d.preventDefault());}),onPointerDown:st(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),f.thumbs.has(l)?l.focus():a(d);}),onPointerMove:st(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&n(d);}),onPointerUp:st(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),r(d));})})}),fm="SliderTrack",mm=Se.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Ns(fm,t);return jsx(wt.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...a,ref:o})});mm.displayName=fm;var rd="SliderRange",pm=Se.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Ns(rd,t),r=um(rd,t),s=Se.useRef(null),u=Ut(o,s),i=n.values.length,c=n.values.map(l=>xm(l,n.min,n.max)),f=i>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(wt.span,{"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,...a,ref:u,style:{...e.style,[r.startEdge]:f+"%",[r.endEdge]:d+"%"}})});pm.displayName=rd;var nd="SliderThumb",hm=Se.forwardRef((e,o)=>{let t=Aw(e.__scopeSlider),[a,n]=Se.useState(null),r=Ut(o,u=>n(u)),s=Se.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(Fw,{...e,ref:r,index:s})}),Fw=Se.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:n,...r}=e,s=Ns(nd,t),u=um(nd,t),[i,c]=Se.useState(null),f=Ut(o,g=>c(g)),d=i?s.form||!!i.closest("form"):true,l=om(i),m=s.values[a],h=m===void 0?0:xm(m,s.min,s.max),p=Nw(a,s.values.length),v=l?.[u.size],y=v?qw(v,h,u.direction):0;return Se.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(od.ItemSlot,{scope:e.__scopeSlider,children:jsx(wt.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:st(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),d&&jsx(gm,{name:n??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:m},a)]})});hm.displayName=nd;var Bw="RadioBubbleInput",gm=Se.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let n=Se.useRef(null),r=Ut(n,a),s=tm(o);return Se.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(wt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});gm.displayName=Bw;function Ow(e=[],o,t){let a=[...e];return a[t]=o,a.sort((n,r)=>n-r)}function xm(e,o,t){let r=100/(t-o)*(e-o);return ad(r,[0,100])}function Nw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Hw(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 qw(e,o,t){let a=e/2,r=sd([0,50],[0,a]);return (a-r(o)*t)*t}function Vw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function zw(e,o){if(o>0){let t=Vw(e);return Math.min(...t)>=o}return true}function sd(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 Ww(e){return (String(e).split(".")[1]||"").length}function Uw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var bm=lm,vm=mm,ym=pm,wm=hm;function Hs({className:e,defaultValue:o,value:t,min:a=0,max:n=100,rangeClassName:r,trackClassName:s,thumbClassName:u,...i}){let c=Se.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,n],[t,o,a,n]);return jsxs(bm,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:n,className:Wa("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(vm,{"data-slot":"slider-track",className:Wa("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(ym,{"data-slot":"slider-range",className:Wa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(f,d)=>jsx(wm,{"data-slot":"slider-thumb",className:Wa("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 vS=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a,onVisibilityChange:n}={})=>{let r=we(),s=te(P=>P.canvas.slides.find(ne=>ne.id===P.canvas.currentSlideId)),u=s?.videos||[],i=s?.editingFlashcard,c=te(P=>P.toolbar.selectedTool),f=te(P=>P.toolbar.penColor),d=te(P=>P.toolbar.strokeWidth),l=te(P=>P.canvas.editingOverlayPosition),m=s?.showMcqForm,h=s?.showFlashcardForm,p=useRef(null);useEffect(()=>{let P=ne=>{(ne.ctrlKey||ne.metaKey)&&ne.key==="z"&&!ne.shiftKey&&(ne.preventDefault(),r(Mo())),(ne.ctrlKey&&ne.shiftKey&&ne.key==="Z"||ne.ctrlKey&&ne.key==="y")&&(ne.preventDefault(),r(Ao()));};return window.addEventListener("keydown",P),()=>{window.removeEventListener("keydown",P);}},[r]);let v=useMemo(()=>td(a),[a]),{tools:y,actions:g}=v,x=u.some(P=>P.isRecorded&&P.isPlaying),L=te(P=>P.toolbar.fontSize),I=te(P=>P.toolbar.fontFamily),F=te(P=>P.toolbar.fontStyle),C=te(P=>P.toolbar.fontWeight),b=te(P=>P.toolbar.textDecoration),k=te(P=>P.toolbar.textColor),[w,E]=useState(false),[M,A]=useState(false),[U,G]=useState(false),[B,W]=useState(false),[q,N]=useState(false),[Z,X]=useState(false),[V,O]=useState(false),[K,j]=useState(false),[ee,Y]=useState(true),le=useRef(null),pe=useRef(null),ye=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],ce=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"}],[]),ge=useMemo(()=>[{name:"rectangle",icon:Square,label:"Square"},{name:"rectangle",icon:Rectangle,label:"Rectangle"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Yf,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Jf,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"}],[]),Le=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),Ae=useMemo(()=>ce.filter(P=>{let ne=y[P.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[y,ce]),re=useMemo(()=>{let P=y.shapes;return P===false?[]:P===true?ge:Array.isArray(P)?ge.filter(ne=>P.includes(ne.name)):ge},[y.shapes,ge]),Xe=useMemo(()=>{let P=y.activities;return P===false?[]:P===true?Le:Array.isArray(P)?Le.filter(ne=>P.includes(ne.name)):Le},[y.activities,Le]),wo=useMemo(()=>{let P=y.media;return P===false?{photoFrame:false,image:false,video:false}:P===true?{photoFrame:true,image:true,video:true}:Array.isArray(P)?{photoFrame:P.includes("photo-frame"),image:P.includes("image"),video:P.includes("video")}:{photoFrame:true,image:true,video:true}},[y.media]),rn=useMemo(()=>{let P=y.activities;return P===false?false:P===true?true:Array.isArray(P)?P.includes("flashcard"):true},[y.activities]),nn=P=>{let ne=P.target.files;!ne||ne.length===0||(r(ra("select")),r(It(false)),W(false),Array.from(ne).forEach(ke=>{let Ie=new FileReader;Ie.onload=fe=>{let ie=new window.Image;ie.src=fe.target?.result,ie.onload=()=>{let De=ie.width/ie.height,lt=300,sa=300,Je=ie.width,Ne=ie.height;Je>lt&&(Je=lt,Ne=Je/De),Ne>sa&&(Ne=sa,Je=Ne*De),r(de());let dt=l?.left||800-Je/2,ia=l?.top||450-Ne/2;r(ui({id:v4(),src:ie.src,x:dt,y:ia,width:Je,height:Ne,draggable:true,rotation:0}));};},Ie.readAsDataURL(ke);}),P.target.value="");},sn=async P=>{let ne=P.target.files;if(!(!ne||ne.length===0)){console.log("files",P),r(ra("select")),r(It(false)),W(false);for(let ke of Array.from(ne))try{let Ie=URL.createObjectURL(ke),fe=document.createElement("video");console.log("video",fe),fe.src=Ie,fe.muted=!0,fe.playsInline=!0,fe.preload="auto",fe.load(),await new Promise((Gt,jt)=>{let se=setTimeout(()=>jt(new Error("Metadata load timeout")),1e4);fe.onloadedmetadata=()=>{clearTimeout(se),Gt();},fe.onerror=()=>{clearTimeout(se),jt(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:fe.duration,width:fe.videoWidth,height:fe.videoHeight}),await new Promise((Gt,jt)=>{let se=setTimeout(()=>jt(new Error("Video load timeout")),1e4);fe.readyState>=2?(clearTimeout(se),Gt()):fe.onloadeddata=()=>{clearTimeout(se),Gt();};});let ie=Math.min(.8,fe.duration/2);console.log("Seeking to:",ie),fe.currentTime=ie,await new Promise(Gt=>{let jt=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Gt();},5e3);fe.onseeked=()=>{clearTimeout(jt),console.log("Seek completed"),Gt();};});let De=document.createElement("canvas"),lt=fe.videoWidth/fe.videoHeight,sa=400,Je=400,Ne=fe.videoWidth,dt=fe.videoHeight;Ne>sa&&(Ne=sa,dt=Ne/lt),dt>Je&&(dt=Je,Ne=dt*lt),De.width=Ne,De.height=dt;let ia=De.getContext("2d",{willReadFrequently:!1});if(!ia)throw new Error("Failed to get canvas context");if(await new Promise(Gt=>setTimeout(Gt,100)),fe.videoWidth===0||fe.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ne,height:dt}),ia.drawImage(fe,0,0,Ne,dt);let wa=De.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",wa.length),r(de());let Qs=800-Ne/2,ei=450-dt/2,fn=v4();await ca(fn,ke,wa),r(ko({id:fn,objectUrl:Ie,thumbnailDataUrl:wa,videoBlob:ke,x:Qs,y:ei,width:Ne,height:dt,draggable:!0,isPlaying:!1,rotation:0})),fe.src="",fe.load(),console.log(`Video uploaded: ${ke.name}`);}catch(Ie){console.error("Error processing video:",Ie),alert(`Failed to process video: ${ke.name}`);}P.target.value="";}},ln=(P,ne,ke)=>{r(de()),r(ra("select")),r(It(false));let Ie=300,fe=300,ie=800-Ie/2,De=450-fe/2;r(ke?To({id:ke,images:P,order:ne,x:ie,y:De,width:Ie,height:fe,rotation:0,draggable:true}):mi({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:P,currentIndex:0,order:ne,x:ie,y:De,width:Ie,height:fe,rotation:0,draggable:true})),r(eo(false));},Gs=()=>{r(de()),r(ra("select")),r(It(false));let P=400,ne=300,ke=800-P/2,Ie=450-ne/2;r(gi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ke,y:Ie,width:P,height:ne,rotation:0,draggable:true,isCapturing:false})),W(false);},js=P=>{let ie={};switch(P.name){case "rectangle":P.label==="Rectangle"?(ie.width=120,ie.height=80):(ie.width=100,ie.height=100);break;case "circle":case "ring":case "wedge":case "arc":ie.radius=50,(P.name==="ring"||P.name==="arc")&&(ie.innerRadius=25,ie.outerRadius=50),(P.name==="wedge"||P.name==="arc")&&(ie.angle=P.name==="wedge"?60:90);break;case "ellipse":ie.radiusX=60,ie.radiusY=40;break;case "triangle":ie.radius=50,ie.sides=3;break;case "polygon":ie.radius=50,ie.sides=6;break;case "star":ie.innerRadius=25,ie.outerRadius=50,ie.numPoints=5;break;case "arrow":case "line":ie.points=[0,0,100,0],P.name==="arrow"&&(ie.pointerLength=10,ie.pointerWidth=10);break}let De={id:`shape-${Date.now()}`,type:P.name,x:750,y:400,width:100,height:100,rotation:0,color:f,...ie};r(de()),r(It(false)),r(ra(P.name)),r(ci(De)),G(false);},ja=P=>{if(r(ra(P)),P==="select")r(It(false));else if(P==="text"){r(It(false)),r(de());let ne=200,ke=50,Ie=800-ne/2,fe=450-ke/2,De=window.innerWidth<768?Math.max(L,32):L,lt=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(fi({id:lt,text:"",x:Ie,y:fe,width:ne,height:ke,rotation:0,draggable:true,fontSize:De,fontFamily:I,fontStyle:F,fontWeight:C,textDecoration:b,fill:k,align:"left"})),setTimeout(()=>{r(vr(lt));},100),t&&t(lt);}else r(It(true));},_s=()=>{r(br()),r(It(false));},Xs=()=>{e?e():o?E(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},_a=()=>{A(true);},$s=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:Gs,enabled:wo.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>le.current?.click(),enabled:wo.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>pe.current?.click(),enabled:wo.video}],dn=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Mo()),enabled:g.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(Ao()),enabled:g.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:Xs,enabled:g.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:_a,enabled:g.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:_s,enabled:g.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],Xa=async(P,ne)=>{try{r(ra("select")),r(It(!1));let ke=URL.createObjectURL(P),Ie=document.createElement("video");Ie.src=ke,Ie.muted=!0,Ie.playsInline=!0,Ie.preload="auto",await new Promise((dt,ia)=>{let wa=setTimeout(()=>ia(new Error("Metadata load timeout")),1e4);Ie.onloadedmetadata=()=>{clearTimeout(wa),dt();},Ie.onerror=()=>{clearTimeout(wa),ia(new Error("Failed to load video"));};});let fe=640,ie=Ie.videoWidth/Ie.videoHeight,De=fe,lt=De/ie;r(de());let sa=800-De/2,Je=450-lt/2,Ne=v4();await ca(Ne,P,ne),r(ko({id:Ne,objectUrl:ke,thumbnailDataUrl:ne,videoBlob:P,x:sa,y:Je,width:De,height:lt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),E(!1),A(!1);}catch(ke){console.error("Error adding recorded video to canvas:",ke),alert("Failed to add video to canvas. Please try again.");}},un=P=>{r(ra("select")),r(It(false)),r(gr(null)),P&&r(Ti(P)),r(Ia(!m)),N(false);},Ys=()=>{r(hr(null)),r(eo(true)),N(false);},ir=()=>{G(!U);},So=()=>{W(!B);},cn=()=>{N(!q);},Zs=()=>{X(!Z);},Js=()=>{let P=!ee;P||(G(false),W(false),N(false),X(false),j(false),O(false)),Y(P),n?.(P);};return useEffect(()=>{if(!K)return;let P=ne=>{p.current&&!p.current.contains(ne.target)&&j(false);};return document.addEventListener("mousedown",P),()=>{document.removeEventListener("mousedown",P);}},[K]),x?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:Js,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:ee?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),ee&&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(Ua,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:Ae.map((P,ne)=>jsx("div",{title:P.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${P.name===c?"bg-primary/10":P.name==="style"?"md:hidden":""}`,onClick:()=>{P.name==="image"?(So(),G(false),N(false),X(false),ja(P.name)):P.name==="shapes"?(ir(),W(false),N(false),X(false),ja(P.name)):P.name==="activities"?(ja(P.name),cn(),G(false),W(false),X(false)):P.name==="style"?(Zs(),G(false),W(false),N(false),ja(P.name)):(ja(P.name),G(false),W(false),N(false),X(false));},children:jsx(P.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ne))}),U&&jsx(Ua,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:re.map((P,ne)=>jsx("div",{title:P.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>js(P),children:jsx(P.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ne))}),B&&jsx(Ua,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:$s.filter(P=>P.enabled).map(P=>jsx("div",{title:P.title,onClick:P.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(P.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},P.key))}),q&&jsxs(Ua,{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:[rn&&jsx("div",{title:"Flashcard",onClick:()=>Ys(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),Xe.map((P,ne)=>jsx("div",{title:P.label,onClick:()=>un(P.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(P.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},ne))]}),Z&&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(Hs,{value:[d],onValueChange:P=>{r(Zr(P[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:[ye.map(P=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${f===P.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:P.value},onClick:()=>{r(ha(P.value)),X(false);},title:P.name},P.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:P=>r(ha(P.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:P=>{r(pr(P.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"})]})]})]})]})]}),dn.some(P=>P.enabled)&&jsx(Ua,{type:"single",className:"hidden flex-col border bg-white p-1 shadow-xl md:flex",children:dn.filter(P=>P.enabled).map(P=>jsx("button",{onClick:P.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${P.colorClass}`,title:P.title,children:jsx(P.icon,{weight:P.iconWeight,className:"text-lg md:text-xl"})},P.key))})]}),jsx("input",{ref:le,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:nn}),jsx("input",{ref:pe,type:"file",accept:"video/*",className:"hidden",onChange:sn}),!e&&w&&o&&jsx(to,{onClose:()=>E(false),stageRef:o,onRecordingComplete:Xa}),M&&jsx(Fs,{onClose:()=>A(false),onRecordingComplete:Xa}),h&&jsx(em,{editingFlashcard:i,onConfirm:ln,onCancel:()=>r(eo(false))}),V&&jsx(ts,{defaultColor:f,onConfirm:P=>{r(ha(P)),O(false);},onCancel:()=>O(false)})]})},yS=vS;var cd=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let n=Fe(ka),r=Fe(Oi),s=a?r:n,u=Fe(wr),f=(Fe(g=>g.canvas.slides.find(x=>x.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.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 g=await e(s,u,x=>{h(x);});g.success?v({type:"success",message:g.message}):v({type:"error",message:g.message});}catch(g){v({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),v(null);},3e3);}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 CS=({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=Fe(wr),v=Fe(Ni),y=e??(v?p.title:"")??"Untitled",g=o??(v?p.description:"")??"Add a description...",[x,L]=useState(false),[I,F]=useState(false),[C,b]=useState(y),[k,w]=useState(g),E=useRef(null),M=useRef(null);useEffect(()=>{b(y);},[y]),useEffect(()=>{w(g);},[g]),useEffect(()=>{x&&E.current&&(E.current.focus(),E.current.select());},[x]),useEffect(()=>{I&&M.current&&(M.current.focus(),M.current.select());},[I]);let A=()=>{i&&L(true);},U=()=>{c&&F(true);},G=()=>{L(false),C.trim()&&C!==y?n?n(C.trim()):h(Ri(C.trim())):C.trim()||b(y);},B=()=>{F(false),k.trim()&&k!==g?r?r(k.trim()):h(Fi(k.trim())):k.trim()||w(g);},W=N=>{N.key==="Enter"?G():N.key==="Escape"&&(b(y),L(false));},q=N=>{N.key==="Enter"?B():N.key==="Escape"&&(w(g),F(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:[x?jsx("input",{ref:E,type:"text",value:C,onChange:N=>b(N.target.value),onBlur:G,onKeyDown:W,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:A,title:C,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:C}),I?jsx("input",{ref:M,type:"text",value:k,onChange:N=>w(N.target.value),onBlur:B,onKeyDown:q,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:U,title:k,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${c?"hover:border-primary cursor-text":""}`,children:k})]})]}),d||s&&a&&jsx(cd,{onPublish:a,includeInactiveSlides:m})]})};var ES=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],DS=({colors:e=ES,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:n=""})=>{let[r,s]=useState(true),u=te(ve),i=te(l=>l.toolbar.penColor),c=te(l=>l.toolbar.strokeWidth),f=u?.backgroundColor,d=we();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(Hs,{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(Ua,{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(ha(l.value))},l.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:l=>d(ha(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 Mm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),RS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),md=e=>{let o=RS(e);return o.charAt(0).toUpperCase()+o.slice(1)},Ws=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Am=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 Dm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:n="",children:r,iconNode:s,...u},i)=>createElement("svg",{ref:i,...Pm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Ws("lucide",n),...!r&&!Am(u)&&{"aria-hidden":"true"},...u},[...s.map(([c,f])=>createElement(c,f)),...Array.isArray(r)?r:[r]]));var Us=(e,o)=>{let t=forwardRef(({className:a,...n},r)=>createElement(Dm,{ref:r,iconNode:o,className:Ws(`lucide-${Mm(md(e))}`,`lucide-${e}`,a),...n}));return t.displayName=md(e),t};var NS=[["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=Us("copy",NS);var HS=[["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=Us("trash-2",HS);var Fm=({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 WS=({softDelete:e=false})=>{let o=$e(),t=Fe(ka),a=Fe(Ca),n=Fe(yr),[r,s]=useState(true),c=(Fe(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(Fm,{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,ZS=({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]})]}),JS=({softDelete:e=false})=>{let o=$e(),t=Fe(ka),a=Fe(Ca),n=Fe(yr),[r,s]=useState(false),[u,i]=useState(false),[c,f]=useState(false),d=useRef(null),h=(Fe(I=>I.canvas.slides.find(F=>F.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));},g=I=>{t.length>1&&o(cr({id:I,softDelete:e}));},x=()=>{if(!d.current)return;let{scrollLeft:I,scrollWidth:F,clientWidth:C}=d.current,b=F>C+5;i(b&&I>5),f(b&&I<F-C-5);},L=I=>{if(!d.current)return;let F=177,C=I==="left"?d.current.scrollLeft-F:d.current.scrollLeft+F;d.current.scrollTo({left:C,behavior:"smooth"});};return useEffect(()=>{if(r){let I=setTimeout(()=>{requestAnimationFrame(()=>{x();});},350);return ()=>clearTimeout(I)}},[t,r]),useEffect(()=>{let I=d.current;if(!(!I||!r))return I.addEventListener("scroll",x),window.addEventListener("resize",x),()=>{I.removeEventListener("scroll",x),window.removeEventListener("resize",x);}},[r]),h?null:jsx("div",{className:"fixed bottom-0 left-1/2 z-50 flex w-full -translate-x-1/2 flex-col gap-4 md:hidden",children:jsxs(AnimatePresence,{mode:"wait",children:[r&&jsxs(motion.div,{initial:{y:230,opacity:0},animate:{y:0,opacity:1},exit:{y:230,opacity:0},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},onAnimationComplete:()=>x(),className:"border bg-white md:hidden",children:[jsxs("div",{className:"flex w-full items-center justify-between px-4 py-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Cards,{size:24,weight:"fill",className:"text-[#096b76]"}),jsx("span",{className:"text-base font-bold text-black/80",children:"Pages"}),jsxs("span",{className:"text-base font-bold text-black/80",children:["(",t.length,"/",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:()=>L("left"),className:"absolute top-1/2 left-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll left",children:jsx(CaretLeft,{size:20,weight:"bold",className:"text-black/80"})}),c&&jsx("button",{onClick:()=>L("right"),className:"absolute top-1/2 right-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll right",children:jsx(CaretRight,{size:20,weight:"bold",className:"text-black/80"})}),jsx("div",{ref:d,className:"scrollbar-hide flex gap-[11px] overflow-x-auto px-4 pb-4",children:t.map((I,F)=>jsx(ZS,{slide:I,index:F,isSelected:I.id===a,isSingleSlide:t.length===1,onSelect:()=>v(I.id),onDuplicate:()=>y(I.id),onDelete:()=>g(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")]})})},hd=JS;var sL=({stageRef:e,onScreenRecord:o,visible:t=true,config:a={}})=>{let n=$e(),[r,s]=useState(false),[u,i]=useState(false),c=Fe(L=>L.canvas.slides.find(I=>I.id===L.canvas.currentSlideId)),f=Fe(L=>L.canvas.zoomLevel),l=(c?.videos||[]).some(L=>L.isRecorded&&L.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(L,I)=>{let F=v4(),C=URL.createObjectURL(L),b=document.createElement("video");b.src=C,b.muted=true,b.playsInline=true,b.preload="auto",await new Promise((A,U)=>{let G=setTimeout(()=>U(new Error("Metadata load timeout")),1e4);b.onloadedmetadata=()=>{clearTimeout(G),A();},b.onerror=()=>{clearTimeout(G),U(new Error("Failed to load video"));};});let k=640,w=b.videoWidth/b.videoHeight,E=k,M=E/w;await ca(F,L,I),n(ko({id:F,objectUrl:C,thumbnailDataUrl:I,videoBlob:L,x:100,y:100,width:E,height:M,draggable:true,isPlaying:false,rotation:0,isRecorded:true}));},x=[{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(Ud()),enabled:m.resetZoom&&f!==1,iconWeight:"bold",colorClass:"text-primary"}].filter(L=>L.enabled);return !t||l||x.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:x.map(L=>jsx("button",{onClick:L.onClick,className:`flex size-10 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-black/5 ${L.colorClass}`,title:L.title,children:jsx(L.icon,{weight:L.iconWeight,className:"text-xl"})},L.key))}),!o&&r&&e&&jsx(to,{onClose:()=>s(false),stageRef:e,onRecordingComplete:y}),u&&jsx(Fs,{onClose:()=>i(false),onRecordingComplete:y})]})},gd=sL;var dL=({stageRef:e,onScreenRecord:o,softDelete:t=false,actionButtonsVisible:a=true,actionButtonsConfig:n})=>jsxs(Fragment,{children:[jsx(gd,{stageRef:e,onScreenRecord:o,visible:a,config:n}),jsx(hd,{softDelete:t})]}),uL=dL;var mL="SchooplaEditorDB",pL=1,Ka="slides",Ga="metadata",xd="schoopla_current_slide_id",Wm="presentation_metadata",on=()=>new Promise((e,o)=>{let t=indexedDB.open(mL,pL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(Ka)||n.createObjectStore(Ka,{keyPath:"id"}),n.objectStoreNames.contains(Ga)||n.createObjectStore(Ga,{keyPath:"id"});};}),bd=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await on(),a=o.transaction([Ka],"readwrite").objectStore(Ka);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);}}},vd=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await on(),t=e.transaction([Ka],"readonly").objectStore(Ka);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}}},Ks=async()=>{try{let e=await on(),o=e.transaction([Ka,Ga],"readwrite"),t=o.objectStore(Ka),a=o.objectStore(Ga);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(xd),localStorage.removeItem("schoopla_presentation_metadata"),await Jc(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},yd=e=>{try{localStorage.setItem(xd,e);}catch(o){console.error("Error saving current slide ID:",o);}},wd=()=>{try{return localStorage.getItem(xd)}catch(e){return console.error("Error loading current slide ID:",e),null}},Sd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Ld=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await on(),a=o.transaction([Ga],"readwrite").objectStore(Ga);await new Promise((n,r)=>{let s=a.put({id:Wm,...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);}}},Id=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await on(),t=e.transaction([Ga],"readonly").objectStore(Ga);return new Promise((a,n)=>{let r=t.get(Wm);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 hL=["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"],gL=["canvas/clearCanvas"],xL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],bL=Sd((e,o)=>{bd(e),yd(o);},500),vL=Sd(e=>{Ld(e);},500),yL=(e,o)=>{bd(e),yd(o);},Cd=false,Um=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;ql(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=>{ql(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&&ca(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&&gL.includes(t.type)){if(!Cd){Cd=true;try{let{slides:r,currentSlideId:s}=n.canvas;yL(r,s);}finally{setTimeout(()=>{Cd=false;},0);}}}else if(t.type&&hL.includes(t.type)){let{slides:r,currentSlideId:s}=n.canvas;bL(r,s);}else if(t.type&&xL.includes(t.type)){let{presentationMetadata:r}=n.canvas;vL(r);}return a});new QueryClient;var SL=configureStore({reducer:{toolbar:Jl,canvas:Hi},middleware:e=>e({serializableCheck:false}).concat(Um)}),LL=()=>configureStore({reducer:{toolbar:Jl,canvas:Hi},middleware:e=>e({serializableCheck:false})});var IL=(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")}},CL=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);}})},kL=(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 TL=(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))},kd=(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=TL(e[s],n,r);u>t&&(t=u,a=s);}if(t>o){let s=kd(e.slice(0,a+1),o),u=kd(e.slice(a),o);return [...s.slice(0,-1),...u]}return [n,r]},ML=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},AL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Gm=(e,o=1.5)=>{if(e.length<=4)return e;let t=ML(e),a=kd(t,o);return AL(a)},jm=(e,o=1.5)=>({...e,points:Gm(e.points,o)}),PL=(e,o=1.5)=>e.map(t=>jm(t,o)),EL=(e,o)=>{let t=e.length/2,a=o.length/2,n=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${n}%`}};var DL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var _m=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=DL(e),m=f.toDataURL(l,n);r(m);},u.onerror=s,u.src=e;})};var yo=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",RL=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 _m(m,{maxWidth:a,maxHeight:n,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(m.startsWith("data:")){let h=yo(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=yo(l.audioData),g=nr(l.audioData);u+=y.byteLength,v.audioBuffer=y,v.audioMimeType=g;}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=yo(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=yo(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=yo(l.capturedImageUrl),p=nr(l.capturedImageUrl);u+=h.byteLength,m.buffer=h,m.mimeType=p;}if(l.audioData&&l.audioData.startsWith("data:")){let h=yo(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}},FL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},BL=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=yo(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 HL=()=>{let e=$e(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let n=await vd(),r=wd(),s=await Id();if(n&&n.length>0){let u=await Zc(),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=Qc(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?Bi({title:s.title,description:s.description}):_n(!0));}catch(n){console.error("Error loading persisted slides:",n),e(_n(true));}finally{t(false);}})();},[e]),{isLoading:o}};var $m=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||""})),Ym=new WeakSet,Zm=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);}}},qL=()=>{let e=$e(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Ym.has(a))return;Ym.add(a);let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await Ks(),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=$m(n);e(Io({slides:i,currentSlideId:u})),await Zm(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 Ks(),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=$m(n);e(Io({slides:i,currentSlideId:u})),await Zm(i);},[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{Tw as BASIC_EDITOR_TOOLBAR_CONFIG,DS as BottomToolbar,Pv as Canvas,Cw as DEFAULT_CONTEXT_MENU_CONFIG,Bs as DEFAULT_TOOLBAR_CONFIG,Fg as EditorRoot,gd as MobileActionButtons,uL as MobileBottomSection,hd as MobilePrevPanel,cd as PublishButton,to as ScreenRecorder,WS as SlideNavigation,yS as Toolbar,CS as TopNavBar,kw as VIEWER_TOOLBAR_CONFIG,ki as addFillInTheBlanks,mi as addFlashcard,ui as addImage,bi as addImageAnnotation,di as addLine,Ci as addLongAnswer,wi as addMultipleChoice,gi as addPhotoFrame,yi as addPhotoFrameAnnotation,ci as addShape,Ii as addShortAnswer,ur as addSlide,fi as addText,Li as addTrueFalse,ko as addVideo,FL as arrayBufferToBase64,Mi as bringToFront,br as clearCanvas,Dp as clearImageAnnotations,Ks as clearLocalData,Fp as clearPhotoFrameAnnotations,ii as createEmptySlide,LL as createViewerStore,Vn as deleteFillInTheBlanks,Mn as deleteFlashcard,vn as deleteImage,jn as deleteLineById,Hn as deleteLongAnswer,Dn as deleteMultipleChoice,Pn as deletePhotoFrame,Cn as deleteShape,On as deleteShortAnswer,cr as deleteSlide,kn as deleteText,Fn as deleteTrueFalse,Sn as deleteVideo,zn as duplicateFillInTheBlanks,An as duplicateFlashcard,yn as duplicateImage,Di as duplicateLine,qn as duplicateLongAnswer,Rn as duplicateMultipleChoice,En as duplicatePhotoFrame,In as duplicateShape,Nn as duplicateShortAnswer,fr as duplicateSlide,Tn as duplicateText,Bn as duplicateTrueFalse,Ln as duplicateVideo,hr as editFlashcard,Bp as editMultipleChoice,CL as exportSlideAsBlob,IL as exportSlideAsImage,Ei as finalizeDrawing,EL as getCompressionStats,kL as getSlideDataURL,wd as loadCurrentSlideId,vd as loadFromIndexedDB,Bi as loadPresentationMetadata,Id as loadPresentationMetadataFromDB,Io as loadSlides,td as mergeToolbarConfig,pi as nextFlashcard,BL as prepareFormData,RL as prepareSlidesForPublishing,hi as previousFlashcard,Ao as redo,bn as removeLine,Pp as reorderSlides,Ld as savePresentationMetadata,de as saveToHistory,ka as selectAllSlides,Oi as selectAllSlidesIncludingInactive,yr as selectCanAddSlide,ve as selectCurrentSlide,Ca as selectCurrentSlideId,Ni as selectMetadataLoaded,wr as selectPresentationMetadata,Vp as selectSlideById,Ai as sendToBack,Ti as setActivityType,Un as setAltText,Kn as setAudioData,pr as setBackgroundColor,mr as setCurrentSlide,gr as setEditingActivity,vr as setEditingTextId,Np as setLines,Wn as setLink,_n as setMetadataLoaded,ha as setPenColor,Fi as setPresentationDescription,Ri as setPresentationTitle,eo as setShowFlashcardForm,Ia as setShowMcqForm,It as setSketchMode,Zr as setStrokeWidth,ra as setTool,Ap as setViewerMode,Gm as simplifyFlatPoints,jm as simplifyLine,PL as simplifyLines,SL as store,xi as toggleImageDrawingMode,Pi as toggleLock,vi as togglePhotoFrameDrawingMode,qp as toggleSketchMode,Za as toggleVideoPlaying,Mo as undo,xr as updateElementOrder,la as updateFillInTheBlanks,To as updateFlashcard,Co as updateImage,Ep as updateImageAnnotation,Op as updateLastLine,Hp as updateLinePosition,Gn as updateLineTransform,La as updateLongAnswer,xt as updateMultipleChoice,Qa as updatePhotoFrame,Rp as updatePhotoFrameAnnotation,Ja as updateShape,ea as updateShortAnswer,li as updateSlideThumbnail,Ft as updateText,Qe as updateTrueFalse,wn as updateVideo,we as useDispatch,qL as useInitialSlides,sl as useModalPortal,te as useSelector,HL as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
21
  //# sourceMappingURL=index.js.map