@turnix-co/konva-editor 3.0.55 → 3.0.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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 as X$1,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Palette,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,List,Plus,Export,CaretLeft,CaretDown,CaretUp,SidebarSimple,CaretRight,ArrowsOut,SpeakerHifiIcon,NotePencilIcon,PencilSimple,CopySimple,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,TextUnderline,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Copy,Pen}from'@phosphor-icons/react/dist/ssr';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import jd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import $u from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {Stack as Stack$1,X as X$2,DotsSixVertical,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Bd=e=>{throw TypeError(e)};var Od=(e,o,t)=>o.has(e)||Bd("Cannot "+t);var $=(e,o,t)=>(Od(e,o,"read from private field"),t?t.call(e):o.get(e)),Be=(e,o,t)=>o.has(e)?Bd("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Pe=(e,o,t,a)=>(Od(e,o,"write to private field"),o.set(e,t),t);var Nd=(e,o,t,a)=>({set _(n){Pe(e,o,n);},get _(){return $(e,o,a)}});var Se=()=>useDispatch(),J=e=>useSelector(e),$e=Se,Ee=J;var ri=20,si=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}),oi=si("Slide 1"),vp={slides:[oi],currentSlideId:oi.id,history:{[oi.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},Hd=createSlice({name:"canvas",initialState:vp,reducers:{addSlide:e=>{if(e.slides.length>=ri)return;let o=si(`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>=ri)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],n={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),isActive:true,lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,n),e.currentSlideId=n.id,e.history[n.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},setViewerMode:(e,o)=>{e.viewerMode=o.payload;},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[n]=e.slides.splice(t,1);e.slides.splice(a,0,n);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(n=>n.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload);if(a){let n={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(n),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,newTimestamp:r}=o.payload;switch(n){case "image":let 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 m=t.flashcards.find(g=>g.id===a);m&&(m.timestamp=r);break;case "photoFrame":let l=t.photoFrames.find(g=>g.id===a);l&&(l.timestamp=r);break;case "mcq":let d=t.multipleChoices.find(g=>g.id===a);d&&(d.timestamp=r);break;case "trueFalse":let f=t.trueFalses.find(g=>g.id===a);f&&(f.timestamp=r);break;case "shortAnswer":let h=t.shortAnswers.find(g=>g.id===a);h&&(h.timestamp=r);break;case "longAnswer":let p=t.LongAnswer.find(g=>g.id===a);p&&(p.timestamp=r);break;case "fillInTheBlanks":let y=t.fillInTheBlanks.find(g=>g.id===a);y&&(y.timestamp=r);break;case "line":let w=t.lines.find(g=>g.id===a);w&&(w.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={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(n),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let n=t.shortAnswers[t.shortAnswers.length-1];a.x=n.x+20,a.y=n.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(n=>n.id===o.payload);if(a){let n={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(n),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let n=t.LongAnswer[t.LongAnswer.length-1];a.x=n.x+20,a.y=n.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload);if(a){let n={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(n),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let n=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=n.x+20,a.y=n.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(n=>n.id===o.payload);if(a){let n={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(n),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(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:ir,deleteSlide:lr,duplicateSlide:dr,setCurrentSlide:ur,setViewerMode:yp,updateSlideThumbnail:ii,setBackgroundColor:cr,reorderSlides:wp,loadSlides:vo,addLine:li,removeLine:yn,addImage:di,updateImage:yo,deleteImage:wn,duplicateImage:Sn,addVideo:wo,updateVideo:Ln,deleteVideo:In,duplicateVideo:Cn,toggleVideoPlaying:Ga,addShape:ui,updateShape:So,duplicateShape:kn,deleteShape:Tn,addText:ci,editingOverlayPosition:qd,updateText:Rt,deleteText:Mn,duplicateText:An,addFlashcard:fi,updateFlashcard:Lo,deleteFlashcard:Pn,duplicateFlashcard:En,editFlashcard:fr,nextFlashcard:mi,previousFlashcard:pi,addPhotoFrame:hi,updatePhotoFrame:ja,deletePhotoFrame:Dn,duplicatePhotoFrame:Rn,toggleImageDrawingMode:gi,addImageAnnotation:xi,updateImageAnnotation:Sp,clearImageAnnotations:Lp,togglePhotoFrameDrawingMode:bi,addPhotoFrameAnnotation:vi,updatePhotoFrameAnnotation:Ip,clearPhotoFrameAnnotations:Cp,addMultipleChoice:yi,updateMultipleChoice:Zt,updateMultipleChoiceDragAndDrop:wi,editMultipleChoice:kp,deleteMultipleChoice:Fn,duplicateMultipleChoice:Bn,addTrueFalse:Si,updateTrueFalse:Ft,deleteTrueFalse:On,duplicateTrueFalse:Nn,addShortAnswer:Li,updateShortAnswer:ya,deleteShortAnswer:Hn,duplicateShortAnswer:qn,addLongAnswer:Ii,updateLongAnswer:_a,deleteLongAnswer:Vn,duplicateLongAnswer:zn,addFillInTheBlanks:Ci,updateFillInTheBlanks:$a,deleteFillInTheBlanks:Un,duplicateFillInTheBlanks:Wn,setShowMcqForm:wa,setShowFlashcardForm:Xa,setActivityType:ki,setEditingActivity:mr,bringToFront:Ti,sendToBack:Mi,toggleLock:Ai,setLink:Kn,setAltText:Gn,setAudioData:jn,updateLastLine:Tp,finalizeDrawing:Pi,setLines:Mp,updateLinePosition:Ap,updateLineTransform:_n,deleteLineById:$n,duplicateLine:Ei,updateElementOrder:pr,clearCanvas:hr,undo:Io,redo:Co,saveToHistory:fe,toggleSketchMode:Pp,setSketchMode:wt,setEditingTextId:gr,setPresentationTitle:Di,setPresentationDescription:Ri,loadPresentationMetadata:Fi,setMetadataLoaded:Xn,setZoomLevel:BL,zoomIn:OL,zoomOut:NL,resetZoom:Vd}=Hd.actions;var zd=e=>e.canvas.slides,Sa=e=>e.canvas.currentSlideId,ye=createSelector([zd,Sa],(e,o)=>e.find(t=>t.id===o)),La=createSelector([zd],e=>e.filter(o=>o.isActive!==false)),Bi=e=>e.canvas.slides,xr=createSelector([La],e=>e.length<ri),Ep=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},br=e=>e.canvas.presentationMetadata,Oi=e=>e.canvas.metadataLoaded,Yn=e=>e.canvas.viewerMode,Ni=Hd.reducer;var Wd=e=>{let o=Se(),t=useRef(null),a=useRef(false),n=J(f=>f.toolbar.selectedTool),r=J(f=>f.toolbar.penColor),s=J(f=>f.toolbar.strokeWidth),u=J(f=>f.canvas.isSketchMode),i=J(f=>f.canvas.slides.find(p=>p.id===f.canvas.currentSlideId)?.lines||[]),c=useCallback(f=>{t.current=f;},[]),m=useCallback(f=>{n==="pen"&&t.current&&(o(fe()),t.current.startDrawing(f),a.current=true);},[n,o]),l=useCallback(f=>{!t.current||!a.current||t.current.draw(f);},[]),d=useCallback(()=>{if(!t.current||!a.current)return;let f=t.current.stopDrawing();a.current=false,f&&f.points.length>=4&&o(li(f)),o(Pi()),e?.();},[o,e]);return {lines:i,tool:n,color:r,strokeWidth:s,isSketchMode:u,setCanvasRef:c,startDrawing:m,draw:l,stopDrawing:d}};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 m=useRef(null),l=useRef(false),d=useRef([]),f=useRef([]),h=useRef(null),p=useRef(t),y=useRef(a),w=useRef(n),g=useRef(r),x=useRef(u),I=useRef(i);useEffect(()=>{p.current=t,y.current=a,w.current=n,g.current=r,x.current=u,I.current=i;},[t,a,n,r,u,i]);let L=useCallback(()=>{let C=m.current;if(!C)return;let b=C.getContext("2d");b&&b.clearRect(0,0,C.width,C.height);},[]),P=useCallback(()=>{let C=m.current,b=f.current;if(!C||b.length<1)return;let v=C.getContext("2d");if(!v)return;if(v.clearRect(0,0,C.width,C.height),p.current==="eraser"?(v.globalCompositeOperation="destination-out",v.fillStyle="rgba(0,0,0,1)"):(v.globalCompositeOperation="source-over",v.fillStyle=y.current),b.length===1){v.beginPath(),v.arc(b[0].x,b[0].y,w.current/2,0,Math.PI*2),v.fill();return}let T=jd(b,{size:w.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:F=>F,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(T.length<2)){v.beginPath(),v.moveTo(T[0][0],T[0][1]);for(let F=1;F<T.length;F++)v.lineTo(T[F][0],T[F][1]);v.closePath(),v.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:C=>{l.current=true;let b={x:C.x-x.current,y:C.y-I.current};d.current=[{x:C.x,y:C.y}],f.current=[b],h.current=C,P();},draw:C=>{if(!l.current||!h.current)return;let b=C.x-h.current.x,v=C.y-h.current.y;if(Math.sqrt(b*b+v*v)<2)return;let T={x:C.x-x.current,y:C.y-I.current};d.current.push({x:C.x,y:C.y}),f.current.push(T),h.current=C,P();},stopDrawing:()=>{if(!l.current)return null;if(l.current=false,d.current.length<2)return d.current=[],f.current=[],h.current=null,L(),null;let b=jd(d.current,{size:w.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:k=>k,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(k=>[k[0],k[1]]),v={tool:p.current,points:b,color:y.current,strokeWidth:w.current,isSketch:true};return d.current=[],f.current=[],h.current=null,L(),v},clear:()=>{L(),d.current=[],f.current=[],h.current=null,l.current=false;},isDrawing:()=>l.current,getCanvasElement:()=>m.current}),[L,P]),useEffect(()=>{let C=m.current;C&&(C.width=e,C.height=o);},[e,o]),jsx("canvas",{ref:m,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});_d.displayName="DirectDrawingCanvas";var $d=_d;var Yd=e=>{let o=Se(),a=J(ye)?.images||[],n=useRef(new Map),r=useRef(new Map),s=useRef(new Set);useEffect(()=>{let m=new Set(a.map(l=>l.id));s.current.forEach(l=>{if(!m.has(l)){let d=r.current.get(l);d&&(d.src="",r.current.delete(l)),n.current.delete(l);}}),s.current=m;},[a]),useEffect(()=>()=>{r.current.forEach(m=>{m.src="";}),r.current.clear(),n.current.clear();},[]);let u=useCallback(m=>{if(r.current.has(m.id))return r.current.get(m.id);let l=new window.Image;return (m.src.startsWith("http://")||m.src.startsWith("https://"))&&(l.crossOrigin="anonymous"),l.src=m.src,r.current.set(m.id,l),l},[]),i=useCallback((m,l)=>{let d=m.target,f=d.id();a.find(p=>p.id===f)&&(o(yo({id:f,x:d.x(),y:d.y(),width:d.width(),height:d.height(),rotation:d.rotation()})),l?.());},[a,o]),c=useCallback((m,l)=>{let d=l.target,f=n.current.get(m);if(!f){console.error("\u274C Image node not found for id:",m);return}let h=d.scaleX(),p=d.scaleY(),y=d.rotation(),w=f.width(),g=f.height(),x=Math.max(5,w*h),I=Math.max(5,g*p);d.scaleX(1),d.scaleY(1),f.width(x),f.height(I),o(yo({id:m,width:x,height:I,x:d.x(),y:d.y(),rotation:y})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:u,imageRefs:n,handleDragEnd:i,handleImageTransformEnd:c}};var Zd=e=>{let o=useDispatch(),t=useSelector(ye),a=useRef(new Map),n=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((u,i)=>{let c=i.target,m=c.scaleX(),l=c.scaleY(),d=c.rotation();o(Zt({id:u,scaleX:m,scaleY:l,x:c.x(),y:c.y(),rotation:d})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:n,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(u,i)=>{o(Zt({id:i,x:u.target.x(),y:u.target.y()})),e?.();}}};var Jd=e=>{let o=useDispatch(),t=useSelector(ye),a=useRef(new Map),n=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((u,i)=>{let c=i.target,m=c.scaleX(),l=c.scaleY(),d=c.rotation(),f=Math.max(5,c.width()*m),h=Math.max(5,c.height()*l);c.scaleX(1),c.scaleY(1),c.width(f),c.height(h),o(Ft({id:u,width:f,height:h,x:c.x(),y:c.y(),rotation:d})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:n,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(u,i)=>{o(Ft({id:i,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var Qd=e=>{let o=Se(),a=J(ye)?.videos||[],n=useRef(new Map),r=useCallback(i=>{o(Ga(i));},[o]),s=useCallback((i,c)=>{let m=c.target;o(Ln({id:i,x:m.x(),y:m.y()})),e?.();},[o,e]),u=useCallback((i,c)=>{let m=c.target,l=m.scaleX(),d=m.scaleY(),f=m.rotation(),h=Math.max(5,m.width()*l),p=Math.max(5,m.height()*d);m.scaleX(1),m.scaleY(1),m.width(h),m.height(p),o(Ln({id:i,width:h,height:p,x:m.x(),y:m.y(),rotation:f})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:n,handleVideoClick:r,handleVideoDragEnd:s,handleVideoTransformEnd:u}};var au=e=>{let o=Se(),a=J(ye)?.shapes||[],n=useRef(new Map),r=useRef(new Map),[s,u]=useState(false),i=useCallback((m,l)=>{let d=l.target;o(So({id:m,x:d.x(),y:d.y()})),e?.();},[o,e]),c=useCallback((m,l)=>{let d=l.target,f=a.find(x=>x.id===m);if(!f)return;let h=d.scaleX(),p=d.scaleY(),y=f.type?.toLowerCase();y==="arrow"||y==="line"||(d.scaleX(1),d.scaleY(1));let g={id:m,x:d.x(),y:d.y(),width:Math.max(5,d.width()*h),height:Math.max(5,d.height()*p),rotation:d.rotation()};switch(y){case "circle":g.radius=d.width()*h/2;break;case "star":g.innerRadius=d.width()*h/4,g.outerRadius=d.width()*h/2;break;case "triangle":g.radius=d.width()*h/2;break;case "ellipse":g.radiusX=d.width()*h/2,g.radiusY=d.height()*p/2;break;case "polygon":g.radius=d.width()*h/2;break;case "ring":let x=h;g.innerRadius=f.innerRadius&&f.innerRadius*x,g.outerRadius=f.outerRadius&&f.outerRadius*x;break;case "wedge":g.radius=f.radius&&f.radius*h;break;case "arc":g.innerRadius=f.innerRadius&&f.innerRadius*h,g.outerRadius=f.outerRadius&&f.outerRadius*h;break;case "arrow":case "line":{g.scaleX=h,g.scaleY=p,delete g.width,delete g.height;break}}o(So(g)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:n,isDragging:s,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:c}};var ru=(e,o)=>{let t=$e(),n=J(ye)?.texts||[],r=useRef(new Map),[s,u]=useState(null),[i,c]=useState("");return {texts:n,textRefs:r,handleDragEnd:(y,w)=>{let g=y.target;t(fe()),t(Rt({id:w,x:g.x(),y:g.y()})),e();},handleTransformEnd:y=>{let w=r.current.get(y);if(!w)return;let g=w.scaleX(),x=w.scaleY(),I=n.find(P=>P.id===y);if(!I)return;let L=(g+x)/2;w.scaleX(1),w.scaleY(1),t(fe()),t(Rt({id:y,x:w.x(),y:w.y(),width:Math.max(5,(I.width||100)*g),height:Math.max(5,(I.height||50)*x),fontSize:Math.round(Math.max(8,I.fontSize*L)),rotation:w.rotation()})),e();},handleDoubleClick:y=>{let w=n.find(g=>g.id===y);w&&!w.locked&&(u(y),c(w.text));},startEditing:y=>{let w=n.find(g=>g.id===y);w&&!w.locked&&(u(y),c(w.text));},editingTextId:s,editingValue:i,handleEditingChange:y=>{c(y);},finishEditing:()=>{if(s){let y=r.current.get(s),w=n.find(x=>x.id===s);t(fe());let g={id:s,text:i};if(w&&(w.fontWeight!==void 0&&(g.fontWeight=w.fontWeight),w.fontStyle!==void 0&&(g.fontStyle=w.fontStyle),w.textDecoration!==void 0&&(g.textDecoration=w.textDecoration)),o?.current&&i.trim()){let x=o.current,I=x.offsetWidth,L=x.offsetHeight,P=1;if(y){let U=y.getStage();U&&(P=U.scaleX());}let C=14,b=(I-C)/P,v=(L-C)/P,k=i.split(`
|
|
3
|
-
`).length,F=n.find(U=>U.id===s)?.fontSize||24,O=k*F*1.2+10;g.width=Math.max(200,b),g.height=Math.max(50,v,O);}else if(y&&i.trim()){let x=y.text(),I=y.width();y.text(i),y.width(void 0);let L=y.width(),P=y.height();y.text(x),y.width(I),g.width=Math.max(200,L+20),g.height=Math.max(50,P+20);}t(Rt(g)),u(null),c(""),t(gr(null)),e();}}}};var nu=e=>{let o=useDispatch(),a=useSelector(ye)?.shortAnswers||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(ya({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:n,handleShortAnswerDragEnd:r}};var su=e=>{let o=useDispatch(),t=useSelector(ye),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),n=useCallback((r,s)=>{let u=r.target;o(_a({id:s,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:n}};var lu=e=>{let o=Se(),a=J(ye)?.flashcards||[],n=useRef(new Map),r=useRef(new Map),s=useCallback((l,d)=>{if(r.current.has(d))return r.current.get(d);let f=new window.Image;return (l.startsWith("http://")||l.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=l,r.current.set(d,f),f},[]),u=useCallback(l=>{let d=l.target,f=d.id();a.find(p=>p.id===f)&&(o(Lo({id:f,x:d.x(),y:d.y()})),e?.());},[a,o,e]),i=useCallback((l,d)=>{let f=d.target,h=f.scaleX(),p=f.scaleY(),y=f.rotation(),w=Math.max(50,f.width()*h),g=Math.max(50,f.height()*p);f.scaleX(1),f.scaleY(1),f.width(w),f.height(g),o(Lo({id:l,width:w,height:g,x:f.x(),y:f.y(),rotation:y})),f.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(l=>{o(mi(l)),e?.();},[o,e]),m=useCallback(l=>{o(pi(l)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:n,handleDragEnd:u,handleFlashcardTransformEnd:i,handleNext:c,handlePrevious:m}};var cu=e=>{let o=Se(),a=J(ye)?.photoFrames||[],n=useRef(new Map),[r,s]=useState(new Map),u=useCallback((f,h)=>{console.log("handleDragEnd"),o(ja({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),i=useCallback((f,h)=>{let p=h.target,y=p.scaleX(),w=p.scaleY(),g=p.rotation(),x=a.find(P=>P.id===f);if(!x)return;let I=Math.max(100,x.width*y),L=Math.max(100,x.height*w);p.scaleX(1),p.scaleY(1),o(ja({id:f,width:I,height:L,x:p.x(),y:p.y(),rotation:g})),p.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(p=>{let y=new Map(p);return y.set(f,h),y}),o(ja({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),m=useCallback(f=>{let h=r.get(f);h&&(h.getTracks().forEach(p=>p.stop()),s(p=>{let y=new Map(p);return y.delete(f),y}),o(ja({id:f,isCapturing:false})),e?.());},[r,o,e]),l=useCallback((f,h)=>{let p=document.createElement("canvas");p.width=h.videoWidth,p.height=h.videoHeight;let y=p.getContext("2d");if(y){y.drawImage(h,0,0,p.width,p.height);let w=p.toDataURL("image/jpeg",.8);return o(ja({id:f,capturedImageUrl:w,isCapturing:false})),m(f),e?.(),w}return null},[o,m,e]),d=useRef(r);return useEffect(()=>{d.current=r;},[r]),useEffect(()=>()=>{d.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:n,handleDragEnd:u,handlePhotoFrameTransformEnd:i,startCamera:c,stopCamera:m,capturePhoto:l,cameraStreams:r}};var fu=()=>{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,m,l,d=[])=>{if(e.current){if(r&&!d.find(p=>p.id===r)?.isPlaying){let p=s.get(r)||u.get(r)||i.get(r)||c.get(r)||m.get(r)||(l?l.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 nh=(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])},gu=(e,o)=>{let t=$e(),a=Ee(Yn),n=useRef(e);useEffect(()=>{n.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(ii({id:n.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),s=nh(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var ih=e=>e.flatMap(o=>[o[0],o[1]]),Jn=(e,o)=>{let t=jd(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 ih(t)};var xu=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null),u=J(x=>x.toolbar.selectedTool),i=J(x=>x.toolbar.penColor),c=J(x=>x.toolbar.strokeWidth),m=J(x=>x.canvas.isSketchMode),l=J(x=>x.canvas.slides.find(L=>L.id===x.canvas.currentSlideId)?.images.find(L=>L.id===e)),d=l?.annotations||[],f=l?.isDrawingMode||false,h=l?.width||1,p=l?.height||1,y=useCallback(x=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,n.current=[{x:x.x,y:x.y}];let I=x.x/h,L=x.y/p;s({tool:u,points:[I,L],color:i,strokeWidth:c/h,isSketch:m});},[u,i,c,m,h,p]),w=useCallback(x=>{if(!t.current||!r)return;a.current=true;let I=n.current[n.current.length-1];if(Math.sqrt(Math.pow(x.x-I.x,2)+Math.pow(x.y-I.y,2))<2)return;n.current.push({x:x.x,y:x.y});let P;if(m)P=Jn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,v)=>v%2===0?b/h:b/p);else {let C=x.x/h,b=x.y/p;P=[...r.points,C,b];}s(C=>C?{...C,points:P}:null);},[m,c,r,h,p]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(xi({imageId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:d,activeLine:r,isDrawingMode:f,startDrawing:y,draw:w,stopDrawing:g,tool:u}};function qe({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],m=Math.abs(c.clientX-n.current.x),l=Math.abs(c.clientY-n.current.y);(m>t||l>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 Su=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u})=>{let{annotations:i,activeLine:c,stopDrawing:d,tool:f}=xu(e.id),{createHandlers:h}=qe({onLongPress:u});useEffect(()=>{let x=t.current.get(e.id);x&&(x.width()!==e.width||x.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:x.width(),konvaHeight:x.height()}),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[d,p]);let y=x=>{{r(e.id);return}},w=x=>{return;},g=x=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="eraser",children:[jsx(Image$1,{id:e.id,ref:x=>{if(x)t.current.set(e.id,x),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw();else {let I=t.current.get(e.id);I?._contextMenuCleanup&&I._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:x=>n(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:x=>{x.evt.preventDefault();let I=x.evt;s(I,e.id,"image");},...f!=="pen"&&f!=="eraser"?{onClick:y,onTap:y,onMouseDown:y,onMouseMove:w,onMouseUp:g,...h(e.id,"image")}:{}}),i?.map((x,I)=>{let L=x.points.map((C,b)=>b%2===0?C*e.width+e.x:C*e.height+e.y),P=x.strokeWidth*e.width;return jsx(Line,{points:L,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:P,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},I)}),c&&jsx(Line,{points:c.points.map((x,I)=>I%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")]})});Su.displayName="ImageWithDrawing";var Ki=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(Su,{img:i,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u},i.id):null})}));Ki.displayName="ImageLayer";var bh=({src:e,x:o,id:t,y:a,width:n,height:r,isSelected:s,rotation:u=0,onTransformEnd:i,onDragEnd:c})=>{let m=Se(),l=useRef(null),d=f=>{m(Ga(f));};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:l,src:e,controls:true,autoPlay:true,onClick:()=>d(t),onSeeking:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Lu=bh;var kh=({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),m=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let p=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(p.crossOrigin="anonymous"),p.src=e.thumbnailDataUrl,p.onload=()=>{i(p);};}},[e.thumbnailDataUrl]),!u)return null;let l=e.width/2,d=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,80));return jsxs(Group,{draggable:!m,listening:!m,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...m?{}:{onDragEnd:a,onTransformEnd:n},ref:p=>{if(s(p),p){let y=p.getStage()?.container();if(y){let w=g=>{let x=p.getStage()?.getPointerPosition();if(x){let I={x:e.x,y:e.y,width:e.width,height:e.height};x.x>=I.x&&x.x<=I.x+I.width&&x.y>=I.y&&x.y<=I.y+I.height&&r(g);}};y.addEventListener("contextmenu",w),p._contextMenuCleanup=()=>{y.removeEventListener("contextmenu",w);};}}},children:[jsx(Image$1,{image:u,width:e.width,height:e.height,listening:!m,...m?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:l,y:d,radius:h,fill:"white",listening:!m,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...m?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:l,y:d,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!m,...m?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:l+h*.1,y:d,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!m,...m?{}:{onClick:t,onTap:t}})]})},Cu=kh;var _i=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(Cu,{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(Lu,{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))}));_i.displayName="VideoLayer";var $i=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:n,handleShapeDragStart:r,onContextMenu:s,onLongPress:u})=>{let i=useSelector(l=>l.toolbar.selectedTool),c=i==="pen"||i==="eraser",{createHandlers:m}=qe({onLongPress:u});return jsx(Fragment,{children:e.map((l,d)=>{let f=l.id||d,h={id:l.id,x:l.x,y:l.y,rotation:l.rotation,draggable:!l.locked&&!c,listening:!c,fill:l.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(l.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},radius:l.radius||l.width/2,width:l.width,height:l.width},f);case "star":return jsx(Star,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},numPoints:5,innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},sides:3,radius:l.radius||l.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},sides:l.sides||6,radius:l.radius||l.width/2},f);case "ellipse":return jsx(Ellipse,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},radiusX:l.radiusX||l.width/2,radiusY:l.radiusY||l.height/2},f);case "ring":return jsx(Ring,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},f);case "wedge":return jsx(Wedge,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},radius:l.radius||l.width/2,angle:l.angle||60},f);case "arrow":return jsx(Arrow,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},points:l.points||[0,0,l.width,0],pointerLength:l.pointerLength||10,pointerWidth:l.pointerWidth||10,stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},f);case "line":return jsx(Line,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},points:l.points||[0,0,l.width,0],stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2,angle:l.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},width:l.width,height:l.height,cornerRadius:l.type==="rounded-rectangle"?10:0},f)}})})});$i.displayName="ShapeLayer";var Mu=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:n,onContextMenu:r,onDoubleClick:s,editingTextId:u,onLongPress:i})=>{useEffect(()=>{e.forEach(d=>{let f=o.current.get(d.id);f&&(f.cache(),f.getLayer()?.batchDraw());});},[e,o]);let c=useSelector(d=>d.toolbar.selectedTool),m=c==="pen"||c==="eraser",{createHandlers:l}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(d=>{let f=d.id===u,h=d.fontWeight==="bold",p=h?Math.max(1,d.fontSize/25):0;return jsx(Text,{id:d.id,ref:y=>{y?o.current.set(d.id,y):o.current.delete(d.id);},text:d.text,x:d.x,y:d.y,width:d.width,height:d.height,rotation:d.rotation,draggable:!d.locked&&!f&&!m,listening:!m,fontSize:d.fontSize,fontFamily:d.fontFamily,fontStyle:d.fontStyle,fontWeight:d.fontWeight,textDecoration:d.textDecoration,fill:d.fill,stroke:h?d.fill:void 0,strokeWidth:p,align:d.align,wrap:"word",lineHeight:1.2,opacity:f?0:1,visible:!f,...m?{}:{onClick:()=>n(d.id),onTap:()=>n(d.id),onDblClick:()=>s(d.id),onDblTap:()=>s(d.id),onDragEnd:y=>t(y,d.id),onTransformEnd:()=>a(d.id),onContextMenu:y=>{y.evt.preventDefault();let w=y.evt;r(w,d.id,"text");},...l(d.id,"text")}},d.id)})})};var Jh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onNext:s,onPrevious:u,nodeRef:i,touchHandlers:c,currentTool:m})=>{let[l,d]=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=()=>{d(g);};}},[e.images,e.currentIndex]),!l||e.images.length===0)return null;let f=8,h=2,p=Math.min(e.width,e.height)*.08,y=Math.max(16,Math.min(p,32)),w=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked&&m==="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 I=L=>{let P=g.getStage()?.getPointerPosition();if(P){let C={x:e.x,y:e.y,width:e.width,height:e.height};P.x>=C.x&&P.x<=C.x+C.width&&P.y>=C.y&&P.y<=C.y+C.height&&r(L);}};x.addEventListener("contextmenu",I),g._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",I);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,stroke:"#E5E7EB",strokeWidth:h,listening:false}),jsx(Image$1,{x:h+4,y:h+4,image:l,width:e.width-(h+4)*2,height:e.height-(h+4)*2,cornerRadius:f-h,onClick:t,onTap:t}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:w+y,y:e.height/2,onClick:g=>{g.cancelBubble=true,u();},onTap:g=>{g.cancelBubble=true,u();},children:[jsx(Circle,{radius:y,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-w-y,y:e.height/2,onClick:g=>{g.cancelBubble=true,s();},onTap:g=>{g.cancelBubble=true,s();},children:[jsx(Circle,{radius:y,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Eu=Jh;var Ji=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onNext:s,onPrevious:u,onContextMenu:i,onLongPress:c})=>{let{createHandlers:m}=qe({onLongPress:c}),l=J(d=>d.toolbar.selectedTool);return jsx(Fragment,{children:e.map(d=>jsx(Eu,{flashcard:d,isSelected:t===d.id,onClick:()=>r(d.id),currentTool:l,onDragEnd:a,onTransformEnd:f=>n(d.id,f),onContextMenu:f=>i(f,d.id,"flashcard"),onNext:()=>s(d.id),onPrevious:()=>u(d.id),touchHandlers:m(d.id,"flashcard"),nodeRef:f=>{f?o.current.set(d.id,f):o.current.delete(d.id);}},d.id))})});Ji.displayName="FlashcardLayer";var Ru=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null);J(x=>x.toolbar.selectedTool);let i=J(x=>x.toolbar.penColor),c=J(x=>x.toolbar.strokeWidth),m=J(x=>x.canvas.isSketchMode),l=J(x=>x.canvas.slides.find(L=>L.id===x.canvas.currentSlideId)?.photoFrames.find(L=>L.id===e)),d=l?.annotations||[],f=l?.isDrawingMode||false,h=l?.width||1,p=l?.height||1,y=useCallback(x=>{if(!f)return;t.current=true,a.current=false,n.current=[{x:x.x,y:x.y}];let I=x.x/h,L=x.y/p;s({tool:"pen",points:[I,L],color:i,strokeWidth:c/h,isSketch:m});},[f,i,c,m,h,p]),w=useCallback(x=>{if(!t.current||!r)return;a.current=true;let I=n.current[n.current.length-1];if(Math.sqrt(Math.pow(x.x-I.x,2)+Math.pow(x.y-I.y,2))<2)return;n.current.push({x:x.x,y:x.y});let P;if(m)P=Jn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,v)=>v%2===0?b/h:b/p);else {let C=x.x/h,b=x.y/p;P=[...r.points,C,b];}s(C=>C?{...C,points:P}:null);},[m,c,r,h,p]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(vi({frameId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:d,activeLine:r,isDrawingMode:f,startDrawing:y,draw:w,stopDrawing:g}};var sg=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onStartCamera:s,onCapture:u,cameraStream:i,nodeRef:c,touchHandlers:m})=>{let[l,d]=useState(null),[f,h]=useState(null),p=useRef(null),y=useRef(null),w=useRef(null),g=useRef(null),x=useRef(0),I=33,L=useSelector(z=>z.toolbar.selectedTool),P=L==="pen"||L==="eraser",{annotations:C,activeLine:b,isDrawingMode:v,startDrawing:k,draw:T,stopDrawing:F}=Ru(e.id);useEffect(()=>{if(!v)return;let z=()=>{F();},N=()=>{F();};return window.addEventListener("mouseup",z),window.addEventListener("touchend",N),()=>{window.removeEventListener("mouseup",z),window.removeEventListener("touchend",N);}},[F,v]),useEffect(()=>{if(e.capturedImageUrl){let z=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(z.crossOrigin="anonymous"),z.src=e.capturedImageUrl,z.onload=()=>{d(z);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),y.current||(y.current=document.createElement("canvas"));let z=p.current,N=y.current;z.srcObject=i;let _=()=>{N.width=z.videoWidth||640,N.height=z.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",N.width,N.height);let Z=ae=>{if(ae-x.current<I){w.current=requestAnimationFrame(Z);return}x.current=ae;let Q=N.getContext("2d");if(Q&&z.readyState===z.HAVE_ENOUGH_DATA){Q.drawImage(z,0,0,N.width,N.height);let pe=N.toDataURL("image/jpeg",.6),ue=new window.Image;ue.onload=()=>{h(ue);},ue.src=pe;}w.current=requestAnimationFrame(Z);};w.current=requestAnimationFrame(Z);};return z.onloadedmetadata=_,z.readyState>=z.HAVE_METADATA&&_(),z.play().catch(Z=>console.error("Error playing video:",Z)),()=>{w.current&&(cancelAnimationFrame(w.current),w.current=null);}}return ()=>{h(null),g.current&&(g.current.src="");}},[e.isCapturing,i]);let V=()=>{p.current&&e.isCapturing&&u(p.current);},O=z=>{if(e.capturedImageUrl){if(!v){t();return}let N=z.currentTarget,_=N.getAbsoluteTransform().copy(),ae=N.getStage()?.getPointerPosition();if(ae){_.invert();let Q=_.point(ae);k(Q);}z.cancelBubble=true;}else t();},U=z=>{if(!v||!e.capturedImageUrl)return;let N=z.currentTarget,_=N.getAbsoluteTransform().copy(),ae=N.getStage()?.getPointerPosition();if(ae){_.invert();let Q=_.point(ae);T(Q);}},H=()=>{!v||!e.capturedImageUrl||F();},K=e.isCapturing?f:l,E=Math.min(e.width,e.height)*.12,W=Math.max(25,Math.min(E,50)),te=e.width/2,G=e.height/2;return jsxs(Group,{id:e.id,draggable:!v&&!P,listening:true,onClick:t,onTap:t,x:e.x,y:e.y,...m,...P?{}:{onDragEnd:a,onTransformEnd:n},rotation:e.rotation,width:e.width,height:e.height,ref:z=>{if(c(z),z){let N=z.getStage()?.container();if(N){let _=Z=>{let ae=z.getStage()?.getPointerPosition();if(ae){let Q={x:e.x,y:e.y,width:e.width,height:e.height};ae.x>=Q.x&&ae.x<=Q.x+Q.width&&ae.y>=Q.y&&ae.y<=Q.y+Q.height&&r(Z);}};N.addEventListener("contextmenu",_),z._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:O,onTap:O,onMouseDown:O,onTouchStart:O,onMouseMove:U,onTouchMove:U,onMouseUp:H,onTouchEnd:H,...P?{}:{onDragEnd:a,onTransformEnd:n}}),C?.map((z,N)=>{let _=z.points.map((ae,Q)=>Q%2===0?ae*e.width:ae*e.height),Z=z.strokeWidth*e.width;return jsx(Line,{points:_,stroke:z.tool==="eraser"?"white":z.color,strokeWidth:Z,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:z.tool==="eraser"?"destination-out":"source-over",fill:z.isSketch?z.color:void 0,closed:z.isSketch,listening:false},N)}),b&&jsx(Line,{points:b.points.map((z,N)=>N%2===0?z*e.width:z*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"),!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:G-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:te-W+6,y:G-60,width:W*1.6,height:W*1.6,radius:W,fill:"white",cornerRadius:8,listening:true,onClick:z=>{z.cancelBubble=true,e.isCapturing?V():s();},onTap:z=>{z.cancelBubble=true,e.isCapturing?V():s();}}),jsx(Html,{groupProps:{x:te-12,y:G-40,width:W*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:z=>{z.stopPropagation(),e.isCapturing?V():s();}})})]}),jsx(Text,{x:0,y:G,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:G+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:te-24,y:G+104,width:W*1.6,height:W*1.6,radius:W,fill:"#096B76",cornerRadius:W,listening:true,onClick:z=>{z.cancelBubble=true,e.isCapturing?V():s();},onTap:z=>{z.cancelBubble=true,e.isCapturing?V():s();}}),jsx(Html,{groupProps:{x:te-8,y:G+120,width:W*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:z=>{z.stopPropagation(),e.isCapturing?V():s();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:te-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:z=>{z.stopPropagation(),V();},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})})})})]})]})},Nu=sg;var rl=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onStartCamera:s,onCapture:u,cameraStreams:i,onContextMenu:c,onLongPress:m})=>{let{createHandlers:l}=qe({onLongPress:m});return jsx(Fragment,{children:e.map(d=>jsx(Nu,{photoFrame:d,isSelected:t===d.id,onClick:()=>r(d.id),onDragEnd:f=>a(f,d.id),onContextMenu:f=>c(f,d.id,"photoFrame"),onStartCamera:()=>s(d.id),onCapture:f=>u(d.id,f),cameraStream:i.get(d.id),touchHandlers:l(d.id,"photoFrame"),nodeRef:f=>{f?o.current.set(d.id,f):o.current.delete(d.id);}},d.id))})});rl.displayName="PhotoFrameLayer";var zu=({x:e,y:o,onAction:t,onClose:a,type:n,isDrawingMode:r,menuRef:s})=>{useEffect(()=>{let m=d=>{s?.current&&!s.current.contains(d.target)&&a();},l=d=>{d.key==="Escape"&&a();};return document.addEventListener("mousedown",m),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("keydown",l);}},[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:"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(l=>!(l.showForTypes&&!l.showForTypes.includes(n)||l.hideForTypes&&l.hideForTypes.includes(n))),[n,r]),i=(m,l)=>{m==="order"||m==="lock"?t(m,l):(t(m),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((m,l)=>jsxs("button",{onClick:d=>i(m.action,d),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] ${m.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[m.icon,jsx("span",{className:`font-medium ${m.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:m.label})]}),m.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},l))})});return createPortal(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 Ku=createContext(null),nl=()=>useContext(Ku);function kg({children:e,className:o="",style:t}){let a=useRef(null),[n,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Ku.Provider,{value:n,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function Ve(){let e=nl();return typeof document>"u"?null:e||document.body}var Gu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:n,onClose:r})=>{let[s,u]=useState(a),i=useRef(null),c=Ve();useEffect(()=>{i.current?.focus();},[]);let m=()=>{n(s),r();},l=f=>{f.key==="Enter"?m():f.key==="Escape"&&r();};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:i,type:"text",value:s,onChange:f=>u(f.target.value),onKeyDown:l,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:r,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:m,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),c):null};var os=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,n]=useState(e),r=useRef(null),s=Ve();useEffect(()=>{let l=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[t]);let u=l=>{l.preventDefault(),o(a);},i=(l,d,f)=>{f/=100;let h=d*Math.min(f,1-f)/100,p=y=>{let w=(y+l/30)%12,g=f-h*Math.max(Math.min(w-3,9-w,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 m=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:l=>l.stopPropagation(),onMouseUp:l=>l.stopPropagation(),onMouseMove:l=>l.stopPropagation(),onTouchStart:l=>l.stopPropagation(),onTouchMove:l=>l.stopPropagation(),onTouchEnd:l=>l.stopPropagation(),children:jsxs("div",{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:l=>l.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:u,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:l=>n(l.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:l=>n(l.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:l=>{let d=parseInt(l.target.value),f=i(d,100,50);n(f);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(l=>jsx("button",{type:"button",onClick:()=>n(l),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===l.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:l},title:l},l))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(m,s)};var Gg=({imageSrc:e,onCrop:o})=>{let[t]=$u(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 d=s.width*.5,f=s.height*.5,h=(s.width-d)/2,p=(s.height-f)/2;return {x:h,y:p,width:d,height:f}},[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 m=()=>{let d=n.current;if(!d)return;let f=d.scaleX(),h=d.scaleY();d.scaleX(1),d.scaleY(1),c({x:d.x(),y:d.y(),width:Math.max(20,d.width()*f),height:Math.max(20,d.height()*h)});},l=()=>{let d=n.current;d&&c({x:d.x(),y:d.y(),width:d.width(),height:d.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:l,onTransformEnd:m,dragBoundFunc:d=>{let f=Math.max(0,Math.min(d.x,s.width-i.width)),h=Math.max(0,Math.min(d.y,s.height-i.height));return {x:f,y:h}}}),jsx(Transformer,{ref:r,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(d,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>s.width||f.y+f.height>s.height?d:f})]})})},Xu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[n,r]=useState({x:0,y:0,width:0,height:0}),[s]=$u(e),u=Ve();useEffect(()=>{let l=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[t]);let i=(l,d,f,h)=>{r({x:l,y:d,width:f,height:h});},c=()=>{if(!s)return;let f=Math.min(600/s.width,400/s.height),h=n.x/f,p=n.y/f,y=n.width/f,w=n.height/f,g=document.createElement("canvas");g.width=y,g.height=w;let x=g.getContext("2d");if(!x)return;x.drawImage(s,h,p,y,w,0,0,y,w);let I=g.toDataURL("image/png");o(I);};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:l=>l.stopPropagation(),onMouseUp:l=>l.stopPropagation(),onMouseMove:l=>l.stopPropagation(),onTouchStart:l=>l.stopPropagation(),onTouchMove:l=>l.stopPropagation(),onTouchEnd:l=>l.stopPropagation(),children:jsxs("div",{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:l=>l.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(Gg,{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 Ya=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let n=Ve(),[r,s]=useState(false),[u,i]=useState(null),[c,m]=useState(0),[l,d]=useState(true),f=useRef(null),h=useRef([]),p=useRef(null),y=useRef(null),w=useRef(null),g=useRef(null),x=useRef(null),I=useRef(null);useEffect(()=>()=>{w.current&&cancelAnimationFrame(w.current),p.current&&clearInterval(p.current),y.current&&y.current.getTracks().forEach(k=>k.stop());},[]);let L=async()=>{try{let k,T=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let H=o.current.getLayers();console.log("Konva layers:",H.length),H.forEach((_,Z)=>{let ae=_.getChildren();console.log(`Layer ${Z} children count:`,ae.length);});let K=document.createElement("canvas");K.width=o.current.width(),K.height=o.current.height();let E=K.getContext("2d",{willReadFrequently:!1});if(!E){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",K.width,"x",K.height),x.current=K;let W=()=>{if(E.clearRect(0,0,K.width,K.height),H.forEach(_=>{let Z=_.getCanvas()._canvas;Z&&E.drawImage(Z,0,0);}),a?.current){let _=a.current;E.drawImage(_,0,0);}};I.current=W,o.current.draw(),W(),await new Promise(_=>setTimeout(_,100)),console.log("Creating captureStream..."),k=K.captureStream(30),console.log("Canvas stream created, tracks:",k.getTracks().length);let G=k.getVideoTracks()[0];G&&console.log("Video track:",G.label,"state:",G.readyState);let z=0,N=()=>{W(),o?.current&&(o.current.getLayers().forEach(Z=>{Z.batchDraw();}),z++,z%60===0&&console.log("Drawing frame:",z)),w.current=requestAnimationFrame(N);};N();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(l)try{T=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(H){console.warn("Microphone access denied:",H);}let F=[...k.getVideoTracks()];T&&F.push(...T.getAudioTracks());let V=new MediaStream(F);y.current=V;let O="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?O="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?O="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?O="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(O="video/webm;codecs=vp8"),console.log("Using mimeType:",O);let U=new MediaRecorder(V,{mimeType:O,videoBitsPerSecond:25e5});f.current=U,h.current=[],U.ondataavailable=H=>{console.log("Data available, size:",H.data.size),H.data.size>0&&h.current.push(H.data);},U.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let H=new Blob(h.current,{type:O});console.log("Final blob size:",H.size),o?.current&&I.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(E=>{E.batchDraw();}),I.current(),g.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",g.current.length)),V.getTracks().forEach(K=>K.stop()),p.current&&clearInterval(p.current),w.current&&(cancelAnimationFrame(w.current),w.current=null),i(H);},U.onerror=H=>{console.error("MediaRecorder error:",H);},console.log("Starting recording..."),U.start(1e3),s(!0),m(0),p.current=setInterval(()=>{m(H=>H+1);},1e3);}catch(k){console.error("Error starting screen recording:",k),alert("Failed to start recording. Please ensure you granted permission.");}},P=()=>{f.current&&r&&(console.log("Stopping recording, state:",f.current.state),f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),s(false));},C=()=>{if(u){let k=URL.createObjectURL(u),T=document.createElement("a");T.href=k,T.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(k);}},b=k=>{let T=Math.floor(k/60),F=k%60;return `${T.toString().padStart(2,"0")}:${F.toString().padStart(2,"0")}`};if(!n)return null;if(r){let k=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:P,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(k,n)}let v=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!u&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>d(!l),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${l?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:l?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:L,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),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),m(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})});return createPortal(v,n)};var Qu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:n})=>{let r=Ve(),[s,u]=useState(false),[i,c]=useState(null),[m,l]=useState(false),[d,f]=useState(0),h=useRef(null),p=useRef([]),y=useRef(null),w=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(k=>k.blob()).then(k=>c(k)).catch(k=>console.error("Error loading audio:",k));},[o,i]);let g=async()=>{try{let k=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),T=new MediaRecorder(k);h.current=T,p.current=[],T.ondataavailable=F=>{F.data.size>0&&p.current.push(F.data);},T.onstop=()=>{let F=new Blob(p.current,{type:"audio/webm"});c(F),k.getTracks().forEach(V=>V.stop()),y.current&&clearInterval(y.current);},T.start(),u(!0),f(0),y.current=setInterval(()=>{f(F=>F+1);},1e3);}catch(k){console.error("Error starting audio recording:",k),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{h.current&&s&&(h.current.stop(),u(false));},I=()=>{if(i){let k=URL.createObjectURL(i),T=new Audio(k);w.current=T,T.onended=()=>{l(false),URL.revokeObjectURL(k);},T.play(),l(true);}},L=()=>{w.current&&(w.current.pause(),w.current.currentTime=0,l(false));},P=async()=>{if(i){let k=new FileReader;k.onloadend=()=>{let T=k.result;t(T),n();},k.readAsDataURL(i);}},C=()=>{c(null),a();},b=k=>{let T=Math.floor(k/60),F=k%60;return `${T.toString().padStart(2,"0")}:${F.toString().padStart(2,"0")}`};if(!r)return null;if(s){let k=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(d)})]}),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(k,r)}let v=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:m?L:I,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"}),m?"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:P,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(v,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,m]=useState(false),l=useRef(null),d=p=>{if(p.stopPropagation(),c&&l.current)l.current.pause(),l.current.currentTime=0,m(false);else {let y=new Audio(e);l.current=y,y.onended=()=>{m(false);},y.onerror=()=>{console.error("Error playing audio"),m(false);},y.play(),m(true);}},f=(o+a)*n+r-15,h=t*n+s+u-15;return jsx("button",{onClick:d,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${c?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${f}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var ac=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=Se(),n=J(ye),r=Ve(),s=useMemo(()=>{if(!n)return [];let w=[];return n.images?.forEach(g=>{w.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),n.videos?.forEach(g=>{w.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),n.shapes?.forEach(g=>{w.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),n.texts?.forEach(g=>{w.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),n.flashcards?.forEach(g=>{w.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),n.photoFrames?.forEach(g=>{w.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),n.multipleChoices?.forEach(g=>{w.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),n.trueFalses?.forEach(g=>{w.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),n.shortAnswers?.forEach(g=>{w.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),n.LongAnswer?.forEach(g=>{w.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),n.fillInTheBlanks?.forEach(g=>{w.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),n.lines?.forEach(g=>{g.id&&w.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),w.sort((g,x)=>x.timestamp-g.timestamp)},[n]),[u,i]=useState(s),[c,m]=useState(false);useEffect(()=>{c||i(s);},[s]);let l=w=>{let g="h-5 w-5";switch(w){case "image":return jsx(Image$3,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes$1,{className:g});case "text":return jsx(TextT,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners,{className:g});case "line":return jsx(Pen,{className:g});default:return jsx(Question,{className:g})}},h=w=>{m(true),i(w);},p=()=>{m(false);let w=Date.now();u.forEach((g,x)=>{let I=w-x;a(pr({id:g.id,type:g.type,newTimestamp:I}));});};if(!r)return null;let y=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-50 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-50 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$2,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:u.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:u,onReorder:h,className:"space-y-1",children:u.map(w=>{let g=w.id===e;return jsxs(Reorder.Item,{value:w,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(w.id,w.type),className:`font-medium ${g?"text-[#096B76]":"text-[#00000099]"}`,children:w.name})}),jsx("div",{className:`${g?"text-[#096B76]":"text-[#00000099]"}`,children:l(w.type)})]},w.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[u.length," Layers"]})]})]})]});return createPortal(y,r)};var ds=(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 m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},oc=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,touchHandlers:s})=>{let u=useSelector(F=>F.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,m]=useState(new Set),[l,d]=useState(false),[f,h]=useState(null),p=useRef(null),y=useDispatch();useEffect(()=>{let F=p.current;if(F)return a.current.set(e.id,F),()=>{a.current.delete(e.id);}},[e.id]);let w=new Set(e.data.responseOptions.correctIndex),g=w.size>1,x=F=>{if(l)return;let V;g?(V=new Set(c),V.has(F)?V.delete(F):V.add(F)):V=new Set([F]),m(V);let O=Array.from(V),U=O.length===e.data.responseOptions.correctIndex.length&&O.every(H=>e.data.responseOptions.correctIndex.includes(H));y(Zt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:O,isCorrect:U}}}));},I=()=>{c.size>0&&d(true);},L=()=>{d(false),m(new Set);},P=c.size===w.size&&Array.from(c).every(F=>w.has(F)),C=Array.from(c).filter(F=>w.has(F)),b=g&&C.length>0&&!P,v=()=>P?"\u2713 Correct! Great job! \u{1F389}":b?`\u26A0 Partially correct (${C.length}/${w.size})`:"\u2717 Try again!",k=()=>P?{bg:"#dcfce7",text:"#166534"}:b?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},T=useMemo(()=>{let W=e.data.feedbackMode==="practice"?48:0,te=12,G=e.width-48,z=G-80,N=Math.max(60,ds(e.data.question,20,G,"bold")+20),_=`Select ${w.size} answers (${c.size}/${w.size} selected)`,Z=g&&!l&&e.data.feedbackMode==="practice"?ds(_,14,G)+10:0,ae=l&&e.data.feedbackMode==="practice"?Math.max(60,ds(v(),16,G-40)+30):0,Q=e.data.responseOptions.options.map(he=>{let ce=ds(he,16,z);return Math.max(55,ce+20)}),pe=N+Z+ae,ue=Q.reduce((he,ce)=>he+ce+8,-8),le=pe+ue+te+W+24;return {padding:24,questionHeight:N,instructionHeight:Z,feedbackHeight:ae,optionsStartY:pe,optionHeights:Q,totalHeight:le,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:W,buttonTopMargin:te,availableWidth:G,optionTextWidth:z}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,l,c.size,w.size,g,v]);return jsxs(Group,{ref:p,name:"mcq-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:T.totalHeight,onTransformEnd:F=>o(e.id,F),...s,...i?{}:{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:T.totalHeight,width:e.width,onContextMenu:F=>{F.cancelBubble=true,r(F.evt,e.id,"mcq");}}),jsx(Text,{x:T.padding+8,y:T.padding,text:e.data.question,fontSize:T.questionFontSize,fontStyle:"bold",fill:"#111827",width:T.availableWidth,height:T.questionHeight-T.padding,wrap:"word",ellipsis:true,listening:false}),T.instructionHeight>0&&jsx(Text,{x:T.padding,y:T.questionHeight,text:`Select ${w.size} answers (${c.size}/${w.size} selected)`,fontSize:T.instructionFontSize,fill:"#6b7280",width:T.availableWidth,wrap:"word",listening:false}),l&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:T.padding+24,y:T.questionHeight+T.instructionHeight+10,width:T.availableWidth-40,height:T.feedbackHeight-20,fill:k().bg,cornerRadius:8}),jsx(Text,{x:T.padding+24,y:T.questionHeight+T.instructionHeight+10,width:T.availableWidth-40,height:T.feedbackHeight-20,text:v(),fontSize:T.feedbackFontSize,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((F,V)=>{let O=w.has(V),U=c.has(V),H=T.optionsStartY;for(let G=0;G<V;G++)H+=T.optionHeights[G]+T.optionGap;let K=T.optionHeights[V],E="#e5e7eb",W="#ffffff",te="#111827";return l&&O?(E="#22c55e",W="#dcfce7",te="#1B9D2C"):l&&U&&!O?(E="#ef4444",W="#fee2e2",te="#ef4444"):U&&(E="#096B76",W="#ECFFF8",te="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:T.padding+12,y:H+(K-20)/2,width:20,height:20,fill:U?"#096B76":"white",stroke:U?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:g?4:10,onClick:G=>{G.cancelBubble=true,x(V);},onTap:G=>{G.cancelBubble=true,x(V);}}),U&&jsx(Text,{x:T.padding+12,y:H+(K-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:T.padding+44,y:H,width:T.availableWidth-60,height:K,fill:W,stroke:E,strokeWidth:2,cornerRadius:8,onClick:G=>{G.cancelBubble=true,x(V);},onTap:G=>{G.cancelBubble=true,x(V);}}),jsx(Text,{x:T.padding+60,y:H+10,width:T.optionTextWidth,height:K-20,text:F,fontSize:T.optionFontSize,fill:te,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},V)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:T.optionsStartY+T.optionHeights.reduce((F,V)=>F+V+T.optionGap,-T.optionGap)+T.buttonTopMargin,children:[jsxs(Group,{onMouseDown:F=>{F.cancelBubble=true,h("check");},onMouseUp:F=>{F.cancelBubble=true,h(null),I();},onMouseLeave:F=>{F.cancelBubble=true,h(null);},onTouchStart:F=>{F.cancelBubble=true,h("check");},onTouchEnd:F=>{F.cancelBubble=true,h(null),I();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:T.padding+14,width:(T.availableWidth-24)/(l?2:1),height:T.buttonHeight,fill:c.size===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:T.padding+14,width:(T.availableWidth-24)/(l?2:1),height:T.buttonHeight,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-T.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),L();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),L();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:T.padding,width:(T.availableWidth-8)/2,height:T.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:T.padding,width:(T.availableWidth-8)/2,height:T.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});oc.displayName="MultipleChoice";var rc=oc;var Nx=(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 m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),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(E=>E.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,m]=useState(false),[l,d]=useState(new Set),[f,h]=useState(false),[p,y]=useState(false),[w,g]=useState(0),x=new Set(e.data.responseOptions.correctIndex),I=Array.from(l).filter(E=>x.has(E)),L=l.size===x.size&&Array.from(l).every(E=>x.has(E)),P=I.length>0&&!L,C=()=>L?"\u2713 Correct! Great job!":P?`\u26A0 Partially correct (${I.length}/${x.size})`:"\u2717 Try again!",b=useCallback(E=>{let W=E.target;s(wi({id:e.id,dragDropPos:{x:W.x(),y:W.y()}})),r?.();},[s,e.id,r]),v=useMemo(()=>{let W=Math.max(window.innerWidth*.4,500),te=20,G=18,z=28,N=40,_=50,Z=20,ae=60,Q=Math.max(W-40,400),pe=Math.max(60,Nx(e.data.question,te,Q,"bold")),ue=Math.max(W-Z*2,400),le=Math.max(150,window.innerHeight*.3),he=e.data.feedbackMode==="practice",ce=pe+20+le+(f?ae+18:0)+(he?N+(f?_:0)+20:0),_e=ce+100;return {screenWidth:W,screenHeight:_e,dropZoneWidth:ue,dropZoneHeight:le,questionFontSize:te,questionHeight:pe,feedbackFontSize:G,feedbackHeight:ae,dropHereFontSize:z,buttonHeight:N,buttonGap:_,padding:Z,contentWidth:Q,totalContentHeight:ce,isPracticeMode:he}},[e.data.question,e.data.feedbackMode,f,l.size]),k=useRef(null);useEffect(()=>{let E=k.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id]);let T=E=>{s(wi({id:e.id,dragDropPos:{x:E.target.x(),y:E.target.y()}})),r?.();},F=E=>{let W=E.target,te=W.x(),G=W.y(),z=window.innerWidth*.2,N=50,_=v.padding,Z=v.padding+v.dropZoneWidth,ae=v.questionHeight+20,Q=v.questionHeight+20+v.dropZoneHeight,pe=te+z>_&&te<Z&&G+N>ae&&G<Q;m(pe);},V=(E,W)=>{let te=W.target,G=te.x(),z=te.y(),N=window.innerWidth*.2,_=50,Z=v.padding,ae=v.padding+v.dropZoneWidth,Q=v.questionHeight+20,pe=v.questionHeight+20+v.dropZoneHeight,ue=G+N>Z&&G<ae&&z+_>Q&&z<pe,le;ue?le=new Set(l).add(E):(le=new Set(l),le.delete(E)),d(le),m(false);let he=Array.from(le),ce=he.length===x.size&&he.every(_e=>x.has(_e));s(Zt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:he,isCorrect:ce}}}));},O=()=>{h(true);},U=()=>{h(false),d(new Set),g(E=>E+1);},H=()=>L?{bg:"#dcfce7",text:"#166534"}:P?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},K=()=>f?L?"#4CAF50":P?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:k,x:e.dragDropPos?.x,y:e.dragDropPos?.y,name:"mcq-element",width:v.screenWidth,height:v.screenHeight,draggable:!i,listening:!i,onDragMove:b,...n,...i?{}:{onClick:E=>t&&t(e.id),onTap:E=>t&&t(e.id),onContextMenu:E=>{E.evt.preventDefault(),o(E.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:v.totalContentHeight+20,width:v.screenWidth,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:v.padding,y:v.padding,width:v.contentWidth,height:v.questionHeight-v.padding,text:e.data.question,fontSize:v.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:v.padding,y:v.questionHeight+20,width:v.dropZoneWidth,height:v.dropZoneHeight,fill:"#EBF6F7",stroke:K(),strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:v.padding+3,y:v.questionHeight+20+v.dropZoneHeight+18,width:v.dropZoneWidth-5,height:v.feedbackHeight,fill:H().bg,cornerRadius:8}),jsx(Text,{x:v.padding,y:v.questionHeight+20+v.dropZoneHeight+20,width:v.dropZoneWidth,height:v.feedbackHeight,text:C(),fontSize:v.feedbackFontSize,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),l.size===0&&!f&&jsx(Text,{x:v.padding,y:v.questionHeight+20,width:v.dropZoneWidth,height:v.dropZoneHeight,text:x.size>1?`Drop ${x.size} Correct Answers Here`:"Drop Here",fontSize:v.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),v.isPracticeMode?jsxs(Group,{x:v.padding,y:v.questionHeight+20+v.dropZoneHeight+(f?v.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:()=>{y(true),O();},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{y(true),O();},onTouchEnd:()=>y(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:v.buttonHeight,width:v.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:v.dropZoneWidth,height:v.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:v.buttonGap,onMouseDown:U,onTouchStart:U,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:v.buttonHeight,width:v.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:v.dropZoneWidth,height:v.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((E,W)=>{let te=W%2,G=Math.floor(W/2),z=Math.max(window.innerWidth*.2,250),N=50,_=10,Z=l.has(W),ae=x.has(W),Q=f&&Z,pe="transparent";Q?pe=ae?"#4CAF50":"#ef4444":Z&&(pe="#4CAF50");let ue=f?0:1;return jsxs(Group,{x:te*(z+_),y:v.totalContentHeight+30+G*(N+_),draggable:!f,onDragStart:le=>{le.cancelBubble=true;},onDragMove:le=>{le.cancelBubble=true,F(le);},onDragEnd:le=>{le.cancelBubble=true,V(W,le);},opacity:ue,children:[jsx(Rect,{width:z-20,height:N,fill:"white",stroke:pe,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:z-20,height:N,text:E,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${W}-${w}`)})]})};dl.displayName="MultipleChoiceDragAndDrop";var nc=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(rc,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:m=>n(m,c.id),onContextMenu:r,touchHandlers:i(c.id,"mcq")},c.id):jsx(dl,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id))})};var sc=(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 m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},ic=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s})=>{let u=useSelector(v=>v.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,m]=useState(null),[l,d]=useState(false),[f,h]=useState(null),p=useDispatch(),y=useRef(null);useEffect(()=>{let v=y.current;if(v)return a.current.set(e.id,v),()=>{a.current.delete(e.id);}},[e.id]);let w=()=>{c!==null&&d(true);},g=()=>{d(false),m(null);},x=e.data.responseOptions.correctAnswer,I=c===x,L=v=>{if(l)return;m(v);let k=v===e.data.responseOptions.correctAnswer;p(Ft({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:v,isCorrect:k}}}));},P=()=>I?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>I?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},b=useMemo(()=>{let U=e.data.feedbackMode==="practice"?48:0,H=12,K=e.width-48,E=Math.max(60,sc(e.data.question,20,K,"bold")+20),W=l&&e.data.feedbackMode==="practice"?Math.max(60,sc(P(),16,K-40)+30):0,te=E+W,G=164,z=te+G+H+U+24;return {padding:24,questionHeight:E,feedbackHeight:W,optionsStartY:te,optionsHeight:G,totalHeight:z,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:U,buttonTopMargin:H,availableWidth:K}},[e.width,e.data.question,e.data.feedbackMode,l,P]);return jsxs(Group,{ref:y,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:b.totalHeight,...s,...i?{}:{onDragEnd:v=>r(v,e.id),onClick:v=>t&&t(e.id),onTap:v=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:b.totalHeight,width:e.width,onTransformEnd:v=>o(e.id,v),onContextMenu:v=>{v.cancelBubble=true,n(v.evt,e.id,"trueFalse");}}),jsx(Text,{x:b.padding+8,y:b.padding,text:e.data.question,fontSize:b.questionFontSize,fontStyle:"bold",fill:"#111827",width:b.availableWidth,height:b.questionHeight-b.padding,wrap:"word",ellipsis:true,listening:false}),l&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:b.padding+24,y:b.questionHeight+10,width:b.availableWidth-40,height:b.feedbackHeight-20,fill:C().bg,cornerRadius:8}),jsx(Text,{x:b.padding+24,y:b.questionHeight+10,width:b.availableWidth-40,height:b.feedbackHeight-20,text:P(),fontSize:b.feedbackFontSize,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((v,k)=>{let T=x===v.value,F=c===v.value,V=(e.width-b.padding*3)/2,O=b.padding+k*(V+b.padding),U=b.optionsStartY,H=v.value===true,K=H?"#10b981":"#ef4444",E="#ffffff",W="#ffffff",te="#e5e7eb";return l&&(T?(W=H?"#f0fdf4":"#fef2f2",te=H?"#86efac":"#fecaca"):F&&!T&&(W="#fee2e2",te="#ef4444")),F&&!l&&(te="#096B76",W="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:O,y:U,width:V,height:b.optionHeight+50,fill:W,stroke:te,strokeWidth:2,cornerRadius:12,onClick:G=>{G.cancelBubble=true,L(v.value);},onTap:G=>{G.cancelBubble=true,L(v.value);}}),jsx(Circle,{x:O+V/2,y:U+40,radius:28,fill:K,listening:false}),H?jsx(Text,{x:O+V/2-14,y:U+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:E,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:O+V/2-14,y:U+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:E,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:O,y:U+85,width:V,height:30,text:v.label,fontSize:b.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},v.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:b.optionsStartY+2*(b.optionHeight+b.optionGap)+b.buttonTopMargin,children:[jsxs(Group,{onMouseDown:v=>{v.cancelBubble=true,h("check");},onMouseUp:v=>{v.cancelBubble=true,h(null),w();},onMouseLeave:v=>{v.cancelBubble=true,h(null);},onTouchStart:v=>{v.cancelBubble=true,h("check");},onTouchEnd:v=>{v.cancelBubble=true,h(null),w();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:b.padding+14,width:(b.availableWidth-24)/(l?2:1),height:b.buttonHeight,fill:c===null||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true}),jsx(Text,{x:b.padding+14,width:(b.availableWidth-24)/(l?2:1),height:b.buttonHeight,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-b.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),g();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),g();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:b.padding,width:(b.availableWidth-8)/2,height:b.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true}),jsx(Text,{x:b.padding,width:(b.availableWidth-8)/2,height:b.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});ic.displayName="TrueFalse";var lc=ic;var Qx="#FFFFFF",fl=({trueFalse:e,onContextMenu:o,handleSelect:t,trueFalseRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(N=>N.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,m]=useState(false),[l,d]=useState(null),[f,h]=useState(false),[p,y]=useState(false),[w,g]=useState(0),x=340,I=100,L=Math.max(window.innerWidth*.4,400),P=window.innerHeight*.5,C=useRef(null);useEffect(()=>{let N=C.current;if(N)return a.current.set(e.id,N),()=>{a.current.delete(e.id);}},[e.id]);let v=Math.max(60,((N,_,Z,ae)=>{let pe=document.createElement("canvas").getContext("2d");if(!pe)return _;pe.font=`${ae} ${_}px Arial, sans-serif`;let ue=N.split(" "),le=[],he="";return ue.forEach(ce=>{let _e=he?`${he} ${ce}`:ce;pe.measureText(_e).width>Z&&he!==""?(le.push(he),he=ce):he=_e;}),he&&le.push(he),le.length*_*1.2})(e.data.question,20,L-40,"bold")+20),k=v+10,T=L-40,F=P-v-250,V=useCallback(N=>{let _=N.target;s(Ft({id:e.id,dragDropPos:{x:_.x(),y:_.y()}})),r?.();},[s,e.id,r]),O=N=>{s(Ft({id:e.id,dragDropPos:{x:N.target.x(),y:N.target.y()}})),r?.();},U=N=>{let _=N.target,Z=_.x(),ae=_.y(),Q=window.innerWidth*.2-40,pe=50,ue=20,le=20+T,he=k,ce=k+F,_e=Z+Q>ue&&Z<le&&ae+pe>he&&ae<ce;m(_e);},H=(N,_)=>{let Z=_.target,ae=Z.x(),Q=Z.y(),pe=window.innerWidth*.2-40,ue=50,le=20,he=20+T,ce=k,_e=k+F;if(!(ae+pe>le&&ae<he&&Q+ue>ce&&Q<_e)){m(false);return}d(N),m(false);let ga=N===e.data.responseOptions.correctAnswer;s(Ft({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:N,isCorrect:ga}}}));},K=()=>{h(true);},E=()=>{h(false),d(null),g(N=>N+1);},W=e.data.responseOptions.correctAnswer,te=l===W,G=()=>te?"\u2713 Correct! Great job!":"\u2717 Try again!",z=()=>te?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:C,name:"trueFalse-element",width:L,height:P,x:e.dragDropPos?.x,y:e.dragDropPos?.y,draggable:!i,listening:!i,onDragMove:V,...n,...i?{}:{onClick:N=>t&&t(e.id),onTap:N=>t&&t(e.id),onContextMenu:N=>{N.evt.preventDefault(),o(N.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:I,rotation:e.rotation,onDragEnd:O,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:f?P:e.data.feedbackMode==="practice"?P-50:P-100,width:L,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:k,width:T,height:F,fill:"transparent",stroke:c?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:k,width:T,height:60,fill:z().bg,cornerRadius:8}),jsx(Text,{x:20,y:k,width:T,height:60,text:G(),fontSize:18,fontStyle:"bold",fill:z().text,align:"center",verticalAlign:"middle"})]}),l===null&&!f&&jsx(Text,{x:20,y:k,width:T,height:F,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:P-100,children:[jsxs(Group,{onMouseDown:()=>{l!==null&&(y(true),K());},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{l!==null&&(y(true),K());},onTouchEnd:()=>y(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:l===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:T}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:T,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:E,onTouchStart:E,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:T}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:T,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((N,_)=>{let Z=Math.max(window.innerWidth*.2,200),ae=50,Q=10,pe=l===N.value,ue=W===N.value,le=f&&pe,he="transparent";return le?he=ue?"#4CAF50":"#ef4444":pe&&(he="#4CAF50"),jsxs(Group,{x:16+_*(Z+Q),y:I+P-300,draggable:!f,onDragStart:ce=>{ce.cancelBubble=true;},onDragMove:ce=>{ce.cancelBubble=true,U(ce);},onDragEnd:ce=>{ce.cancelBubble=true,H(N.value,ce);},opacity:f&&!pe?.5:1,children:[jsx(Rect,{width:Z-40,height:ae,fill:"#075560",stroke:he,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z-40,height:ae,text:N.label,fontSize:18,fontStyle:"bold",fill:Qx,align:"center",verticalAlign:"middle",listening:false})]},`${N.value}-${w}`)})]})})};fl.displayName="TrueFalseDragAndDrop";var dc=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(lc,{trueFalse:c,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i(c.id,"trueFalse")},c.id):jsx(fl,{trueFalse:c,handleSelect:t,trueFalseRefs:a,onContextMenu:r,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id))})};var Ta=new WeakMap,No=new WeakMap,Dr={current:[]},pl=false,Er=0,Pr=new Set,us=new Map;function uc(e){let o=Array.from(e).sort((t,a)=>t instanceof Gt&&t.options.deps.includes(a)?1:a instanceof Gt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(Dr.current.includes(t))continue;Dr.current.push(t),t.recompute();let a=No.get(t);if(a)for(let n of a){let r=Ta.get(n);r&&uc(r);}}}function ab(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function ob(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function cs(e){if(Er>0&&!us.has(e)&&us.set(e,e.prevState),Pr.add(e),!(Er>0)&&!pl)try{for(pl=!0;Pr.size>0;){let o=Array.from(Pr);Pr.clear();for(let t of o){let a=us.get(t)??t.prevState;t.prevState=a,ab(t);}for(let t of o){let a=Ta.get(t);a&&(Dr.current.push(t),uc(a));}for(let t of o){let a=Ta.get(t);if(a)for(let n of a)ob(n);}}}finally{pl=false,Dr.current=[],us.clear();}}function Ct(e){Er++;try{e();}finally{if(Er--,Er===0){let o=Pr.values().next().value;o&&cs(o);}}}function cc(e){return typeof e=="function"}var Qt=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):cc(o)?this.state=o(this.prevState):this.state=o,(n=(a=this.options)==null?void 0:a.onUpdate)==null||n.call(a),cs(this);}};var Gt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),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 Qt){let a=Ta.get(t);a||(a=new Set,Ta.set(t,a)),a.add(this);let n=No.get(this);n||(n=new Set,No.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 Qt){let a=Ta.get(t);a&&a.delete(this);let n=No.get(this);n&&n.delete(t);}}};function rb(e){return typeof e=="function"}function hl(e,...o){return rb(e)?e(...o):e}function fc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Ma,pt,st,Rr,Aa,eo,na,Ho,Fr,fs,Br,qo,to=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:n=1e3}){Be(this,Ma,true);Be(this,pt);Be(this,st);Be(this,Rr);Be(this,Aa);Be(this,eo);Be(this,na);Be(this,Ho);Be(this,Fr,0);Be(this,fs,5);Be(this,Br,()=>{this.debugLog("Connected to event bus"),Pe(this,eo,true),this.debugLog("Emitting queued events",$(this,Aa)),$(this,Aa).forEach(o=>this.emitEventToBus(o)),Pe(this,Aa,[]),this.stopConnectLoop(),$(this,st).call(this).removeEventListener("tanstack-connect-success",$(this,Br));});Be(this,qo,()=>{if($(this,st).call(this).addEventListener("tanstack-connect-success",$(this,Br)),$(this,Fr)<$(this,fs)){Nd(this,Fr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}$(this,st).call(this).removeEventListener("tanstack-connect",$(this,qo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Pe(this,pt,o),Pe(this,Ma,a),Pe(this,st,this.getGlobalTarget),Pe(this,Rr,t),this.debugLog(" Initializing event subscription for plugin",$(this,pt)),Pe(this,Aa,[]),Pe(this,eo,false),Pe(this,na,null),Pe(this,Ho,n);}startConnectLoop(){$(this,na)!==null||$(this,eo)||(this.debugLog(`Starting connect loop (every ${$(this,Ho)}ms)`),Pe(this,na,setInterval($(this,qo),$(this,Ho))));}stopConnectLoop(){$(this,na)!==null&&(clearInterval($(this,na)),Pe(this,na,null),this.debugLog("Stopped connect loop"));}debugLog(...o){$(this,Rr)&&console.log(`\u{1F334} [tanstack-devtools:${$(this,pt)}-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,pt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});$(this,st).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{$(this,st).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,Ma)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!$(this,eo)){this.debugLog("Bus not available, will be pushed as soon as connected"),$(this,Aa).push({type:`${$(this,pt)}:${o}`,payload:t,pluginId:$(this,pt)}),typeof CustomEvent<"u"&&($(this,qo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${$(this,pt)}:${o}`,payload:t,pluginId:$(this,pt)})}on(o,t){let a=`${$(this,pt)}:${o}`;if(!$(this,Ma))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,st).call(this).addEventListener(a,n),this.debugLog("Registered event to bus",a),()=>{$(this,st).call(this).removeEventListener(a,n);}}onAll(o){if(!$(this,Ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;o(n);};return $(this,st).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,st).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!$(this,Ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;$(this,pt)&&n.pluginId!==$(this,pt)||o(n);};return $(this,st).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,st).call(this).removeEventListener("tanstack-devtools-global",t)}};Ma=new WeakMap,pt=new WeakMap,st=new WeakMap,Rr=new WeakMap,Aa=new WeakMap,eo=new WeakMap,na=new WeakMap,Ho=new WeakMap,Fr=new WeakMap,fs=new WeakMap,Br=new WeakMap,qo=new WeakMap;var gl=class extends to{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},mc=(e,o)=>{xl.emit(e,o);},xl=new gl;function pc(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var nb={enabled:true,leading:true,trailing:true,wait:0},Pa,kt,ao,oo,ro,Vo,ms=class{constructor(o,t){Be(this,Pa);Be(this,kt);Be(this,ao);Be(this,oo);Be(this,ro);Be(this,Vo);this.fn=o,this.store=new Qt(pc()),this.setOptions=a=>{this.options={...this.options,...a},$(this,ao).call(this)||this.cancel();},Pe(this,kt,a=>{this.store.setState(n=>{let r={...n,...a},{isPending:s}=r;return {...r,status:$(this,ao).call(this)?s?"pending":"idle":"disabled"}}),mc("Throttler",this);}),Pe(this,ao,()=>!!hl(this.options.enabled,this)),Pe(this,oo,()=>hl(this.options.wait,this)),this.maybeExecute=(...a)=>{$(this,kt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let n=Date.now(),r=n-this.store.state.lastExecutionTime,s=$(this,oo).call(this);if(this.options.leading&&r>=s)$(this,ro).call(this,...a);else if($(this,kt).call(this,{lastArgs:a}),!$(this,Pa)&&this.options.trailing){let u=this.store.state.lastExecutionTime?n-this.store.state.lastExecutionTime:0,i=s-u;$(this,kt).call(this,{isPending:true}),Pe(this,Pa,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&$(this,ro).call(this,...c);},i));}},Pe(this,ro,(...a)=>{if(!$(this,ao).call(this))return;this.fn(...a);let n=Date.now(),r=n+$(this,oo).call(this);$(this,Vo).call(this),$(this,kt).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,kt).call(this,{nextExecutionTime:void 0});},$(this,oo).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&$(this,ro).call(this,...this.store.state.lastArgs);},Pe(this,Vo,()=>{$(this,Pa)&&(clearTimeout($(this,Pa)),Pe(this,Pa,void 0));}),this.cancel=()=>{$(this,Vo).call(this),$(this,kt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{$(this,kt).call(this,pc());},this.key=fc(t.key),this.options={...nb,...t},$(this,kt).call(this,this.options.initialState??{}),xl.on("d-Throttler",a=>{a.payload.key===this.key&&($(this,kt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Pa=new WeakMap,kt=new WeakMap,ao=new WeakMap,oo=new WeakMap,ro=new WeakMap,Vo=new WeakMap;function bl(e,o){return new ms(e,o).maybeExecute}function Ea(e,o){return typeof e=="function"?e(o):e}function Da(e,o){return xs(o).reduce((a,n)=>{if(a===null)return null;if(typeof a<"u")return a[n]},e)}function zo(e,o,t){let a=xs(o);function n(r){if(!a.length)return Ea(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 yl(e,o){let t=xs(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,m)=>m!==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 sb=/^(\d+)$/gm,ib=/\.(\d+)(?=\.)/gm,lb=/^(\d+)\./gm,db=/\.(\d+$)/gm,ub=/\.{2,}/gm,vl="__int__",ps=`${vl}$1`;function xs(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(sb,ps).replace(ib,`.${ps}.`).replace(lb,`${ps}.`).replace(db,`.${ps}`).replace(ub,".").split(".").map(o=>{if(o.startsWith(vl)){let t=o.substring(vl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function wl(e){return !(Array.isArray(e)&&e.length===0)}function Uo(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 Wo(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 m=c?.cause||e,l=s;switch(m){case "change":l=n??s;break;case "blur":l=a??s;break;case "dynamic":l=r??s;break;case "submit":l=0;break}return e==="submit"&&(l=0),{cause:m,validate:c.fn,debounceMs:l}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var Or=e=>!!e&&typeof e=="object"&&"fields"in e;function Ra(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)||!Ra(e[n],o[n]))return false;return true}var bs=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},vs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Je(e,o){return e==null?o:{...e,...o}}var no=256,gs=[],hs;for(;no--;)gs[no]=(no+256).toString(16).substring(1);function Sl(){let e=0,o,t="";if(!hs||no+16>256){for(hs=new Array(256),e=256;e--;)hs[e]=256*Math.random()|0;e=0,no=0;}for(;e<16;e++)o=hs[no+e],e===6?t+=gs[o&15|64]:e===8?t+=gs[o&63|128]:t+=gs[o],e&1&&e>1&&e<11&&(t+="-");return no++,t}var Fa=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 cb(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,m=Number(c);Array.isArray(r)&&!Number.isNaN(m)?s+=`[${m}]`: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 hc=(e,o)=>{let t=cb(e,o);return {form:t,fields:t}},Ba={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:hc(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:hc(a.issues,e)}},ys=e=>!!e&&"~standard"in e;var Ko={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function Nr(e){function o(l,d,f,h){let p=a(l,d,f,h);({insert:()=>u(p,l,d),remove:()=>i(p),swap:()=>h!==void 0&&m(p,l,d,h),move:()=>h!==void 0&&c(p,l,d,h)})[f]();}function t(l,d){return `${l}[${d}]`}function a(l,d,f,h){let p=[t(l,d)];if(f==="swap")p.push(t(l,h));else if(f==="move"){let[y,w]=[Math.min(d,h),Math.max(d,h)];for(let g=y;g<=w;g++)p.push(t(l,g));}else {let y=e.getFieldValue(l),w=Array.isArray(y)?y.length:0;for(let g=d+1;g<w;g++)p.push(t(l,g));}return Object.keys(e.fieldInfo).filter(y=>p.some(w=>y.startsWith(w)))}function n(l,d){return l.replace(/\[(\d+)\]/,(f,h)=>{let p=parseInt(h,10);return `[${d==="up"?p+1:Math.max(0,p-1)}]`})}function r(l,d){(d==="up"?l:[...l].reverse()).forEach(h=>{let p=n(h.toString(),d),y=e.getFieldMeta(p);y?e.setFieldMeta(h,y):e.setFieldMeta(h,s());});}let s=()=>Ko,u=(l,d,f)=>{r(l,"down"),l.forEach(h=>{h.toString().startsWith(t(d,f))&&e.setFieldMeta(h,s());});},i=l=>{r(l,"up");},c=(l,d,f,h)=>{let p=new Map(Object.keys(e.fieldInfo).filter(y=>y.startsWith(t(d,f))).map(y=>[y,e.getFieldMeta(y)]));r(l,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(y=>y.startsWith(t(d,h))).forEach(y=>{let w=y.replace(t(d,h),t(d,f)),g=p.get(w);g&&e.setFieldMeta(y,g);});},m=(l,d,f,h)=>{l.forEach(p=>{if(!p.toString().startsWith(t(d,f)))return;let y=p.toString().replace(t(d,f),t(d,h)),[w,g]=[e.getFieldMeta(p),e.getFieldMeta(y)];w&&e.setFieldMeta(y,w),g&&e.setFieldMeta(p,g);});};return {handleArrayFieldMetaShift:o}}var Ll=class extends to{constructor(){super({pluginId:"form-devtools"});}},Tt=new Ll;function Il(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var qr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),n=this.store.mount(),r=()=>{a(),n(),Tt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return Tt.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&&!Ra(a.defaultValues,n.defaultValues)&&!this.state.isTouched,u=!Ra(a.defaultState,n.defaultState)&&!this.state.isTouched;!s&&!u&&!r||(Ct(()=>{this.baseStore.setState(()=>Il(Object.assign({},this.state,u?a.defaultState:{},s?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),Tt.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(()=>Il({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let n=[];return Ct(()=>{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 d=n+1;d<=(u??0);d++)i.push(`${a}[${d}]`);let c=Object.keys(this.fieldInfo).filter(d=>i.some(f=>d.startsWith(f))),m=[];return Ct(()=>{c.forEach(d=>{m.push(Promise.resolve().then(()=>this.validateField(d,r)));});}),(await Promise.all(m)).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=Uo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Fa}),r=false,s={};return Ct(()=>{for(let c of n){if(!c.validate)continue;let m=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:l,fieldErrors:d}=ws(m),f=Hr(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let p=this.getFieldMeta(h);if(!p)continue;let{errorMap:y,errorSourceMap:w}=p,g=d?.[h],{newErrorValue:x,newSource:I}=bs({newFormValidatorError:g,isPreviousErrorFromFormValidator:w?.[f]==="form",previousErrorValue:y?.[f]});I==="form"&&(s[h]={...s[h],[f]:g}),y?.[f]!==x&&this.setFieldMeta(h,L=>({...L,errorMap:{...L.errorMap,[f]:x},errorSourceMap:{...L.errorSourceMap,[f]:I}}));}this.state.errorMap?.[f]!==l&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:l}})),(l||d)&&(r=!0);}let u=Hr("submit");this.state.errorMap?.[u]&&a!=="submit"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let i=Hr("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=Wo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Fa});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let r=[],s;for(let c of n){if(!c.validate)continue;let m=Hr(c.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let d=new AbortController;this.state.validationMetaMap[m]={lastAbortController:d},r.push(new Promise(async f=>{let h;try{h=await new Promise((g,x)=>{setTimeout(async()=>{if(d.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:d.signal},type:"validateAsync"}));}catch(I){x(I);}},c.debounceMs);});}catch(g){h=g;}let{formError:p,fieldErrors:y}=ws(h);y&&(s=s?{...s,...y}:y);let w=Hr(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:I,errorSourceMap:L}=x,P=s?.[g],{newErrorValue:C,newSource:b}=bs({newFormValidatorError:P,isPreviousErrorFromFormValidator:L?.[w]==="form",previousErrorValue:I?.[w]});I?.[w]!==C&&this.setFieldMeta(g,v=>({...v,errorMap:{...v.errorMap,[w]:C},errorSourceMap:{...v.errorSourceMap,[w]:b}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[w]:p}})),f(s?{fieldErrors:s,errorMapKey:w}:void 0);}));}let u=[],i={};if(r.length){u=await Promise.all(r);for(let c of u)if(c?.fieldErrors){let{errorMapKey:m}=c;for(let[l,d]of Object.entries(c.fieldErrors)){let h={...i[l]||{},[m]:d};i[l]=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=>Da(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]:Ea(n,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((n,r)=>{let s=r;return n[s]=Ko,n},{}),this.setFieldValue=(a,n,r)=>{let s=r?.dontUpdateMeta??false,u=r?.dontRunListeners??false,i=r?.dontValidate??false;Ct(()=>{s||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:zo(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=yl(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)],Je(s,{dontValidate:true}));let u=s?.dontValidate??false;u||await this.validateField(a,"change"),Nr(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,m)=>m===n?r:c),Je(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((m,l)=>l!==n),Je(r,{dontValidate:true})),Nr(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],m=i[r];return zo(zo(i,`${n}`,m),`${r}`,c)},Je(s,{dontValidate:true})),Nr(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},Je(s,{dontValidate:true})),Nr(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,[],Je(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]:Ko},values:this.options.defaultValues?zo(n.values,a,Da(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=>Ba.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ba.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Sl(),this._devtoolsSubmissionOverride=false,this.baseStore=new Qt(Il({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Gt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=0,m={};for(let l of Object.keys(i.fieldMetaBase)){let d=i.fieldMetaBase[l],f=u?.fieldMetaBase[l],h=s?.[l],p=Da(i.values,l),y=h?.errors;if(!f||d.errorMap!==f.errorMap){y=Object.values(d.errorMap??{}).filter(L=>L!==void 0);let I=this.getFieldInfo(l)?.instance;I&&!I.options.disableErrorFlat&&(y=y?.flat(1));}let w=!wl(y??[]),g=!d.isDirty,x=Ra(p,Da(this.options.defaultValues,l))||Ra(p,this.getFieldInfo(l)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===w&&h.isDefaultValue===x&&h.errors===y&&d===f){m[l]=h,c++;continue}m[l]={...d,errors:y,isPristine:g,isValid:w,isDefaultValue:x};}return Object.keys(i.fieldMetaBase).length&&s&&c===Object.keys(i.fieldMetaBase).length?s:m}}),this.store=new Gt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=n[1],m=Object.values(c).filter(Boolean),l=m.some(O=>O.isValidating),d=m.every(O=>O.isValid),f=m.some(O=>O.isTouched),h=m.some(O=>O.isBlurred),p=m.every(O=>O.isDefaultValue),y=f&&i.errorMap?.onMount,w=m.some(O=>O.isDirty),g=!w,x=!!(i.errorMap?.onMount||m.some(O=>O?.errorMap?.onMount)),I=!!l,L=s?.errors??[];(!u||i.errorMap!==u.errorMap)&&(L=Object.values(i.errorMap).reduce((O,U)=>U===void 0?O:U&&Or(U)?(O.push(U.form),O):(O.push(U),O),[]));let P=L.length===0,C=d&&P,b=this.options.canSubmitWhenInvalid??false,v=i.submissionAttempts===0&&!f&&!x||!I&&!i.isSubmitting&&C||b,k=i.errorMap;if(y&&(L=L.filter(O=>O!==i.errorMap.onMount),k=Object.assign(k,{onMount:void 0})),s&&u&&s.errorMap===k&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===L&&s.isFieldsValidating===l&&s.isFieldsValid===d&&s.isFormValid===P&&s.isValid===C&&s.canSubmit===v&&s.isTouched===f&&s.isBlurred===h&&s.isPristine===g&&s.isDefaultValue===p&&s.isDirty===w&&Ra(u,i))return s;let T={...i,errorMap:k,fieldMeta:this.fieldMetaDerived.state,errors:L,isFieldsValidating:l,isFieldsValid:d,isFormValid:P,isValid:C,canSubmit:v,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:p,isDirty:w},F=this.options.transform?.deps??[];if(F.length!==this.prevTransformArray.length||F.some((O,U)=>O!==this.prevTransformArray[U])){let O=Object.assign({},this,{state:T});this.options.transform?.fn(O),T=O.state,this.prevTransformArray=F;}return T}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=bl(a=>Tt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),Tt.on("request-form-state",a=>{a.payload.id===this._formId&&Tt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Tt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),Tt.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return ys(o.validate)?Ba[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})),Ct(()=>{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}),Tt.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}),Tt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}Ct(()=>{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}),Ct(()=>{this.baseStore.setState(n=>({...n,isSubmitted:!0,isSubmitSuccessful:!0})),Tt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(n){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),Tt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:n}),a(),n}}setErrorMap(o){Ct(()=>{Object.entries(o).forEach(([t,a])=>{let n=t;if(Or(a)){let{formError:r,fieldErrors:s}=ws(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 ws(e){if(e){if(Or(e)){let o=ws(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function Hr(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 Vr=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=Da(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,Je(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,n)=>{this.form.insertFieldValue(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,n)=>{this.form.replaceFieldValue(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,n)=>{this.form.swapFieldValues(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,n)=>{this.form.moveFieldValues(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Je(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),n=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo: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=Uo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Fa}),s=this.getLinkedFields(t).reduce((c,m)=>{let l=Uo(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Fa});return l.forEach(d=>{d.field=m;}),c.concat(l)},[]),u=false;Ct(()=>{let c=(m,l)=>{let d=Ss(l.cause),f=l.validate?gc(m.runValidator({validate:l.validate,value:{value:m.store.state.value,validationSource:"field",fieldApi:m},type:"validate"})):void 0,h=a[d],{newErrorValue:p,newSource:y}=vs({formLevelError:h,fieldLevelError:f});m.state.meta.errorMap?.[d]!==p&&m.setMeta(w=>({...w,errorMap:{...w.errorMap,[d]:p},errorSourceMap:{...w.errorSourceMap,[d]:y}})),p&&(u=!0);};for(let m of n)c(this,m);for(let m of s)m.validate&&c(m.field,m);});let i=Ss("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=Wo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Fa}),r=await a,s=this.getLinkedFields(t),u=s.reduce((d,f)=>{let h=Wo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Fa});return h.forEach(p=>{p.field=f;}),d.concat(h)},[]);this.state.meta.isValidating||this.setMeta(d=>({...d,isValidating:true}));for(let d of s)d.setMeta(f=>({...f,isValidating:true}));let i=[],c=[],m=(d,f,h)=>{let p=Ss(f.cause);d.getInfo().validationMetaMap[p]?.lastAbortController.abort();let w=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:w},h.push(new Promise(async g=>{let x;try{x=await new Promise((b,v)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(w.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:f.validate,value:{value:d.store.state.value,fieldApi:d,signal:w.signal,validationSource:"field"},type:"validateAsync"}));}catch(k){v(k);}},f.debounceMs);});}catch(b){x=b;}if(w.signal.aborted)return g(void 0);let I=gc(x),L=r[this.name]?.[p],{newErrorValue:P,newSource:C}=vs({formLevelError:L,fieldLevelError:I});d.setMeta(b=>({...b,errorMap:{...b?.errorMap,[p]:P},errorSourceMap:{...b.errorSourceMap,[p]:C}})),g(P);}));};for(let d of n)d.validate&&m(this,d,i);for(let d of u)d.validate&&m(d.field,d,c);let l=[];(i.length||c.length)&&(l=await Promise.all(i),await Promise.all(c)),this.setMeta(d=>({...d,isValidating:false}));for(let d of s)d.setMeta(f=>({...f,isValidating:false}));return l.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[Ss(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Ba.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ba.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Gt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Ko,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return ys(o.validate)?Ba[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 gc(e){if(e)return e}function Ss(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function Ls(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,mb)}function mb(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,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=xc(e);if(t.length!==xc(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 xc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Go=typeof window<"u"?useLayoutEffect:useEffect;function yb(e){let[o]=useState(()=>{let a=new Vr({...e,form:e.form,name:e.name});return a.Field=Cl,a});return Go(o.mount,[o]),Go(()=>{o.update(e);}),Ls(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Cl=(({children:e,...o})=>{let t=yb(o),a=useMemo(()=>Ea(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Lb({form:e,selector:o,children:t}){let a=Ls(e.store,o);return Ea(t,a)}function kl(e){let o=useId(),[t]=useState(()=>{let a=new qr({...e,formId:o}),n=a;return n.Field=function(s){return jsx(Cl,{...s,form:a})},n.Subscribe=function(s){return jsx(Lb,{form:a,selector:s.selector,children:s.children})},n});return Go(t.mount,[]),Go(()=>{t.update(e);}),t}function Tl({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 Rb=({editElement:e})=>{let o=useDispatch(),t=useSelector(ye),a=useRef(null),n=Ve(),r=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[u,i]=useState(s),c=kl({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:d})=>{if(d.questionType==="true-false"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctAnswer:d.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?Ft(f):Si(f));}else if(d.questionType==="multiple-choice"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctIndex:d.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?Zt(f):yi(f));}else if(d.questionType==="short-answer"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.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?ya(f):Li(f));}else if(d.questionType==="fill-in-the-blank"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.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?$a(f):Ci(f));}else if(d.questionType==="long-answer"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctLongAnswer:d.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?_a(f):Ii(f));}o(wa(false));}}),m=()=>{o(wa(false));};if(!n)return null;let l=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:d=>{d.preventDefault(),d.stopPropagation(),c.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{m();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(c.Field,{name:"questionType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:f=>{d.handleChange(f.target.value),i(f.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(Tl,{field:d})]})}),u&&!["short-answer","fill-in-the-blank","long-answer"].includes(u)&&jsx(c.Field,{name:"responseType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:f=>d.handleChange(f.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(Tl,{field:d})]})})]}),jsx(c.Field,{name:"feedbackMode",children:d=>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:()=>d.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 ${d.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:()=>d.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 ${d.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(Tl,{field:d})]})}),jsx(c.Field,{name:"question",validators:{onChange:({value:d})=>d?void 0:"A question is required"},children:d=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:d.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:d.state.value,onChange:f=>d.handleChange(f.target.value),onBlur:d.handleBlur,placeholder:"Enter Your Question"})}),d.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:d.state.meta.errors.join(", ")})]})}),u==="true-false"&&jsx(c.Field,{name:"responseOptions.correctAnswer",children:d=>{let f=d.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:()=>d.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${f===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),f===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>d.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${f===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),f===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value:d})=>{if(d.options.filter(h=>!h.trim()).length>0)return "All options must have text";if(!d.correctIndex||d.correctIndex.length===0)return "Please select at least one correct answer"}},children:d=>{let f=(w,g)=>{let x=[...d.state.value.options];x[w]=g,d.handleChange({...d.state.value,options:x});},h=()=>{if(d.state.value.options.length>=6){alert("Maximum 6 options allowed");return}d.handleChange({...d.state.value,options:[...d.state.value.options,""]});},p=w=>{if(d.state.value.options.length<=2){alert("Minimum 2 options required");return}let g=d.state.value.options.filter((I,L)=>L!==w),x=d.state.value.correctIndex?.filter(I=>I!==w).map(I=>I>w?I-1:I);d.handleChange({...d.state.value,options:g,correctIndex:x});},y=w=>{let g=d.state.value.correctIndex||[];if(g.includes(w))d.handleChange({...d.state.value,correctIndex:g.filter(I=>I!==w)});else {if(g.length>=6){alert("Maximum 6 correct answers allowed");return}d.handleChange({...d.state.value,correctIndex:[...g,w]});}};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:d.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:d.state.value.options.map((w,g)=>{let x=!w.trim(),I=d.state.value.correctIndex?.includes(g),L=d.state.meta.isTouched&&x;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>y(g),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${I?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:I&&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 ${L?"border-red-500 bg-red-50":I?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${g+1}`,value:w,onChange:P=>f(g,P.target.value),onBlur:d.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"})}),d.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:d.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"}),d.state.value.correctIndex.length===0||d.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:d.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:d=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:d.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:d.state.value,onChange:f=>{d.handleChange(f.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:d.state.meta.errors.join(", ")})]})}),u==="long-answer"&&jsx(c.Field,{name:"responseOptions.correctLongAnswer",children:d=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:d.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:d.state.value,onChange:f=>{d.handleChange(f.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:d.state.meta.errors.join(", ")})]})}),jsx(c.Subscribe,{selector:d=>[d.canSubmit,d.isSubmitting],children:([d,f])=>jsx("button",{type:"submit",disabled:!d,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:f?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(l,n)},yc=Rb;var Ic=({text:e,position:o})=>{let t=Se(),a=(m,l,d,f,h)=>{let y=document.createElement("canvas").getContext("2d");if(!y)return {width:e.width,height:e.height};y.font=`${h} ${f} ${l}px ${d}`;let w=m.split(`
|
|
4
|
-
`),
|
|
5
|
-
`),f=0;document.body.appendChild(l);for(let p of d){l.textContent=p||" ";let y=l.offsetWidth;y>f&&(f=y);}document.body.removeChild(l);let h=10;m.style.width=`${Math.max(200,f+h+20)}px`;},[]);return useEffect(()=>{let m=u.current;m&&(m.style.fontSize=`${e.fontSize*r}px`,m.style.fontFamily=e.fontFamily,m.style.fontStyle=e.fontStyle,m.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",m.style.textDecoration=e.textDecoration,m.style.color=e.fill,c(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,c]),jsx("div",{style:{position:"absolute",top:`${n.top}px`,left:`${n.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(u.current=m,s.current=m,m){m.focus();let l=m.value.length;m.setSelectionRange(l,l),c(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:i},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Tc=(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 m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},Mc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s})=>{let u=useSelector(v=>v.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useDispatch(),m=useRef(null),[l,d]=useState(""),[f,h]=useState(false),[p,y]=useState(null);useEffect(()=>{let v=m.current;if(v)return a.current.set(e.id,v),()=>{a.current.delete(e.id);}},[e.id,a]);let w=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=f&&l.trim().toLowerCase()===w,x=v=>{d(v);let k=v.trim(),T=k.toLowerCase()===w;c(ya({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:k,isCorrect:T}}}));},I=()=>{h(false),d(""),c(ya({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:"",isCorrect:false}}}));},L=()=>g?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",P=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},C=e.data.feedbackMode==="practice",b=useMemo(()=>{let O=C?48:0,U=12,H=30,K=e.width-48,E=Math.max(60,Tc(e.data.question,18,K,"bold")+20),W=f?Math.max(40,Tc(L(),12,K/2)+20):0,te=f?54:20,G=E+W+H+50+12+U+O+24;return {padding:24,questionHeight:E,questionFontSize:18,feedbackHeight:W,feedbackFontSize:12,inputY:te,inputHeight:50,inputMargin:12,buttonHeight:O,buttonTopMargin:U,placeholderHeight:H,contentWidth:K,totalHeight:G}},[e.width,e.data.question,f,g,C,L]);return jsxs(Group,{ref:m,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:b.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:b.totalHeight,onTransformEnd:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,n(v.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:b.padding+8,y:b.padding,fontSize:b.questionFontSize,fontStyle:"bold",fill:"#111827",width:b.contentWidth,height:b.questionHeight-b.padding,wrap:"word",listening:false}),jsx(Rect,{x:b.padding,y:b.questionHeight+b.feedbackHeight+b.placeholderHeight-b.inputY,width:b.contentWidth+4,height:b.inputHeight+6,fill:"#ffffff",stroke:g?"#22c55e":f?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:b.padding,y:b.questionHeight+b.feedbackHeight+b.placeholderHeight-b.inputY},divProps:{style:{width:`${b.contentWidth-4}px`,height:`${b.inputHeight}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:l,onChange:v=>x(v.target.value),disabled:f,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:f?"none":"auto"}})}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:b.padding,y:b.questionHeight+80,width:e.width/2+24,height:b.feedbackHeight,fill:P().bg,cornerRadius:8}),jsx(Text,{x:36,y:b.questionHeight+80,width:b.contentWidth,height:b.feedbackHeight,text:L(),fontSize:b.feedbackFontSize,fontStyle:"bold",fill:P().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:b.questionHeight+b.feedbackHeight+b.placeholderHeight+b.inputHeight+b.inputMargin+b.buttonTopMargin,children:[jsxs(Group,{onMouseDown:v=>{v.cancelBubble=true,y("check");},onMouseUp:v=>{v.cancelBubble=true,y(null),l.length>0&&h(true);},onMouseLeave:v=>{v.cancelBubble=true,y(null);},onTouchStart:v=>{v.cancelBubble=true,y("check");},onTouchEnd:v=>{v.cancelBubble=true,y(null),l.length>0&&h(true);},scaleX:p==="check"?.95:1,scaleY:p==="check"?.95:1,children:[jsx(Rect,{x:b.padding+14,width:(b.contentWidth-24)/(f?2:1),height:b.buttonHeight,fill:l.length===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true}),jsx(Text,{x:b.padding+14,width:(b.contentWidth-24)/(f?2:1),height:b.buttonHeight,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-b.padding*2)/2+8,onMouseDown:()=>y("reset"),onMouseUp:()=>{y(null),I();},onMouseLeave:()=>y(null),onTouchStart:()=>y("reset"),onTouchEnd:()=>{y(null),I();},scaleX:p==="reset"?.95:1,scaleY:p==="reset"?.95:1,children:[jsx(Rect,{x:b.padding,width:(b.contentWidth-8)/2,height:b.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true}),jsx(Text,{x:b.padding,width:(b.contentWidth-8)/2,height:b.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Mc.displayName="ShortAnswer";var Ac=Mc;var Ec=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Ac,{shortAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"shortAnswer")},i.id))})};var Dc=e=>{let o=useDispatch(),a=useSelector(ye)?.fillInTheBlanks||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o($a({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:n,handleFillInTheBlanksDragEnd:r}};var Pl=(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 m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},Rc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:n,fibRefs:r,touchHandlers:s})=>{let u=useSelector(v=>v.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),m=useDispatch(),[l,d]=useState(""),[f,h]=useState(false),[p,y]=useState(null);useEffect(()=>{let v=c.current;if(v)return r.current.set(e.id,v),()=>{r.current.delete(e.id);}},[e.id,r]);let w=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=f&&l.trim().toLowerCase()===w,x=v=>{d(v);let k=v.trim(),T=k.toLowerCase()===w;m($a({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:k,isCorrect:T}}}));},I=()=>{h(false),d("");},L=()=>{l.length>0&&h(true);},P=e.data.feedbackMode==="practice",C=useMemo(()=>{let H=e.width-48,K=(H-15)/2,E=24,W=E,te=Math.max(60,Pl(e.data.question.replace("_____","________"),24,H,"bold")+20);E+=te;let G=E,z=Math.max(35,Pl("Enter your answer in the blank.",16,H)+10);E+=z;let N=E;E+=67;let _=E,Z=f?Math.max(32,Pl(g?"Right Answer, Great Job!":"Wrong Answer",14,H-40)+16):0;f&&(E+=Z+16);let ae=E;return P&&(E+=64),E+=24,{padding:24,questionY:W,questionHeight:te,questionFontSize:24,helperTextY:G,helperTextHeight:z,helperTextFontSize:16,inputY:N,inputHeight:51,feedbackY:_,feedbackHeight:Z,feedbackFontSize:14,buttonsY:ae,buttonHeight:64,buttonGap:15,buttonWidth:K,contentWidth:H,totalHeight:E}},[e.width,e.data.question,f,g,P]),b=()=>f?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:v=>a(v,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:C.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,n?.(v.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:C.padding,y:C.questionY,fontSize:C.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:C.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:C.padding,y:C.helperTextY,fontSize:C.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:C.contentWidth,height:C.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:C.padding,y:C.inputY,width:C.contentWidth,height:C.inputHeight,fill:"#ffffff",stroke:b(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:C.padding,y:C.inputY},divProps:{style:{width:`${C.contentWidth}px`,height:`${C.inputHeight}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:l,onChange:v=>x(v.target.value),disabled:f,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),f&&jsxs(Group,{y:C.feedbackY,children:[jsx(Rect,{x:C.padding,width:g?206:140,height:C.feedbackHeight,fill:g?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:g?"\u2713":"\u2717",x:C.padding+10,y:0,width:16,height:C.feedbackHeight,fontSize:C.feedbackFontSize,fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:g?"Right Answer, Great Job!":"Wrong Answer",x:C.padding+30,y:0,height:C.feedbackHeight,fontSize:C.feedbackFontSize,fontStyle:"600",fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),P&&jsxs(Group,{y:C.buttonsY,children:[jsxs(Group,{x:C.padding,onMouseDown:v=>{v.cancelBubble=true,y("reset");},onMouseUp:v=>{v.cancelBubble=true,y(null),I();},onMouseLeave:v=>{v.cancelBubble=true,y(null);},onTouchStart:v=>{v.cancelBubble=true,y("reset");},onTouchEnd:v=>{v.cancelBubble=true,y(null),I();},scaleX:p==="reset"?.98:1,scaleY:p==="reset"?.98:1,children:[jsx(Rect,{width:C.buttonWidth,height:C.buttonHeight,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:C.buttonWidth,height:C.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:C.padding+C.buttonWidth+C.buttonGap,onMouseDown:v=>{v.cancelBubble=true,y("submit");},onMouseUp:v=>{v.cancelBubble=true,y(null),L();},onMouseLeave:v=>{v.cancelBubble=true,y(null);},onTouchStart:v=>{v.cancelBubble=true,y("submit");},onTouchEnd:v=>{v.cancelBubble=true,y(null),L();},scaleX:p==="submit"?.98:1,scaleY:p==="submit"?.98:1,children:[jsx(Rect,{width:C.buttonWidth,height:C.buttonHeight,fill:l.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:C.buttonWidth,height:C.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Rc.displayName="FillInTheBlanks";var Fc=Rc;var Oc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,onLongPress:r,fibRefs:s})=>{let{createHandlers:u}=qe({onLongPress:r});return jsx(Fragment,{children:e.map(i=>jsx(Fc,{fillInTheBlank:i,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,fibRefs:s,touchHandlers:u(i.id,"fillInTheBlanks")},i.id))})};var Rl=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},Bl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,touchHandlers:r,handleDragEnd:s})=>{let u=useSelector(b=>b.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),m=useDispatch(),[l,d]=useState(""),[f,h]=useState(false),[p,y]=useState(null);useEffect(()=>{let b=c.current;if(b)return a.current.set(e.id,b),()=>{a.current.delete(e.id);}},[e.id,a]);let w=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",g=f&&l.trim().toLowerCase()===w,x=b=>{d(b);let v=b.trim();v.toLowerCase()===w;m(_a({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:v}}}));},I=()=>{h(false),d("");},L=()=>g?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",P=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},C=useMemo(()=>{let H=e.width-48,K=Math.max(60,Rl(e.data.question,20,H,"bold")+20),E=f?Math.max(60,Rl(L(),14,H)+30):0,te=Math.max(30,Rl("Answer (Extended response):",14,H)+10),G=K+E+te+120+12+12+48+24;return {padding:24,questionHeight:K,questionFontSize:20,feedbackHeight:E,feedbackFontSize:14,placeholderHeight:te,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:H,totalHeight:G}},[e.width,e.data.question,f,g,L]);return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:C.totalHeight,...r,name:"la-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:b=>{let v=c.current?.getStage()?.getPointerPosition();if(!v||!n)return;let k={x:e.x,y:e.y,width:e.width,height:C.totalHeight};v.x>=k.x&&v.x<=k.x+k.width&&v.y>=k.y&&v.y<=k.y+k.height&&n(b.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:C.totalHeight-50,onTransformEnd:b=>t(e.id,b)}),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}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:C.padding,y:C.questionHeight,width:C.contentWidth,height:C.feedbackHeight,fill:P().bg,cornerRadius:8}),jsx(Text,{x:C.padding,y:C.questionHeight,width:C.contentWidth,height:C.feedbackHeight,text:L(),fontSize:C.feedbackFontSize,fontStyle:"bold",fill:P().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:f?"none":"auto"}},children:jsx("textarea",{value:l,onChange:b=>x(b.target.value),disabled:f,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:"14px",pointerEvents:f?"none":"auto"}})}),jsx(Group,{y:C.questionHeight+C.feedbackHeight+C.placeholderHeight+C.textareaHeight+C.textareaMargin+C.buttonTopMargin,children:f&&jsxs(Group,{onMouseDown:()=>y("reset"),onMouseUp:()=>{y(null),I();},onMouseLeave:()=>y(null),onTouchStart:()=>y("reset"),onTouchEnd:()=>{y(null),I();},scaleX:p==="reset"?.95:1,scaleY:p==="reset"?.95:1,children:[jsx(Rect,{x:C.padding,width:C.contentWidth,height:C.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:b=>b.cancelBubble=true,onTap:b=>b.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})]})})]})});Bl.displayName="LongAnswer";var Hc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Bl,{longAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"longAnswer")},i.id))})};var io=1600,lo=900,Uc=3200,Wc=1800,yv=e=>{let o=0,t=0,a=io,n=lo;if(!e)return {minX:o,minY:t,maxX:a,maxY:n,width:io,height:lo};let r=(i,c,m,l)=>{o=Math.min(o,i),t=Math.min(t,c),a=Math.max(a,i+m),n=Math.max(n,c+l);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let c=i.x||0,m=i.y||0,l=i.scaleX||1,d=i.scaleY||1;for(let f=0;f<i.points.length;f+=2){let h=c+i.points[f]*l,p=m+i.points[f+1]*d;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,Wc);return o=Math.max(o,a-Uc),t=Math.max(t,n-Wc),{minX:o,minY:t,maxX:a,maxY:n,width:s,height:u}},wv=(e,o,t={minX:0,minY:0,maxX:io,maxY:lo,width:io,height:lo})=>{let a=Math.max(t.width,io),n=Math.max(t.height,lo),r=e/o,s=a/n,u,i,c,l=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;l=(o-d)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:l,baseWidth:u,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},Kc=(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}},Sv=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:n={enabled:true}}={})=>{let r=$e(),s=Ve(),u=J(S=>S.toolbar.selectedTool),i=J(ye),c=J(Sa),m=J(Yn),l=J(S=>S.canvas.zoomLevel),f=(i?.videos||[]).find(S=>S.isRecorded&&S.isPlaying),h=!!f,p=useCallback(()=>{f&&r(Ga(f.id));},[r,f]),y=i?.editingActivity,w=i?.showMcqForm,g=i?.lines||[],x=useRef(null),I=useRef(null),[L,P]=useState(null),[C,b]=useState(""),v=useRef(null),[k,T]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:io,stageHeight:lo,offsetX:0,offsetY:0,baseWidth:io,baseHeight:lo,contentOffsetX:0,contentOffsetY:0}),F=useMemo(()=>yv(i||null),[c]),[V,O]=useState(null),[U,H]=useState(null),[K,E]=useState(null),[W,te]=useState(null),[G,z]=useState(null),[N,_]=useState(null),[Z,ae]=useState(null),[Q,pe]=useState(false),[ue,le]=useState(null),[he,ce]=useState(false),_e=useRef(null),or=useRef(null),ga=useRef(null),{debouncedGenerateThumbnail:on}=gu(c,x);useEffect(()=>{let S=()=>{if(I.current){let D=I.current.getBoundingClientRect(),B=wv(D.width,D.height,F);T(B);}};S();let M=new ResizeObserver(S);return I.current&&M.observe(I.current),window.addEventListener("resize",S),()=>{M.disconnect(),window.removeEventListener("resize",S);}},[F]),useEffect(()=>{if(x.current){let S=x.current.container();S&&(S.style.cursor="");}},[u]);let ne=useCallback(()=>{x.current&&requestAnimationFrame(()=>{if(!x.current)return;if(x.current.getLayers().forEach(M=>M.batchDraw()),!m)try{let D=x.current.toDataURL({pixelRatio:.16666666666666666});b(D),on();}catch(M){console.warn("Preview generation failed (CORS):",M);}});},[on,m]),rn=useRef(c);useEffect(()=>{rn.current!==c&&(rn.current=c,ne());},[c,ne]);let nn=useRef(null),sn=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),M=nn.current?.count!==S;!sn.current&&M&&setTimeout(()=>{ne();},100),nn.current={slideId:c,count:S},sn.current=false;},[i,c,ne]),useEffect(()=>{x.current&&e&&e(x);},[e]),useEffect(()=>{ga.current&&a&&a(ga);},[a]);let{startDrawing:ln,draw:dn,stopDrawing:un,setCanvasRef:Wa,tool:_s,color:$s,strokeWidth:Xs,isSketchMode:Ys}=Wd(ne),xa=useRef(new Map),{images:cn,getLoadedImage:Zs,imageRefs:go,handleDragEnd:fn,handleImageTransformEnd:Js}=Yd(ne),{videos:rr,videoRefs:xo,handleVideoClick:mn,handleVideoDragEnd:A,handleVideoTransformEnd:re}=Qd(ne),{multipleChoice:Ae,handleMcqTransform:we,mcqRefs:ie,handleDragEnd:ge}=Zd(ne),{trueFalse:He,handleTrueFalseTransform:lt,trueFalseRefs:Et,handleTrueFalseDragEnd:bt}=Jd(ne),{shortAnswers:Fe,saRefs:ze,handleShortAnswerDragEnd:oa}=nu(ne),{longAnswers:ba,handleLongAnswerDragEnd:Qs}=su(ne),{fillInTheBlanks:ei,handleFillInTheBlanksDragEnd:pn,fibRefs:dt}=Dc(ne),{transformerRef:se,boundBoxFunc:vt}=fu(),{shapes:Um,shapeRefs:hn,isDragging:Cd,handleShapeDragEnd:Wm,handleShapeResizeEnd:Km}=au(ne),{texts:nr,textRefs:va,handleDragEnd:Gm,handleTransformEnd:jm,handleDoubleClick:_m,startEditing:gn,editingTextId:ve,editingValue:kd,handleEditingChange:Td,finishEditing:ti}=ru(ne,_e);useEffect(()=>{t&&t(gn);},[t,gn]);let xn=J(S=>S.canvas.editingTextId);useEffect(()=>{xn&&xn!==ve&&gn(xn);},[xn,ve,gn]);let{flashcards:$m,flashcardRefs:bn,handleDragEnd:Xm,handleFlashcardTransformEnd:Ym,handleNext:Zm,handlePrevious:Jm}=lu(ne),{photoFrames:Md,photoFrameRefs:vn,handleDragEnd:Qm,handlePhotoFrameTransformEnd:ep,startCamera:tp,capturePhoto:ap,cameraStreams:op}=cu(ne);useEffect(()=>{if(se.current){if(ve){se.current.nodes([]),se.current.getLayer()?.batchDraw();return}if(L&&!rr.find(D=>D.id===L)?.isPlaying){let D=xa.current.get(L)||go.current.get(L)||xo.current.get(L)||hn.current.get(L)||va.current.get(L)||ie.current.get(L)||bn.current.get(L)||vn.current.get(L)||ze.current.get(L)||Et.current.get(L)||dt.current.get(L);if(D){let B=D.attrs?.locked;if(D.visible()&&B!==true){se.current.nodes([D]),se.current.getLayer()?.batchDraw();return}}}se.current.nodes([]),se.current.getLayer()?.batchDraw();}},[L,ve,rr,xa,go,xo,hn,va,bn,vn,Md,ie,Et,dt,se]);let Ue=useCallback(S=>{P(S),o?.(S);},[o]),bo=useCallback(()=>{P(null),o?.(null),se.current&&(se.current.nodes([]),se.current.getLayer()?.batchDraw());},[se,o]),Ad=useCallback(S=>i?i.lines?.some(M=>M.id===S)?"line":i.images?.some(M=>M.id===S)?"image":i.videos?.some(M=>M.id===S)?"video":i.shapes?.some(M=>M.id===S)?"shape":i.texts?.some(M=>M.id===S)?"text":i.flashcards?.some(M=>M.id===S)?"flashcard":i.photoFrames?.some(M=>M.id===S)?"photoFrame":i.multipleChoices?.some(M=>M.id===S)?"mcq":i.trueFalses?.some(M=>M.id===S)?"trueFalse":i.shortAnswers?.some(M=>M.id===S)?"shortAnswer":i.LongAnswer?.some(M=>M.id===S)?"longAnswer":i.fillInTheBlanks?.some(M=>M.id===S)?"fillInTheBlanks":null:null,[i]),Pd=useCallback((S,M)=>{switch(r(fe()),M){case "line":r($n(S));break;case "image":r(wn(S));break;case "video":r(In(S));break;case "shape":r(Tn(S));break;case "text":r(Mn(S));break;case "flashcard":r(Pn(S));break;case "photoFrame":r(Dn(S));break;case "mcq":r(Fn(S));break;case "trueFalse":r(On(S));break;case "shortAnswer":r(Hn(S));break;case "longAnswer":r(Vn(S));break;case "fillInTheBlanks":r(Un(S));break}bo(),ne();},[r,bo,ne]);useEffect(()=>{let S=M=>{if(M.key!=="Delete"||!L||ve)return;let D=document.activeElement;if(D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement||D?.getAttribute("contenteditable")==="true")return;M.preventDefault();let Ie=Ad(L);Ie&&Pd(L,Ie);};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[L,ve,Ad,Pd]),useEffect(()=>{let S=se.current;return ()=>{S&&S.nodes([]);}},[c]),useEffect(()=>{let S=M=>{ve&&M.target.tagName!=="TEXTAREA"&&ti();};return document.addEventListener("mousedown",S),()=>{document.removeEventListener("mousedown",S);}},[ve,ti]),useEffect(()=>{let S=ve||L;if(!S||L&&ve){H(null);return}let M=va.current.get(S),D=x.current;if(!M||!D){H(null);return}let B=D.container().getBoundingClientRect(),Ie=M.absolutePosition(),be=D.scaleX();H({x:B.left+(Ie.x+M.width()*be/2)*be+k.offsetX,y:B.top+Ie.y*be+k.offsetY-70});},[L,ve,nr,va,k.offsetX,k.offsetY]),useEffect(()=>{if(!ve){E(null);return}let S=va.current.get(ve),M=x.current;if(!S||!M){E(null);return}let D=S.getClientRect({relativeTo:M}),B=M.container().getBoundingClientRect(),Ie=M.scaleX(),be=M.position(),oe={top:B.top+be.y+D.y*Ie,left:B.left+be.x+D.x*Ie,scale:Ie};E(oe),r(qd(oe));},[ve,nr,va,k.offsetY,k.offsetX]);let Ed=useCallback(S=>{let M=S.target.getClassName(),D=S.target===S.target.getStage(),B=M==="Transformer"||S.target.getParent()?.getClassName()==="Transformer",Ie=M==="Image",be=M==="Text",oe=M==="Group"||S.target.getParent()?.getClassName()==="Group",ut=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&S.target.attrs.id,ct=M==="Group";if(D&&!B&&!Ie&&!be&&!oe&&!ut&&!ct&&bo(),!(u==="pen"||u==="eraser")&&(Ie||be||B||oe||ut||ct))return;let We=S.target.getStage()?.getPointerPosition();if(!We)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let q=Kc(We,k,l);ln(q);}},[u,ln,bo,k,l]),Dd=useCallback(S=>{if(Cd)return;let M=S.target.getStage()?.getPointerPosition();if(!M)return;let D=Kc(M,k,l);dn(D);},[dn,Cd,k,l]),Rd=useCallback(()=>{un();},[un]),rp=useCallback(S=>{fn(S,ne);},[fn,ne]),np=useCallback(S=>{mn(S),Ue(S);},[mn,Ue]),Dt=useCallback((S,M,D)=>{if(S.preventDefault(),!n.enabled)return;let B=S.clientX,Ie=S.clientY,be=v.current?.offsetHeight||250,oe=v.current?.offsetWidth||200,ut=window.innerHeight,ct=window.innerWidth,et=B,We=Ie;Ie+be>ut&&(We=Ie-be),B+oe>ct&&(et=B-oe),Ue(M),O({x:et,y:We,elementId:M,elementType:D});},[Ue,n.enabled]),Ka=useRef(null),sr=useRef(null),yt=useCallback((S,M)=>D=>{if(!n.enabled)return;D.preventDefault();let B=D.changedTouches[0];if(!B)return;let Ie=B.clientX,be=B.clientY,oe=v.current?.offsetHeight||200,ut=v.current?.offsetWidth||200,ct=window.innerHeight,et=window.innerWidth,We=Ie,tt=be;be+oe>ct&&(tt=be-oe),Ie+ut>et&&(We=Ie-ut),Ue(S),O({x:We,y:tt,elementId:S,elementType:M});},[Ue,n.enabled]),sp=useCallback((S,M)=>({onTouchStart:D=>{let B=D.evt.touches[0];sr.current={x:B.clientX,y:B.clientY},Ka.current=setTimeout(()=>{yt(S,M)(D.evt);},500);},onTouchMove:D=>{if(!sr.current)return;let B=D.evt.touches[0],Ie=Math.abs(B.clientX-sr.current.x),be=Math.abs(B.clientY-sr.current.y);(Ie>10||be>10)&&Ka.current&&(clearTimeout(Ka.current),Ka.current=null);},onTouchEnd:()=>{Ka.current&&(clearTimeout(Ka.current),Ka.current=null),sr.current=null;}}),[yt]),Fd=useCallback(S=>{r(mr(S)),r(wa(true));},[r]),ip=useCallback(S=>{r(fr(S)),r(Xa(true));},[r]),lp=useCallback((S,M)=>{if(!V)return;let{elementId:D,elementType:B}=V;switch(S){case "order":if(M){let R=M.target.getBoundingClientRect();te({x:R.right+5,y:R.top,type:"order"});}break;case "lock":if(M){let R=M.target.getBoundingClientRect();te({x:R.right+5,y:R.top,type:"lock"});}break;case "link":if(O(null),B==="line")break;let Ie=i?B==="image"?i.images.find(R=>R.id===D):i.videos.find(R=>R.id===D):null;z({type:"link",defaultValue:Ie?.link||""});break;case "voice":if(O(null),B==="line")break;let be=i?B==="image"?i.images.find(R=>R.id===D):B==="video"?i.videos.find(R=>R.id===D):B==="text"?i.texts.find(R=>R.id===D):B==="flashcard"?i.flashcards.find(R=>R.id===D):B==="photoFrame"?i.photoFrames.find(R=>R.id===D):B==="mcq"?i.multipleChoices.find(R=>R.id===D):B==="fillInTheBlanks"?i.fillInTheBlanks.find(R=>R.id===D):B==="longAnswer"?i.LongAnswer.find(R=>R.id===D):B==="shortAnswer"?i.shortAnswers.find(R=>R.id===D):B==="trueFalse"?i.trueFalses.find(R=>R.id===D):B==="shape"?i.shapes.find(R=>R.id===D):null:null;le({elementId:D,elementType:B,existingAudio:be?.audioData});break;case "edit":O(null);let oe=null;B==="mcq"?oe=i?.multipleChoices.find(R=>R.id===D):B==="trueFalse"?oe=i?.trueFalses.find(R=>R.id===D):B==="shortAnswer"?oe=i?.shortAnswers.find(R=>R.id===D):B==="longAnswer"?oe=i?.LongAnswer.find(R=>R.id===D):B==="fillInTheBlanks"&&(oe=i?.fillInTheBlanks.find(R=>R.id===D)),oe&&Fd(oe);break;case "editFlashcard":O(null);let ut=i?.flashcards.find(R=>R.id===D);ut&&ip(ut);break;case "color":O(null);let ct=i?.shapes.find(R=>R.id===D);_({elementId:D,elementType:"shape",defaultColor:ct?.color||"#096B76"});break;case "crop":if(O(null),B==="image"){let R=i?.images.find(hp=>hp.id===D);R&&ae({elementId:D,imageSrc:R.src});}break;case "draw":O(null),B==="image"?r(gi(D)):B==="photoFrame"&&r(bi(D));break;case "duplicate":r(fe()),B==="line"?r(Ei(D)):B==="image"?r(Sn(D)):B==="video"?r(Cn(D)):B==="shape"?r(kn(D)):B==="text"?r(An(D)):B==="flashcard"?r(En(D)):B==="photoFrame"?r(Rn(D)):B==="mcq"?r(Bn(D)):B==="trueFalse"?r(Nn(D)):B==="shortAnswer"?r(qn(D)):B==="fillInTheBlanks"?r(Wn(D)):B==="longAnswer"&&r(zn(D)),ne();break;case "infinite-clone":r(fe());let et=5;for(let R=0;R<et;R++)B==="image"?r(Sn(D)):B==="video"?r(Cn(D)):B==="shape"?r(kn(D)):B==="text"?r(An(D)):B==="flashcard"?r(En(D)):B==="photoFrame"?r(Rn(D)):B==="mcq"?r(Bn(D)):B==="trueFalse"?r(Nn(D)):B==="shortAnswer"?r(qn(D)):B==="fillInTheBlanks"?r(Wn(D)):B==="longAnswer"&&r(zn(D));ne();break;case "make-response":if(O(null),B==="line")break;let We=`#response-${D}`;r(fe()),r(Kn({id:D,type:B,link:We})),(i?B==="image"?i.images.find(R=>R.id===D):B==="video"?i.videos.find(R=>R.id===D):B==="shape"?i.shapes.find(R=>R.id===D):B==="flashcard"?i.flashcards.find(R=>R.id===D):B==="photoFrame"?i.photoFrames.find(R=>R.id===D):i.multipleChoices.find(R=>R.id===D):null)?.altText||r(Gn({id:D,type:B,altText:"Interactive response area"})),ne(),console.log(`Element ${D} marked as interactive response area`);break;case "accessibility":if(O(null),B==="line")break;let q=i?B==="image"?i.images.find(R=>R.id===D):B==="video"?i.videos.find(R=>R.id===D):B==="shape"?i.shapes.find(R=>R.id===D):null:null;z({type:"altText",defaultValue:q?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),O(null),ce(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(fe()),B==="line"?r($n(D)):B==="image"?r(wn(D)):B==="video"?r(In(D)):B==="shape"?r(Tn(D)):B==="text"?r(Mn(D)):B==="flashcard"?r(Pn(D)):B==="photoFrame"?r(Dn(D)):B==="mcq"?r(Fn(D)):B==="trueFalse"?r(On(D)):B==="shortAnswer"?r(Hn(D)):B==="longAnswer"?r(Vn(D)):B==="fillInTheBlanks"&&r(Un(D)),bo(),ne();break}},[V,r,ne,bo,i,Fd]),dp=useCallback(()=>{O(null),te(null);},[]),ai=useCallback(S=>{if(!V)return;let{elementId:M,elementType:D}=V;switch(r(fe()),S){case "bring-to-front":D!=="line"&&r(Ti({id:M,type:D}));break;case "send-to-back":D!=="line"&&r(Mi({id:M,type:D}));break;case "lock":case "unlock":D!=="line"&&r(Ai({id:M,type:D}));break}ne(),O(null),te(null);},[V,r,ne]),up=useCallback(S=>{if(!V||!G)return;let{elementId:M,elementType:D}=V;r(fe()),G.type==="link"&&D!=="line"?r(Kn({id:M,type:D,link:S})):G.type==="altText"&&D!=="line"&&r(Gn({id:M,type:D,altText:S})),ne(),z(null);},[V,G,r,ne]),cp=useCallback(S=>{if(!ue)return;let{elementId:M,elementType:D}=ue;r(fe()),r(jn({id:M,type:D,audioData:S})),ne(),le(null);},[ue,r,ne]),fp=useCallback(()=>{if(!ue)return;let{elementId:S,elementType:M}=ue;r(fe()),r(jn({id:S,type:M,audioData:""})),ne();},[ue,r,ne]),mp=useCallback(S=>{if(!N)return;let{elementId:M}=N;r(fe()),r(So({id:M,color:S})),ne(),_(null);},[N,r,ne]),pp=useCallback(S=>{if(!Z)return;let{elementId:M}=Z;r(fe()),r(yo({id:M,src:S})),ne(),ae(null);},[Z,r,ne]);return jsxs("div",{ref:I,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx($d,{ref:S=>{if(or.current=S,Wa(S),S){let M=S.getCanvasElement();M&&(ga.current=M,a&&a(ga));}},width:k.baseWidth,height:k.baseHeight,tool:_s,color:$s,strokeWidth:Xs/(k.scale*l),isSketchMode:Ys,xOffset:k.contentOffsetX,yOffset:k.contentOffsetY-k.offsetY/k.scale,style:{width:k.stageWidth,height:k.stageHeight}}),jsxs(Stage,{ref:x,width:k.stageWidth,height:k.stageHeight,scaleX:k.scaleX*l,scaleY:k.scaleY*l,x:k.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:k.baseWidth,height:k.stageHeight/k.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-k.contentOffsetX,y:k.offsetY/k.scale-k.contentOffsetY,children:(()=>{let S=[];return g.forEach((M,D)=>{S.push({type:"line",timestamp:M.timestamp||D,element:{...M,id:M.id??`line-${D}`},index:D});}),Um.forEach(M=>{S.push({type:"shape",timestamp:M.timestamp||0,element:M});}),cn.forEach(M=>{S.push({type:"image",timestamp:M.timestamp||0,element:M});}),rr.forEach(M=>{S.push({type:"video",timestamp:M.timestamp||0,element:M});}),nr.forEach(M=>{S.push({type:"text",timestamp:M.timestamp||0,element:M});}),$m.forEach(M=>{S.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Md.forEach(M=>{S.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),Ae.forEach(M=>{S.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),He.forEach(M=>{S.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),Fe.forEach(M=>{S.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),ba.forEach(M=>{S.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),ei.forEach(M=>{S.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),S.sort((M,D)=>M.timestamp-D.timestamp),S.map((M,D)=>{let B=`${M.type}-${"id"in M.element&&M.element.id||M.index||D}`,Ie="id"in M.element?M.element.id:void 0,be=Ie&&L===Ie;switch(M.type){case "line":let oe=M.element,ut=M.index||0,ct=oe.tool==="eraser",et=oe.isSketch&&oe.tool==="pen",We=oe.isSketch&&ct,tt=oe.id||`line-${ut}`;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:et||We?void 0:oe.color,strokeWidth:et||We?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:et||We?ct?"black":oe.color:void 0,closed:et||We,tension:0,globalCompositeOperation:ct?"destination-out":"source-over",listening:true,onClick:()=>{r(fe()),r(yn(ut));},onTap:()=>{r(fe()),r(yn(ut));},hitStrokeWidth:Math.max(20,(oe.strokeWidth??0)*2),onMouseEnter:q=>{let R=q.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:q=>{let R=q.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`);}})},B):jsxs(Le__default.Fragment,{children:[jsx(Group,{id:tt,ref:q=>{q?xa.current.set(tt,q):xa.current.delete(tt);},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:",tt),Ue(tt));},onTap:()=>{u==="select"&&(console.log("Line tapped:",tt),Ue(tt));},onDragEnd:q=>{r(fe()),r(_n({id:tt,x:q.target.x(),y:q.target.y(),scaleX:q.target.scaleX(),scaleY:q.target.scaleY(),rotation:q.target.rotation()})),ne();},onTransformEnd:q=>{r(fe()),r(_n({id:tt,x:q.target.x(),y:q.target.y(),scaleX:q.target.scaleX(),scaleY:q.target.scaleY(),rotation:q.target.rotation()})),ne();},onMouseEnter:q=>{if(u==="select"){let R=q.target.getStage();R&&(R.container().style.cursor="move");}},onMouseLeave:q=>{if(u==="select"){let R=q.target.getStage();R&&(R.container().style.cursor="default");}},onContextMenu:q=>{let R=q.evt;R.preventDefault(),Dt(R,tt,"line");},...sp(tt,"line"),children:jsx(Line,{points:oe.points||[],stroke:et||We?void 0:oe.color,strokeWidth:et||We?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:et||We?ct?"black":oe.color:void 0,closed:et||We,tension:0,globalCompositeOperation:ct?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=xa.current.get(L);console.log("Line Transformer - selectedId:",L,"node found:",!!R),R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "shape":return jsxs(Le__default.Fragment,{children:[jsx($i,{onSelect:Ue,shapes:[M.element],shapeRefs:hn,handleShapeDragEnd:Wm,handleShapeResizeEnd:Km,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=hn.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "image":return jsxs(Le__default.Fragment,{children:[jsx(Ki,{images:[M.element],getLoadedImage:Zs,imageRefs:go,onDragEnd:rp,onTransform:Js,onSelect:Ue,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=go.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "video":return jsxs(Le__default.Fragment,{children:[jsx(_i,{videos:[M.element],selectedId:L,videoRefs:xo,onVideoClick:np,onDragEnd:A,onTransformEnd:re,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=xo.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "text":return jsxs(Le__default.Fragment,{children:[jsx(Mu,{texts:[M.element],textRefs:va,onDragEnd:Gm,onTransformEnd:jm,onSelect:Ue,onContextMenu:Dt,onLongPress:yt,onDoubleClick:_m,editingTextId:ve,editingValue:kd,onEditingChange:Td}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=va.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "flashcard":return jsxs(Le__default.Fragment,{children:[jsx(Ji,{flashcards:[M.element],flashcardRefs:bn,selectedId:L,onDragEnd:Xm,onTransform:Ym,onSelect:Ue,onNext:Zm,onPrevious:Jm,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=bn.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "photoFrame":return jsxs(Le__default.Fragment,{children:[jsx(rl,{photoFrames:[M.element],photoFrameRefs:vn,selectedId:L,onDragEnd:Qm,onTransform:ep,onSelect:Ue,onStartCamera:tp,onCapture:ap,cameraStreams:op,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=vn.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "mcq":return jsxs(Le__default.Fragment,{children:[jsx(nc,{handleMcqTransform:we,multipleChoice:[M.element],handleSelect:Ue,mcqRefs:ie,handleDragEnd:ge,onContextMenu:Dt,onLongPress:yt,onUpdate:ne}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=ie.current.get(L);R&&R.visible()&&(q.nodes([R]),q.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"]})]},B);case "trueFalse":return jsxs(Le__default.Fragment,{children:[jsx(dc,{trueFalses:[M.element],handleTrueFalseTransform:lt,handleSelect:Ue,trueFalseRefs:Et,onContextMenu:Dt,onLongPress:yt,handleDragEnd:bt,onUpdate:ne}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=Et.current.get(L);R&&R.visible()&&(q.nodes([R]),q.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"]})]},B);case "shortAnswer":return jsxs(Le__default.Fragment,{children:[jsx(Ec,{shortAnswers:[M.element],handleSelect:Ue,handleTransform:we,saRefs:ze,onContextMenu:Dt,onLongPress:yt,handleDragEnd:oa}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=ze.current.get(L);R&&R.visible()&&(q.nodes([R]),q.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"]})]},B);case "longAnswer":return jsxs(Le__default.Fragment,{children:[jsx(Hc,{longAnswer:[M.element],handleSelect:Ue,handleTransform:we,saRefs:ze,onContextMenu:Dt,onLongPress:yt,handleDragEnd:Qs}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=ze.current.get(L);R&&R.visible()&&(q.nodes([R]),q.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"]})]},B);case "fillInTheBlanks":return jsxs(Le__default.Fragment,{children:[jsx(Oc,{fillInTheBlanks:[M.element],handleSelect:Ue,handleTransform:we,onContextMenu:Dt,onLongPress:yt,handleDragEnd:pn,fibRefs:dt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=dt.current.get(L);R&&R.visible()&&(q.nodes([R]),q.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"]})]},B);default:return null}})})()})]}),V&&jsx(zu,{menuRef:v,x:V.x,y:V.y,type:V.elementType,onAction:lp,onClose:dp,isDrawingMode:V.elementType==="image"?i?.images.find(S=>S.id===V.elementId)?.isDrawingMode:V.elementType==="photoFrame"?i?.photoFrames.find(S=>S.id===V.elementId)?.isDrawingMode:false}),W&&V&&jsx(Uu,{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&&(V.elementType==="image"?i.images.find(S=>S.id===V.elementId)?.locked:i.videos.find(S=>S.id===V.elementId)?.locked)?"Unlock":"Lock",onClick:()=>ai(i&&(V.elementType==="image"?i.images.find(S=>S.id===V.elementId)?.locked:i.videos.find(S=>S.id===V.elementId)?.locked)?"unlock":"lock")}],onClose:()=>te(null)}),G&&jsx(Gu,{title:G.type==="link"?"Add Link":"Add Alt Text",label:G.type==="link"?"URL":"Alternative Text",placeholder:G.type==="link"?"https://example.com":"Describe this image/video",defaultValue:G.defaultValue,onSave:up,onClose:()=>z(null)}),N&&jsx(os,{defaultColor:N.defaultColor,onConfirm:mp,onCancel:()=>_(null)}),Z&&jsx(Xu,{imageSrc:Z.imageSrc,onConfirm:pp,onCancel:()=>ae(null)}),Q&&jsx(Ya,{onClose:()=>pe(false),stageRef:x}),ue&&jsx(Qu,{elementId:ue.elementId,elementType:ue.elementType,existingAudio:ue.existingAudio,onSave:cp,onDelete:fp,onClose:()=>le(null)}),he&&jsx(ac,{selectedElementId:L||void 0,onClose:()=>ce(false),onSelectElement:S=>{Ue(S),ce(false);}}),i?.images.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.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:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),w&&jsx(yc,{editElement:y}),U&&(()=>{let S=ve||L;if(!S)return null;let M=nr.find(D=>D.id===S);return M?jsx(Ic,{text:M,position:U}):null})(),K&&ve&&(()=>{let S=nr.find(M=>M.id===ve);return S?jsx(kc,{text:S,editingValue:kd,onEditingChange:Td,onFinish:ti,position:{top:K.top,left:K.left},scale:K.scale,textareaRef:_e},ve):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:f?.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$1,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),s)]})},Lv=Sv;var Cv="SchooplaVideoStorage";var ea="videos",Ms=()=>new Promise((e,o)=>{let t=indexedDB.open(Cv,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(ea)||n.createObjectStore(ea,{keyPath:"id"});};}),sa=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Ms(),r=a.transaction([ea],"readwrite").objectStore(ea),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 Gc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Ms(),t=e.transaction([ea],"readonly").objectStore(ea);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}},Ol=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Ms(),a=o.transaction([ea],"readwrite").objectStore(ea);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 Ms(),t=e.transaction([ea],"readwrite").objectStore(ea);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 Oa(e,o=[]){let t=[];function a(r,s){let u=Le.createContext(s),i=t.length;t=[...t,s];let c=l=>{let{scope:d,children:f,...h}=l,p=d?.[e]?.[i]||u,y=Le.useMemo(()=>h,Object.values(h));return jsx(p.Provider,{value:y,children:f})};c.displayName=r+"Provider";function m(l,d){let f=d?.[e]?.[i]||u,h=Le.useContext(f);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${l}\` must be used within \`${r}\``)}return [c,m]}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,Tv(n,...o)]}function Tv(...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 l=i(r)[`__scope${c}`];return {...u,...l}},{});return Le.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function $c(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=$c(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():$c(e[n],null);}}}}function Ut(...e){return Le.useCallback(_r(...e),e)}function Zc(e){let o=Mv(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Pv);if(i){let c=i.props.children,m=u.map(l=>l===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:l);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,m):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Mv(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Dv(n),u=Ev(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 Av=Symbol("radix.slottable");function Pv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Av}function Ev(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 Dv(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var Bv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gt=Bv.reduce((e,o)=>{let t=Zc(`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 ot(e,o,{checkForDefaultPrevented:t=true}={}){return function(n){if(e?.(n),t===false||!n.defaultPrevented)return o?.(n)}}function Nl(e){let o=Ov(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Hv);if(i){let c=i.props.children,m=u.map(l=>l===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:l);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,m):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Ov(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Vv(n),u=qv(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 Nv=Symbol("radix.slottable");function Hv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Nv}function qv(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 Vv(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 As(e){let o=e+"CollectionProvider",[t,a]=Oa(o),[n,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=p=>{let{scope:y,children:w}=p,g=Le__default.useRef(null),x=Le__default.useRef(new Map).current;return jsx(n,{scope:y,itemMap:x,collectionRef:g,children:w})};s.displayName=o;let u=e+"CollectionSlot",i=Nl(u),c=Le__default.forwardRef((p,y)=>{let{scope:w,children:g}=p,x=r(u,w),I=Ut(y,x.collectionRef);return jsx(i,{ref:I,children:g})});c.displayName=u;let m=e+"CollectionItemSlot",l="data-radix-collection-item",d=Nl(m),f=Le__default.forwardRef((p,y)=>{let{scope:w,children:g,...x}=p,I=Le__default.useRef(null),L=Ut(y,I),P=r(m,w);return Le__default.useEffect(()=>(P.itemMap.set(I,{ref:I,...x}),()=>void P.itemMap.delete(I))),jsx(d,{[l]:"",ref:L,children:g})});f.displayName=m;function h(p){let y=r(e+"CollectionConsumer",p);return Le__default.useCallback(()=>{let g=y.collectionRef.current;if(!g)return [];let x=Array.from(g.querySelectorAll(`[${l}]`));return Array.from(y.itemMap.values()).sort((P,C)=>x.indexOf(P.ref.current)-x.indexOf(C.ref.current))},[y.collectionRef,y.itemMap])}return [{Provider:s,Slot:c,ItemSlot:f},h,a]}var _o=globalThis?.document?Le.useLayoutEffect:()=>{};var zv=Le[" useId ".trim().toString()]||(()=>{}),Uv=0;function tf(e){let[o,t]=Le.useState(zv());return _o(()=>{t(a=>a??String(Uv++));},[e]),(o?`radix-${o}`:"")}function af(e){let o=Le.useRef(e);return Le.useEffect(()=>{o.current=e;}),Le.useMemo(()=>(...t)=>o.current?.(...t),[])}var Wv=Le[" useInsertionEffect ".trim().toString()]||_o;function la({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[n,r,s]=Kv({defaultProp:o,onChange:t}),u=e!==void 0,i=u?e:n;{let m=Le.useRef(e!==void 0);Le.useEffect(()=>{let l=m.current;l!==u&&console.warn(`${a} is changing from ${l?"controlled":"uncontrolled"} to ${u?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=u;},[u,a]);}let c=Le.useCallback(m=>{if(u){let l=Gv(m)?m(e):m;l!==e&&s.current?.(l);}else r(m);},[u,e,r,s]);return [i,c]}function Kv({defaultProp:e,onChange:o}){let[t,a]=Le.useState(e),n=Le.useRef(t),r=Le.useRef(o);return Wv(()=>{r.current=o;},[o]),Le.useEffect(()=>{n.current!==t&&(r.current?.(t),n.current=t);},[t,n]),[t,a,r]}function Gv(e){return typeof e=="function"}var jv=Le.createContext(void 0);function Xo(e){let o=Le.useContext(jv);return e||o||"ltr"}var Vl="rovingFocusGroup.onEntryFocus",_v={bubbles:false,cancelable:true},$r="RovingFocusGroup",[zl,of,$v]=As($r),[Xv,Ul]=Oa($r,[$v]),[Yv,Zv]=Xv($r),rf=Le.forwardRef((e,o)=>jsx(zl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(zl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Jv,{...e,ref:o})})}));rf.displayName=$r;var Jv=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:n=false,dir:r,currentTabStopId:s,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:i,onEntryFocus:c,preventScrollOnEntryFocus:m=false,...l}=e,d=Le.useRef(null),f=Ut(o,d),h=Xo(r),[p,y]=la({prop:s,defaultProp:u??null,onChange:i,caller:$r}),[w,g]=Le.useState(false),x=af(c),I=of(t),L=Le.useRef(false),[P,C]=Le.useState(0);return Le.useEffect(()=>{let b=d.current;if(b)return b.addEventListener(Vl,x),()=>b.removeEventListener(Vl,x)},[x]),jsx(Yv,{scope:t,orientation:a,dir:h,loop:n,currentTabStopId:p,onItemFocus:Le.useCallback(b=>y(b),[y]),onItemShiftTab:Le.useCallback(()=>g(true),[]),onFocusableItemAdd:Le.useCallback(()=>C(b=>b+1),[]),onFocusableItemRemove:Le.useCallback(()=>C(b=>b-1),[]),children:jsx(gt.div,{tabIndex:w||P===0?-1:0,"data-orientation":a,...l,ref:f,style:{outline:"none",...e.style},onMouseDown:ot(e.onMouseDown,()=>{L.current=true;}),onFocus:ot(e.onFocus,b=>{let v=!L.current;if(b.target===b.currentTarget&&v&&!w){let k=new CustomEvent(Vl,_v);if(b.currentTarget.dispatchEvent(k),!k.defaultPrevented){let T=I().filter(H=>H.focusable),F=T.find(H=>H.active),V=T.find(H=>H.id===p),U=[F,V,...T].filter(Boolean).map(H=>H.ref.current);lf(U,m);}}L.current=false;}),onBlur:ot(e.onBlur,()=>g(false))})})}),nf="RovingFocusGroupItem",sf=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:n=false,tabStopId:r,children:s,...u}=e,i=tf(),c=r||i,m=Zv(nf,t),l=m.currentTabStopId===c,d=of(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:p}=m;return Le.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(zl.ItemSlot,{scope:t,id:c,focusable:a,active:n,children:jsx(gt.span,{tabIndex:l?0:-1,"data-orientation":m.orientation,...u,ref:o,onMouseDown:ot(e.onMouseDown,y=>{a?m.onItemFocus(c):y.preventDefault();}),onFocus:ot(e.onFocus,()=>m.onItemFocus(c)),onKeyDown:ot(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){m.onItemShiftTab();return}if(y.target!==y.currentTarget)return;let w=ty(y,m.orientation,m.dir);if(w!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let x=d().filter(I=>I.focusable).map(I=>I.ref.current);if(w==="last")x.reverse();else if(w==="prev"||w==="next"){w==="prev"&&x.reverse();let I=x.indexOf(y.currentTarget);x=m.loop?ay(x,I+1):x.slice(I+1);}setTimeout(()=>lf(x));}}),children:typeof s=="function"?s({isCurrentTabStop:l,hasTabStop:p!=null}):s})})});sf.displayName=nf;var Qv={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ey(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ty(e,o,t){let a=ey(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Qv[a]}function lf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function ay(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var df=rf,uf=sf;var ff="Toggle",Wl=Le.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:n,...r}=e,[s,u]=la({prop:t,onChange:n,defaultProp:a??false,caller:ff});return jsx(gt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:ot(e.onClick,()=>{e.disabled||u(!s);})})});Wl.displayName=ff;var Na="ToggleGroup",[pf]=Oa(Na,[Ul]),hf=Ul(),Kl=Le__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(ny,{...a,ref:o});if(t==="multiple")return jsx(sy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Na}\``)});Kl.displayName=Na;var[gf,xf]=pf(Na),ny=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=la({prop:t,defaultProp:a??"",onChange:n,caller:Na});return jsx(gf,{scope:e.__scopeToggleGroup,type:"single",value:Le__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:u,onItemDeactivate:Le__default.useCallback(()=>u(""),[u]),children:jsx(bf,{...r,ref:o})})}),sy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=la({prop:t,defaultProp:a??[],onChange:n,caller:Na}),i=Le__default.useCallback(m=>u((l=[])=>[...l,m]),[u]),c=Le__default.useCallback(m=>u((l=[])=>l.filter(d=>d!==m)),[u]);return jsx(gf,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:c,children:jsx(bf,{...r,ref:o})})});Kl.displayName=Na;var[iy,ly]=pf(Na),bf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:n=true,orientation:r,dir:s,loop:u=true,...i}=e,c=hf(t),m=Xo(s),l={role:"group",dir:m,...i};return jsx(iy,{scope:t,rovingFocus:n,disabled:a,children:n?jsx(df,{asChild:true,...c,orientation:r,dir:m,loop:u,children:jsx(gt.div,{...l,ref:o})}):jsx(gt.div,{...l,ref:o})})}),Ds="ToggleGroupItem",dy=Le__default.forwardRef((e,o)=>{let t=xf(Ds,e.__scopeToggleGroup),a=ly(Ds,e.__scopeToggleGroup),n=hf(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(uf,{asChild:true,...n,focusable:!s,active:r,ref:i,children:jsx(mf,{...u,ref:o})}):jsx(mf,{...u,ref:o})});dy.displayName=Ds;var mf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...n}=e,r=xf(Ds,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=r.type==="single"?s:void 0;return jsx(Wl,{...u,...n,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),vf=Kl;function yf(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=yf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Rs(){for(var e,o,t=0,a="",n=arguments.length;t<n;t++)(e=arguments[t])&&(o=yf(e))&&(a&&(a+=" "),a+=o);return a}var cy=(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},fy=(e,o)=>({classGroupId:e,validator:o}),Cf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var wf=[],my="arbitrary..",py=e=>{let o=gy(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return hy(s);let u=s.split("-"),i=u[0]===""&&u.length>1?1:0;return kf(u,i,o)},getConflictingClassGroupIds:(s,u)=>{if(u){let i=a[s],c=t[s];return i?c?cy(c,i):i:c||wf}return t[s]||wf}}},kf=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let n=e[o],r=t.nextPart.get(n);if(r){let c=kf(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 m=s[c];if(m.validator(u))return m.classGroupId}},hy=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?my+a:void 0})(),gy=e=>{let{theme:o,classGroups:t}=e;return xy(t,o)},xy=(e,o)=>{let t=Cf();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];by(s,o,t,a);}},by=(e,o,t,a)=>{if(typeof e=="string"){vy(e,o,t);return}if(typeof e=="function"){yy(e,o,t,a);return}wy(e,o,t,a);},vy=(e,o,t)=>{let a=e===""?o:Tf(o,e);a.classGroupId=t;},yy=(e,o,t,a)=>{if(Sy(e)){_l(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(fy(t,e));},wy=(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,Tf(o,u),t,a);}},Tf=(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=Cf(),t.nextPart.set(s,u)),t=u;}return t},Sy=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Ly=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 Iy=[],Sf=(e,o,t,a,n)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:n}),Cy=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=n=>{let r=[],s=0,u=0,i=0,c,m=n.length;for(let p=0;p<m;p++){let y=n[p];if(s===0&&u===0){if(y===":"){r.push(n.slice(i,p)),i=p+1;continue}if(y==="/"){c=p;continue}}y==="["?s++:y==="]"?s--:y==="("?u++:y===")"&&u--;}let l=r.length===0?n:n.slice(i),d=l,f=false;l.endsWith("!")?(d=l.slice(0,-1),f=true):l.startsWith("!")&&(d=l.slice(1),f=true);let h=c&&c>i?c-i:void 0;return Sf(r,f,d,h)};if(o){let n=o+":",r=a;a=s=>s.startsWith(n)?r(s.slice(n.length)):Sf(Iy,false,s,void 0,true);}if(t){let n=a;a=r=>t({className:r,parseClassName:n});}return a},ky=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}},Ty=e=>({cache:Ly(e.cacheSize),parseClassName:Cy(e),sortModifiers:ky(e),...py(e)}),My=/\s+/,Ay=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:n,sortModifiers:r}=o,s=[],u=e.trim().split(My),i="";for(let c=u.length-1;c>=0;c-=1){let m=u[c],{isExternal:l,modifiers:d,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:p}=t(m);if(l){i=m+(i.length>0?" "+i:i);continue}let y=!!p,w=a(y?h.substring(0,p):h);if(!w){if(!y){i=m+(i.length>0?" "+i:i);continue}if(w=a(h),!w){i=m+(i.length>0?" "+i:i);continue}y=false;}let g=d.length===0?"":d.length===1?d[0]:r(d).join(":"),x=f?g+"!":g,I=x+w;if(s.indexOf(I)>-1)continue;s.push(I);let L=n(w,y);for(let P=0;P<L.length;++P){let C=L[P];s.push(x+C);}i=m+(i.length>0?" "+i:i);}return i},Py=(...e)=>{let o=0,t,a,n="";for(;o<e.length;)(t=e[o++])&&(a=Mf(t))&&(n&&(n+=" "),n+=a);return n},Mf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Mf(e[a]))&&(t&&(t+=" "),t+=o);return t},Ey=(e,...o)=>{let t,a,n,r,s=i=>{let c=o.reduce((m,l)=>l(m),e());return t=Ty(c),a=t.cache.get,n=t.cache.set,r=u,u(i)},u=i=>{let c=a(i);if(c)return c;let m=Ay(i,t);return n(i,m),m};return r=s,(...i)=>r(Py(...i))},Dy=[],je=e=>{let o=t=>t[e]||Dy;return o.isThemeGetter=true,o},Af=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Pf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Ry=/^\d+\/\d+$/,Fy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,By=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Oy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Ny=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Hy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Yo=e=>Ry.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ha=e=>!!e&&Number.isInteger(Number(e)),Gl=e=>e.endsWith("%")&&de(e.slice(0,-1)),da=e=>Fy.test(e),qy=()=>true,Vy=e=>By.test(e)&&!Oy.test(e),Ef=()=>false,zy=e=>Ny.test(e),Uy=e=>Hy.test(e),Wy=e=>!X(e)&&!Y(e),Ky=e=>Zo(e,Ff,Ef),X=e=>Af.test(e),fo=e=>Zo(e,Bf,Vy),jl=e=>Zo(e,Xy,de),Lf=e=>Zo(e,Df,Ef),Gy=e=>Zo(e,Rf,Uy),Fs=e=>Zo(e,Of,zy),Y=e=>Pf.test(e),Xr=e=>Jo(e,Bf),jy=e=>Jo(e,Yy),If=e=>Jo(e,Df),_y=e=>Jo(e,Ff),$y=e=>Jo(e,Rf),Bs=e=>Jo(e,Of,true),Zo=(e,o,t)=>{let a=Af.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Jo=(e,o,t=false)=>{let a=Pf.exec(e);return a?a[1]?o(a[1]):t:false},Df=e=>e==="position"||e==="percentage",Rf=e=>e==="image"||e==="url",Ff=e=>e==="length"||e==="size"||e==="bg-size",Bf=e=>e==="length",Xy=e=>e==="number",Yy=e=>e==="family-name",Of=e=>e==="shadow";var Zy=()=>{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"),m=je("shadow"),l=je("inset-shadow"),d=je("text-shadow"),f=je("drop-shadow"),h=je("blur"),p=je("perspective"),y=je("aspect"),w=je("ease"),g=je("animate"),x=()=>["auto","avoid","all","avoid-page","page","left","right","column"],I=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],L=()=>[...I(),Y,X],P=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],b=()=>[Y,X,i],v=()=>[Yo,"full","auto",...b()],k=()=>[Ha,"none","subgrid",Y,X],T=()=>["auto",{span:["full",Ha,Y,X]},Ha,Y,X],F=()=>[Ha,"auto",Y,X],V=()=>["auto","min","max","fr",Y,X],O=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],H=()=>["auto",...b()],K=()=>[Yo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],E=()=>[e,Y,X],W=()=>[...I(),If,Lf,{position:[Y,X]}],te=()=>["no-repeat",{repeat:["","x","y","space","round"]}],G=()=>["auto","cover","contain",_y,Ky,{size:[Y,X]}],z=()=>[Gl,Xr,fo],N=()=>["","none","full",c,Y,X],_=()=>["",de,Xr,fo],Z=()=>["solid","dashed","dotted","double"],ae=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Q=()=>[de,Gl,If,Lf],pe=()=>["","none",h,Y,X],ue=()=>["none",de,Y,X],le=()=>["none",de,Y,X],he=()=>[de,Y,X],ce=()=>[Yo,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[da],breakpoint:[da],color:[qy],container:[da],"drop-shadow":[da],ease:["in","out","in-out"],font:[Wy],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[da],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[da],shadow:[da],spacing:["px",de],text:[da],"text-shadow":[da],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Yo,X,Y,y]}],container:["container"],columns:[{columns:[de,X,Y,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:L()}],overflow:[{overflow:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:v()}],"inset-x":[{"inset-x":v()}],"inset-y":[{"inset-y":v()}],start:[{start:v()}],end:[{end:v()}],top:[{top:v()}],right:[{right:v()}],bottom:[{bottom:v()}],left:[{left:v()}],visibility:["visible","invisible","collapse"],z:[{z:[Ha,"auto",Y,X]}],basis:[{basis:[Yo,"full","auto",u,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Yo,"auto","initial","none",X]}],grow:[{grow:["",de,Y,X]}],shrink:[{shrink:["",de,Y,X]}],order:[{order:[Ha,"first","last","none",Y,X]}],"grid-cols":[{"grid-cols":k()}],"col-start-end":[{col:T()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":k()}],"row-start-end":[{row:T()}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":V()}],"auto-rows":[{"auto-rows":V()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...O(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...O()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":O()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:H()}],mx:[{mx:H()}],my:[{my:H()}],ms:[{ms:H()}],me:[{me:H()}],mt:[{mt:H()}],mr:[{mr:H()}],mb:[{mb:H()}],ml:[{ml:H()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"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,Xr,fo]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,Y,jl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Gl,X]}],"font-family":[{font:[jy,X,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[n,Y,X]}],"line-clamp":[{"line-clamp":[de,"none",Y,jl]}],leading:[{leading:[r,...b()]}],"list-image":[{"list-image":["none",Y,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Y,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:E()}],"text-color":[{text:E()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Z(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",Y,fo]}],"text-decoration-color":[{decoration:E()}],"underline-offset":[{"underline-offset":[de,"auto",Y,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Y,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Y,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:W()}],"bg-repeat":[{bg:te()}],"bg-size":[{bg:G()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ha,Y,X],radial:["",Y,X],conic:[Ha,Y,X]},$y,Gy]}],"bg-color":[{bg:E()}],"gradient-from-pos":[{from:z()}],"gradient-via-pos":[{via:z()}],"gradient-to-pos":[{to:z()}],"gradient-from":[{from:E()}],"gradient-via":[{via:E()}],"gradient-to":[{to:E()}],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:[...Z(),"hidden","none"]}],"divide-style":[{divide:[...Z(),"hidden","none"]}],"border-color":[{border:E()}],"border-color-x":[{"border-x":E()}],"border-color-y":[{"border-y":E()}],"border-color-s":[{"border-s":E()}],"border-color-e":[{"border-e":E()}],"border-color-t":[{"border-t":E()}],"border-color-r":[{"border-r":E()}],"border-color-b":[{"border-b":E()}],"border-color-l":[{"border-l":E()}],"divide-color":[{divide:E()}],"outline-style":[{outline:[...Z(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,Y,X]}],"outline-w":[{outline:["",de,Xr,fo]}],"outline-color":[{outline:E()}],shadow:[{shadow:["","none",m,Bs,Fs]}],"shadow-color":[{shadow:E()}],"inset-shadow":[{"inset-shadow":["none",l,Bs,Fs]}],"inset-shadow-color":[{"inset-shadow":E()}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:E()}],"ring-offset-w":[{"ring-offset":[de,fo]}],"ring-offset-color":[{"ring-offset":E()}],"inset-ring-w":[{"inset-ring":_()}],"inset-ring-color":[{"inset-ring":E()}],"text-shadow":[{"text-shadow":["none",d,Bs,Fs]}],"text-shadow-color":[{"text-shadow":E()}],opacity:[{opacity:[de,Y,X]}],"mix-blend":[{"mix-blend":[...ae(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ae()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":Q()}],"mask-image-linear-to-pos":[{"mask-linear-to":Q()}],"mask-image-linear-from-color":[{"mask-linear-from":E()}],"mask-image-linear-to-color":[{"mask-linear-to":E()}],"mask-image-t-from-pos":[{"mask-t-from":Q()}],"mask-image-t-to-pos":[{"mask-t-to":Q()}],"mask-image-t-from-color":[{"mask-t-from":E()}],"mask-image-t-to-color":[{"mask-t-to":E()}],"mask-image-r-from-pos":[{"mask-r-from":Q()}],"mask-image-r-to-pos":[{"mask-r-to":Q()}],"mask-image-r-from-color":[{"mask-r-from":E()}],"mask-image-r-to-color":[{"mask-r-to":E()}],"mask-image-b-from-pos":[{"mask-b-from":Q()}],"mask-image-b-to-pos":[{"mask-b-to":Q()}],"mask-image-b-from-color":[{"mask-b-from":E()}],"mask-image-b-to-color":[{"mask-b-to":E()}],"mask-image-l-from-pos":[{"mask-l-from":Q()}],"mask-image-l-to-pos":[{"mask-l-to":Q()}],"mask-image-l-from-color":[{"mask-l-from":E()}],"mask-image-l-to-color":[{"mask-l-to":E()}],"mask-image-x-from-pos":[{"mask-x-from":Q()}],"mask-image-x-to-pos":[{"mask-x-to":Q()}],"mask-image-x-from-color":[{"mask-x-from":E()}],"mask-image-x-to-color":[{"mask-x-to":E()}],"mask-image-y-from-pos":[{"mask-y-from":Q()}],"mask-image-y-to-pos":[{"mask-y-to":Q()}],"mask-image-y-from-color":[{"mask-y-from":E()}],"mask-image-y-to-color":[{"mask-y-to":E()}],"mask-image-radial":[{"mask-radial":[Y,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":Q()}],"mask-image-radial-to-pos":[{"mask-radial-to":Q()}],"mask-image-radial-from-color":[{"mask-radial-from":E()}],"mask-image-radial-to-color":[{"mask-radial-to":E()}],"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":I()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":Q()}],"mask-image-conic-to-pos":[{"mask-conic-to":Q()}],"mask-image-conic-from-color":[{"mask-conic-from":E()}],"mask-image-conic-to-color":[{"mask-conic-to":E()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:W()}],"mask-repeat":[{mask:te()}],"mask-size":[{mask:G()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Y,X]}],filter:[{filter:["","none",Y,X]}],blur:[{blur:pe()}],brightness:[{brightness:[de,Y,X]}],contrast:[{contrast:[de,Y,X]}],"drop-shadow":[{"drop-shadow":["","none",f,Bs,Fs]}],"drop-shadow-color":[{"drop-shadow":E()}],grayscale:[{grayscale:["",de,Y,X]}],"hue-rotate":[{"hue-rotate":[de,Y,X]}],invert:[{invert:["",de,Y,X]}],saturate:[{saturate:[de,Y,X]}],sepia:[{sepia:["",de,Y,X]}],"backdrop-filter":[{"backdrop-filter":["","none",Y,X]}],"backdrop-blur":[{"backdrop-blur":pe()}],"backdrop-brightness":[{"backdrop-brightness":[de,Y,X]}],"backdrop-contrast":[{"backdrop-contrast":[de,Y,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,Y,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,Y,X]}],"backdrop-invert":[{"backdrop-invert":["",de,Y,X]}],"backdrop-opacity":[{"backdrop-opacity":[de,Y,X]}],"backdrop-saturate":[{"backdrop-saturate":[de,Y,X]}],"backdrop-sepia":[{"backdrop-sepia":["",de,Y,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Y,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",Y,X]}],ease:[{ease:["linear","initial",w,Y,X]}],delay:[{delay:[de,Y,X]}],animate:[{animate:["none",g,Y,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,Y,X]}],"perspective-origin":[{"perspective-origin":L()}],rotate:[{rotate:ue()}],"rotate-x":[{"rotate-x":ue()}],"rotate-y":[{"rotate-y":ue()}],"rotate-z":[{"rotate-z":ue()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":["scale-3d"],skew:[{skew:he()}],"skew-x":[{"skew-x":he()}],"skew-y":[{"skew-y":he()}],transform:[{transform:[Y,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:L()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ce()}],"translate-x":[{"translate-x":ce()}],"translate-y":[{"translate-y":ce()}],"translate-z":[{"translate-z":ce()}],"translate-none":["translate-none"],accent:[{accent:E()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:E()}],"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",Y,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Y,X]}],fill:[{fill:["none",...E()]}],"stroke-w":[{stroke:[de,Xr,fo,jl]}],stroke:[{stroke:["none",...E()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var Nf=Ey(Zy);function qa(...e){return Nf(Rs(e))}var Qy=Le.createContext({size:"default",variant:"default",spacing:0});function Va({className:e,variant:o,size:t,spacing:a=1,children:n,...r}){return jsx(vf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:qa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Qy.Provider,{value:{variant:o,size:t,spacing:a},children:n})})}var tw={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Uf=createSlice({name:"toolbar",initialState:tw,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:ta,setPenColor:ua,setStrokeWidth:Yr,setFontSize:qD,setFontFamily:VD,setFontStyle:zD,setFontWeight:UD,setTextDecoration:WD,setTextColor:KD}=Uf.actions,Xl=Uf.reducer;var Os=({onClose:e,onRecordingComplete:o})=>{let t=Ve(),[a,n]=useState(false),[r,s]=useState(null),[u,i]=useState(0),[c,m]=useState(null),[l,d]=useState(false),f=useRef(null),h=useRef([]),p=useRef(null),y=useRef(null),w=useRef(null);useEffect(()=>((async()=>{try{let v=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(v),d(!0),w.current&&(w.current.srcObject=v);}catch(v){console.error("Error accessing camera:",v),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),c&&c.getTracks().forEach(v=>v.stop());}),[]);let g=()=>{c&&(c.getTracks().forEach(b=>b.stop()),m(null),d(false));},x=async()=>{try{let b=null,v=null;try{b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(O){console.error("Error accessing camera for recording:",O),alert("Failed to access camera for recording.");return}try{v=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(O){console.warn("Microphone access denied:",O);}let k=[...b.getVideoTracks()];v&&k.push(...v.getAudioTracks());let T=new MediaStream(k),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");let V=new MediaRecorder(T,{mimeType:F,videoBitsPerSecond:25e5});f.current=V,h.current=[],V.ondataavailable=O=>{O.data.size>0&&h.current.push(O.data);},V.onstop=()=>{let O=new Blob(h.current,{type:F}),U=document.createElement("video");U.src=URL.createObjectURL(O),U.muted=!0,U.currentTime=.1,U.onseeked=()=>{let H=document.createElement("canvas");H.width=U.videoWidth,H.height=U.videoHeight;let K=H.getContext("2d");K&&(K.drawImage(U,0,0),y.current=H.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(U.src);},T.getTracks().forEach(H=>H.stop()),b&&b.getTracks().forEach(H=>H.stop()),v&&v.getTracks().forEach(H=>H.stop()),p.current&&clearInterval(p.current),s(O),g();},V.onerror=O=>{console.error("MediaRecorder error:",O);},V.start(1e3),n(!0),i(0),p.current=setInterval(()=>{i(O=>O+1);},1e3);}catch(b){console.error("Error starting camera recording:",b),alert("Failed to start recording. Please check permissions.");}},I=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),n(false));},L=()=>{if(r){let b=URL.createObjectURL(r),v=document.createElement("a");v.href=b,v.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(v),v.click(),document.body.removeChild(v),URL.revokeObjectURL(b);}},P=b=>{let v=Math.floor(b/60),k=b%60;return `${v.toString().padStart(2,"0")}:${k.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$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:w,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:!l,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"})})}),!l&&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:I,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:P(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: ",P(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:L,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&y.current&&(o(r,y.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(C,t)};var ca=40,Kf=({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),m=Ve(),l=useRef(null);useEffect(()=>{let x=I=>{I.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let d=x=>{let I=x.target.files;if(!I||I.length===0)return;let L=ca-a.length;if(L<=0){alert(`You can only upload a maximum of ${ca} images`);return}let P=Array.from(I).slice(0,L);P.length<I.length&&alert(`Only ${L} more images can be added (max ${ca} total)`);let C=P.map(b=>new Promise((v,k)=>{let T=new FileReader;T.onload=F=>{F.target?.result?v(F.target.result):k(new Error("Failed to read file"));},T.onerror=k,T.readAsDataURL(b);}));Promise.all(C).then(b=>{n(v=>[...v,...b]),l.current&&(l.current.value="");});},f=x=>{x.preventDefault(),i(false);let I=Array.from(x.dataTransfer.files).filter(b=>b.type.startsWith("image/"));if(I.length===0)return;let L=ca-a.length;if(L<=0){alert(`You can only upload a maximum of ${ca} images`);return}let P=I.slice(0,L);P.length<I.length&&alert(`Only ${L} more images can be added (max ${ca} total)`);let C=P.map(b=>new Promise((v,k)=>{let T=new FileReader;T.onload=F=>{F.target?.result?v(F.target.result):k(new Error("Failed to read file"));},T.onerror=k,T.readAsDataURL(b);}));Promise.all(C).then(b=>{n(v=>[...v,...b]);});},h=x=>{x.preventDefault(),i(true);},p=()=>{i(false);},y=x=>{n(I=>I.filter((L,P)=>P!==x));},w=x=>{if(x.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!m)return null;let g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:w,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>=ca?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ca," images"]}):jsxs("span",{children:[a.length,"/",ca," images"]})})]}),jsx("input",{ref:l,type:"file",accept:"image/*",multiple:true,onChange:d,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:f,onDragOver:h,onDragLeave:p,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>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,I)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${I+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>y(I),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:I+1})]},I))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(g,m)};var Ns={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},xw={enabled:true};function Jl(e){return e?{tools:{...Ns.tools,...e.tools},actions:{...Ns.actions,...e.actions}}:Ns}var bw={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},vw={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 Ql(e,[o,t]){return Math.min(t,Math.max(o,e))}function Gf(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 _f(e){let[o,t]=Le.useState(void 0);return _o(()=>{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 $f=["PageUp","PageDown"],Xf=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Yf={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Qo="Slider",[ed,ww,Sw]=As(Qo),[Zf]=Oa(Qo,[Sw]),[Lw,qs]=Zf(Qo),Jf=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:m,onValueChange:l=()=>{},onValueCommit:d=()=>{},inverted:f=false,form:h,...p}=e,y=Le.useRef(new Set),w=Le.useRef(0),x=s==="horizontal"?Iw:Cw,[I=[],L]=la({prop:m,defaultProp:c,onChange:T=>{[...y.current][w.current]?.focus(),l(T);}}),P=Le.useRef(I);function C(T){let F=Pw(I,T);k(T,F);}function b(T){k(T,w.current);}function v(){let T=P.current[w.current];I[w.current]!==T&&d(I);}function k(T,F,{commit:V}={commit:false}){let O=Fw(r),U=Bw(Math.round((T-a)/r)*r+a,O),H=Ql(U,[a,n]);L((K=[])=>{let E=Mw(K,H,F);if(Rw(E,i*r)){w.current=E.indexOf(H);let W=String(E)!==String(K);return W&&V&&d(E),W?E:K}else return K});}return jsx(Lw,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:n,valueIndexToChangeRef:w,thumbs:y.current,values:I,orientation:s,form:h,children:jsx(ed.Provider,{scope:e.__scopeSlider,children:jsx(ed.Slot,{scope:e.__scopeSlider,children:jsx(x,{"aria-disabled":u,"data-disabled":u?"":void 0,...p,ref:o,onPointerDown:ot(p.onPointerDown,()=>{u||(P.current=I);}),min:a,max:n,inverted:f,onSlideStart:u?void 0:C,onSlideMove:u?void 0:b,onSlideEnd:u?void 0:v,onHomeKeyDown:()=>!u&&k(a,0,{commit:true}),onEndKeyDown:()=>!u&&k(n,I.length-1,{commit:true}),onStepKeyDown:({event:T,direction:F})=>{if(!u){let U=$f.includes(T.key)||T.shiftKey&&Xf.includes(T.key)?10:1,H=w.current,K=I[H],E=r*U*F;k(K+E,H,{commit:true});}}})})})})});Jf.displayName=Qo;var[Qf,em]=Zf(Qo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Iw=Le.forwardRef((e,o)=>{let{min:t,max:a,dir:n,inverted:r,onSlideStart:s,onSlideMove:u,onSlideEnd:i,onStepKeyDown:c,...m}=e,[l,d]=Le.useState(null),f=Ut(o,x=>d(x)),h=Le.useRef(void 0),p=Xo(n),y=p==="ltr",w=y&&!r||!y&&r;function g(x){let I=h.current||l.getBoundingClientRect(),L=[0,I.width],C=od(L,w?[t,a]:[a,t]);return h.current=I,C(x-I.left)}return jsx(Qf,{scope:e.__scopeSlider,startEdge:w?"left":"right",endEdge:w?"right":"left",direction:w?1:-1,size:"width",children:jsx(tm,{dir:p,"data-orientation":"horizontal",...m,ref:f,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:x=>{let I=g(x.clientX);s?.(I);},onSlideMove:x=>{let I=g(x.clientX);u?.(I);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:x=>{let L=Yf[w?"from-left":"from-right"].includes(x.key);c?.({event:x,direction:L?-1:1});}})})}),Cw=Le.forwardRef((e,o)=>{let{min:t,max:a,inverted:n,onSlideStart:r,onSlideMove:s,onSlideEnd:u,onStepKeyDown:i,...c}=e,m=Le.useRef(null),l=Ut(o,m),d=Le.useRef(void 0),f=!n;function h(p){let y=d.current||m.current.getBoundingClientRect(),w=[0,y.height],x=od(w,f?[a,t]:[t,a]);return d.current=y,x(p-y.top)}return jsx(Qf,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(tm,{"data-orientation":"vertical",...c,ref:l,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:p=>{let y=h(p.clientY);r?.(y);},onSlideMove:p=>{let y=h(p.clientY);s?.(y);},onSlideEnd:()=>{d.current=void 0,u?.();},onStepKeyDown:p=>{let w=Yf[f?"from-bottom":"from-top"].includes(p.key);i?.({event:p,direction:w?-1:1});}})})}),tm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:n,onSlideEnd:r,onHomeKeyDown:s,onEndKeyDown:u,onStepKeyDown:i,...c}=e,m=qs(Qo,t);return jsx(gt.span,{...c,ref:o,onKeyDown:ot(e.onKeyDown,l=>{l.key==="Home"?(s(l),l.preventDefault()):l.key==="End"?(u(l),l.preventDefault()):$f.concat(Xf).includes(l.key)&&(i(l),l.preventDefault());}),onPointerDown:ot(e.onPointerDown,l=>{let d=l.target;d.setPointerCapture(l.pointerId),l.preventDefault(),m.thumbs.has(d)?d.focus():a(l);}),onPointerMove:ot(e.onPointerMove,l=>{l.target.hasPointerCapture(l.pointerId)&&n(l);}),onPointerUp:ot(e.onPointerUp,l=>{let d=l.target;d.hasPointerCapture(l.pointerId)&&(d.releasePointerCapture(l.pointerId),r(l));})})}),am="SliderTrack",om=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=qs(am,t);return jsx(gt.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...a,ref:o})});om.displayName=am;var td="SliderRange",rm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=qs(td,t),r=em(td,t),s=Le.useRef(null),u=Ut(o,s),i=n.values.length,c=n.values.map(d=>im(d,n.min,n.max)),m=i>1?Math.min(...c):0,l=100-Math.max(...c);return jsx(gt.span,{"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,...a,ref:u,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:l+"%"}})});rm.displayName=td;var ad="SliderThumb",nm=Le.forwardRef((e,o)=>{let t=ww(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(kw,{...e,ref:r,index:s})}),kw=Le.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:n,...r}=e,s=qs(ad,t),u=em(ad,t),[i,c]=Le.useState(null),m=Ut(o,g=>c(g)),l=i?s.form||!!i.closest("form"):true,d=_f(i),f=s.values[a],h=f===void 0?0:im(f,s.min,s.max),p=Aw(a,s.values.length),y=d?.[u.size],w=y?Ew(y,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}% + ${w}px)`},children:[jsx(ed.ItemSlot,{scope:e.__scopeSlider,children:jsx(gt.span,{role:"slider","aria-label":e["aria-label"]||p,"aria-valuemin":s.min,"aria-valuenow":f,"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:m,style:f===void 0?{display:"none"}:e.style,onFocus:ot(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),l&&jsx(sm,{name:n??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:f},a)]})});nm.displayName=ad;var Tw="RadioBubbleInput",sm=Le.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let n=Le.useRef(null),r=Ut(n,a),s=Gf(o);return Le.useEffect(()=>{let u=n.current;if(!u)return;let i=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==o&&m){let l=new Event("input",{bubbles:true});m.call(u,o),u.dispatchEvent(l);}},[s,o]),jsx(gt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});sm.displayName=Tw;function Mw(e=[],o,t){let a=[...e];return a[t]=o,a.sort((n,r)=>n-r)}function im(e,o,t){let r=100/(t-o)*(e-o);return Ql(r,[0,100])}function Aw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Pw(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 Ew(e,o,t){let a=e/2,r=od([0,50],[0,a]);return (a-r(o)*t)*t}function Dw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Rw(e,o){if(o>0){let t=Dw(e);return Math.min(...t)>=o}return true}function od(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 Fw(e){return (String(e).split(".")[1]||"").length}function Bw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var lm=Jf,dm=om,um=rm,cm=nm;function Vs({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(lm,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:n,className:qa("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(dm,{"data-slot":"slider-track",className:qa("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(um,{"data-slot":"slider-range",className:qa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(m,l)=>jsx(cm,{"data-slot":"slider-thumb",className:qa("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)},l))]})}var dS=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a,onVisibilityChange:n}={})=>{let r=Se(),s=J(A=>A.canvas.slides.find(re=>re.id===A.canvas.currentSlideId)),u=s?.videos||[],i=s?.editingFlashcard,c=J(A=>A.toolbar.selectedTool),m=J(A=>A.toolbar.penColor),l=J(A=>A.toolbar.strokeWidth),d=J(A=>A.canvas.editingOverlayPosition),f=s?.showMcqForm,h=s?.showFlashcardForm,p=useRef(null);useEffect(()=>{let A=re=>{(re.ctrlKey||re.metaKey)&&re.key==="z"&&!re.shiftKey&&(re.preventDefault(),r(Io())),(re.ctrlKey&&re.shiftKey&&re.key==="Z"||re.ctrlKey&&re.key==="y")&&(re.preventDefault(),r(Co()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[r]);let y=useMemo(()=>Jl(a),[a]),{tools:w,actions:g}=y,x=u.some(A=>A.isRecorded&&A.isPlaying),I=J(A=>A.toolbar.fontSize),L=J(A=>A.toolbar.fontFamily),P=J(A=>A.toolbar.fontStyle),C=J(A=>A.toolbar.fontWeight),b=J(A=>A.toolbar.textDecoration),v=J(A=>A.toolbar.textColor),[k,T]=useState(false),[F,V]=useState(false),[O,U]=useState(false),[H,K]=useState(false),[E,W]=useState(false),[te,G]=useState(false),[z,N]=useState(false),[_,Z]=useState(false),[ae,Q]=useState(true),pe=useRef(null),ue=useRef(null),le=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],he=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"}],[]),ce=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),_e=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),or=useMemo(()=>he.filter(A=>{let re=w[A.configKey];return typeof re=="boolean"?re:Array.isArray(re)?re.length>0:true}),[w,he]),ga=useMemo(()=>{let A=w.shapes;return A===false?[]:A===true?ce:Array.isArray(A)?ce.filter(re=>A.includes(re.name)):ce},[w.shapes,ce]),on=useMemo(()=>{let A=w.activities;return A===false?[]:A===true?_e:Array.isArray(A)?_e.filter(re=>A.includes(re.name)):_e},[w.activities,_e]),ne=useMemo(()=>{let A=w.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}},[w.media]),rn=useMemo(()=>{let A=w.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[w.activities]),nn=A=>{let re=A.target.files;!re||re.length===0||(r(ta("select")),r(wt(false)),K(false),Array.from(re).forEach(Ae=>{let we=new FileReader;we.onload=ie=>{let ge=new window.Image;ge.src=ie.target?.result,ge.onload=()=>{let He=ge.width/ge.height,lt=300,Et=300,bt=ge.width,Fe=ge.height;bt>lt&&(bt=lt,Fe=bt/He),Fe>Et&&(Fe=Et,bt=Fe*He),r(fe());let ze=d?.left||800-bt/2,oa=d?.top||450-Fe/2;r(di({id:v4(),src:ge.src,x:ze,y:oa,width:bt,height:Fe,draggable:true,rotation:0}));};},we.readAsDataURL(Ae);}),A.target.value="");},sn=async A=>{let re=A.target.files;if(!(!re||re.length===0)){console.log("files",A),r(ta("select")),r(wt(false)),K(false);for(let Ae of Array.from(re))try{let we=URL.createObjectURL(Ae),ie=document.createElement("video");console.log("video",ie),ie.src=we,ie.muted=!0,ie.playsInline=!0,ie.preload="auto",ie.load(),await new Promise((dt,se)=>{let vt=setTimeout(()=>se(new Error("Metadata load timeout")),1e4);ie.onloadedmetadata=()=>{clearTimeout(vt),dt();},ie.onerror=()=>{clearTimeout(vt),se(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ie.duration,width:ie.videoWidth,height:ie.videoHeight}),await new Promise((dt,se)=>{let vt=setTimeout(()=>se(new Error("Video load timeout")),1e4);ie.readyState>=2?(clearTimeout(vt),dt()):ie.onloadeddata=()=>{clearTimeout(vt),dt();};});let ge=Math.min(.8,ie.duration/2);console.log("Seeking to:",ge),ie.currentTime=ge,await new Promise(dt=>{let se=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),dt();},5e3);ie.onseeked=()=>{clearTimeout(se),console.log("Seek completed"),dt();};});let He=document.createElement("canvas"),lt=ie.videoWidth/ie.videoHeight,Et=400,bt=400,Fe=ie.videoWidth,ze=ie.videoHeight;Fe>Et&&(Fe=Et,ze=Fe/lt),ze>bt&&(ze=bt,Fe=ze*lt),He.width=Fe,He.height=ze;let oa=He.getContext("2d",{willReadFrequently:!1});if(!oa)throw new Error("Failed to get canvas context");if(await new Promise(dt=>setTimeout(dt,100)),ie.videoWidth===0||ie.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Fe,height:ze}),oa.drawImage(ie,0,0,Fe,ze);let ba=He.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",ba.length),r(fe());let Qs=800-Fe/2,ei=450-ze/2,pn=v4();await sa(pn,Ae,ba),r(wo({id:pn,objectUrl:we,thumbnailDataUrl:ba,videoBlob:Ae,x:Qs,y:ei,width:Fe,height:ze,draggable:!0,isPlaying:!1,rotation:0})),ie.src="",ie.load(),console.log(`Video uploaded: ${Ae.name}`);}catch(we){console.error("Error processing video:",we),alert(`Failed to process video: ${Ae.name}`);}A.target.value="";}},ln=(A,re,Ae)=>{r(fe()),r(ta("select")),r(wt(false));let we=300,ie=300,ge=800-we/2,He=450-ie/2;r(Ae?Lo({id:Ae,images:A,order:re,x:ge,y:He,width:we,height:ie,rotation:0,draggable:true}):fi({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:re,x:ge,y:He,width:we,height:ie,rotation:0,draggable:true})),r(Xa(false));},dn=()=>{r(fe()),r(ta("select")),r(wt(false));let A=400,re=300,Ae=800-A/2,we=450-re/2;r(hi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ae,y:we,width:A,height:re,rotation:0,draggable:true,isCapturing:false})),K(false);},un=A=>{let ge={};switch(A.name){case "circle":case "ring":case "wedge":case "arc":ge.radius=50,(A.name==="ring"||A.name==="arc")&&(ge.innerRadius=25,ge.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(ge.angle=A.name==="wedge"?60:90);break;case "ellipse":ge.radiusX=60,ge.radiusY=40;break;case "triangle":ge.radius=50,ge.sides=3;break;case "polygon":ge.radius=50,ge.sides=6;break;case "star":ge.innerRadius=25,ge.outerRadius=50,ge.numPoints=5;break;case "arrow":case "line":ge.points=[0,0,100,0],A.name==="arrow"&&(ge.pointerLength=10,ge.pointerWidth=10);break}let He={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:m,...ge};r(fe()),r(wt(false)),r(ta(A.name)),r(ui(He)),U(false);},Wa=A=>{if(r(ta(A)),A==="select")r(wt(false));else if(A==="text"){r(wt(false)),r(fe());let re=200,Ae=50,we=800-re/2,ie=450-Ae/2,He=window.innerWidth<768?Math.max(I,32):I,lt=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(ci({id:lt,text:"",x:we,y:ie,width:re,height:Ae,rotation:0,draggable:true,fontSize:He,fontFamily:L,fontStyle:P,fontWeight:C,textDecoration:b,fill:v,align:"left"})),setTimeout(()=>{r(gr(lt));},100),t&&t(lt);}else r(wt(true));},_s=()=>{r(hr()),r(wt(false));},$s=()=>{e?e():o?T(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Xs=()=>{V(true);},Ys=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:dn,enabled:ne.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>pe.current?.click(),enabled:ne.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>ue.current?.click(),enabled:ne.video}],xa=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Io()),enabled:g.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(Co()),enabled:g.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:$s,enabled:g.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:Xs,enabled:g.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:_s,enabled:g.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],cn=async(A,re)=>{try{r(ta("select")),r(wt(!1));let Ae=URL.createObjectURL(A),we=document.createElement("video");we.src=Ae,we.muted=!0,we.playsInline=!0,we.preload="auto",await new Promise((ze,oa)=>{let ba=setTimeout(()=>oa(new Error("Metadata load timeout")),1e4);we.onloadedmetadata=()=>{clearTimeout(ba),ze();},we.onerror=()=>{clearTimeout(ba),oa(new Error("Failed to load video"));};});let ie=640,ge=we.videoWidth/we.videoHeight,He=ie,lt=He/ge;r(fe());let Et=800-He/2,bt=450-lt/2,Fe=v4();await sa(Fe,A,re),r(wo({id:Fe,objectUrl:Ae,thumbnailDataUrl:re,videoBlob:A,x:Et,y:bt,width:He,height:lt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),T(!1),V(!1);}catch(Ae){console.error("Error adding recorded video to canvas:",Ae),alert("Failed to add video to canvas. Please try again.");}},Zs=A=>{r(ta("select")),r(wt(false)),r(mr(null)),A&&r(ki(A)),r(wa(!f)),W(false);},go=()=>{r(fr(null)),r(Xa(true)),W(false);},fn=()=>{U(!O);},Js=()=>{K(!H);},rr=()=>{W(!E);},xo=()=>{G(!te);},mn=()=>{let A=!ae;A||(U(false),K(false),W(false),G(false),Z(false),N(false)),Q(A),n?.(A);};return useEffect(()=>{if(!_)return;let A=re=>{p.current&&!p.current.contains(re.target)&&Z(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[_]),x?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:mn,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:ae?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),ae&&jsxs("div",{className:"fixed top-[168px] left-4 z-50 flex flex-col gap-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(Va,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:or.map((A,re)=>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"?(Js(),U(false),W(false),G(false),Wa(A.name)):A.name==="shapes"?(fn(),K(false),W(false),G(false),Wa(A.name)):A.name==="activities"?(Wa(A.name),rr(),U(false),K(false),G(false)):A.name==="style"?(xo(),U(false),K(false),W(false),Wa(A.name)):(Wa(A.name),U(false),K(false),W(false),G(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},re))}),O&&jsx(Va,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:ga.map((A,re)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>un(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},re))}),H&&jsx(Va,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:Ys.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),E&&jsxs(Va,{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:()=>go(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),on.map((A,re)=>jsx("div",{title:A.label,onClick:()=>Zs(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},re))]}),te&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Vs,{value:[l],onValueChange:A=>{r(Yr(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 ${m===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{r(ua(A.value)),G(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:m,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>r(ua(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:m,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{r(cr(A.target.value)),G(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),xa.some(A=>A.enabled)&&jsx(Va,{type:"single",className:"hidden flex-col border bg-white p-1 shadow-xl md:flex",children:xa.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:nn}),jsx("input",{ref:ue,type:"file",accept:"video/*",className:"hidden",onChange:sn}),!e&&k&&o&&jsx(Ya,{onClose:()=>T(false),stageRef:o,onRecordingComplete:cn}),F&&jsx(Os,{onClose:()=>V(false),onRecordingComplete:cn}),h&&jsx(Kf,{editingFlashcard:i,onConfirm:ln,onCancel:()=>r(Xa(false))}),z&&jsx(os,{defaultColor:m,onConfirm:A=>{r(ua(A)),N(false);},onCancel:()=>N(false)})]})},uS=dS;var dd=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let n=Ee(La),r=Ee(Bi),s=a?r:n,u=Ee(br),m=(Ee(g=>g.canvas.slides.find(x=>x.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[l,d]=useState(false),[f,h]=useState(null),[p,y]=useState(null),w=async()=>{if(n.length===0){y({type:"error",message:"No slides to publish"});return}if(!e){y({type:"error",message:"No publish handler provided"});return}d(true),y(null);try{let g=await e(s,u,x=>{h(x);});g.success?y({type:"success",message:g.message}):y({type:"error",message:g.message});}catch(g){y({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{d(false),setTimeout(()=>{h(null),y(null);},3e3);}console.log("For checking>>>>>>>>>>>",s,"<<<<<<<<<<<<<");};return m?null:jsxs("button",{onClick:w,disabled:l||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 hS=({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:m="",rightContent:l,leftContent:d,includeInactiveSlides:f=false})=>{let h=$e(),p=Ee(br),y=Ee(Oi),w=e??(y?p.title:"")??"Untitled",g=o??(y?p.description:"")??"Add a description...",[x,I]=useState(false),[L,P]=useState(false),[C,b]=useState(w),[v,k]=useState(g),T=useRef(null),F=useRef(null);useEffect(()=>{b(w);},[w]),useEffect(()=>{k(g);},[g]),useEffect(()=>{x&&T.current&&(T.current.focus(),T.current.select());},[x]),useEffect(()=>{L&&F.current&&(F.current.focus(),F.current.select());},[L]);let V=()=>{i&&I(true);},O=()=>{c&&P(true);},U=()=>{I(false),C.trim()&&C!==w?n?n(C.trim()):h(Di(C.trim())):C.trim()||b(w);},H=()=>{P(false),v.trim()&&v!==g?r?r(v.trim()):h(Ri(v.trim())):v.trim()||k(g);},K=W=>{W.key==="Enter"?U():W.key==="Escape"&&(b(w),I(false));},E=W=>{W.key==="Enter"?H():W.key==="Escape"&&(k(g),P(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${m}`,children:[d||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:T,type:"text",value:C,onChange:W=>b(W.target.value),onBlur:U,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:V,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}),L?jsx("input",{ref:F,type:"text",value:v,onChange:W=>k(W.target.value),onBlur:H,onKeyDown:E,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:O,title:v,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:v})]})]}),l||s&&a&&jsx(dd,{onPublish:a,includeInactiveSlides:f})]})};var wS=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],SS=({colors:e=wS,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:n=""})=>{let[r,s]=useState(true),u=J(ye),i=J(d=>d.toolbar.penColor),c=J(d=>d.toolbar.strokeWidth),m=u?.backgroundColor,l=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(Vs,{defaultValue:[20],max:36,min:8,step:2,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:d=>l(Yr(d[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(Va,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(d=>jsx("button",{value:d.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${i===d.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:d.value},onClick:()=>l(ua(d.value))},d.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>l(ua("#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:d=>l(ua(d.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:m},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:d=>l(cr(d.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 bm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),LS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),cd=e=>{let o=LS(e);return o.charAt(0).toUpperCase()+o.slice(1)},Ks=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),vm=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var ym={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 Sm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:n="",children:r,iconNode:s,...u},i)=>createElement("svg",{ref:i,...ym,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Ks("lucide",n),...!r&&!vm(u)&&{"aria-hidden":"true"},...u},[...s.map(([c,m])=>createElement(c,m)),...Array.isArray(r)?r:[r]]));var Gs=(e,o)=>{let t=forwardRef(({className:a,...n},r)=>createElement(Sm,{ref:r,iconNode:o,className:Ks(`lucide-${bm(cd(e))}`,`lucide-${e}`,a),...n}));return t.displayName=cd(e),t};var TS=[["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"}]],Qr=Gs("copy",TS);var MS=[["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"}]],en=Gs("trash-2",MS);var Im=({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(Qr,{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(en,{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 DS=({softDelete:e=false})=>{let o=$e(),t=Ee(La),a=Ee(Sa),n=Ee(xr),[r,s]=useState(true),c=(Ee(h=>h.canvas.slides.find(p=>p.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),m=()=>{n&&o(ir());},l=h=>{o(ur(h));},d=h=>{o(dr(h));},f=h=>{t.length>1&&o(lr({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(Im,{slide:h,index:p,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>l(h.id),onDuplicate:()=>d(h.id),onDelete:()=>f(h.id)},h.id))}),jsxs("button",{onClick:m,disabled:!n,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${n?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>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 er=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]})]}),US=({softDelete:e=false})=>{let o=$e(),t=Ee(La),a=Ee(Sa),n=Ee(xr),[r,s]=useState(false),[u,i]=useState(false),[c,m]=useState(false),l=useRef(null),h=(Ee(L=>L.canvas.slides.find(P=>P.id===L.canvas.currentSlideId))?.videos||[]).some(L=>L.isRecorded&&L.isPlaying),p=()=>{n&&t.length<er&&o(ir());},y=L=>{o(ur(L));},w=L=>{t.length<er&&o(dr(L));},g=L=>{t.length>1&&o(lr({id:L,softDelete:e}));},x=()=>{if(!l.current)return;let{scrollLeft:L,scrollWidth:P,clientWidth:C}=l.current,b=P>C+5;i(b&&L>5),m(b&&L<P-C-5);},I=L=>{if(!l.current)return;let P=177,C=L==="left"?l.current.scrollLeft-P:l.current.scrollLeft+P;l.current.scrollTo({left:C,behavior:"smooth"});};return useEffect(()=>{if(r){let L=setTimeout(()=>{requestAnimationFrame(()=>{x();});},350);return ()=>clearTimeout(L)}},[t,r]),useEffect(()=>{let L=l.current;if(!(!L||!r))return L.addEventListener("scroll",x),window.addEventListener("resize",x),()=>{L.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,"/",er,")"]})]}),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:()=>I("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:()=>I("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:l,className:"scrollbar-hide flex gap-[11px] overflow-x-auto px-4 pb-4",children:t.map((L,P)=>jsx(zS,{slide:L,index:P,isSelected:L.id===a,isSingleSlide:t.length===1,onSelect:()=>y(L.id),onDuplicate:()=>w(L.id),onDelete:()=>g(L.id)},L.id))})]}),jsx("button",{onClick:p,disabled:!n||t.length>=er,className:`px-4 pb-4 text-base font-bold ${n&&t.length<er?"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,"/",er,")"]})]}),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=US;var YS=({stageRef:e,onScreenRecord:o,visible:t=true,config:a={}})=>{let n=$e(),[r,s]=useState(false),[u,i]=useState(false),c=Ee(I=>I.canvas.slides.find(L=>L.id===I.canvas.currentSlideId)),m=Ee(I=>I.canvas.zoomLevel),d=(c?.videos||[]).some(I=>I.isRecorded&&I.isPlaying),f={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);},y=()=>{n(hr());},w=async(I,L)=>{let P=v4(),C=URL.createObjectURL(I),b=document.createElement("video");b.src=C,b.muted=true,b.playsInline=true,b.preload="auto",await new Promise((V,O)=>{let U=setTimeout(()=>O(new Error("Metadata load timeout")),1e4);b.onloadedmetadata=()=>{clearTimeout(U),V();},b.onerror=()=>{clearTimeout(U),O(new Error("Failed to load video"));};});let v=640,k=b.videoWidth/b.videoHeight,T=v,F=T/k;await sa(P,I,L),n(wo({id:P,objectUrl:C,thumbnailDataUrl:L,videoBlob:I,x:100,y:100,width:T,height:F,draggable:true,isPlaying:false,rotation:0,isRecorded:true}));},x=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>n(Io()),enabled:f.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>n(Co()),enabled:f.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:h,enabled:f.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:p,enabled:f.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:y,enabled:f.clear,iconWeight:"fill",colorClass:"text-[#E92222]"},{key:"resetZoom",title:"Reset Zoom",icon:ArrowsOut,onClick:()=>n(Vd()),enabled:f.resetZoom&&m!==1,iconWeight:"bold",colorClass:"text-primary"}].filter(I=>I.enabled);return !t||d||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(I=>jsx("button",{onClick:I.onClick,className:`flex size-10 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-black/5 ${I.colorClass}`,title:I.title,children:jsx(I.icon,{weight:I.iconWeight,className:"text-xl"})},I.key))}),!o&&r&&e&&jsx(Ya,{onClose:()=>s(false),stageRef:e,onRecordingComplete:w}),u&&jsx(Os,{onClose:()=>i(false),onRecordingComplete:w})]})},pd=YS;var QS=({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})]}),eL=QS;var oL="SchooplaEditorDB",rL=1,za="slides",Ua="metadata",hd="schoopla_current_slide_id",Dm="presentation_metadata",an=()=>new Promise((e,o)=>{let t=indexedDB.open(oL,rL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(za)||n.createObjectStore(za,{keyPath:"id"}),n.objectStoreNames.contains(Ua)||n.createObjectStore(Ua,{keyPath:"id"});};}),gd=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await an(),a=o.transaction([za],"readwrite").objectStore(za);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 an(),t=e.transaction([za],"readonly").objectStore(za);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}}},js=async()=>{try{let e=await an(),o=e.transaction([za,Ua],"readwrite"),t=o.objectStore(za),a=o.objectStore(Ua);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 jc(),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 an(),a=o.transaction([Ua],"readwrite").objectStore(Ua);await new Promise((n,r)=>{let s=a.put({id:Dm,...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 an(),t=e.transaction([Ua],"readonly").objectStore(Ua);return new Promise((a,n)=>{let r=t.get(Dm);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 nL=["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"],sL=["canvas/clearCanvas"],iL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],lL=yd((e,o)=>{gd(e),bd(o);},500),dL=yd(e=>{wd(e);},500),uL=(e,o)=>{gd(e),bd(o);},Ld=false,Rm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Ol(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=>{Ol(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(),l=c.canvas.slides.find(d=>d.id===c.canvas.currentSlideId)?.videos.find(d=>d.id!==r&&d.x===i.x+20&&d.y===i.y+20);l&&i.videoBlob&&sa(l.id,i.videoBlob,l.thumbnailDataUrl).catch(d=>{console.error("Error saving duplicated video blob:",d);});},0);}let a=o(t),n=e.getState();if(n.canvas.viewerMode)return a;if(t.type&&sL.includes(t.type)){if(!Ld){Ld=true;try{let{slides:r,currentSlideId:s}=n.canvas;uL(r,s);}finally{setTimeout(()=>{Ld=false;},0);}}}else if(t.type&&nL.includes(t.type)){let{slides:r,currentSlideId:s}=n.canvas;lL(r,s);}else if(t.type&&iL.includes(t.type)){let{presentationMetadata:r}=n.canvas;dL(r);}return a});new QueryClient;var fL=configureStore({reducer:{toolbar:Xl,canvas:Ni},middleware:e=>e({serializableCheck:false}).concat(Rm)}),mL=()=>configureStore({reducer:{toolbar:Xl,canvas:Ni},middleware:e=>e({serializableCheck:false})});var pL=(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")}},hL=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);}})},gL=(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 xL=(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=xL(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]},bL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},vL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Bm=(e,o=1.5)=>{if(e.length<=4)return e;let t=bL(e),a=Id(t,o);return vL(a)},Om=(e,o=1.5)=>({...e,points:Bm(e.points,o)}),yL=(e,o=1.5)=>e.map(t=>Om(t,o)),wL=(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 SL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Nm=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 m=document.createElement("canvas");m.width=i,m.height=c;let l=m.getContext("2d");if(!l){s(new Error("Failed to get canvas context"));return}l.drawImage(u,0,0,i,c);let d=SL(e),f=m.toDataURL(d,n);r(f);},u.onerror=s,u.src=e;})};var ho=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},tr=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",ar=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",LL=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=[],m=[],l=[];for(let d of i.images){let f=d.src;if(t&&f.startsWith("data:"))try{f=await Nm(f,{maxWidth:a,maxHeight:n,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=ho(f),p=tr(f);u+=h.byteLength;let y={id:d.id,x:d.x,y:d.y,width:d.width,height:d.height,draggable:d.draggable,rotation:d.rotation,locked:d.locked,link:d.link,altText:d.altText,zIndex:d.zIndex,buffer:h,mimeType:p};if(d.audioData&&d.audioData.startsWith("data:")){let w=ho(d.audioData),g=tr(d.audioData);u+=w.byteLength,y.audioBuffer=w,y.audioMimeType=g;}c.push(y);}}for(let d of i.videos){let f,h;if(d.videoBlob)f=await d.videoBlob.arrayBuffer(),h=d.videoBlob.type;else if(d.videoData&&d.videoData.startsWith("data:"))f=ho(d.videoData),h=tr(d.videoData);else {console.warn(`Video ${d.id} has no blob or videoData, skipping`);continue}u+=f.byteLength;let p={id:d.id,thumbnailDataUrl:d.thumbnailDataUrl,x:d.x,y:d.y,width:d.width,height:d.height,draggable:d.draggable,isPlaying:d.isPlaying,rotation:d.rotation,locked:d.locked,link:d.link,altText:d.altText,zIndex:d.zIndex,isRecorded:d.isRecorded,buffer:f,mimeType:h};if(d.audioData&&d.audioData.startsWith("data:")){let y=ho(d.audioData),w=tr(d.audioData);u+=y.byteLength,p.audioBuffer=y,p.audioMimeType=w;}m.push(p);}for(let d of i.photoFrames){let f={id:d.id,x:d.x,y:d.y,width:d.width,height:d.height,rotation:d.rotation,draggable:d.draggable,locked:d.locked,link:d.link,altText:d.altText,zIndex:d.zIndex,isCapturing:d.isCapturing};if(d.capturedImageUrl&&d.capturedImageUrl.startsWith("data:")){let h=ho(d.capturedImageUrl),p=tr(d.capturedImageUrl);u+=h.byteLength,f.buffer=h,f.mimeType=p;}if(d.audioData&&d.audioData.startsWith("data:")){let h=ho(d.audioData),p=tr(d.audioData);u+=h.byteLength,f.audioBuffer=h,f.audioMimeType=p;}l.push(f);}s.push({...i,images:c,videos:m,photoFrames:l});}return {slides:s,totalSize:u}},IL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},CL=e=>{let o=new FormData,t=e.slides.map((a,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}.${ar(r.mimeType)}`;if(o.append(`slide_${n}_image_${s}`,u,i),r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${ar(r.audioMimeType)}`;o.append(`slide_${n}_image_${s}_audio`,c,m);}}),a.videos.forEach((r,s)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${ar(r.mimeType)}`;if(o.append(`slide_${n}_video_${s}`,u,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let c=ho(r.thumbnailDataUrl),m=new Blob([c],{type:"image/jpeg"}),l=`${r.id}_thumbnail.jpg`;o.append(`slide_${n}_video_${s}_thumbnail`,m,l);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${ar(r.audioMimeType)}`;o.append(`slide_${n}_video_${s}_audio`,c,m);}}),a.photoFrames.forEach((r,s)=>{if(r.buffer&&r.mimeType){let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${ar(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.${ar(r.audioMimeType)}`;o.append(`slide_${n}_photoframe_${s}_audio`,u,i);}});}),o};var ML=()=>{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 Gc(),i=n.map(m=>{if(m.videos&&m.videos.length>0){let l=m.videos.map(d=>{let f=u.get(d.id);if(f){let h=_c(f.blob);return {...d,objectUrl:h,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return d});return {...m,videos:l}}return m}),c=r&&i.find(m=>m.id===r)?r:i[0].id;e(vo({slides:i,currentSlideId:c}));}e(s?Fi({title:s.title,description:s.description}):Xn(!0));}catch(n){console.error("Error loading persisted slides:",n),e(Xn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var qm=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||""})),Vm=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 sa(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},AL=()=>{let e=$e(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Vm.has(a))return;Vm.add(a);let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await js(),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=qm(n);e(vo({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 js(),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=qm(n);e(vo({slides:i,currentSlideId:u})),await zm(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
|
|
2
|
+
export{default as Konva}from'konva';import*as Ie from'react';import Ie__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,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 Le=()=>useDispatch(),Q=e=>useSelector(e),Ye=Le,Re=Q;var ni=20,ii=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now(),isActive:true}),ri=ii("Slide 1"),vp={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},qd=createSlice({name:"canvas",initialState:vp,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={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),isActive:true,lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,n),e.currentSlideId=n.id,e.history[n.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},setViewerMode:(e,o)=>{e.viewerMode=o.payload;},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[n]=e.slides.splice(t,1);e.slides.splice(a,0,n);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(n=>n.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload);if(a){let n={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(n),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,newTimestamp:r}=o.payload;switch(n){case "image":let s=t.images.find(x=>x.id===a);s&&(s.timestamp=r);break;case "video":let u=t.videos.find(x=>x.id===a);u&&(u.timestamp=r);break;case "shape":let i=t.shapes.find(x=>x.id===a);i&&(i.timestamp=r);break;case "text":let c=t.texts.find(x=>x.id===a);c&&(c.timestamp=r);break;case "flashcard":let f=t.flashcards.find(x=>x.id===a);f&&(f.timestamp=r);break;case "photoFrame":let d=t.photoFrames.find(x=>x.id===a);d&&(d.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(x=>x.id===a);l&&(l.timestamp=r);break;case "trueFalse":let m=t.trueFalses.find(x=>x.id===a);m&&(m.timestamp=r);break;case "shortAnswer":let h=t.shortAnswers.find(x=>x.id===a);h&&(h.timestamp=r);break;case "longAnswer":let p=t.LongAnswer.find(x=>x.id===a);p&&(p.timestamp=r);break;case "fillInTheBlanks":let b=t.fillInTheBlanks.find(x=>x.id===a);b&&(b.timestamp=r);break;case "line":let y=t.lines.find(x=>x.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={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(n),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let n=t.shortAnswers[t.shortAnswers.length-1];a.x=n.x+20,a.y=n.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(n=>n.id===o.payload);if(a){let n={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(n),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let n=t.LongAnswer[t.LongAnswer.length-1];a.x=n.x+20,a.y=n.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload);if(a){let n={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(n),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let n=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=n.x+20,a.y=n.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(n=>n.id===o.payload);if(a){let n={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(n),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(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:dr,deleteSlide:ur,duplicateSlide:cr,setCurrentSlide:fr,setViewerMode:yp,updateSlideThumbnail:li,setBackgroundColor:mr,reorderSlides:wp,loadSlides:So,addLine:di,removeLine:yn,addImage:ui,updateImage:Lo,deleteImage:wn,duplicateImage:Sn,addVideo:Io,updateVideo:Ln,deleteVideo:In,duplicateVideo:Cn,toggleVideoPlaying:$a,addShape:ci,updateShape:Xa,duplicateShape:kn,deleteShape:Tn,addText:fi,editingOverlayPosition:Vd,updateText:Nt,deleteText:Mn,duplicateText:An,addFlashcard:mi,updateFlashcard:Co,deleteFlashcard:Pn,duplicateFlashcard:En,editFlashcard:pr,nextFlashcard:pi,previousFlashcard:hi,addPhotoFrame:gi,updatePhotoFrame:Ya,deletePhotoFrame:Dn,duplicatePhotoFrame:Rn,toggleImageDrawingMode:xi,addImageAnnotation:bi,updateImageAnnotation:Sp,clearImageAnnotations:Lp,togglePhotoFrameDrawingMode:vi,addPhotoFrameAnnotation:yi,updatePhotoFrameAnnotation:Ip,clearPhotoFrameAnnotations:Cp,addMultipleChoice:wi,updateMultipleChoice:Ht,updateMultipleChoiceDragAndDrop:Si,editMultipleChoice:kp,deleteMultipleChoice:Fn,duplicateMultipleChoice:Bn,addTrueFalse:Li,updateTrueFalse:gt,deleteTrueFalse:On,duplicateTrueFalse:Nn,addShortAnswer:Ii,updateShortAnswer:ia,deleteShortAnswer:Hn,duplicateShortAnswer:qn,addLongAnswer:Ci,updateLongAnswer:Za,deleteLongAnswer:Vn,duplicateLongAnswer:zn,addFillInTheBlanks:ki,updateFillInTheBlanks:La,deleteFillInTheBlanks:Un,duplicateFillInTheBlanks:Wn,setShowMcqForm:Ia,setShowFlashcardForm:Ja,setActivityType:Ti,setEditingActivity:hr,bringToFront:Mi,sendToBack:Ai,toggleLock:Pi,setLink:Kn,setAltText:Gn,setAudioData:jn,updateLastLine:Tp,finalizeDrawing:Ei,setLines:Mp,updateLinePosition:Ap,updateLineTransform:_n,deleteLineById:$n,duplicateLine:Di,updateElementOrder:gr,clearCanvas:xr,undo:ko,redo:To,saveToHistory:ce,toggleSketchMode:Pp,setSketchMode:Ct,setEditingTextId:br,setPresentationTitle:Ri,setPresentationDescription:Fi,loadPresentationMetadata:Bi,setMetadataLoaded:Xn,setZoomLevel:OL,zoomIn:NL,zoomOut:HL,resetZoom:zd}=qd.actions;var Ud=e=>e.canvas.slides,Ca=e=>e.canvas.currentSlideId,ye=createSelector([Ud,Ca],(e,o)=>e.find(t=>t.id===o)),ka=createSelector([Ud],e=>e.filter(o=>o.isActive!==false)),Oi=e=>e.canvas.slides,vr=createSelector([ka],e=>e.length<ni),Ep=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},yr=e=>e.canvas.presentationMetadata,Ni=e=>e.canvas.metadataLoaded,Yn=e=>e.canvas.viewerMode,Hi=qd.reducer;var Kd=e=>{let o=Le(),t=useRef(null),a=useRef(false),n=Q(m=>m.toolbar.selectedTool),r=Q(m=>m.toolbar.penColor),s=Q(m=>m.toolbar.strokeWidth),u=Q(m=>m.canvas.isSketchMode),i=Q(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(ce()),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 $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),b=useRef(a),y=useRef(n),x=useRef(r),g=useRef(u),L=useRef(i);useEffect(()=>{p.current=t,b.current=a,y.current=n,x.current=r,g.current=u,L.current=i;},[t,a,n,r,u,i]);let I=useCallback(()=>{let C=f.current;if(!C)return;let w=C.getContext("2d");w&&w.clearRect(0,0,C.width,C.height);},[]),R=useCallback(()=>{let C=f.current,w=m.current;if(!C||w.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=b.current),w.length===1){k.beginPath(),k.arc(w[0].x,w[0].y,y.current/2,0,Math.PI*2),k.fill();return}let M=_d(w,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:A=>A,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(M.length<2)){k.beginPath(),k.moveTo(M[0][0],M[0][1]);for(let A=1;A<M.length;A++)k.lineTo(M[A][0],M[A][1]);k.closePath(),k.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:C=>{d.current=true;let w={x:C.x-g.current,y:C.y-L.current};l.current=[{x:C.x,y:C.y}],m.current=[w],h.current=C,R();},draw:C=>{if(!d.current||!h.current)return;let w=C.x-h.current.x,k=C.y-h.current.y;if(Math.sqrt(w*w+k*k)<2)return;let M={x:C.x-g.current,y:C.y-L.current};l.current.push({x:C.x,y:C.y}),m.current.push(M),h.current=C,R();},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 w=_d(l.current,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:v=>v,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(v=>[v[0],v[1]]),k={tool:p.current,points:w,color:b.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,R]),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}})});$d.displayName="DirectDrawingCanvas";var Xd=$d;var Zd=e=>{let o=Le(),a=Q(ye)?.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(Lo({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(),b=l.rotation(),y=m.width(),x=m.height(),g=Math.max(5,y*h),L=Math.max(5,x*p);l.scaleX(1),l.scaleY(1),m.width(g),m.height(L),o(Lo({id:f,width:g,height:L,x:l.x(),y:l.y(),rotation:b})),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(ye),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(Ht({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(Ht({id:i,x:u.target.x(),y:u.target.y()})),e?.();}}};var Qd=e=>{let o=useDispatch(),t=useSelector(ye),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(gt({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(gt({id:i,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var eu=e=>{let o=Le(),a=Q(ye)?.videos||[],n=useRef(new Map),r=useCallback(i=>{o($a(i));},[o]),s=useCallback((i,c)=>{let f=c.target;o(Ln({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(Ln({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=Le(),a=Q(ye)?.shapes||[],n=useRef(new Map),r=useRef(new Map),[s,u]=useState(false),i=useCallback((f,d)=>{let l=d.target;o(Xa({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(),b=m.type?.toLowerCase();b==="arrow"||b==="line"||(l.scaleX(1),l.scaleY(1));let x={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(b){case "circle":x.radius=l.width()*h/2;break;case "star":x.innerRadius=l.width()*h/4,x.outerRadius=l.width()*h/2;break;case "triangle":x.radius=l.width()*h/2;break;case "ellipse":x.radiusX=l.width()*h/2,x.radiusY=l.height()*p/2;break;case "polygon":x.radius=l.width()*h/2;break;case "ring":let g=h;x.innerRadius=m.innerRadius&&m.innerRadius*g,x.outerRadius=m.outerRadius&&m.outerRadius*g;break;case "wedge":x.radius=m.radius&&m.radius*h;break;case "arc":x.innerRadius=m.innerRadius&&m.innerRadius*h,x.outerRadius=m.outerRadius&&m.outerRadius*h;break;case "arrow":case "line":{x.scaleX=h,x.scaleY=p,delete x.width,delete x.height;break}}o(Xa(x)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:n,isDragging:s,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:c}};var nu=(e,o)=>{let t=Ye(),n=Q(ye)?.texts||[],r=useRef(new Map),[s,u]=useState(null),[i,c]=useState("");return {texts:n,textRefs:r,handleDragEnd:(b,y)=>{let x=b.target;t(ce()),t(Nt({id:y,x:x.x(),y:x.y()})),e();},handleTransformEnd:b=>{let y=r.current.get(b);if(!y)return;let x=y.scaleX(),g=y.scaleY(),L=n.find(R=>R.id===b);if(!L)return;let I=(x+g)/2;y.scaleX(1),y.scaleY(1),t(ce()),t(Nt({id:b,x:y.x(),y:y.y(),width:Math.max(5,(L.width||100)*x),height:Math.max(5,(L.height||50)*g),fontSize:Math.round(Math.max(8,L.fontSize*I)),rotation:y.rotation()})),e();},handleDoubleClick:b=>{let y=n.find(x=>x.id===b);y&&!y.locked&&(u(b),c(y.text));},startEditing:b=>{let y=n.find(x=>x.id===b);y&&!y.locked&&(u(b),c(y.text));},editingTextId:s,editingValue:i,handleEditingChange:b=>{c(b);},finishEditing:()=>{if(s){let b=r.current.get(s),y=n.find(g=>g.id===s);t(ce());let x={id:s,text:i};if(y&&(y.fontWeight!==void 0&&(x.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(x.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(x.textDecoration=y.textDecoration)),o?.current&&i.trim()){let g=o.current,L=g.offsetWidth,I=g.offsetHeight,R=1;if(b){let V=b.getStage();V&&(R=V.scaleX());}let C=14,w=(L-C)/R,k=(I-C)/R,v=i.split(`
|
|
3
|
+
`).length,A=n.find(V=>V.id===s)?.fontSize||24,E=v*A*1.2+10;x.width=Math.max(200,w),x.height=Math.max(50,k,E);}else if(b&&i.trim()){let g=b.text(),L=b.width();b.text(i),b.width(void 0);let I=b.width(),R=b.height();b.text(g),b.width(L),x.width=Math.max(200,I+20),x.height=Math.max(50,R+20);}t(Nt(x)),u(null),c(""),t(br(null)),e();}}}};var su=e=>{let o=useDispatch(),a=useSelector(ye)?.shortAnswers||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(ia({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(ye),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),n=useCallback((r,s)=>{let u=r.target;o(Za({id:s,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:n}};var du=e=>{let o=Le(),a=Q(ye)?.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(Co({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(),b=m.rotation(),y=Math.max(50,m.width()*h),x=Math.max(50,m.height()*p);m.scaleX(1),m.scaleY(1),m.width(y),m.height(x),o(Co({id:d,width:y,height:x,x:m.x(),y:m.y(),rotation:b})),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 fu=e=>{let o=Le(),a=Q(ye)?.photoFrames||[],n=useRef(new Map),[r,s]=useState(new Map),u=useCallback((m,h)=>{console.log("handleDragEnd"),o(Ya({id:h,x:m.target.x(),y:m.target.y()})),e?.();},[o,e]),i=useCallback((m,h)=>{let p=h.target,b=p.scaleX(),y=p.scaleY(),x=p.rotation(),g=a.find(R=>R.id===m);if(!g)return;let L=Math.max(100,g.width*b),I=Math.max(100,g.height*y);p.scaleX(1),p.scaleY(1),o(Ya({id:m,width:L,height:I,x:p.x(),y:p.y(),rotation:x})),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 b=new Map(p);return b.set(m,h),b}),o(Ya({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 b=new Map(p);return b.delete(m),b}),o(Ya({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 b=p.getContext("2d");if(b){b.drawImage(h,0,0,p.width,p.height);let y=p.toDataURL("image/jpeg",.8);return o(Ya({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 nh=(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=Ye(),a=Re(Yn),n=useRef(e);useEffect(()=>{n.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(li({id:n.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),s=nh(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var ih=e=>e.flatMap(o=>[o[0],o[1]]),Jn=(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 ih(t)};var bu=e=>{let o=Le(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null),u=Q(g=>g.toolbar.selectedTool),i=Q(g=>g.toolbar.penColor),c=Q(g=>g.toolbar.strokeWidth),f=Q(g=>g.canvas.isSketchMode),d=Q(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,b=useCallback(g=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,n.current=[{x:g.x,y:g.y}];let L=g.x/h,I=g.y/p;s({tool:u,points:[L,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 L=n.current[n.current.length-1];if(Math.sqrt(Math.pow(g.x-L.x,2)+Math.pow(g.y-L.y,2))<2)return;n.current.push({x:g.x,y:g.y});let R;if(f)R=Jn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((w,k)=>k%2===0?w/h:w/p);else {let C=g.x/h,w=g.y/p;R=[...r.points,C,w];}s(C=>C?{...C,points:R}:null);},[f,c,r,h,p]),x=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:b,draw:y,stopDrawing:x,tool:u}};function Ue({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}=Ue({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 b=g=>{{r(e.id);return}},y=g=>{return;},x=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 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: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 L=g.evt;s(L,e.id,"image");},...m!=="pen"&&m!=="eraser"?{onClick:b,onTap:b,onMouseDown:b,onMouseMove:y,onMouseUp:x,...h(e.id,"image")}:{}}),i?.map((g,L)=>{let I=g.points.map((C,w)=>w%2===0?C*e.width+e.x:C*e.height+e.y),R=g.strokeWidth*e.width;return jsx(Line,{points:I,stroke:g.tool==="eraser"?"white":g.color,strokeWidth:R,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},L)}),c&&jsx(Line,{points:c.points.map((g,L)=>L%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 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(Lu,{img:i,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u},i.id):null})}));Gi.displayName="ImageLayer";var bh=({src:e,x:o,id:t,y:a,width:n,height:r,isSelected:s,rotation:u=0,onTransformEnd:i,onDragEnd:c})=>{let f=Le(),d=useRef(null),l=m=>{f($a(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=bh;var kh=({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 b=p.getStage()?.container();if(b){let y=x=>{let g=p.getStage()?.getPointerPosition();if(g){let L={x:e.x,y:e.y,width:e.width,height:e.height};g.x>=L.x&&g.x<=L.x+L.width&&g.y>=L.y&&g.y<=L.y+L.height&&r(x);}};b.addEventListener("contextmenu",y),p._contextMenuCleanup=()=>{b.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=kh;var $i=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:n,onTransformEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(u=>jsxs(Ie__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))}));$i.displayName="VideoLayer";var Xi=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}=Ue({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)}})})});Xi.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}=Ue({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:b=>{b?o.current.set(l.id,b):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:b=>t(b,l.id),onTransformEnd:()=>a(l.id),onContextMenu:b=>{b.evt.preventDefault();let y=b.evt;r(y,l.id,"text");},...d(l.id,"text")}},l.id)})})};var Jh=({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 x=new window.Image,g=e.images[e.currentIndex];(g.startsWith("http://")||g.startsWith("https://"))&&(x.crossOrigin="anonymous"),x.src=g,x.onload=()=>{l(x);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let m=8,h=2,p=Math.min(e.width,e.height)*.08,b=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:x=>{if(i(x),x){let g=x.getStage()?.container();if(g){let L=I=>{let R=x.getStage()?.getPointerPosition();if(R){let C={x:e.x,y:e.y,width:e.width,height:e.height};R.x>=C.x&&R.x<=C.x+C.width&&R.y>=C.y&&R.y<=C.y+C.height&&r(I);}};g.addEventListener("contextmenu",L),x._contextMenuCleanup=()=>{g.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+b,y:e.height/2,onClick:x=>{x.cancelBubble=true,u();},onTap:x=>{x.cancelBubble=true,u();},children:[jsx(Circle,{radius:b,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-b,y:e.height/2,onClick:x=>{x.cancelBubble=true,s();},onTap:x=>{x.cancelBubble=true,s();},children:[jsx(Circle,{radius:b,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=Jh;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}=Ue({onLongPress:c}),d=Q(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))})});Qi.displayName="FlashcardLayer";var Fu=e=>{let o=Le(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null);Q(g=>g.toolbar.selectedTool);let i=Q(g=>g.toolbar.penColor),c=Q(g=>g.toolbar.strokeWidth),f=Q(g=>g.canvas.isSketchMode),d=Q(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,b=useCallback(g=>{if(!m)return;t.current=true,a.current=false,n.current=[{x:g.x,y:g.y}];let L=g.x/h,I=g.y/p;s({tool:"pen",points:[L,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 L=n.current[n.current.length-1];if(Math.sqrt(Math.pow(g.x-L.x,2)+Math.pow(g.y-L.y,2))<2)return;n.current.push({x:g.x,y:g.y});let R;if(f)R=Jn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((w,k)=>k%2===0?w/h:w/p);else {let C=g.x/h,w=g.y/p;R=[...r.points,C,w];}s(C=>C?{...C,points:R}:null);},[f,c,r,h,p]),x=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:b,draw:y,stopDrawing:x}};var sg=({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),b=useRef(null),y=useRef(null),x=useRef(null),g=useRef(0),L=33,I=useSelector(O=>O.toolbar.selectedTool),R=I==="pen"||I==="eraser",{annotations:C,activeLine:w,isDrawingMode:k,startDrawing:v,draw:M,stopDrawing:A}=Fu(e.id);useEffect(()=>{if(!k)return;let O=()=>{A();},z=()=>{A();};return window.addEventListener("mouseup",O),window.addEventListener("touchend",z),()=>{window.removeEventListener("mouseup",O),window.removeEventListener("touchend",z);}},[A,k]),useEffect(()=>{if(e.capturedImageUrl){let O=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(O.crossOrigin="anonymous"),O.src=e.capturedImageUrl,O.onload=()=>{l(O);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),b.current||(b.current=document.createElement("canvas"));let O=p.current,z=b.current;O.srcObject=i;let U=()=>{z.width=O.videoWidth||640,z.height=O.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",z.width,z.height);let J=ee=>{if(ee-g.current<L){y.current=requestAnimationFrame(J);return}g.current=ee;let X=z.getContext("2d");if(X&&O.readyState===O.HAVE_ENOUGH_DATA){X.drawImage(O,0,0,z.width,z.height);let xe=z.toDataURL("image/jpeg",.6),ne=new window.Image;ne.onload=()=>{h(ne);},ne.src=xe;}y.current=requestAnimationFrame(J);};y.current=requestAnimationFrame(J);};return O.onloadedmetadata=U,O.readyState>=O.HAVE_METADATA&&U(),O.play().catch(J=>console.error("Error playing video:",J)),()=>{y.current&&(cancelAnimationFrame(y.current),y.current=null);}}return ()=>{h(null),x.current&&(x.current.src="");}},[e.isCapturing,i]);let B=()=>{p.current&&e.isCapturing&&u(p.current);},E=O=>{if(e.capturedImageUrl){if(!k){t();return}let z=O.currentTarget,U=z.getAbsoluteTransform().copy(),ee=z.getStage()?.getPointerPosition();if(ee){U.invert();let X=U.point(ee);v(X);}O.cancelBubble=true;}else t();},V=O=>{if(!k||!e.capturedImageUrl)return;let z=O.currentTarget,U=z.getAbsoluteTransform().copy(),ee=z.getStage()?.getPointerPosition();if(ee){U.invert();let X=U.point(ee);M(X);}},W=()=>{!k||!e.capturedImageUrl||A();},G=e.isCapturing?m:d,H=Math.min(e.width,e.height)*.12,j=Math.max(25,Math.min(H,50)),ie=e.width/2,K=e.height/2;return jsxs(Group,{id:e.id,draggable:!k&&!R,listening:true,onClick:t,onTap:t,x:e.x,y:e.y,...f,...R?{}:{onDragEnd:a,onTransformEnd:n},rotation:e.rotation,width:e.width,height:e.height,ref:O=>{if(c(O),O){let z=O.getStage()?.container();if(z){let U=J=>{let ee=O.getStage()?.getPointerPosition();if(ee){let X={x:e.x,y:e.y,width:e.width,height:e.height};ee.x>=X.x&&ee.x<=X.x+X.width&&ee.y>=X.y&&ee.y<=X.y+X.height&&r(J);}};z.addEventListener("contextmenu",U),O._contextMenuCleanup=()=>{z.removeEventListener("contextmenu",U);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:G?"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}}),G&&jsx(Image$1,{image:G,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:E,onTap:E,onMouseDown:E,onTouchStart:E,onMouseMove:V,onTouchMove:V,onMouseUp:W,onTouchEnd:W,...R?{}:{onDragEnd:a,onTransformEnd:n}}),C?.map((O,z)=>{let U=O.points.map((ee,X)=>X%2===0?ee*e.width:ee*e.height),J=O.strokeWidth*e.width;return jsx(Line,{points:U,stroke:O.tool==="eraser"?"white":O.color,strokeWidth:J,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:O.tool==="eraser"?"destination-out":"source-over",fill:O.isSketch?O.color:void 0,closed:O.isSketch,listening:false},z)}),w&&jsx(Line,{points:w.points.map((O,z)=>z%2===0?O*e.width:O*e.height),stroke:w.tool==="eraser"?"white":w.color,strokeWidth:w.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:w.tool==="eraser"?"destination-out":"source-over",fill:w.isSketch?w.color:void 0,closed:w.isSketch,listening:false},"active"),!G&&!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:K-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:ie-j+6,y:K-60,width:j*1.6,height:j*1.6,radius:j,fill:"white",cornerRadius:8,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?B():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?B():s();}}),jsx(Html,{groupProps:{x:ie-12,y:K-40,width:j*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:O=>{O.stopPropagation(),e.isCapturing?B():s();}})})]}),jsx(Text,{x:0,y:K,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:K+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:ie-24,y:K+104,width:j*1.6,height:j*1.6,radius:j,fill:"#096B76",cornerRadius:j,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?B():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?B():s();}}),jsx(Html,{groupProps:{x:ie-8,y:K+120,width:j*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:O=>{O.stopPropagation(),e.isCapturing?B():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:ie-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:O=>{O.stopPropagation(),B();},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=sg;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}=Ue({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))})});nl.displayName="PhotoFrameLayer";var Uu=({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 Wu=({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),sl=()=>useContext(Gu);function Tg({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 We(){let e=sl();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=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 os=({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=b=>{let y=(b+d/30)%12,x=m-h*Math.max(Math.min(y-3,9-y,1),-1);return Math.round(255*x).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 jg=({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=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,b=n.width/m,y=n.height/m,x=document.createElement("canvas");x.width=b,x.height=y;let g=x.getContext("2d");if(!g)return;g.drawImage(s,h,p,b,y,0,0,b,y);let L=x.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(jg,{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 Qa=({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),b=useRef(null),y=useRef(null),x=useRef(null),g=useRef(null),L=useRef(null);useEffect(()=>()=>{y.current&&cancelAnimationFrame(y.current),p.current&&clearInterval(p.current),b.current&&b.current.getTracks().forEach(v=>v.stop());},[]);let I=async()=>{try{let v,M=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let W=o.current.getLayers();console.log("Konva layers:",W.length),W.forEach((U,J)=>{let ee=U.getChildren();console.log(`Layer ${J} children count:`,ee.length);});let G=document.createElement("canvas");G.width=o.current.width(),G.height=o.current.height();let H=G.getContext("2d",{willReadFrequently:!1});if(!H){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",G.width,"x",G.height),g.current=G;let j=()=>{if(H.clearRect(0,0,G.width,G.height),W.forEach(U=>{let J=U.getCanvas()._canvas;J&&H.drawImage(J,0,0);}),a?.current){let U=a.current;H.drawImage(U,0,0);}};L.current=j,o.current.draw(),j(),await new Promise(U=>setTimeout(U,100)),console.log("Creating captureStream..."),v=G.captureStream(30),console.log("Canvas stream created, tracks:",v.getTracks().length);let K=v.getVideoTracks()[0];K&&console.log("Video track:",K.label,"state:",K.readyState);let O=0,z=()=>{j(),o?.current&&(o.current.getLayers().forEach(J=>{J.batchDraw();}),O++,O%60===0&&console.log("Drawing frame:",O)),y.current=requestAnimationFrame(z);};z();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(W){console.warn("Microphone access denied:",W);}let A=[...v.getVideoTracks()];M&&A.push(...M.getAudioTracks());let B=new MediaStream(A);b.current=B;let E="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?E="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?E="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?E="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(E="video/webm;codecs=vp8"),console.log("Using mimeType:",E);let V=new MediaRecorder(B,{mimeType:E,videoBitsPerSecond:25e5});m.current=V,h.current=[],V.ondataavailable=W=>{console.log("Data available, size:",W.data.size),W.data.size>0&&h.current.push(W.data);},V.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let W=new Blob(h.current,{type:E});console.log("Final blob size:",W.size),o?.current&&L.current&&g.current&&(o.current.draw(),o.current.getLayers().forEach(H=>{H.batchDraw();}),L.current(),x.current=g.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",x.current.length)),B.getTracks().forEach(G=>G.stop()),p.current&&clearInterval(p.current),y.current&&(cancelAnimationFrame(y.current),y.current=null),i(W);},V.onerror=W=>{console.error("MediaRecorder error:",W);},console.log("Starting recording..."),V.start(1e3),s(!0),f(0),p.current=setInterval(()=>{f(W=>W+1);},1e3);}catch(v){console.error("Error starting screen recording:",v),alert("Failed to start recording. Please ensure you granted permission.");}},R=()=>{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 v=URL.createObjectURL(u),M=document.createElement("a");M.href=v,M.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(v);}},w=v=>{let M=Math.floor(v/60),A=v%60;return `${M.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`};if(!n)return null;if(r){let v=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:w(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:R,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(v,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: ",w(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&x.current&&(t(u,x.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick: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 ec=({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([]),b=useRef(null),y=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(v=>v.blob()).then(v=>c(v)).catch(v=>console.error("Error loading audio:",v));},[o,i]);let x=async()=>{try{let v=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),M=new MediaRecorder(v);h.current=M,p.current=[],M.ondataavailable=A=>{A.data.size>0&&p.current.push(A.data);},M.onstop=()=>{let A=new Blob(p.current,{type:"audio/webm"});c(A),v.getTracks().forEach(B=>B.stop()),b.current&&clearInterval(b.current);},M.start(),u(!0),m(0),b.current=setInterval(()=>{m(A=>A+1);},1e3);}catch(v){console.error("Error starting audio recording:",v),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{h.current&&s&&(h.current.stop(),u(false));},L=()=>{if(i){let v=URL.createObjectURL(i),M=new Audio(v);y.current=M,M.onended=()=>{d(false),URL.revokeObjectURL(v);},M.play(),d(true);}},I=()=>{y.current&&(y.current.pause(),y.current.currentTime=0,d(false));},R=async()=>{if(i){let v=new FileReader;v.onloadend=()=>{let M=v.result;t(M),n();},v.readAsDataURL(i);}},C=()=>{c(null),a();},w=v=>{let M=Math.floor(v/60),A=v%60;return `${M.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`};if(!r)return null;if(s){let v=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:w(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(v,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:x,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:R,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 zt=({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 b=new Audio(e);d.current=b,b.onended=()=>{f(false);},b.onerror=()=>{console.error("Error playing audio"),f(false);},b.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=Le(),n=Q(ye),r=We(),s=useMemo(()=>{if(!n)return [];let y=[];return n.images?.forEach(x=>{y.push({id:x.id,type:"image",name:"Image",timestamp:x.timestamp||0});}),n.videos?.forEach(x=>{y.push({id:x.id,type:"video",name:"Video",timestamp:x.timestamp||0});}),n.shapes?.forEach(x=>{y.push({id:x.id,type:"shape",name:`${x.type} Shape`,timestamp:x.timestamp||0});}),n.texts?.forEach(x=>{y.push({id:x.id,type:"text",name:x.text.substring(0,20)+(x.text.length>20?"...":""),timestamp:x.timestamp||0});}),n.flashcards?.forEach(x=>{y.push({id:x.id,type:"flashcard",name:`Flashcard (${x.images.length} images)`,timestamp:x.timestamp||0});}),n.photoFrames?.forEach(x=>{y.push({id:x.id,type:"photoFrame",name:"Photo Frame",timestamp:x.timestamp||0});}),n.multipleChoices?.forEach(x=>{y.push({id:x.id,type:"mcq",name:"Multiple Choice",timestamp:x.timestamp||0});}),n.trueFalses?.forEach(x=>{y.push({id:x.id,type:"trueFalse",name:"True/False",timestamp:x.timestamp||0});}),n.shortAnswers?.forEach(x=>{y.push({id:x.id,type:"shortAnswer",name:"Short Answer",timestamp:x.timestamp||0});}),n.LongAnswer?.forEach(x=>{y.push({id:x.id,type:"longAnswer",name:"Long Answer",timestamp:x.timestamp||0});}),n.fillInTheBlanks?.forEach(x=>{y.push({id:x.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:x.timestamp||0});}),n.lines?.forEach(x=>{x.id&&y.push({id:x.id,type:"line",name:"Drawn Line",timestamp:x.timestamp||0});}),y.sort((x,g)=>g.timestamp-x.timestamp)},[n]),[u,i]=useState(s),[c,f]=useState(false);useEffect(()=>{c||i(s);},[s]);let d=y=>{let x="h-5 w-5";switch(y){case "image":return jsx(Image$3,{className:x});case "video":return jsx(VideoCamera,{className:x});case "shape":return jsx(Shapes$1,{className:x});case "text":return jsx(TextT,{className:x});case "flashcard":return jsx(Cards$1,{className:x});case "photoFrame":return jsx(FrameCorners$1,{className:x});case "line":return jsx(Pen,{className:x});default:return jsx(Question,{className:x})}},h=y=>{f(true),i(y);},p=()=>{f(false);let y=Date.now();u.forEach((x,g)=>{let L=y-g;a(gr({id:x.id,type:x.type,newTimestamp:L}));});};if(!r)return null;let b=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 x=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 ${x?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(y.id,y.type),className:`font-medium ${x?"text-[#096B76]":"text-[#00000099]"}`,children:y.name})}),jsx("div",{className:`${x?"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(b,r)};var ds=(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(E=>E.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(null),l=e.data.responseOptions.attempts||0,m=useRef(null),h=useDispatch(),[p,b]=useState(new Set(e.data.responseOptions.selectedIndices||[])),[y,x]=useState(false);useEffect(()=>{let E=m.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id]);let g=new Set(e.data.responseOptions.correctIndex),L=g.size>1,I=E=>{if(y)return;let V;L?(V=new Set(p),V.has(E)?V.delete(E):V.add(E)):V=new Set([E]),b(V);let W=Array.from(V),G=W.length===e.data.responseOptions.correctIndex.length&&W.every(H=>e.data.responseOptions.correctIndex.includes(H));h(Ht({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:W,isCorrect:G}}})),u?.();},R=()=>{p.size>0&&(x(true),h(Ht({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},C=()=>{x(false),b(new Set);},w=p.size===g.size&&Array.from(p).every(E=>g.has(E)),k=Array.from(p).filter(E=>g.has(E)),v=L&&k.length>0&&!w,M=()=>w?"\u2713 Correct! Great job! \u{1F389}":v?`\u26A0 Partially correct (${k.length}/${g.size})`:"\u2717 Try again!",A=()=>w?{bg:"#dcfce7",text:"#166534"}:v?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},B=useMemo(()=>{let K=e.data.feedbackMode==="practice"?48:0,O=12,z=e.width-48,U=z-80,J=Math.max(60,ds(e.data.question,20,z,"bold")+20),ee=`Select ${g.size} answers (${p.size}/${g.size} selected)`,X=L&&!y&&e.data.feedbackMode==="practice"?ds(ee,14,z)+10:0,xe=y&&e.data.feedbackMode==="practice"?Math.max(60,ds(M(),16,z-40)+30):0,ne=e.data.responseOptions.options.map(ue=>{let Pe=ds(ue,16,U);return Math.max(55,Pe+20)}),we=J+X+xe,be=ne.reduce((ue,Pe)=>ue+Pe+8,-8),me=we+be+O+K+24;return {padding:24,questionHeight:J,instructionHeight:X,feedbackHeight:xe,optionsStartY:we,optionHeights:ne,totalHeight:me,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:K,buttonTopMargin:O,availableWidth:z,optionTextWidth:U}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,y,p.size,g.size,L,M]);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:B.totalHeight,onTransformEnd:E=>o(e.id,E),...s,...c?{}:{onDragEnd:n,onClick:E=>t&&t(e.id),onTap:E=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:B.totalHeight,width:e.width,onContextMenu:E=>{E.cancelBubble=true,r(E.evt,e.id,"mcq");}}),jsx(Text,{x:B.padding+8,y:B.padding,text:e.data.question,fontSize:B.questionFontSize,fontStyle:"bold",fill:"#111827",width:B.availableWidth,height:B.questionHeight-B.padding,wrap:"word",ellipsis:true,listening:false}),B.instructionHeight>0&&jsx(Text,{x:B.padding,y:B.questionHeight,text:`Select ${g.size} answers (${p.size}/${g.size} selected)`,fontSize:B.instructionFontSize,fill:"#6b7280",width:B.availableWidth,wrap:"word",listening:false}),y&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:B.padding+24,y:B.questionHeight+B.instructionHeight+10,width:B.availableWidth-40,height:B.feedbackHeight-20,fill:A().bg,cornerRadius:8}),jsx(Text,{x:B.padding+24,y:B.questionHeight+B.instructionHeight+10,width:B.availableWidth-40,height:B.feedbackHeight-20,text:M()+` (${l} attempts)`,fontSize:B.feedbackFontSize,fontStyle:"bold",fill:A().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((E,V)=>{let W=g.has(V),G=p.has(V),H=B.optionsStartY;for(let z=0;z<V;z++)H+=B.optionHeights[z]+B.optionGap;let j=B.optionHeights[V],ie="#e5e7eb",K="#ffffff",O="#111827";return y&&G&&!W?(ie="#ef4444",K="#fee2e2",O="#ef4444"):G&&(ie="#096B76",K="#ECFFF8",O="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:B.padding+12,y:H+(j-20)/2,width:20,height:20,fill:G?"#096B76":"white",stroke:G?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:L?4:10,onClick:z=>{z.cancelBubble=true,I(V);},onTap:z=>{z.cancelBubble=true,I(V);}}),G&&jsx(Text,{x:B.padding+12,y:H+(j-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:B.padding+44,y:H,width:B.availableWidth-60,height:j,fill:K,stroke:ie,strokeWidth:2,cornerRadius:8,onClick:z=>{z.cancelBubble=true,I(V);},onTap:z=>{z.cancelBubble=true,I(V);}}),jsx(Text,{x:B.padding+60,y:H+10,width:B.optionTextWidth,height:j-20,text:E,fontSize:B.optionFontSize,fill:O,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},V)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:B.optionsStartY+B.optionHeights.reduce((E,V)=>E+V+B.optionGap,-B.optionGap)+B.buttonTopMargin,children:[jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,d("check");},onMouseUp:E=>{E.cancelBubble=true,d(null),R();},onMouseLeave:E=>{E.cancelBubble=true,d(null);},onTouchStart:E=>{E.cancelBubble=true,d("check");},onTouchEnd:E=>{E.cancelBubble=true,d(null),R();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:B.padding+14,width:(B.availableWidth-24)/(y?2:1),height:B.buttonHeight,fill:p.size===0||y?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:B.padding+14,width:(B.availableWidth-24)/(y?2:1),height:B.buttonHeight,text:y?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),y&&jsxs(Group,{x:(e.width-B.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:B.padding,width:(B.availableWidth-8)/2,height:B.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:B.padding,width:(B.availableWidth-8)/2,height:B.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});rc.displayName="MultipleChoice";var nc=rc;var Hx=(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},ul=({multipleChoice:e,onContextMenu:o,handleSelect:t,mcqRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(K=>K.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,f]=useState(false),[d,l]=useState(new Set),[m,h]=useState(false),[p,b]=useState(false),[y,x]=useState(0),g=e.data.responseOptions.attempts||0,[L,I]=useState(new Map),R=new Set(e.data.responseOptions.correctIndex),C=Array.from(d).filter(K=>R.has(K)),w=d.size===R.size&&Array.from(d).every(K=>R.has(K)),k=C.length>0&&!w,v=()=>w?"\u2713 Correct! Great job!":k?`\u26A0 Partially correct (${C.length}/${R.size})`:"\u2717 Try again!",M=useCallback(K=>{let O=K.target;s(Si({id:e.id,dragDropPos:{x:O.x(),y:O.y()}})),r?.();},[s,e.id,r]),A=useMemo(()=>{let O=Math.max(window.innerWidth*.3,500),z=20,U=18,J=28,ee=40,X=50,xe=20,ne=60,we=Math.max(O-40,400),be=Math.max(60,Hx(e.data.question,z,we,"bold")),me=Math.max(O-xe*2,400),ue=Math.max(150,window.innerHeight*.2),Pe=e.data.feedbackMode==="practice",it=be+20+ue+(m?ne+18:0)+(Pe?ee+(m?X:0)+20:0),Ve=it+100;return {screenWidth:O,screenHeight:Ve,dropZoneWidth:me,dropZoneHeight:ue,questionFontSize:z,questionHeight:be,feedbackFontSize:U,feedbackHeight:ne,dropHereFontSize:J,buttonHeight:ee,buttonGap:X,padding:xe,contentWidth:we,totalContentHeight:it,isPracticeMode:Pe}},[e.data.question,e.data.feedbackMode,m,d.size]),B=useRef(null);useEffect(()=>{let K=B.current;if(K)return a.current.set(e.id,K),()=>{a.current.delete(e.id);}},[e.id]);let E=K=>{s(Si({id:e.id,dragDropPos:{x:K.target.x(),y:K.target.y()}})),r?.();},V=K=>{let O=K.target,z=O.x(),U=O.y(),J=window.innerWidth*.2,ee=50,X=A.padding,xe=A.padding+A.dropZoneWidth,ne=A.questionHeight+20,we=A.questionHeight+20+A.dropZoneHeight,be=z+J>X&&z<xe&&U+ee>ne&&U<we;f(be),r?.();},W=(K,O)=>{let z=O.target,U=z.x(),J=z.y(),ee=window.innerWidth*.2,X=50;I(Ve=>{let re=new Map(Ve);return re.set(K,{x:U,y:J}),re});let xe=A.padding,ne=A.padding+A.dropZoneWidth,we=A.questionHeight+20,be=A.questionHeight+20+A.dropZoneHeight,me=U+ee>xe&&U<ne&&J+X>we&&J<be,ue;me?ue=new Set(d).add(K):(ue=new Set(d),ue.delete(K)),l(ue),f(false);let Pe=Array.from(ue),it=Pe.length===R.size&&Pe.every(Ve=>R.has(Ve));s(Ht({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:Pe,isCorrect:it}}})),r?.();},G=()=>{h(true),s(Ht({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},H=()=>{h(false),l(new Set),I(new Map),x(K=>K+1);},j=()=>w?{bg:"#dcfce7",text:"#166534"}:k?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},ie=()=>m?w?"#4CAF50":k?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:B,x:e.dragDropPos?.x,y:e.dragDropPos?.y,name:"mcq-element",width:A.screenWidth,height:A.screenHeight,draggable:!i,listening:!i,onDragMove:M,...n,...i?{}:{onClick:K=>t&&t(e.id),onTap:K=>t&&t(e.id),onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"mcq");}},children:[jsxs(Group,{rotation:e.rotation,onDragEnd:E,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:A.totalContentHeight+20,width:A.screenWidth,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:A.padding,y:A.padding,width:A.contentWidth,height:A.questionHeight-A.padding,text:e.data.question,fontSize:A.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:A.padding,y:A.questionHeight+20,width:A.dropZoneWidth,height:A.dropZoneHeight,fill:"#EBF6F7",stroke:ie(),strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:A.padding+3,y:A.questionHeight+20+A.dropZoneHeight+18,width:A.dropZoneWidth-5,height:A.feedbackHeight,fill:j().bg,cornerRadius:8}),jsx(Text,{x:A.padding,y:A.questionHeight+20+A.dropZoneHeight+20,width:A.dropZoneWidth,height:A.feedbackHeight,text:v()+` (${g} attempts)`,fontSize:A.feedbackFontSize,fontStyle:"bold",fill:j().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),d.size===0&&!m&&jsx(Text,{x:A.padding,y:A.questionHeight+20,width:A.dropZoneWidth,height:A.dropZoneHeight,text:R.size>1?`Drop ${R.size} Correct Answers Here`:"Drop Here",fontSize:A.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),A.isPracticeMode?jsxs(Group,{x:A.padding,y:A.questionHeight+20+A.dropZoneHeight+(m?A.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:K=>{K.cancelBubble=true,!(m||d.size===0)&&(b(true),G());},onMouseUp:()=>b(false),onMouseLeave:()=>b(false),onTouchStart:()=>{b(true),G();},onTouchEnd:()=>b(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:m||d.size===0?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:A.buttonHeight,width:A.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:m||d.size===0?"#9ca3af":"white",width:A.dropZoneWidth,height:A.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:A.buttonGap,onMouseDown:H,onTouchStart:H,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:A.buttonHeight,width:A.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:A.dropZoneWidth,height:A.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((K,O)=>{let z=O%2,U=Math.floor(O/2),J=Math.max(window.innerWidth*.1,290),ee=50,X=10,xe=d.has(O),ne=R.has(O),we=m&&xe,be="transparent";we?be=ne?"#4CAF50":"#ef4444":xe&&(be="#4CAF50");let me=m&&!xe?0:1,ue=L.get(O),Pe=ue?.x??z*(J+X),it=ue?.y??A.totalContentHeight+30+U*(ee+X);return jsxs(Group,{x:Pe,y:it,draggable:!m,onDragStart:Ve=>{Ve.cancelBubble=true;},onDragMove:Ve=>{Ve.cancelBubble=true,V(Ve);},onDragEnd:Ve=>{Ve.cancelBubble=true,W(O,Ve);},opacity:me,children:[jsx(Rect,{width:J-20,height:ee,fill:"white",stroke:be,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:J-20,height:ee,text:K,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${O}-${y}`)})]})};ul.displayName="MultipleChoiceDragAndDrop";var sc=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=Ue({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(ul,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id))})};var ic=(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(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s,onUpdate:u})=>{let i=useSelector(M=>M.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(false),l=e.data.responseOptions.attempts||0,[m,h]=useState(null),p=useDispatch(),[b,y]=useState(e.data.responseOptions.selectedResponse??null),x=useRef(null);useEffect(()=>{let M=x.current;if(M)return a.current.set(e.id,M),()=>{a.current.delete(e.id);}},[e.id]);let g=()=>{b!==null&&d(true),p(gt({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,R=b===I,C=M=>{if(f)return;y(M);let A=M===e.data.responseOptions.correctAnswer;p(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:M,isCorrect:A}}})),u?.();},w=()=>R?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",k=()=>R?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},v=useMemo(()=>{let G=e.data.feedbackMode==="practice"?48:0,H=12,j=e.width-48,ie=Math.max(60,ic(e.data.question,20,j,"bold")+20),K=f&&e.data.feedbackMode==="practice"?Math.max(60,ic(w(),16,j-40)+30):0,O=ie+K,z=164,U=O+z+H+G+24;return {padding:24,questionHeight:ie,feedbackHeight:K,optionsStartY:O,optionsHeight:z,totalHeight:U,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:G,buttonTopMargin:H,availableWidth:j}},[e.width,e.data.question,e.data.feedbackMode,f,w]);return jsxs(Group,{ref:x,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:v.totalHeight,...s,...c?{}:{onDragEnd:M=>r(M,e.id),onClick:M=>t&&t(e.id),onTap:M=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:v.totalHeight,width:e.width,onTransformEnd:M=>o(e.id,M),onContextMenu:M=>{M.cancelBubble=true,n(M.evt,e.id,"trueFalse");}}),jsx(Text,{x:v.padding+8,y:v.padding,text:e.data.question,fontSize:v.questionFontSize,fontStyle:"bold",fill:"#111827",width:v.availableWidth,height:v.questionHeight-v.padding,wrap:"word",ellipsis:true,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:v.padding+24,y:v.questionHeight+10,width:v.availableWidth-40,height:v.feedbackHeight-20,fill:k().bg,cornerRadius:8}),jsx(Text,{x:v.padding+24,y:v.questionHeight+10,width:v.availableWidth-40,height:v.feedbackHeight-20,text:w()+` (${l} attempts)`,fontSize:v.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((M,A)=>{let B=I===M.value,E=b===M.value,V=(e.width-v.padding*3)/2,W=v.padding+A*(V+v.padding),G=v.optionsStartY,H=M.value===true,j=H?"#10b981":"#ef4444",ie="#ffffff",K="#ffffff",O="#e5e7eb";return f&&E&&(B?(K=H?"#f0fdf4":"#fef2f2",O=H?"#86efac":"#fecaca"):(K="#fee2e2",O="#ef4444")),E&&!f&&(O="#096B76",K="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:W,y:G,width:V,height:v.optionHeight+50,fill:K,stroke:O,strokeWidth:2,cornerRadius:12,onClick:z=>{z.cancelBubble=true,C(M.value);},onTap:z=>{z.cancelBubble=true,C(M.value);}}),jsx(Circle,{x:W+V/2,y:G+40,radius:28,fill:j,listening:false}),H?jsx(Text,{x:W+V/2-14,y:G+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:ie,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:W+V/2-14,y:G+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:ie,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:W,y:G+85,width:V,height:30,text:M.label,fontSize:v.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},M.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:v.optionsStartY+2*(v.optionHeight+v.optionGap)+v.buttonTopMargin,children:[jsxs(Group,{onMouseDown:M=>{M.cancelBubble=true,h("check");},onMouseUp:M=>{M.cancelBubble=true,h(null),g();},onMouseLeave:M=>{M.cancelBubble=true,h(null);},onTouchStart:M=>{M.cancelBubble=true,h("check");},onTouchEnd:M=>{M.cancelBubble=true,h(null),g();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:v.padding+14,width:(v.availableWidth-24)/(f?2:1),height:v.buttonHeight,fill:b===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:M=>M.cancelBubble=true,onTap:M=>M.cancelBubble=true}),jsx(Text,{x:v.padding+14,width:(v.availableWidth-24)/(f?2:1),height:v.buttonHeight,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-v.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:v.padding,width:(v.availableWidth-8)/2,height:v.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:M=>M.cancelBubble=true,onTap:M=>M.cancelBubble=true}),jsx(Text,{x:v.padding,width:(v.availableWidth-8)/2,height:v.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});lc.displayName="TrueFalse";var dc=lc;var eb="#FFFFFF",ml=({trueFalse:e,onContextMenu:o,handleSelect:t,trueFalseRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(U=>U.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,f]=useState(false),[d,l]=useState(null),[m,h]=useState(false),[p,b]=useState(false),[y,x]=useState(0),g=e.data.responseOptions.attempts||0,L=340,I=100,R=Math.max(window.innerWidth*.3,400),C=window.innerHeight*.5,w=useRef(null);useEffect(()=>{let U=w.current;if(U)return a.current.set(e.id,U),()=>{a.current.delete(e.id);}},[e.id]);let v=Math.max(60,((U,J,ee,X)=>{let ne=document.createElement("canvas").getContext("2d");if(!ne)return J;ne.font=`${X} ${J}px Arial, sans-serif`;let we=U.split(" "),be=[],me="";return we.forEach(ue=>{let Pe=me?`${me} ${ue}`:ue;ne.measureText(Pe).width>ee&&me!==""?(be.push(me),me=ue):me=Pe;}),me&&be.push(me),be.length*J*1.2})(e.data.question,20,R-40,"bold")+20),M=v+10,A=R-40,B=C-v-250,E=useCallback(U=>{let J=U.target;s(gt({id:e.id,dragDropPos:{x:J.x(),y:J.y()}})),r?.();},[s,e.id,r]),V=U=>{s(gt({id:e.id,dragDropPos:{x:U.target.x(),y:U.target.y()}})),r?.();},W=U=>{let J=U.target,ee=J.x(),X=J.y(),xe=window.innerWidth*.2-40,ne=50,we=20,be=20+A,me=M,ue=M+B,Pe=ee+xe>we&&ee<be&&X+ne>me&&X<ue;f(Pe),r?.();},G=(U,J)=>{let ee=J.target,X=ee.x(),xe=ee.y(),ne=window.innerWidth*.2-40,we=50,be=20,me=20+A,ue=M,Pe=M+B;if(!(X+ne>be&&X<me&&xe+we>ue&&xe<Pe)){f(false);return}l(U),f(false);let Ve=U===e.data.responseOptions.correctAnswer;s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:U,isCorrect:Ve}}}));},H=()=>{h(true),s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},j=()=>{h(false),l(null),x(U=>U+1);},ie=e.data.responseOptions.correctAnswer,K=d===ie,O=()=>K?"\u2713 Correct! Great job!":"\u2717 Try again!",z=()=>K?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:w,name:"trueFalse-element",width:R,height:C,x:e.dragDropPos?.x,y:e.dragDropPos?.y,draggable:!i,listening:!i,onDragMove:E,...n,...i?{}:{onClick:U=>t&&t(e.id),onTap:U=>t&&t(e.id),onContextMenu:U=>{U.evt.preventDefault(),o(U.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:L,y:I,rotation:e.rotation,onDragEnd:V,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:m?C:e.data.feedbackMode==="practice"?C-50:C-100,width:R,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:R-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:M,width:A,height:B,fill:"transparent",stroke:c?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:M,width:A,height:60,fill:z().bg,cornerRadius:8}),jsx(Text,{x:20,y:M,width:A,height:60,text:O()+" ("+g+" attempts)",fontSize:18,fontStyle:"bold",fill:z().text,align:"center",verticalAlign:"middle"})]}),d===null&&!m&&jsx(Text,{x:20,y:M,width:A,height:B,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:C-100,children:[jsxs(Group,{onMouseDown:U=>{U.cancelBubble=true,!(m||d===null)&&d!==null&&(b(true),H());},onMouseUp:()=>b(false),onMouseLeave:()=>b(false),onTouchStart:()=>{d!==null&&(b(true),H());},onTouchEnd:()=>b(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:m||d===null?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:A}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:m||d===null?"#9ca3af":"white",width:A,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:j,onTouchStart:j,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:A}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:A,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((U,J)=>{let ee=Math.max(window.innerWidth*.1,290),X=50,xe=10,ne=d===U.value,we=ie===U.value,be=m&&ne,me="transparent";return be?me=we?"#4CAF50":"#ef4444":ne&&(me="#4CAF50"),jsxs(Group,{x:16+J*(ee+xe),y:I+C-300,draggable:!m,onDragStart:ue=>{ue.cancelBubble=true;},onDragMove:ue=>{ue.cancelBubble=true,W(ue);},onDragEnd:ue=>{ue.cancelBubble=true,G(U.value,ue);},opacity:m&&!ne?.5:1,children:[jsx(Rect,{width:ee-40,height:X,fill:"#075560",stroke:me,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:ee-40,height:X,text:U.label,fontSize:18,fontStyle:"bold",fill:eb,align:"center",verticalAlign:"middle",listening:false})]},`${U.value}-${y}`)})]})})};ml.displayName="TrueFalseDragAndDrop";var uc=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=Ue({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(dc,{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 Pa=new WeakMap,Vo=new WeakMap,Rr={current:[]},hl=false,Dr=0,Er=new Set,us=new Map;function cc(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=Vo.get(t);if(a)for(let n of a){let r=Pa.get(n);r&&cc(r);}}}function ob(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function rb(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function cs(e){if(Dr>0&&!us.has(e)&&us.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=us.get(t)??t.prevState;t.prevState=a,ob(t);}for(let t of o){let a=Pa.get(t);a&&(Rr.current.push(t),cc(a));}for(let t of o){let a=Pa.get(t);if(a)for(let n of a)rb(n);}}}finally{hl=false,Rr.current=[],us.clear();}}function At(e){Dr++;try{e();}finally{if(Dr--,Dr===0){let o=Er.values().next().value;o&&cs(o);}}}function fc(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):fc(o)?this.state=o(this.prevState):this.state=o,(n=(a=this.options)==null?void 0:a.onUpdate)==null||n.call(a),cs(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=Vo.get(this);n||(n=new Set,Vo.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=Vo.get(this);n&&n.delete(t);}}};function nb(e){return typeof e=="function"}function gl(e,...o){return nb(e)?e(...o):e}function mc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Ea,bt,ct,Fr,Da,oo,da,zo,Br,fs,Or,Uo,ro=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:n=1e3}){Ne(this,Ea,true);Ne(this,bt);Ne(this,ct);Ne(this,Fr);Ne(this,Da);Ne(this,oo);Ne(this,da);Ne(this,zo);Ne(this,Br,0);Ne(this,fs,5);Ne(this,Or,()=>{this.debugLog("Connected to event bus"),De(this,oo,true),this.debugLog("Emitting queued events",$(this,Da)),$(this,Da).forEach(o=>this.emitEventToBus(o)),De(this,Da,[]),this.stopConnectLoop(),$(this,ct).call(this).removeEventListener("tanstack-connect-success",$(this,Or));});Ne(this,Uo,()=>{if($(this,ct).call(this).addEventListener("tanstack-connect-success",$(this,Or)),$(this,Br)<$(this,fs)){Hd(this,Br)._++,this.dispatchCustomEvent("tanstack-connect",{});return}$(this,ct).call(this).removeEventListener("tanstack-connect",$(this,Uo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});De(this,bt,o),De(this,Ea,a),De(this,ct,this.getGlobalTarget),De(this,Fr,t),this.debugLog(" Initializing event subscription for plugin",$(this,bt)),De(this,Da,[]),De(this,oo,false),De(this,da,null),De(this,zo,n);}startConnectLoop(){$(this,da)!==null||$(this,oo)||(this.debugLog(`Starting connect loop (every ${$(this,zo)}ms)`),De(this,da,setInterval($(this,Uo),$(this,zo))));}stopConnectLoop(){$(this,da)!==null&&(clearInterval($(this,da)),De(this,da,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,ct).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{$(this,ct).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,oo)){this.debugLog("Bus not available, will be pushed as soon as connected"),$(this,Da).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,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,ct).call(this).addEventListener(a,n),this.debugLog("Registered event to bus",a),()=>{$(this,ct).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,ct).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,ct).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,bt)&&n.pluginId!==$(this,bt)||o(n);};return $(this,ct).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,ct).call(this).removeEventListener("tanstack-devtools-global",t)}};Ea=new WeakMap,bt=new WeakMap,ct=new WeakMap,Fr=new WeakMap,Da=new WeakMap,oo=new WeakMap,da=new WeakMap,zo=new WeakMap,Br=new WeakMap,fs=new WeakMap,Or=new WeakMap,Uo=new WeakMap;var xl=class extends ro{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},pc=(e,o)=>{bl.emit(e,o);},bl=new xl;function hc(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var sb={enabled:true,leading:true,trailing:true,wait:0},Ra,Pt,no,so,io,Wo,ms=class{constructor(o,t){Ne(this,Ra);Ne(this,Pt);Ne(this,no);Ne(this,so);Ne(this,io);Ne(this,Wo);this.fn=o,this.store=new aa(hc()),this.setOptions=a=>{this.options={...this.options,...a},$(this,no).call(this)||this.cancel();},De(this,Pt,a=>{this.store.setState(n=>{let r={...n,...a},{isPending:s}=r;return {...r,status:$(this,no).call(this)?s?"pending":"idle":"disabled"}}),pc("Throttler",this);}),De(this,no,()=>!!gl(this.options.enabled,this)),De(this,so,()=>gl(this.options.wait,this)),this.maybeExecute=(...a)=>{$(this,Pt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let n=Date.now(),r=n-this.store.state.lastExecutionTime,s=$(this,so).call(this);if(this.options.leading&&r>=s)$(this,io).call(this,...a);else if($(this,Pt).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,Pt).call(this,{isPending:true}),De(this,Ra,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&$(this,io).call(this,...c);},i));}},De(this,io,(...a)=>{if(!$(this,no).call(this))return;this.fn(...a);let n=Date.now(),r=n+$(this,so).call(this);$(this,Wo).call(this),$(this,Pt).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,Pt).call(this,{nextExecutionTime:void 0});},$(this,so).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&$(this,io).call(this,...this.store.state.lastArgs);},De(this,Wo,()=>{$(this,Ra)&&(clearTimeout($(this,Ra)),De(this,Ra,void 0));}),this.cancel=()=>{$(this,Wo).call(this),$(this,Pt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{$(this,Pt).call(this,hc());},this.key=mc(t.key),this.options={...sb,...t},$(this,Pt).call(this,this.options.initialState??{}),bl.on("d-Throttler",a=>{a.payload.key===this.key&&($(this,Pt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Ra=new WeakMap,Pt=new WeakMap,no=new WeakMap,so=new WeakMap,io=new WeakMap,Wo=new WeakMap;function vl(e,o){return new ms(e,o).maybeExecute}function Fa(e,o){return typeof e=="function"?e(o):e}function Ba(e,o){return xs(o).reduce((a,n)=>{if(a===null)return null;if(typeof a<"u")return a[n]},e)}function Ko(e,o,t){let a=xs(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 wl(e,o){let t=xs(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 ib=/^(\d+)$/gm,lb=/\.(\d+)(?=\.)/gm,db=/^(\d+)\./gm,ub=/\.(\d+$)/gm,cb=/\.{2,}/gm,yl="__int__",ps=`${yl}$1`;function xs(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(ib,ps).replace(lb,`.${ps}.`).replace(db,`${ps}.`).replace(ub,`.${ps}`).replace(cb,".").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 Go(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 jo(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 bs=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},vs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function et(e,o){return e==null?o:{...e,...o}}var lo=256,gs=[],hs;for(;lo--;)gs[lo]=(lo+256).toString(16).substring(1);function Ll(){let e=0,o,t="";if(!hs||lo+16>256){for(hs=new Array(256),e=256;e--;)hs[e]=256*Math.random()|0;e=0,lo=0;}for(;e<16;e++)o=hs[lo+e],e===6?t+=gs[o&15|64]:e===8?t+=gs[o&63|128]:t+=gs[o],e&1&&e>1&&e<11&&(t+="-");return lo++,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 fb(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 gc=(e,o)=>{let t=fb(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:gc(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:gc(a.issues,e)}},ys=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[b,y]=[Math.min(l,h),Math.max(l,h)];for(let x=b;x<=y;x++)p.push(t(d,x));}else {let b=e.getFieldValue(d),y=Array.isArray(b)?b.length:0;for(let x=l+1;x<y;x++)p.push(t(d,x));}return Object.keys(e.fieldInfo).filter(b=>p.some(y=>b.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),b=e.getFieldMeta(p);b?e.setFieldMeta(h,b):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(b=>b.startsWith(t(l,m))).map(b=>[b,e.getFieldMeta(b)]));r(d,m<h?"up":"down"),Object.keys(e.fieldInfo).filter(b=>b.startsWith(t(l,h))).forEach(b=>{let y=b.replace(t(l,h),t(l,m)),x=p.get(y);x&&e.setFieldMeta(b,x);});},f=(d,l,m,h)=>{d.forEach(p=>{if(!p.toString().startsWith(t(l,m)))return;let b=p.toString().replace(t(l,m),t(l,h)),[y,x]=[e.getFieldMeta(p),e.getFieldMeta(b)];y&&e.setFieldMeta(b,y),x&&e.setFieldMeta(p,x);});};return {handleArrayFieldMetaShift:o}}var Il=class extends ro{constructor(){super({pluginId:"form-devtools"});}},Et=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(),Et.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return Et.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||(At(()=>{this.baseStore.setState(()=>Cl(Object.assign({},this.state,u?a.defaultState:{},s?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),Et.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 At(()=>{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 At(()=>{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=Go(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Na}),r=false,s={};return At(()=>{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}=ws(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:b,errorSourceMap:y}=p,x=l?.[h],{newErrorValue:g,newSource:L}=bs({newFormValidatorError:x,isPreviousErrorFromFormValidator:y?.[m]==="form",previousErrorValue:b?.[m]});L==="form"&&(s[h]={...s[h],[m]:x}),b?.[m]!==g&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[m]:g},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=jo(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((x,g)=>{setTimeout(async()=>{if(l.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(L){g(L);}},c.debounceMs);});}catch(x){h=x;}let{formError:p,fieldErrors:b}=ws(h);b&&(s=s?{...s,...b}:b);let y=qr(c.cause);for(let x of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[x]===void 0)continue;let g=this.getFieldMeta(x);if(!g)continue;let{errorMap:L,errorSourceMap:I}=g,R=s?.[x],{newErrorValue:C,newSource:w}=bs({newFormValidatorError:R,isPreviousErrorFromFormValidator:I?.[y]==="form",previousErrorValue:L?.[y]});L?.[y]!==C&&this.setFieldMeta(x,k=>({...k,errorMap:{...k.errorMap,[y]:C},errorSourceMap:{...k.errorSourceMap,[y]:w}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.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]=_o,n},{}),this.setFieldValue=(a,n,r)=>{let s=r?.dontUpdateMeta??false,u=r?.dontRunListeners??false,i=r?.dontValidate??false;At(()=>{s||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:Ko(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)],et(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),et(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),et(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 Ko(Ko(i,`${n}`,f),`${r}`,c)},et(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},et(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,[],et(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?Ko(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??Ll(),this._devtoolsSubmissionOverride=false,this.baseStore=new aa(Cl({...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),b=h?.errors;if(!m||l.errorMap!==m.errorMap){b=Object.values(l.errorMap??{}).filter(I=>I!==void 0);let L=this.getFieldInfo(d)?.instance;L&&!L.options.disableErrorFlat&&(b=b?.flat(1));}let y=!Sl(b??[]),x=!l.isDirty,g=Oa(p,Ba(this.options.defaultValues,d))||Oa(p,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===x&&h.isValid===y&&h.isDefaultValue===g&&h.errors===b&&l===m){f[d]=h,c++;continue}f[d]={...l,errors:b,isPristine:x,isValid:y,isDefaultValue:g};}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(E=>E.isValidating),l=f.every(E=>E.isValid),m=f.some(E=>E.isTouched),h=f.some(E=>E.isBlurred),p=f.every(E=>E.isDefaultValue),b=m&&i.errorMap?.onMount,y=f.some(E=>E.isDirty),x=!y,g=!!(i.errorMap?.onMount||f.some(E=>E?.errorMap?.onMount)),L=!!d,I=s?.errors??[];(!u||i.errorMap!==u.errorMap)&&(I=Object.values(i.errorMap).reduce((E,V)=>V===void 0?E:V&&Nr(V)?(E.push(V.form),E):(E.push(V),E),[]));let R=I.length===0,C=l&&R,w=this.options.canSubmitWhenInvalid??false,k=i.submissionAttempts===0&&!m&&!g||!L&&!i.isSubmitting&&C||w,v=i.errorMap;if(b&&(I=I.filter(E=>E!==i.errorMap.onMount),v=Object.assign(v,{onMount:void 0})),s&&u&&s.errorMap===v&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===I&&s.isFieldsValidating===d&&s.isFieldsValid===l&&s.isFormValid===R&&s.isValid===C&&s.canSubmit===k&&s.isTouched===m&&s.isBlurred===h&&s.isPristine===x&&s.isDefaultValue===p&&s.isDirty===y&&Oa(u,i))return s;let M={...i,errorMap:v,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:l,isFormValid:R,isValid:C,canSubmit:k,isTouched:m,isBlurred:h,isPristine:x,isDefaultValue:p,isDirty:y},A=this.options.transform?.deps??[];if(A.length!==this.prevTransformArray.length||A.some((E,V)=>E!==this.prevTransformArray[V])){let E=Object.assign({},this,{state:M});this.options.transform?.fn(E),M=E.state,this.prevTransformArray=A;}return M}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=vl(a=>Et.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),Et.on("request-form-state",a=>{a.payload.id===this._formId&&Et.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Et.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),Et.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return ys(o.validate)?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})),At(()=>{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}),Et.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}),Et.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}At(()=>{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}),At(()=>{this.baseStore.setState(n=>({...n,isSubmitted:!0,isSubmitSuccessful:!0})),Et.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(n){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),Et.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:n}),a(),n}}setErrorMap(o){At(()=>{Object.entries(o).forEach(([t,a])=>{let n=t;if(Nr(a)){let{formError:r,fieldErrors:s}=ws(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 ws(e){if(e){if(Nr(e)){let o=ws(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,et(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,et(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,n)=>{this.form.insertFieldValue(this.name,t,a,et(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,n)=>{this.form.replaceFieldValue(this.name,t,a,et(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,et(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,n)=>{this.form.swapFieldValues(this.name,t,a,et(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,n)=>{this.form.moveFieldValues(this.name,t,a,et(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,et(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=Go(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Na}),s=this.getLinkedFields(t).reduce((c,f)=>{let d=Go(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Na});return d.forEach(l=>{l.field=f;}),c.concat(d)},[]),u=false;At(()=>{let c=(f,d)=>{let l=Ss(d.cause),m=d.validate?xc(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:b}=vs({formLevelError:h,fieldLevelError:m});f.state.meta.errorMap?.[l]!==p&&f.setMeta(y=>({...y,errorMap:{...y.errorMap,[l]:p},errorSourceMap:{...y.errorSourceMap,[l]:b}})),p&&(u=!0);};for(let f of n)c(this,f);for(let f of s)f.validate&&c(f.field,f);});let i=Ss("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=jo(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=jo(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=Ss(m.cause);l.getInfo().validationMetaMap[p]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:y},h.push(new Promise(async x=>{let g;try{g=await new Promise((w,k)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(y.signal.aborted)return w(void 0);try{w(await this.runValidator({validate:m.validate,value:{value:l.store.state.value,fieldApi:l,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(v){k(v);}},m.debounceMs);});}catch(w){g=w;}if(y.signal.aborted)return x(void 0);let L=xc(g),I=r[this.name]?.[p],{newErrorValue:R,newSource:C}=vs({formLevelError:I,fieldLevelError:L});l.setMeta(w=>({...w,errorMap:{...w?.errorMap,[p]:R},errorSourceMap:{...w.errorSourceMap,[p]:C}})),x(R);}));};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[Ss(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>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)??{..._o,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return ys(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 xc(e){if(e)return e}function Ss(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function Ls(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,pb)}function pb(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=bc(e);if(t.length!==bc(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 bc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var $o=typeof window<"u"?useLayoutEffect:useEffect;function wb(e){let[o]=useState(()=>{let a=new zr({...e,form:e.form,name:e.name});return a.Field=kl,a});return $o(o.mount,[o]),$o(()=>{o.update(e);}),Ls(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var kl=(({children:e,...o})=>{let t=wb(o),a=useMemo(()=>Fa(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Ib({form:e,selector:o,children:t}){let a=Ls(e.store,o);return Fa(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(Ib,{form:a,selector:s.selector,children:s.children})},n});return $o(t.mount,[]),$o(()=>{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 Fb=({editElement:e})=>{let o=useDispatch(),t=useSelector(ye),a=useRef(null),n=We(),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?gt(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?Ht(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?ia(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?Za(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(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,x)=>{let g=[...l.state.value.options];g[y]=x,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 x=l.state.value.options.filter((L,I)=>I!==y),g=l.state.value.correctIndex?.filter(L=>L!==y).map(L=>L>y?L-1:L);l.handleChange({...l.state.value,options:x,correctIndex:g});},b=y=>{let x=l.state.value.correctIndex||[];if(x.includes(y))l.handleChange({...l.state.value,correctIndex:x.filter(L=>L!==y)});else {if(x.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...x,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,x)=>{let g=!y.trim(),L=l.state.value.correctIndex?.includes(x),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:()=>b(x),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 ${x+1}`,value:y,onChange:R=>m(x,R.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(x),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"})})]},x)})}),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)},wc=Fb;var Cc=({text:e,position:o})=>{let t=Le(),a=(f,d,l,m,h)=>{let b=document.createElement("canvas").getContext("2d");if(!b)return {width:e.width,height:e.height};b.font=`${h} ${m} ${d}px ${l}`;let y=f.split(`
|
|
4
|
+
`),x=0;for(let I of y){let R=b.measureText(I||" ");R.width>x&&(x=R.width);}let L=y.length*d*1.2;return {width:Math.max(200,x+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(ce()),t(Nt({id:e.id,fontSize:d,width:l.width,height:l.height}));},r=f=>{t(ce()),t(Nt({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(ce()),t(Nt({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(ce()),t(Nt({id:e.id,fontStyle:f,width:d.width,height:d.height}));},i=()=>{t(ce()),t(Nt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},c=f=>{let d=a(e.text,e.fontSize,f,e.fontWeight,e.fontStyle);t(ce()),t(Nt({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 Tc=({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 b=d.offsetWidth;b>m&&(m=b);}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 _b=(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},Mc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s})=>{let u=useSelector(v=>v.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||""),[b,y]=useState(false);useEffect(()=>{let v=f.current;if(v)return a.current.set(e.id,v),()=>{a.current.delete(e.id);}},[e.id,a]);let x=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=b&&h.trim().toLowerCase()===x,L=v=>{p(v);let M=v.trim(),A=M.toLowerCase()===x;c(ia({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:M,isCorrect:A}}}));},I=()=>{y(false),p(""),c(ia({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:"",isCorrect:false}}}));},R=()=>g?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",C=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},w=e.data.feedbackMode==="practice",k=useMemo(()=>{let V=w?48:0,W=12,G=30,H=e.width-48,j=Math.max(60,_b(e.data.question,18,H,"bold")+20),ie=b?40:0,K=b?54:20,O=j+ie+G+50+12+W+V+24;return {padding:24,questionHeight:j,questionFontSize:18,feedbackHeight:ie,feedbackFontSize:12,inputY:K,inputHeight:50,inputMargin:12,buttonHeight:V,buttonTopMargin:W,placeholderHeight:G,contentWidth:H,totalHeight:O}},[e.width,e.data.question,b,g,w,R]);return jsxs(Group,{ref:f,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:k.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:k.totalHeight,onTransformEnd:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,n(v.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:g?"#22c55e":b?"#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:b?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:v=>L(v.target.value),disabled:b,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:b?"none":"auto"}})}),b&&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:R()+` (${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:v=>{v.cancelBubble=true,l("check");},onMouseUp:v=>{v.cancelBubble=true,l(null),h.length>0&&(y(true),c(ia({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},onMouseLeave:v=>{v.cancelBubble=true,l(null);},onTouchStart:v=>{v.cancelBubble=true,l("check");},onTouchEnd:v=>{v.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)/(b?2:1),height:k.buttonHeight,fill:h.length===0||b?"#9ca3af":"#096B76",cornerRadius:8,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true}),jsx(Text,{x:k.padding+14,width:(k.contentWidth-24)/(b?2:1),height:k.buttonHeight,text:b?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),b&&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:v=>v.cancelBubble=true,onTap:v=>v.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})]})]})]})});Mc.displayName="ShortAnswer";var Ac=Mc;var Ec=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=Ue({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Ac,{shortAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"shortAnswer")},i.id))})};var Dc=e=>{let o=useDispatch(),a=useSelector(ye)?.fillInTheBlanks||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(La({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},Rc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:n,fibRefs:r,touchHandlers:s})=>{let u=useSelector(v=>v.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||""),[b,y]=useState(false);useEffect(()=>{let v=c.current;if(v)return r.current.set(e.id,v),()=>{r.current.delete(e.id);}},[e.id,r]);let x=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=b&&h.trim().toLowerCase()===x,L=v=>{p(v);let M=v.trim(),A=M.toLowerCase()===x;f(La({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:M,isCorrect:A}}}));},I=()=>{y(false),p("");},R=()=>{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",w=useMemo(()=>{let G=e.width-48,H=(G-15)/2,j=24,ie=j,K=Math.max(60,El(e.data.question.replace("_____","________"),24,G,"bold")+20);j+=K;let O=j,z=Math.max(35,El("Enter your answer in the blank.",16,G)+10);j+=z;let U=j;j+=67;let J=j,ee=b?Math.max(32,El(g?"Right Answer, Great Job!":"Wrong Answer",14,G-40)+16):0;b&&(j+=ee+16);let X=j;return C&&(j+=64),j+=24,{padding:24,questionY:ie,questionHeight:K,questionFontSize:24,helperTextY:O,helperTextHeight:z,helperTextFontSize:16,inputY:U,inputHeight:51,feedbackY:J,feedbackHeight:ee,feedbackFontSize:14,buttonsY:X,buttonHeight:64,buttonGap:15,buttonWidth:H,contentWidth:G,totalHeight:j}},[e.width,e.data.question,b,g,C]),k=()=>b?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:v=>a(v,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:w.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,n?.(v.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:w.padding,y:w.questionY,fontSize:w.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:w.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:w.padding,y:w.helperTextY,fontSize:w.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:w.contentWidth,height:w.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:w.padding,y:w.inputY,width:w.contentWidth,height:w.inputHeight,fill:"#ffffff",stroke:k(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:w.padding,y:w.inputY},divProps:{style:{width:`${w.contentWidth}px`,height:`${w.inputHeight}px`,pointerEvents:b?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:v=>L(v.target.value),disabled:b,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"}})}),b&&jsxs(Group,{y:w.feedbackY,children:[jsx(Rect,{x:w.padding,width:w.contentWidth,height:w.feedbackHeight,fill:g?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:g?"\u2713":"\u2717",x:w.padding+10,y:0,width:16,height:w.feedbackHeight,fontSize:w.feedbackFontSize,fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:g?`Right Answer, Great Job! (${m} attempts)`:`Wrong Answer (${m} attempts)`,x:w.padding+30,y:0,height:w.feedbackHeight,fontSize:w.feedbackFontSize,fontStyle:"600",fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),C&&jsxs(Group,{y:w.buttonsY,children:[jsxs(Group,{x:w.padding,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true,onMouseDown:v=>{v.cancelBubble=true,l("reset");},onMouseUp:v=>{v.cancelBubble=true,l(null),I();},onMouseLeave:v=>{v.cancelBubble=true,l(null);},onTouchStart:v=>{v.cancelBubble=true,l("reset");},onTouchEnd:v=>{v.cancelBubble=true,l(null),I();},scaleX:d==="reset"?.98:1,scaleY:d==="reset"?.98:1,children:[jsx(Rect,{width:w.buttonWidth,height:w.buttonHeight,fill:b?"#096b76":"#9ca3af",cornerRadius:8}),jsx(Text,{width:w.buttonWidth,height:w.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:w.padding+w.buttonWidth+w.buttonGap,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true,onMouseDown:v=>{v.cancelBubble=true,!b&&l("submit");},onMouseUp:v=>{v.cancelBubble=true,!b&&(l(null),R());},onMouseLeave:v=>{v.cancelBubble=true,l(null);},onTouchStart:v=>{v.cancelBubble=true,!b&&l("submit");},onTouchEnd:v=>{v.cancelBubble=true,!b&&(l(null),R());},scaleX:d==="submit"?.98:1,scaleY:d==="submit"?.98:1,children:[jsx(Rect,{width:w.buttonWidth,height:w.buttonHeight,fill:h.length===0||b?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:w.buttonWidth,height:w.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Rc.displayName="FillInTheBlanks";var Fc=Rc;var Oc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,onLongPress:r,fibRefs:s})=>{let{createHandlers:u}=Ue({onLongPress:r});return jsx(Fragment,{children:e.map(i=>jsx(Fc,{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(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,b]=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()||"",x=p&&m.trim().toLowerCase()===y,g=w=>{h(w);let k=w.trim();k.toLowerCase()===y;f(Za({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:k}}}));},L=()=>{b(false),h("");},I=()=>x?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",R=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},C=useMemo(()=>{let W=e.width-48,G=Math.max(60,Fl(e.data.question,20,W,"bold")+20),H=p?Math.max(60,Fl(I(),14,W)+30):0,ie=Math.max(30,Fl("Answer (Extended response):",14,W)+10),K=G+H+ie+120+12+12+48+24;return {padding:24,questionHeight:G,questionFontSize:20,feedbackHeight:H,feedbackFontSize:14,placeholderHeight:ie,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:W,totalHeight:K}},[e.width,e.data.question,p,x,I]);return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:C.totalHeight,...r,name:"la-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:w=>{let k=c.current?.getStage()?.getPointerPosition();if(!k||!n)return;let v={x:e.x,y:e.y,width:e.width,height:C.totalHeight};k.x>=v.x&&k.x<=v.x+v.width&&k.y>=v.y&&k.y<=v.y+v.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,onTransformEnd:w=>t(e.id,w)}),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:R().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:R().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=>g(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})]})})]})});Ol.displayName="LongAnswer";var Hc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=Ue({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 co=1600,fo=900,Uc=3200,Wc=1800,Sv=e=>{let o=0,t=0,a=co,n=fo;if(!e)return {minX:o,minY:t,maxX:a,maxY:n,width:co,height:fo};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,Wc);return o=Math.max(o,a-Uc),t=Math.max(t,n-Wc),{minX:o,minY:t,maxX:a,maxY:n,width:s,height:u}},Lv=(e,o,t={minX:0,minY:0,maxX:co,maxY:fo,width:co,height:fo})=>{let a=Math.max(t.width,co),n=Math.max(t.height,fo),r=e/o,s=a/n,u,i,c,d=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 l=n*c;d=(o-l)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:d,baseWidth:u,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},Kc=(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}},Iv=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:n={enabled:true}}={})=>{let r=Ye(),s=We(),u=Q(S=>S.toolbar.selectedTool),i=Q(ye),c=Q(Ca),f=Q(Yn),d=Q(S=>S.canvas.zoomLevel),m=(i?.videos||[]).find(S=>S.isRecorded&&S.isPlaying),h=!!m,p=useCallback(()=>{m&&r($a(m.id));},[r,m]),b=i?.editingActivity,y=i?.showMcqForm,x=i?.lines||[],g=useRef(null),L=useRef(null),[I,R]=useState(null),[C,w]=useState(""),k=useRef(null),[v,M]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:co,stageHeight:fo,offsetX:0,offsetY:0,baseWidth:co,baseHeight:fo,contentOffsetX:0,contentOffsetY:0}),A=useMemo(()=>Sv(i||null),[c]),[B,E]=useState(null),[V,W]=useState(null),[G,H]=useState(null),[j,ie]=useState(null),[K,O]=useState(null),[z,U]=useState(null),[J,ee]=useState(null),[X$1,xe]=useState(false),[ne,we]=useState(null),[be,me]=useState(false),ue=useRef(null),Pe=useRef(null),it=useRef(null),{debouncedGenerateThumbnail:Ve}=xu(c,g);useEffect(()=>{let S=()=>{if(L.current){let D=L.current.getBoundingClientRect(),N=Lv(D.width,D.height,A);M(N);}};S();let T=new ResizeObserver(S);return L.current&&T.observe(L.current),window.addEventListener("resize",S),()=>{T.disconnect(),window.removeEventListener("resize",S);}},[A]),useEffect(()=>{if(g.current){let S=g.current.container();S&&(S.style.cursor="");}},[u]);let re=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(T=>T.batchDraw()),!f)try{let D=g.current.toDataURL({pixelRatio:.16666666666666666});w(D),Ve();}catch(T){console.warn("Preview generation failed (CORS):",T);}});},[Ve,f]),rn=useRef(c);useEffect(()=>{rn.current!==c&&(rn.current=c,re());},[c,re]);let nn=useRef(null),sn=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=nn.current?.count!==S;!sn.current&&T&&setTimeout(()=>{re();},100),nn.current={slideId:c,count:S},sn.current=false;},[i,c,re]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{it.current&&a&&a(it);},[a]);let{startDrawing:ln,draw:dn,stopDrawing:un,setCanvasRef:ja,tool:_s,color:$s,strokeWidth:Xs,isSketchMode:Ys}=Kd(re),ya=useRef(new Map),{images:cn,getLoadedImage:Zs,imageRefs:vo,handleDragEnd:fn,handleImageTransformEnd:Js}=Zd(re),{videos:sr,videoRefs:yo,handleVideoClick:mn,handleVideoDragEnd:P,handleVideoTransformEnd:oe}=eu(re),{multipleChoice:Ee,handleMcqTransform:Se,mcqRefs:le,handleDragEnd:de}=Jd(re),{trueFalse:ze,handleTrueFalseTransform:lt,trueFalseRefs:Bt,handleTrueFalseDragEnd:St}=Qd(re),{shortAnswers:Oe,saRefs:Ke,handleShortAnswerDragEnd:sa}=su(re),{longAnswers:wa,handleLongAnswerDragEnd:Qs}=iu(re),{fillInTheBlanks:ei,handleFillInTheBlanksDragEnd:pn,fibRefs:mt}=Dc(re),{transformerRef:se,boundBoxFunc:Lt}=mu(),{shapes:Wm,shapeRefs:hn,isDragging:kd,handleShapeDragEnd:Km,handleShapeResizeEnd:Gm}=ou(re),{texts:ir,textRefs:Sa,handleDragEnd:jm,handleTransformEnd:_m,handleDoubleClick:$m,startEditing:gn,editingTextId:ve,editingValue:Td,handleEditingChange:Md,finishEditing:ti}=nu(re,ue);useEffect(()=>{t&&t(gn);},[t,gn]);let xn=Q(S=>S.canvas.editingTextId);useEffect(()=>{xn&&xn!==ve&&gn(xn);},[xn,ve,gn]);let{flashcards:Xm,flashcardRefs:bn,handleDragEnd:Ym,handleFlashcardTransformEnd:Zm,handleNext:Jm,handlePrevious:Qm}=du(re),{photoFrames:Ad,photoFrameRefs:vn,handleDragEnd:ep,handlePhotoFrameTransformEnd:tp,startCamera:ap,capturePhoto:op,cameraStreams:rp}=fu(re);useEffect(()=>{if(se.current){if(ve){se.current.nodes([]),se.current.getLayer()?.batchDraw();return}if(I&&!sr.find(D=>D.id===I)?.isPlaying){let D=ya.current.get(I)||vo.current.get(I)||yo.current.get(I)||hn.current.get(I)||Sa.current.get(I)||le.current.get(I)||bn.current.get(I)||vn.current.get(I)||Ke.current.get(I)||Bt.current.get(I)||mt.current.get(I);if(D){let N=D.attrs?.locked;if(D.visible()&&N!==true){se.current.nodes([D]),se.current.getLayer()?.batchDraw();return}}}se.current.nodes([]),se.current.getLayer()?.batchDraw();}},[I,ve,sr,ya,vo,yo,hn,Sa,bn,vn,Ad,le,Bt,mt,se]);let Ge=useCallback(S=>{R(S),o?.(S);},[o]),wo=useCallback(()=>{R(null),o?.(null),se.current&&(se.current.nodes([]),se.current.getLayer()?.batchDraw());},[se,o]),Pd=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]),Ed=useCallback((S,T)=>{switch(r(ce()),T){case "line":r($n(S));break;case "image":r(wn(S));break;case "video":r(In(S));break;case "shape":r(Tn(S));break;case "text":r(Mn(S));break;case "flashcard":r(Pn(S));break;case "photoFrame":r(Dn(S));break;case "mcq":r(Fn(S));break;case "trueFalse":r(On(S));break;case "shortAnswer":r(Hn(S));break;case "longAnswer":r(Vn(S));break;case "fillInTheBlanks":r(Un(S));break}wo(),re();},[r,wo,re]);useEffect(()=>{let S=T=>{if(T.key!=="Delete"||!I||ve)return;let D=document.activeElement;if(D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement||D?.getAttribute("contenteditable")==="true")return;T.preventDefault();let Ce=Pd(I);Ce&&Ed(I,Ce);};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[I,ve,Pd,Ed]),useEffect(()=>{let S=se.current;return ()=>{S&&S.nodes([]);}},[c]),useEffect(()=>{let S=T=>{ve&&T.target.tagName!=="TEXTAREA"&&ti();};return document.addEventListener("mousedown",S),()=>{document.removeEventListener("mousedown",S);}},[ve,ti]),useEffect(()=>{let S=ve||I;if(!S||I&&ve){W(null);return}let T=Sa.current.get(S),D=g.current;if(!T||!D){W(null);return}let N=D.container().getBoundingClientRect(),Ce=T.absolutePosition(),ge=D.scaleX();W({x:N.left+(Ce.x+T.width()*ge/2)*ge+v.offsetX,y:N.top+Ce.y*ge+v.offsetY-70});},[I,ve,ir,Sa,v.offsetX,v.offsetY]),useEffect(()=>{if(!ve){H(null);return}let S=Sa.current.get(ve),T=g.current;if(!S||!T){H(null);return}let D=S.getClientRect({relativeTo:T}),N=T.container().getBoundingClientRect(),Ce=T.scaleX(),ge=T.position(),ae={top:N.top+ge.y+D.y*Ce,left:N.left+ge.x+D.x*Ce,scale:Ce};H(ae),r(Vd(ae));},[ve,ir,Sa,v.offsetY,v.offsetX]);let Dd=useCallback(S=>{let T=S.target.getClassName(),D=S.target===S.target.getStage(),N=T==="Transformer"||S.target.getParent()?.getClassName()==="Transformer",Ce=T==="Image",ge=T==="Text",ae=T==="Group"||S.target.getParent()?.getClassName()==="Group",pt=T==="Circle"||T==="Star"||T==="RegularPolygon"||T==="Ellipse"||T==="Ring"||T==="Wedge"||T==="Arrow"||T==="Line"||T==="Arc"||T==="Rect"&&S.target.attrs.id,ht=T==="Group";if(D&&!N&&!Ce&&!ge&&!ae&&!pt&&!ht&&wo(),!(u==="pen"||u==="eraser")&&(Ce||ge||N||ae||pt||ht))return;let je=S.target.getStage()?.getPointerPosition();if(!je)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let q=Kc(je,v,d);ln(q);}},[u,ln,wo,v,d]),Rd=useCallback(S=>{if(kd)return;let T=S.target.getStage()?.getPointerPosition();if(!T)return;let D=Kc(T,v,d);dn(D);},[dn,kd,v,d]),Fd=useCallback(()=>{un();},[un]),np=useCallback(S=>{fn(S,re);},[fn,re]),sp=useCallback(S=>{mn(S),Ge(S);},[mn,Ge]),Ot=useCallback((S,T,D)=>{if(S.preventDefault(),!n.enabled)return;let N=S.clientX,Ce=S.clientY,ge=k.current?.offsetHeight||250,ae=k.current?.offsetWidth||200,pt=window.innerHeight,ht=window.innerWidth,at=N,je=Ce;Ce+ge>pt&&(je=Ce-ge),N+ae>ht&&(at=N-ae),Ge(T),E({x:at,y:je,elementId:T,elementType:D});},[Ge,n.enabled]),_a=useRef(null),lr=useRef(null),It=useCallback((S,T)=>D=>{if(!n.enabled)return;D.preventDefault();let N=D.changedTouches[0];if(!N)return;let Ce=N.clientX,ge=N.clientY,ae=k.current?.offsetHeight||200,pt=k.current?.offsetWidth||200,ht=window.innerHeight,at=window.innerWidth,je=Ce,ot=ge;ge+ae>ht&&(ot=ge-ae),Ce+pt>at&&(je=Ce-pt),Ge(S),E({x:je,y:ot,elementId:S,elementType:T});},[Ge,n.enabled]),ip=useCallback((S,T)=>({onTouchStart:D=>{let N=D.evt.touches[0];lr.current={x:N.clientX,y:N.clientY},_a.current=setTimeout(()=>{It(S,T)(D.evt);},500);},onTouchMove:D=>{if(!lr.current)return;let N=D.evt.touches[0],Ce=Math.abs(N.clientX-lr.current.x),ge=Math.abs(N.clientY-lr.current.y);(Ce>10||ge>10)&&_a.current&&(clearTimeout(_a.current),_a.current=null);},onTouchEnd:()=>{_a.current&&(clearTimeout(_a.current),_a.current=null),lr.current=null;}}),[It]),Bd=useCallback(S=>{r(hr(S)),r(Ia(true));},[r]),lp=useCallback(S=>{r(pr(S)),r(Ja(true));},[r]),dp=useCallback((S,T)=>{if(!B)return;let{elementId:D,elementType:N}=B;switch(S){case "order":if(T){let F=T.target.getBoundingClientRect();ie({x:F.right+5,y:F.top,type:"order"});}break;case "lock":if(T){let F=T.target.getBoundingClientRect();ie({x:F.right+5,y:F.top,type:"lock"});}break;case "link":if(E(null),N==="line")break;let Ce=i?N==="image"?i.images.find(F=>F.id===D):i.videos.find(F=>F.id===D):null;O({type:"link",defaultValue:Ce?.link||""});break;case "voice":if(E(null),N==="line")break;let ge=i?N==="image"?i.images.find(F=>F.id===D):N==="video"?i.videos.find(F=>F.id===D):N==="text"?i.texts.find(F=>F.id===D):N==="flashcard"?i.flashcards.find(F=>F.id===D):N==="photoFrame"?i.photoFrames.find(F=>F.id===D):N==="mcq"?i.multipleChoices.find(F=>F.id===D):N==="fillInTheBlanks"?i.fillInTheBlanks.find(F=>F.id===D):N==="longAnswer"?i.LongAnswer.find(F=>F.id===D):N==="shortAnswer"?i.shortAnswers.find(F=>F.id===D):N==="trueFalse"?i.trueFalses.find(F=>F.id===D):N==="shape"?i.shapes.find(F=>F.id===D):null:null;we({elementId:D,elementType:N,existingAudio:ge?.audioData});break;case "edit":E(null);let ae=null;N==="mcq"?ae=i?.multipleChoices.find(F=>F.id===D):N==="trueFalse"?ae=i?.trueFalses.find(F=>F.id===D):N==="shortAnswer"?ae=i?.shortAnswers.find(F=>F.id===D):N==="longAnswer"?ae=i?.LongAnswer.find(F=>F.id===D):N==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(F=>F.id===D)),ae&&Bd(ae);break;case "editFlashcard":E(null);let pt=i?.flashcards.find(F=>F.id===D);pt&&lp(pt);break;case "color":E(null);let ht=i?.shapes.find(F=>F.id===D);U({elementId:D,elementType:"shape",defaultColor:ht?.color||"#096B76"});break;case "border":if(E(null),N==="shape"){r(ce());let F=i?.shapes.find(oi=>oi.id===D);F&&r(Xa({id:D,hasBorder:!F.hasBorder})),re();}break;case "crop":if(E(null),N==="image"){let F=i?.images.find(oi=>oi.id===D);F&&ee({elementId:D,imageSrc:F.src});}break;case "draw":E(null),N==="image"?r(xi(D)):N==="photoFrame"&&r(vi(D));break;case "duplicate":r(ce()),N==="line"?r(Di(D)):N==="image"?r(Sn(D)):N==="video"?r(Cn(D)):N==="shape"?r(kn(D)):N==="text"?r(An(D)):N==="flashcard"?r(En(D)):N==="photoFrame"?r(Rn(D)):N==="mcq"?r(Bn(D)):N==="trueFalse"?r(Nn(D)):N==="shortAnswer"?r(qn(D)):N==="fillInTheBlanks"?r(Wn(D)):N==="longAnswer"&&r(zn(D)),re();break;case "infinite-clone":r(ce());let at=5;for(let F=0;F<at;F++)N==="image"?r(Sn(D)):N==="video"?r(Cn(D)):N==="shape"?r(kn(D)):N==="text"?r(An(D)):N==="flashcard"?r(En(D)):N==="photoFrame"?r(Rn(D)):N==="mcq"?r(Bn(D)):N==="trueFalse"?r(Nn(D)):N==="shortAnswer"?r(qn(D)):N==="fillInTheBlanks"?r(Wn(D)):N==="longAnswer"&&r(zn(D));re();break;case "make-response":if(E(null),N==="line")break;let je=`#response-${D}`;r(ce()),r(Kn({id:D,type:N,link:je})),(i?N==="image"?i.images.find(F=>F.id===D):N==="video"?i.videos.find(F=>F.id===D):N==="shape"?i.shapes.find(F=>F.id===D):N==="flashcard"?i.flashcards.find(F=>F.id===D):N==="photoFrame"?i.photoFrames.find(F=>F.id===D):i.multipleChoices.find(F=>F.id===D):null)?.altText||r(Gn({id:D,type:N,altText:"Interactive response area"})),re(),console.log(`Element ${D} marked as interactive response area`);break;case "accessibility":if(E(null),N==="line")break;let q=i?N==="image"?i.images.find(F=>F.id===D):N==="video"?i.videos.find(F=>F.id===D):N==="shape"?i.shapes.find(F=>F.id===D):null:null;O({type:"altText",defaultValue:q?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),E(null),me(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ce()),N==="line"?r($n(D)):N==="image"?r(wn(D)):N==="video"?r(In(D)):N==="shape"?r(Tn(D)):N==="text"?r(Mn(D)):N==="flashcard"?r(Pn(D)):N==="photoFrame"?r(Dn(D)):N==="mcq"?r(Fn(D)):N==="trueFalse"?r(On(D)):N==="shortAnswer"?r(Hn(D)):N==="longAnswer"?r(Vn(D)):N==="fillInTheBlanks"&&r(Un(D)),wo(),re();break}},[B,r,re,wo,i,Bd]),up=useCallback(()=>{E(null),ie(null);},[]),ai=useCallback(S=>{if(!B)return;let{elementId:T,elementType:D}=B;switch(r(ce()),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(),E(null),ie(null);},[B,r,re]),cp=useCallback(S=>{if(!B||!K)return;let{elementId:T,elementType:D}=B;r(ce()),K.type==="link"&&D!=="line"?r(Kn({id:T,type:D,link:S})):K.type==="altText"&&D!=="line"&&r(Gn({id:T,type:D,altText:S})),re(),O(null);},[B,K,r,re]),fp=useCallback(S=>{if(!ne)return;let{elementId:T,elementType:D}=ne;r(ce()),r(jn({id:T,type:D,audioData:S})),re(),we(null);},[ne,r,re]),mp=useCallback(()=>{if(!ne)return;let{elementId:S,elementType:T}=ne;r(ce()),r(jn({id:S,type:T,audioData:""})),re();},[ne,r,re]),pp=useCallback(S=>{if(!z)return;let{elementId:T}=z;r(ce()),r(Xa({id:T,color:S})),re(),U(null);},[z,r,re]),hp=useCallback(S=>{if(!J)return;let{elementId:T}=J;r(ce()),r(Lo({id:T,src:S})),re(),ee(null);},[J,r,re]);return jsxs("div",{ref:L,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Xd,{ref:S=>{if(Pe.current=S,ja(S),S){let T=S.getCanvasElement();T&&(it.current=T,a&&a(it));}},width:v.baseWidth,height:v.baseHeight,tool:_s,color:$s,strokeWidth:Xs/(v.scale*d),isSketchMode:Ys,xOffset:v.contentOffsetX,yOffset:v.contentOffsetY-v.offsetY/v.scale,style:{width:v.stageWidth,height:v.stageHeight}}),jsxs(Stage,{ref:g,width:v.stageWidth,height:v.stageHeight,scaleX:v.scaleX*d,scaleY:v.scaleY*d,x:v.offsetX,y:0,onMouseDown:Dd,onMouseMove:Rd,onMouseUp:Fd,onTouchStart:Dd,onTouchMove:Rd,onTouchEnd:Fd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:v.baseWidth,height:v.stageHeight/v.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-v.contentOffsetX,y:v.offsetY/v.scale-v.contentOffsetY,children:(()=>{let S=[];return x.forEach((T,D)=>{S.push({type:"line",timestamp:T.timestamp||D,element:{...T,id:T.id??`line-${D}`},index:D});}),Wm.forEach(T=>{S.push({type:"shape",timestamp:T.timestamp||0,element:T});}),cn.forEach(T=>{S.push({type:"image",timestamp:T.timestamp||0,element:T});}),sr.forEach(T=>{S.push({type:"video",timestamp:T.timestamp||0,element:T});}),ir.forEach(T=>{S.push({type:"text",timestamp:T.timestamp||0,element:T});}),Xm.forEach(T=>{S.push({type:"flashcard",timestamp:T.timestamp||0,element:T});}),Ad.forEach(T=>{S.push({type:"photoFrame",timestamp:T.timestamp||0,element:T});}),Ee.forEach(T=>{S.push({type:"mcq",timestamp:T.timestamp||0,element:T});}),ze.forEach(T=>{S.push({type:"trueFalse",timestamp:T.timestamp||0,element:T});}),Oe.forEach(T=>{S.push({type:"shortAnswer",timestamp:T.timestamp||0,element:T});}),wa.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 N=`${T.type}-${"id"in T.element&&T.element.id||T.index||D}`,Ce="id"in T.element?T.element.id:void 0,ge=Ce&&I===Ce;switch(T.type){case "line":let ae=T.element,pt=T.index||0,ht=ae.tool==="eraser",at=ae.isSketch&&ae.tool==="pen",je=ae.isSketch&&ht,ot=ae.id||`line-${pt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),u==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:at||je?void 0:ae.color,strokeWidth:at||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:at||je?ht?"black":ae.color:void 0,closed:at||je,tension:0,globalCompositeOperation:ht?"destination-out":"source-over",listening:true,onClick:()=>{r(ce()),r(yn(pt));},onTap:()=>{r(ce()),r(yn(pt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:q=>{let F=q.target.getStage();F&&(F.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:q=>{let F=q.target.getStage();F&&(F.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},N):jsxs(Ie__default.Fragment,{children:[jsx(Group,{id:ot,ref:q=>{q?ya.current.set(ot,q):ya.current.delete(ot);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",ot),Ge(ot));},onTap:()=>{u==="select"&&(console.log("Line tapped:",ot),Ge(ot));},onDragEnd:q=>{r(ce()),r(_n({id:ot,x:q.target.x(),y:q.target.y(),scaleX:q.target.scaleX(),scaleY:q.target.scaleY(),rotation:q.target.rotation()})),re();},onTransformEnd:q=>{r(ce()),r(_n({id:ot,x:q.target.x(),y:q.target.y(),scaleX:q.target.scaleX(),scaleY:q.target.scaleY(),rotation:q.target.rotation()})),re();},onMouseEnter:q=>{if(u==="select"){let F=q.target.getStage();F&&(F.container().style.cursor="move");}},onMouseLeave:q=>{if(u==="select"){let F=q.target.getStage();F&&(F.container().style.cursor="default");}},onContextMenu:q=>{let F=q.evt;F.preventDefault(),Ot(F,ot,"line");},...ip(ot,"line"),children:jsx(Line,{points:ae.points||[],stroke:at||je?void 0:ae.color,strokeWidth:at||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:at||je?ht?"black":ae.color:void 0,closed:at||je,tension:0,globalCompositeOperation:ht?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=ya.current.get(I);console.log("Line Transformer - selectedId:",I,"node found:",!!F),F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:Lt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "shape":return jsxs(Ie__default.Fragment,{children:[jsx(Xi,{onSelect:Ge,shapes:[T.element],shapeRefs:hn,handleShapeDragEnd:Km,handleShapeResizeEnd:Gm,onContextMenu:Ot,onLongPress:It}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=hn.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},boundBoxFunc:Lt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "image":return jsxs(Ie__default.Fragment,{children:[jsx(Gi,{images:[T.element],getLoadedImage:Zs,imageRefs:vo,onDragEnd:np,onTransform:Js,onSelect:Ge,onContextMenu:Ot,onLongPress:It}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=vo.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},boundBoxFunc:Lt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "video":return jsxs(Ie__default.Fragment,{children:[jsx($i,{videos:[T.element],selectedId:I,videoRefs:yo,onVideoClick:sp,onDragEnd:P,onTransformEnd:oe,onContextMenu:Ot,onLongPress:It}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=yo.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},boundBoxFunc:Lt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "text":return jsxs(Ie__default.Fragment,{children:[jsx(Au,{texts:[T.element],textRefs:Sa,onDragEnd:jm,onTransformEnd:_m,onSelect:Ge,onContextMenu:Ot,onLongPress:It,onDoubleClick:$m,editingTextId:ve,editingValue:Td,onEditingChange:Md}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=Sa.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},boundBoxFunc:Lt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "flashcard":return jsxs(Ie__default.Fragment,{children:[jsx(Qi,{flashcards:[T.element],flashcardRefs:bn,selectedId:I,onDragEnd:Ym,onTransform:Zm,onSelect:Ge,onNext:Jm,onPrevious:Qm,onContextMenu:Ot,onLongPress:It}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=bn.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},boundBoxFunc:Lt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "photoFrame":return jsxs(Ie__default.Fragment,{children:[jsx(nl,{photoFrames:[T.element],photoFrameRefs:vn,selectedId:I,onDragEnd:ep,onTransform:tp,onSelect:Ge,onStartCamera:ap,onCapture:op,cameraStreams:rp,onContextMenu:Ot,onLongPress:It}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=vn.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},boundBoxFunc:Lt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "mcq":return jsxs(Ie__default.Fragment,{children:[jsx(sc,{handleMcqTransform:Se,multipleChoice:[T.element],handleSelect:Ge,mcqRefs:le,handleDragEnd:de,onContextMenu:Ot,onLongPress:It,onUpdate:re}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=le.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "trueFalse":return jsxs(Ie__default.Fragment,{children:[jsx(uc,{trueFalses:[T.element],handleTrueFalseTransform:lt,handleSelect:Ge,trueFalseRefs:Bt,onContextMenu:Ot,onLongPress:It,handleDragEnd:St,onUpdate:re}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=Bt.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "shortAnswer":return jsxs(Ie__default.Fragment,{children:[jsx(Ec,{shortAnswers:[T.element],handleSelect:Ge,handleTransform:Se,saRefs:Ke,onContextMenu:Ot,onLongPress:It,handleDragEnd:sa}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=Ke.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "longAnswer":return jsxs(Ie__default.Fragment,{children:[jsx(Hc,{longAnswer:[T.element],handleSelect:Ge,handleTransform:Se,saRefs:Ke,onContextMenu:Ot,onLongPress:It,handleDragEnd:Qs}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=Ke.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);case "fillInTheBlanks":return jsxs(Ie__default.Fragment,{children:[jsx(Oc,{fillInTheBlanks:[T.element],handleSelect:Ge,handleTransform:Se,onContextMenu:Ot,onLongPress:It,handleDragEnd:pn,fibRefs:mt}),ge&&!ve&&I&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let F=mt.current.get(I);F&&F.visible()&&(q.nodes([F]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},N);default:return null}})})()})]}),B&&jsx(Uu,{menuRef:k,x:B.x,y:B.y,type:B.elementType,onAction:dp,onClose:up,isDrawingMode:B.elementType==="image"?i?.images.find(S=>S.id===B.elementId)?.isDrawingMode:B.elementType==="photoFrame"?i?.photoFrames.find(S=>S.id===B.elementId)?.isDrawingMode:false}),j&&B&&jsx(Wu,{x:j.x,y:j.y,items:j.type==="order"?[{label:"Bring to Front",onClick:()=>ai("bring-to-front")},{label:"Send to Back",onClick:()=>ai("send-to-back")}]:[{label:i&&(B.elementType==="image"?i.images.find(S=>S.id===B.elementId)?.locked:i.videos.find(S=>S.id===B.elementId)?.locked)?"Unlock":"Lock",onClick:()=>ai(i&&(B.elementType==="image"?i.images.find(S=>S.id===B.elementId)?.locked:i.videos.find(S=>S.id===B.elementId)?.locked)?"unlock":"lock")}],onClose:()=>ie(null)}),K&&jsx(ju,{title:K.type==="link"?"Add Link":"Add Alt Text",label:K.type==="link"?"URL":"Alternative Text",placeholder:K.type==="link"?"https://example.com":"Describe this image/video",defaultValue:K.defaultValue,onSave:cp,onClose:()=>O(null)}),z&&jsx(os,{defaultColor:z.defaultColor,onConfirm:pp,onCancel:()=>U(null)}),J&&jsx(Yu,{imageSrc:J.imageSrc,onConfirm:hp,onCancel:()=>ee(null)}),X$1&&jsx(Qa,{onClose:()=>xe(false),stageRef:g}),ne&&jsx(ec,{elementId:ne.elementId,elementType:ne.elementType,existingAudio:ne.existingAudio,onSave:fp,onDelete:mp,onClose:()=>we(null)}),be&&jsx(oc,{selectedElementId:I||void 0,onClose:()=>me(false),onSelectElement:S=>{Ge(S),me(false);}}),i?.images.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.videos.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.shapes?.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.texts?.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.flashcards?.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.photoFrames?.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.multipleChoices?.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.trueFalses?.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.shortAnswers?.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.LongAnswer?.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),i?.fillInTheBlanks?.filter(S=>S.audioData).map(S=>jsx(zt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:v.scale,offsetX:v.offsetX,offsetY:v.offsetY},`audio-${S.id}`)),y&&jsx(wc,{editElement:b}),V&&(()=>{let S=ve||I;if(!S)return null;let T=ir.find(D=>D.id===S);return T?jsx(Cc,{text:T,position:V}):null})(),G&&ve&&(()=>{let S=ir.find(T=>T.id===ve);return S?jsx(Tc,{text:S,editingValue:Td,onEditingChange:Md,onFinish:ti,position:{top:G.top,left:G.left},scale:G.scale,textareaRef:ue},ve):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)]})},Cv=Iv;var Tv="SchooplaVideoStorage";var oa="videos",Ms=()=>new Promise((e,o)=>{let t=indexedDB.open(Tv,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"});};}),ua=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Ms(),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 Gc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Ms(),t=e.transaction([oa],"readonly").objectStore(oa);return new Promise((a,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 Ms(),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 Ms(),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}},_c=e=>URL.createObjectURL(e);function qa(e,o=[]){let t=[];function a(r,s){let u=Ie.createContext(s),i=t.length;t=[...t,s];let c=d=>{let{scope:l,children:m,...h}=d,p=l?.[e]?.[i]||u,b=Ie.useMemo(()=>h,Object.values(h));return jsx(p.Provider,{value:b,children:m})};c.displayName=r+"Provider";function f(d,l){let m=l?.[e]?.[i]||u,h=Ie.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=>Ie.createContext(s));return function(u){let i=u?.[e]||r;return Ie.useMemo(()=>({[`__scope${e}`]:{...u,[e]:i}}),[u,i])}};return n.scopeName=e,[a,Av(n,...o)]}function Av(...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 Ie.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function $c(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=$c(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():$c(e[n],null);}}}}function jt(...e){return Ie.useCallback($r(...e),e)}function Zc(e){let o=Pv(e),t=Ie.forwardRef((a,n)=>{let{children:r,...s}=a,u=Ie.Children.toArray(r),i=u.find(Dv);if(i){let c=i.props.children,f=u.map(d=>d===i?Ie.Children.count(c)>1?Ie.Children.only(null):Ie.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Ie.isValidElement(c)?Ie.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Pv(e){let o=Ie.forwardRef((t,a)=>{let{children:n,...r}=t;if(Ie.isValidElement(n)){let s=Fv(n),u=Rv(r,n.props);return n.type!==Ie.Fragment&&(u.ref=a?$r(a,s):s),Ie.cloneElement(n,u)}return Ie.Children.count(n)>1?Ie.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Ev=Symbol("radix.slottable");function Dv(e){return Ie.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ev}function Rv(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 Fv(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 Nv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],yt=Nv.reduce((e,o)=>{let t=Zc(`Primitive.${o}`),a=Ie.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=Hv(e),t=Ie.forwardRef((a,n)=>{let{children:r,...s}=a,u=Ie.Children.toArray(r),i=u.find(Vv);if(i){let c=i.props.children,f=u.map(d=>d===i?Ie.Children.count(c)>1?Ie.Children.only(null):Ie.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Ie.isValidElement(c)?Ie.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Hv(e){let o=Ie.forwardRef((t,a)=>{let{children:n,...r}=t;if(Ie.isValidElement(n)){let s=Uv(n),u=zv(r,n.props);return n.type!==Ie.Fragment&&(u.ref=a?$r(a,s):s),Ie.cloneElement(n,u)}return Ie.Children.count(n)>1?Ie.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var qv=Symbol("radix.slottable");function Vv(e){return Ie.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===qv}function zv(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 Uv(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 As(e){let o=e+"CollectionProvider",[t,a]=qa(o),[n,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=p=>{let{scope:b,children:y}=p,x=Ie__default.useRef(null),g=Ie__default.useRef(new Map).current;return jsx(n,{scope:b,itemMap:g,collectionRef:x,children:y})};s.displayName=o;let u=e+"CollectionSlot",i=Hl(u),c=Ie__default.forwardRef((p,b)=>{let{scope:y,children:x}=p,g=r(u,y),L=jt(b,g.collectionRef);return jsx(i,{ref:L,children:x})});c.displayName=u;let f=e+"CollectionItemSlot",d="data-radix-collection-item",l=Hl(f),m=Ie__default.forwardRef((p,b)=>{let{scope:y,children:x,...g}=p,L=Ie__default.useRef(null),I=jt(b,L),R=r(f,y);return Ie__default.useEffect(()=>(R.itemMap.set(L,{ref:L,...g}),()=>void R.itemMap.delete(L))),jsx(l,{[d]:"",ref:I,children:x})});m.displayName=f;function h(p){let b=r(e+"CollectionConsumer",p);return Ie__default.useCallback(()=>{let x=b.collectionRef.current;if(!x)return [];let g=Array.from(x.querySelectorAll(`[${d}]`));return Array.from(b.itemMap.values()).sort((R,C)=>g.indexOf(R.ref.current)-g.indexOf(C.ref.current))},[b.collectionRef,b.itemMap])}return [{Provider:s,Slot:c,ItemSlot:m},h,a]}var Yo=globalThis?.document?Ie.useLayoutEffect:()=>{};var Wv=Ie[" useId ".trim().toString()]||(()=>{}),Kv=0;function tf(e){let[o,t]=Ie.useState(Wv());return Yo(()=>{t(a=>a??String(Kv++));},[e]),(o?`radix-${o}`:"")}function af(e){let o=Ie.useRef(e);return Ie.useEffect(()=>{o.current=e;}),Ie.useMemo(()=>(...t)=>o.current?.(...t),[])}var Gv=Ie[" useInsertionEffect ".trim().toString()]||Yo;function fa({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[n,r,s]=jv({defaultProp:o,onChange:t}),u=e!==void 0,i=u?e:n;{let f=Ie.useRef(e!==void 0);Ie.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=Ie.useCallback(f=>{if(u){let d=_v(f)?f(e):f;d!==e&&s.current?.(d);}else r(f);},[u,e,r,s]);return [i,c]}function jv({defaultProp:e,onChange:o}){let[t,a]=Ie.useState(e),n=Ie.useRef(t),r=Ie.useRef(o);return Gv(()=>{r.current=o;},[o]),Ie.useEffect(()=>{n.current!==t&&(r.current?.(t),n.current=t);},[t,n]),[t,a,r]}function _v(e){return typeof e=="function"}var $v=Ie.createContext(void 0);function Jo(e){let o=Ie.useContext($v);return e||o||"ltr"}var zl="rovingFocusGroup.onEntryFocus",Xv={bubbles:false,cancelable:true},Xr="RovingFocusGroup",[Ul,of,Yv]=As(Xr),[Zv,Wl]=qa(Xr,[Yv]),[Jv,Qv]=Zv(Xr),rf=Ie.forwardRef((e,o)=>jsx(Ul.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Ul.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(ey,{...e,ref:o})})}));rf.displayName=Xr;var ey=Ie.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=Ie.useRef(null),m=jt(o,l),h=Jo(r),[p,b]=fa({prop:s,defaultProp:u??null,onChange:i,caller:Xr}),[y,x]=Ie.useState(false),g=af(c),L=of(t),I=Ie.useRef(false),[R,C]=Ie.useState(0);return Ie.useEffect(()=>{let w=l.current;if(w)return w.addEventListener(zl,g),()=>w.removeEventListener(zl,g)},[g]),jsx(Jv,{scope:t,orientation:a,dir:h,loop:n,currentTabStopId:p,onItemFocus:Ie.useCallback(w=>b(w),[b]),onItemShiftTab:Ie.useCallback(()=>x(true),[]),onFocusableItemAdd:Ie.useCallback(()=>C(w=>w+1),[]),onFocusableItemRemove:Ie.useCallback(()=>C(w=>w-1),[]),children:jsx(yt.div,{tabIndex:y||R===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,w=>{let k=!I.current;if(w.target===w.currentTarget&&k&&!y){let v=new CustomEvent(zl,Xv);if(w.currentTarget.dispatchEvent(v),!v.defaultPrevented){let M=L().filter(W=>W.focusable),A=M.find(W=>W.active),B=M.find(W=>W.id===p),V=[A,B,...M].filter(Boolean).map(W=>W.ref.current);lf(V,f);}}I.current=false;}),onBlur:nt(e.onBlur,()=>x(false))})})}),nf="RovingFocusGroupItem",sf=Ie.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:n=false,tabStopId:r,children:s,...u}=e,i=tf(),c=r||i,f=Qv(nf,t),d=f.currentTabStopId===c,l=of(t),{onFocusableItemAdd:m,onFocusableItemRemove:h,currentTabStopId:p}=f;return Ie.useEffect(()=>{if(a)return m(),()=>h()},[a,m,h]),jsx(Ul.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,b=>{a?f.onItemFocus(c):b.preventDefault();}),onFocus:nt(e.onFocus,()=>f.onItemFocus(c)),onKeyDown:nt(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){f.onItemShiftTab();return}if(b.target!==b.currentTarget)return;let y=oy(b,f.orientation,f.dir);if(y!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let g=l().filter(L=>L.focusable).map(L=>L.ref.current);if(y==="last")g.reverse();else if(y==="prev"||y==="next"){y==="prev"&&g.reverse();let L=g.indexOf(b.currentTarget);g=f.loop?ry(g,L+1):g.slice(L+1);}setTimeout(()=>lf(g));}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:p!=null}):s})})});sf.displayName=nf;var ty={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ay(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function oy(e,o,t){let a=ay(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return ty[a]}function lf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function ry(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var df=rf,uf=sf;var ff="Toggle",Kl=Ie.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:n,...r}=e,[s,u]=fa({prop:t,onChange:n,defaultProp:a??false,caller:ff});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=ff;var Va="ToggleGroup",[pf]=qa(Va,[Wl]),hf=Wl(),Gl=Ie__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(iy,{...a,ref:o});if(t==="multiple")return jsx(ly,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Va}\``)});Gl.displayName=Va;var[gf,xf]=pf(Va),iy=Ie__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=fa({prop:t,defaultProp:a??"",onChange:n,caller:Va});return jsx(gf,{scope:e.__scopeToggleGroup,type:"single",value:Ie__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:u,onItemDeactivate:Ie__default.useCallback(()=>u(""),[u]),children:jsx(bf,{...r,ref:o})})}),ly=Ie__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=fa({prop:t,defaultProp:a??[],onChange:n,caller:Va}),i=Ie__default.useCallback(f=>u((d=[])=>[...d,f]),[u]),c=Ie__default.useCallback(f=>u((d=[])=>d.filter(l=>l!==f)),[u]);return jsx(gf,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:c,children:jsx(bf,{...r,ref:o})})});Gl.displayName=Va;var[dy,uy]=pf(Va),bf=Ie__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:n=true,orientation:r,dir:s,loop:u=true,...i}=e,c=hf(t),f=Jo(s),d={role:"group",dir:f,...i};return jsx(dy,{scope:t,rovingFocus:n,disabled:a,children:n?jsx(df,{asChild:true,...c,orientation:r,dir:f,loop:u,children:jsx(yt.div,{...d,ref:o})}):jsx(yt.div,{...d,ref:o})})}),Ds="ToggleGroupItem",cy=Ie__default.forwardRef((e,o)=>{let t=xf(Ds,e.__scopeToggleGroup),a=uy(Ds,e.__scopeToggleGroup),n=hf(e.__scopeToggleGroup),r=t.value.includes(e.value),s=a.disabled||e.disabled,u={...e,pressed:r,disabled:s},i=Ie__default.useRef(null);return a.rovingFocus?jsx(uf,{asChild:true,...n,focusable:!s,active:r,ref:i,children:jsx(mf,{...u,ref:o})}):jsx(mf,{...u,ref:o})});cy.displayName=Ds;var mf=Ie__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...n}=e,r=xf(Ds,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);}})}),vf=Gl;function yf(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=yf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Rs(){for(var e,o,t=0,a="",n=arguments.length;t<n;t++)(e=arguments[t])&&(o=yf(e))&&(a&&(a+=" "),a+=o);return a}var my=(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},py=(e,o)=>({classGroupId:e,validator:o}),Cf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var wf=[],hy="arbitrary..",gy=e=>{let o=by(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return xy(s);let u=s.split("-"),i=u[0]===""&&u.length>1?1:0;return kf(u,i,o)},getConflictingClassGroupIds:(s,u)=>{if(u){let i=a[s],c=t[s];return i?c?my(c,i):i:c||wf}return t[s]||wf}}},kf=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let n=e[o],r=t.nextPart.get(n);if(r){let c=kf(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}},xy=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?hy+a:void 0})(),by=e=>{let{theme:o,classGroups:t}=e;return vy(t,o)},vy=(e,o)=>{let t=Cf();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];yy(s,o,t,a);}},yy=(e,o,t,a)=>{if(typeof e=="string"){wy(e,o,t);return}if(typeof e=="function"){Sy(e,o,t,a);return}Ly(e,o,t,a);},wy=(e,o,t)=>{let a=e===""?o:Tf(o,e);a.classGroupId=t;},Sy=(e,o,t,a)=>{if(Iy(e)){$l(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(py(t,e));},Ly=(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,Tf(o,u),t,a);}},Tf=(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=Cf(),t.nextPart.set(s,u)),t=u;}return t},Iy=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Cy=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),n=(r,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 ky=[],Sf=(e,o,t,a,n)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:n}),Ty=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 b=n[p];if(s===0&&u===0){if(b===":"){r.push(n.slice(i,p)),i=p+1;continue}if(b==="/"){c=p;continue}}b==="["?s++:b==="]"?s--:b==="("?u++:b===")"&&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 Sf(r,m,l,h)};if(o){let n=o+":",r=a;a=s=>s.startsWith(n)?r(s.slice(n.length)):Sf(ky,false,s,void 0,true);}if(t){let n=a;a=r=>t({className:r,parseClassName:n});}return a},My=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}},Ay=e=>({cache:Cy(e.cacheSize),parseClassName:Ty(e),sortModifiers:My(e),...gy(e)}),Py=/\s+/,Ey=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:n,sortModifiers:r}=o,s=[],u=e.trim().split(Py),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 b=!!p,y=a(b?h.substring(0,p):h);if(!y){if(!b){i=f+(i.length>0?" "+i:i);continue}if(y=a(h),!y){i=f+(i.length>0?" "+i:i);continue}b=false;}let x=l.length===0?"":l.length===1?l[0]:r(l).join(":"),g=m?x+"!":x,L=g+y;if(s.indexOf(L)>-1)continue;s.push(L);let I=n(y,b);for(let R=0;R<I.length;++R){let C=I[R];s.push(g+C);}i=f+(i.length>0?" "+i:i);}return i},Dy=(...e)=>{let o=0,t,a,n="";for(;o<e.length;)(t=e[o++])&&(a=Mf(t))&&(n&&(n+=" "),n+=a);return n},Mf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Mf(e[a]))&&(t&&(t+=" "),t+=o);return t},Ry=(e,...o)=>{let t,a,n,r,s=i=>{let c=o.reduce((f,d)=>d(f),e());return t=Ay(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=Ey(i,t);return n(i,f),f};return r=s,(...i)=>r(Dy(...i))},Fy=[],Xe=e=>{let o=t=>t[e]||Fy;return o.isThemeGetter=true,o},Af=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Pf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,By=/^\d+\/\d+$/,Oy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Ny=/\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$/,Hy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,qy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Vy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Qo=e=>By.test(e),fe=e=>!!e&&!Number.isNaN(Number(e)),za=e=>!!e&&Number.isInteger(Number(e)),jl=e=>e.endsWith("%")&&fe(e.slice(0,-1)),ma=e=>Oy.test(e),zy=()=>true,Uy=e=>Ny.test(e)&&!Hy.test(e),Ef=()=>false,Wy=e=>qy.test(e),Ky=e=>Vy.test(e),Gy=e=>!Y(e)&&!Z(e),jy=e=>er(e,Ff,Ef),Y=e=>Af.test(e),ho=e=>er(e,Bf,Uy),_l=e=>er(e,Zy,fe),Lf=e=>er(e,Df,Ef),_y=e=>er(e,Rf,Ky),Fs=e=>er(e,Of,Wy),Z=e=>Pf.test(e),Yr=e=>tr(e,Bf),$y=e=>tr(e,Jy),If=e=>tr(e,Df),Xy=e=>tr(e,Ff),Yy=e=>tr(e,Rf),Bs=e=>tr(e,Of,true),er=(e,o,t)=>{let a=Af.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},tr=(e,o,t=false)=>{let a=Pf.exec(e);return a?a[1]?o(a[1]):t:false},Df=e=>e==="position"||e==="percentage",Rf=e=>e==="image"||e==="url",Ff=e=>e==="length"||e==="size"||e==="bg-size",Bf=e=>e==="length",Zy=e=>e==="number",Jy=e=>e==="family-name",Of=e=>e==="shadow";var Qy=()=>{let e=Xe("color"),o=Xe("font"),t=Xe("text"),a=Xe("font-weight"),n=Xe("tracking"),r=Xe("leading"),s=Xe("breakpoint"),u=Xe("container"),i=Xe("spacing"),c=Xe("radius"),f=Xe("shadow"),d=Xe("inset-shadow"),l=Xe("text-shadow"),m=Xe("drop-shadow"),h=Xe("blur"),p=Xe("perspective"),b=Xe("aspect"),y=Xe("ease"),x=Xe("animate"),g=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...L(),Z,Y],R=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],w=()=>[Z,Y,i],k=()=>[Qo,"full","auto",...w()],v=()=>[za,"none","subgrid",Z,Y],M=()=>["auto",{span:["full",za,Z,Y]},za,Z,Y],A=()=>[za,"auto",Z,Y],B=()=>["auto","min","max","fr",Z,Y],E=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],V=()=>["start","end","center","stretch","center-safe","end-safe"],W=()=>["auto",...w()],G=()=>[Qo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...w()],H=()=>[e,Z,Y],j=()=>[...L(),If,Lf,{position:[Z,Y]}],ie=()=>["no-repeat",{repeat:["","x","y","space","round"]}],K=()=>["auto","cover","contain",Xy,jy,{size:[Z,Y]}],O=()=>[jl,Yr,ho],z=()=>["","none","full",c,Z,Y],U=()=>["",fe,Yr,ho],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"],X=()=>[fe,jl,If,Lf],xe=()=>["","none",h,Z,Y],ne=()=>["none",fe,Z,Y],we=()=>["none",fe,Z,Y],be=()=>[fe,Z,Y],me=()=>[Qo,"full",...w()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ma],breakpoint:[ma],color:[zy],container:[ma],"drop-shadow":[ma],ease:["in","out","in-out"],font:[Gy],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ma],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ma],shadow:[ma],spacing:["px",fe],text:[ma],"text-shadow":[ma],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Qo,Y,Z,b]}],container:["container"],columns:[{columns:[fe,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:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],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",Z,Y]}],basis:[{basis:[Qo,"full","auto",u,...w()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[fe,Qo,"auto","initial","none",Y]}],grow:[{grow:["",fe,Z,Y]}],shrink:[{shrink:["",fe,Z,Y]}],order:[{order:[za,"first","last","none",Z,Y]}],"grid-cols":[{"grid-cols":v()}],"col-start-end":[{col:M()}],"col-start":[{"col-start":A()}],"col-end":[{"col-end":A()}],"grid-rows":[{"grid-rows":v()}],"row-start-end":[{row:M()}],"row-start":[{"row-start":A()}],"row-end":[{"row-end":A()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":B()}],"auto-rows":[{"auto-rows":B()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...E(),"normal"]}],"justify-items":[{"justify-items":[...V(),"normal"]}],"justify-self":[{"justify-self":["auto",...V()]}],"align-content":[{content:["normal",...E()]}],"align-items":[{items:[...V(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...V(),{baseline:["","last"]}]}],"place-content":[{"place-content":E()}],"place-items":[{"place-items":[...V(),"baseline"]}],"place-self":[{"place-self":["auto",...V()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:W()}],mx:[{mx:W()}],my:[{my:W()}],ms:[{ms:W()}],me:[{me:W()}],mt:[{mt:W()}],mr:[{mr:W()}],mb:[{mb:W()}],ml:[{ml:W()}],"space-x":[{"space-x":w()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":w()}],"space-y-reverse":["space-y-reverse"],size:[{size:G()}],w:[{w:[u,"screen",...G()]}],"min-w":[{"min-w":[u,"screen","none",...G()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[s]},...G()]}],h:[{h:["screen","lh",...G()]}],"min-h":[{"min-h":["screen","lh","none",...G()]}],"max-h":[{"max-h":["screen","lh",...G()]}],"font-size":[{text:["base",t,Yr,ho]}],"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:[$y,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":[fe,"none",Z,_l]}],leading:[{leading:[r,...w()]}],"list-image":[{"list-image":["none",Z,Y]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Z,Y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:H()}],"text-color":[{text:H()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[fe,"from-font","auto",Z,ho]}],"text-decoration-color":[{decoration:H()}],"underline-offset":[{"underline-offset":[fe,"auto",Z,Y]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:w()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Z,Y]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Z,Y]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:j()}],"bg-repeat":[{bg:ie()}],"bg-size":[{bg:K()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},za,Z,Y],radial:["",Z,Y],conic:[za,Z,Y]},Yy,_y]}],"bg-color":[{bg:H()}],"gradient-from-pos":[{from:O()}],"gradient-via-pos":[{via:O()}],"gradient-to-pos":[{to:O()}],"gradient-from":[{from:H()}],"gradient-via":[{via:H()}],"gradient-to":[{to:H()}],rounded:[{rounded:z()}],"rounded-s":[{"rounded-s":z()}],"rounded-e":[{"rounded-e":z()}],"rounded-t":[{"rounded-t":z()}],"rounded-r":[{"rounded-r":z()}],"rounded-b":[{"rounded-b":z()}],"rounded-l":[{"rounded-l":z()}],"rounded-ss":[{"rounded-ss":z()}],"rounded-se":[{"rounded-se":z()}],"rounded-ee":[{"rounded-ee":z()}],"rounded-es":[{"rounded-es":z()}],"rounded-tl":[{"rounded-tl":z()}],"rounded-tr":[{"rounded-tr":z()}],"rounded-br":[{"rounded-br":z()}],"rounded-bl":[{"rounded-bl":z()}],"border-w":[{border:U()}],"border-w-x":[{"border-x":U()}],"border-w-y":[{"border-y":U()}],"border-w-s":[{"border-s":U()}],"border-w-e":[{"border-e":U()}],"border-w-t":[{"border-t":U()}],"border-w-r":[{"border-r":U()}],"border-w-b":[{"border-b":U()}],"border-w-l":[{"border-l":U()}],"divide-x":[{"divide-x":U()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":U()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:H()}],"border-color-x":[{"border-x":H()}],"border-color-y":[{"border-y":H()}],"border-color-s":[{"border-s":H()}],"border-color-e":[{"border-e":H()}],"border-color-t":[{"border-t":H()}],"border-color-r":[{"border-r":H()}],"border-color-b":[{"border-b":H()}],"border-color-l":[{"border-l":H()}],"divide-color":[{divide:H()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[fe,Z,Y]}],"outline-w":[{outline:["",fe,Yr,ho]}],"outline-color":[{outline:H()}],shadow:[{shadow:["","none",f,Bs,Fs]}],"shadow-color":[{shadow:H()}],"inset-shadow":[{"inset-shadow":["none",d,Bs,Fs]}],"inset-shadow-color":[{"inset-shadow":H()}],"ring-w":[{ring:U()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:H()}],"ring-offset-w":[{"ring-offset":[fe,ho]}],"ring-offset-color":[{"ring-offset":H()}],"inset-ring-w":[{"inset-ring":U()}],"inset-ring-color":[{"inset-ring":H()}],"text-shadow":[{"text-shadow":["none",l,Bs,Fs]}],"text-shadow-color":[{"text-shadow":H()}],opacity:[{opacity:[fe,Z,Y]}],"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":[fe]}],"mask-image-linear-from-pos":[{"mask-linear-from":X()}],"mask-image-linear-to-pos":[{"mask-linear-to":X()}],"mask-image-linear-from-color":[{"mask-linear-from":H()}],"mask-image-linear-to-color":[{"mask-linear-to":H()}],"mask-image-t-from-pos":[{"mask-t-from":X()}],"mask-image-t-to-pos":[{"mask-t-to":X()}],"mask-image-t-from-color":[{"mask-t-from":H()}],"mask-image-t-to-color":[{"mask-t-to":H()}],"mask-image-r-from-pos":[{"mask-r-from":X()}],"mask-image-r-to-pos":[{"mask-r-to":X()}],"mask-image-r-from-color":[{"mask-r-from":H()}],"mask-image-r-to-color":[{"mask-r-to":H()}],"mask-image-b-from-pos":[{"mask-b-from":X()}],"mask-image-b-to-pos":[{"mask-b-to":X()}],"mask-image-b-from-color":[{"mask-b-from":H()}],"mask-image-b-to-color":[{"mask-b-to":H()}],"mask-image-l-from-pos":[{"mask-l-from":X()}],"mask-image-l-to-pos":[{"mask-l-to":X()}],"mask-image-l-from-color":[{"mask-l-from":H()}],"mask-image-l-to-color":[{"mask-l-to":H()}],"mask-image-x-from-pos":[{"mask-x-from":X()}],"mask-image-x-to-pos":[{"mask-x-to":X()}],"mask-image-x-from-color":[{"mask-x-from":H()}],"mask-image-x-to-color":[{"mask-x-to":H()}],"mask-image-y-from-pos":[{"mask-y-from":X()}],"mask-image-y-to-pos":[{"mask-y-to":X()}],"mask-image-y-from-color":[{"mask-y-from":H()}],"mask-image-y-to-color":[{"mask-y-to":H()}],"mask-image-radial":[{"mask-radial":[Z,Y]}],"mask-image-radial-from-pos":[{"mask-radial-from":X()}],"mask-image-radial-to-pos":[{"mask-radial-to":X()}],"mask-image-radial-from-color":[{"mask-radial-from":H()}],"mask-image-radial-to-color":[{"mask-radial-to":H()}],"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":[fe]}],"mask-image-conic-from-pos":[{"mask-conic-from":X()}],"mask-image-conic-to-pos":[{"mask-conic-to":X()}],"mask-image-conic-from-color":[{"mask-conic-from":H()}],"mask-image-conic-to-color":[{"mask-conic-to":H()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:j()}],"mask-repeat":[{mask:ie()}],"mask-size":[{mask:K()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Z,Y]}],filter:[{filter:["","none",Z,Y]}],blur:[{blur:xe()}],brightness:[{brightness:[fe,Z,Y]}],contrast:[{contrast:[fe,Z,Y]}],"drop-shadow":[{"drop-shadow":["","none",m,Bs,Fs]}],"drop-shadow-color":[{"drop-shadow":H()}],grayscale:[{grayscale:["",fe,Z,Y]}],"hue-rotate":[{"hue-rotate":[fe,Z,Y]}],invert:[{invert:["",fe,Z,Y]}],saturate:[{saturate:[fe,Z,Y]}],sepia:[{sepia:["",fe,Z,Y]}],"backdrop-filter":[{"backdrop-filter":["","none",Z,Y]}],"backdrop-blur":[{"backdrop-blur":xe()}],"backdrop-brightness":[{"backdrop-brightness":[fe,Z,Y]}],"backdrop-contrast":[{"backdrop-contrast":[fe,Z,Y]}],"backdrop-grayscale":[{"backdrop-grayscale":["",fe,Z,Y]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[fe,Z,Y]}],"backdrop-invert":[{"backdrop-invert":["",fe,Z,Y]}],"backdrop-opacity":[{"backdrop-opacity":[fe,Z,Y]}],"backdrop-saturate":[{"backdrop-saturate":[fe,Z,Y]}],"backdrop-sepia":[{"backdrop-sepia":["",fe,Z,Y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Z,Y]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[fe,"initial",Z,Y]}],ease:[{ease:["linear","initial",y,Z,Y]}],delay:[{delay:[fe,Z,Y]}],animate:[{animate:["none",x,Z,Y]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,Z,Y]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:ne()}],"rotate-x":[{"rotate-x":ne()}],"rotate-y":[{"rotate-y":ne()}],"rotate-z":[{"rotate-z":ne()}],scale:[{scale:we()}],"scale-x":[{"scale-x":we()}],"scale-y":[{"scale-y":we()}],"scale-z":[{"scale-z":we()}],"scale-3d":["scale-3d"],skew:[{skew:be()}],"skew-x":[{"skew-x":be()}],"skew-y":[{"skew-y":be()}],transform:[{transform:[Z,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:me()}],"translate-x":[{"translate-x":me()}],"translate-y":[{"translate-y":me()}],"translate-z":[{"translate-z":me()}],"translate-none":["translate-none"],accent:[{accent:H()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:H()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Z,Y]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Z,Y]}],fill:[{fill:["none",...H()]}],"stroke-w":[{stroke:[fe,Yr,ho,_l]}],stroke:[{stroke:["none",...H()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var Nf=Ry(Qy);function Ua(...e){return Nf(Rs(e))}var tw=Ie.createContext({size:"default",variant:"default",spacing:0});function Wa({className:e,variant:o,size:t,spacing:a=1,children:n,...r}){return jsx(vf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Ua("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(tw.Provider,{value:{variant:o,size:t,spacing:a},children:n})})}var ow={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Uf=createSlice({name:"toolbar",initialState:ow,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:pa,setStrokeWidth:Zr,setFontSize:BD,setFontFamily:OD,setFontStyle:ND,setFontWeight:HD,setTextDecoration:qD,setTextColor:VD}=Uf.actions,Yl=Uf.reducer;var Os=({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),b=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 x=()=>{c&&(c.getTracks().forEach(w=>w.stop()),f(null),l(false));},g=async()=>{try{let w=null,k=null;try{w=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(E){console.error("Error accessing camera for recording:",E),alert("Failed to access camera for recording.");return}try{k=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(E){console.warn("Microphone access denied:",E);}let v=[...w.getVideoTracks()];k&&v.push(...k.getAudioTracks());let M=new MediaStream(v),A="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?A="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?A="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?A="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(A="video/webm;codecs=vp8");let B=new MediaRecorder(M,{mimeType:A,videoBitsPerSecond:25e5});m.current=B,h.current=[],B.ondataavailable=E=>{E.data.size>0&&h.current.push(E.data);},B.onstop=()=>{let E=new Blob(h.current,{type:A}),V=document.createElement("video");V.src=URL.createObjectURL(E),V.muted=!0,V.currentTime=.1,V.onseeked=()=>{let W=document.createElement("canvas");W.width=V.videoWidth,W.height=V.videoHeight;let G=W.getContext("2d");G&&(G.drawImage(V,0,0),b.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(V.src);},M.getTracks().forEach(W=>W.stop()),w&&w.getTracks().forEach(W=>W.stop()),k&&k.getTracks().forEach(W=>W.stop()),p.current&&clearInterval(p.current),s(E),x();},B.onerror=E=>{console.error("MediaRecorder error:",E);},B.start(1e3),n(!0),i(0),p.current=setInterval(()=>{i(E=>E+1);},1e3);}catch(w){console.error("Error starting camera recording:",w),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 w=URL.createObjectURL(r),k=document.createElement("a");k.href=w,k.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(k),k.click(),document.body.removeChild(k),URL.revokeObjectURL(w);}},R=w=>{let k=Math.floor(w/60),v=w%60;return `${k.toString().padStart(2,"0")}:${v.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:w=>{w.target===w.currentTarget&&e(),w.stopPropagation();},onMouseUp:w=>w.stopPropagation(),onMouseMove:w=>w.stopPropagation(),onTouchStart:w=>w.stopPropagation(),onTouchMove:w=>w.stopPropagation(),onTouchEnd:w=>w.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:w=>w.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!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: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:R(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: ",R(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&&b.current&&(o(r,b.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 ha=40,Kf=({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 g=L=>{L.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let l=g=>{let L=g.target.files;if(!L||L.length===0)return;let I=ha-a.length;if(I<=0){alert(`You can only upload a maximum of ${ha} images`);return}let R=Array.from(L).slice(0,I);R.length<L.length&&alert(`Only ${I} more images can be added (max ${ha} total)`);let C=R.map(w=>new Promise((k,v)=>{let M=new FileReader;M.onload=A=>{A.target?.result?k(A.target.result):v(new Error("Failed to read file"));},M.onerror=v,M.readAsDataURL(w);}));Promise.all(C).then(w=>{n(k=>[...k,...w]),d.current&&(d.current.value="");});},m=g=>{g.preventDefault(),i(false);let L=Array.from(g.dataTransfer.files).filter(w=>w.type.startsWith("image/"));if(L.length===0)return;let I=ha-a.length;if(I<=0){alert(`You can only upload a maximum of ${ha} images`);return}let R=L.slice(0,I);R.length<L.length&&alert(`Only ${I} more images can be added (max ${ha} total)`);let C=R.map(w=>new Promise((k,v)=>{let M=new FileReader;M.onload=A=>{A.target?.result?k(A.target.result):v(new Error("Failed to read file"));},M.onerror=v,M.readAsDataURL(w);}));Promise.all(C).then(w=>{n(k=>[...k,...w]);});},h=g=>{g.preventDefault(),i(true);},p=()=>{i(false);},b=g=>{n(L=>L.filter((I,R)=>R!==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 x=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>=ha?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ha," images"]}):jsxs("span",{children:[a.length,"/",ha," 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,L)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${L+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>b(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(x,f)};var Ns={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},vw={enabled:true};function Ql(e){return e?{tools:{...Ns.tools,...e.tools},actions:{...Ns.actions,...e.actions}}:Ns}var yw={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}},ww={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 Gf(e){let o=Ie.useRef({value:e,previous:e});return Ie.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function _f(e){let[o,t]=Ie.useState(void 0);return Yo(()=>{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 $f=["PageUp","PageDown"],Xf=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Yf={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},ar="Slider",[td,Lw,Iw]=As(ar),[Zf]=qa(ar,[Iw]),[Cw,qs]=Zf(ar),Jf=Ie.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,b=Ie.useRef(new Set),y=Ie.useRef(0),g=s==="horizontal"?kw:Tw,[L=[],I]=fa({prop:f,defaultProp:c,onChange:M=>{[...b.current][y.current]?.focus(),d(M);}}),R=Ie.useRef(L);function C(M){let A=Dw(L,M);v(M,A);}function w(M){v(M,y.current);}function k(){let M=R.current[y.current];L[y.current]!==M&&l(L);}function v(M,A,{commit:B}={commit:false}){let E=Ow(r),V=Nw(Math.round((M-a)/r)*r+a,E),W=ed(V,[a,n]);I((G=[])=>{let H=Pw(G,W,A);if(Bw(H,i*r)){y.current=H.indexOf(W);let j=String(H)!==String(G);return j&&B&&l(H),j?H:G}else return G});}return jsx(Cw,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:n,valueIndexToChangeRef:y,thumbs:b.current,values:L,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||(R.current=L);}),min:a,max:n,inverted:m,onSlideStart:u?void 0:C,onSlideMove:u?void 0:w,onSlideEnd:u?void 0:k,onHomeKeyDown:()=>!u&&v(a,0,{commit:true}),onEndKeyDown:()=>!u&&v(n,L.length-1,{commit:true}),onStepKeyDown:({event:M,direction:A})=>{if(!u){let V=$f.includes(M.key)||M.shiftKey&&Xf.includes(M.key)?10:1,W=y.current,G=L[W],H=r*V*A;v(G+H,W,{commit:true});}}})})})})});Jf.displayName=ar;var[Qf,em]=Zf(ar,{startEdge:"left",endEdge:"right",size:"width",direction:1}),kw=Ie.forwardRef((e,o)=>{let{min:t,max:a,dir:n,inverted:r,onSlideStart:s,onSlideMove:u,onSlideEnd:i,onStepKeyDown:c,...f}=e,[d,l]=Ie.useState(null),m=jt(o,g=>l(g)),h=Ie.useRef(void 0),p=Jo(n),b=p==="ltr",y=b&&!r||!b&&r;function x(g){let L=h.current||d.getBoundingClientRect(),I=[0,L.width],C=rd(I,y?[t,a]:[a,t]);return h.current=L,C(g-L.left)}return jsx(Qf,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx(tm,{dir:p,"data-orientation":"horizontal",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:g=>{let L=x(g.clientX);s?.(L);},onSlideMove:g=>{let L=x(g.clientX);u?.(L);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:g=>{let I=Yf[y?"from-left":"from-right"].includes(g.key);c?.({event:g,direction:I?-1:1});}})})}),Tw=Ie.forwardRef((e,o)=>{let{min:t,max:a,inverted:n,onSlideStart:r,onSlideMove:s,onSlideEnd:u,onStepKeyDown:i,...c}=e,f=Ie.useRef(null),d=jt(o,f),l=Ie.useRef(void 0),m=!n;function h(p){let b=l.current||f.current.getBoundingClientRect(),y=[0,b.height],g=rd(y,m?[a,t]:[t,a]);return l.current=b,g(p-b.top)}return jsx(Qf,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:jsx(tm,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:p=>{let b=h(p.clientY);r?.(b);},onSlideMove:p=>{let b=h(p.clientY);s?.(b);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:p=>{let y=Yf[m?"from-bottom":"from-top"].includes(p.key);i?.({event:p,direction:y?-1:1});}})})}),tm=Ie.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:n,onSlideEnd:r,onHomeKeyDown:s,onEndKeyDown:u,onStepKeyDown:i,...c}=e,f=qs(ar,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()):$f.concat(Xf).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));})})}),am="SliderTrack",om=Ie.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=qs(am,t);return jsx(yt.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...a,ref:o})});om.displayName=am;var ad="SliderRange",rm=Ie.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=qs(ad,t),r=em(ad,t),s=Ie.useRef(null),u=jt(o,s),i=n.values.length,c=n.values.map(l=>im(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+"%"}})});rm.displayName=ad;var od="SliderThumb",nm=Ie.forwardRef((e,o)=>{let t=Lw(e.__scopeSlider),[a,n]=Ie.useState(null),r=jt(o,u=>n(u)),s=Ie.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(Mw,{...e,ref:r,index:s})}),Mw=Ie.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:n,...r}=e,s=qs(od,t),u=em(od,t),[i,c]=Ie.useState(null),f=jt(o,x=>c(x)),d=i?s.form||!!i.closest("form"):true,l=_f(i),m=s.values[a],h=m===void 0?0:im(m,s.min,s.max),p=Ew(a,s.values.length),b=l?.[u.size],y=b?Rw(b,h,u.direction):0;return Ie.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(sm,{name:n??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:m},a)]})});nm.displayName=od;var Aw="RadioBubbleInput",sm=Ie.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let n=Ie.useRef(null),r=jt(n,a),s=Gf(o);return Ie.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})});sm.displayName=Aw;function Pw(e=[],o,t){let a=[...e];return a[t]=o,a.sort((n,r)=>n-r)}function im(e,o,t){let r=100/(t-o)*(e-o);return ed(r,[0,100])}function Ew(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Dw(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 Rw(e,o,t){let a=e/2,r=rd([0,50],[0,a]);return (a-r(o)*t)*t}function Fw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Bw(e,o){if(o>0){let t=Fw(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 Ow(e){return (String(e).split(".")[1]||"").length}function Nw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var lm=Jf,dm=om,um=rm,cm=nm;function Vs({className:e,defaultValue:o,value:t,min:a=0,max:n=100,rangeClassName:r,trackClassName:s,thumbClassName:u,...i}){let c=Ie.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,n],[t,o,a,n]);return jsxs(lm,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:n,className:Ua("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(dm,{"data-slot":"slider-track",className:Ua("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(um,{"data-slot":"slider-range",className:Ua("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(f,d)=>jsx(cm,{"data-slot":"slider-thumb",className:Ua("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 uS=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a,onVisibilityChange:n}={})=>{let r=Le(),s=Q(P=>P.canvas.slides.find(oe=>oe.id===P.canvas.currentSlideId)),u=s?.videos||[],i=s?.editingFlashcard,c=Q(P=>P.toolbar.selectedTool),f=Q(P=>P.toolbar.penColor),d=Q(P=>P.toolbar.strokeWidth),l=Q(P=>P.canvas.editingOverlayPosition),m=s?.showMcqForm,h=s?.showFlashcardForm,p=useRef(null);useEffect(()=>{let P=oe=>{(oe.ctrlKey||oe.metaKey)&&oe.key==="z"&&!oe.shiftKey&&(oe.preventDefault(),r(ko())),(oe.ctrlKey&&oe.shiftKey&&oe.key==="Z"||oe.ctrlKey&&oe.key==="y")&&(oe.preventDefault(),r(To()));};return window.addEventListener("keydown",P),()=>{window.removeEventListener("keydown",P);}},[r]);let b=useMemo(()=>Ql(a),[a]),{tools:y,actions:x}=b,g=u.some(P=>P.isRecorded&&P.isPlaying),L=Q(P=>P.toolbar.fontSize),I=Q(P=>P.toolbar.fontFamily),R=Q(P=>P.toolbar.fontStyle),C=Q(P=>P.toolbar.fontWeight),w=Q(P=>P.toolbar.textDecoration),k=Q(P=>P.toolbar.textColor),[v,M]=useState(false),[A,B]=useState(false),[E,V]=useState(false),[W,G]=useState(false),[H,j]=useState(false),[ie,K]=useState(false),[O,z]=useState(false),[U,J]=useState(false),[ee,X]=useState(true),xe=useRef(null),ne=useRef(null),we=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],be=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"}],[]),me=useMemo(()=>[{name:"rectangle",icon:Square,label:"Square"},{name:"rectangle",icon:Square,label:"Rectangle"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),ue=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),Pe=useMemo(()=>be.filter(P=>{let oe=y[P.configKey];return typeof oe=="boolean"?oe:Array.isArray(oe)?oe.length>0:true}),[y,be]),it=useMemo(()=>{let P=y.shapes;return P===false?[]:P===true?me:Array.isArray(P)?me.filter(oe=>P.includes(oe.name)):me},[y.shapes,me]),Ve=useMemo(()=>{let P=y.activities;return P===false?[]:P===true?ue:Array.isArray(P)?ue.filter(oe=>P.includes(oe.name)):ue},[y.activities,ue]),re=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 oe=P.target.files;!oe||oe.length===0||(r(ra("select")),r(Ct(false)),G(false),Array.from(oe).forEach(Ee=>{let Se=new FileReader;Se.onload=le=>{let de=new window.Image;de.src=le.target?.result,de.onload=()=>{let ze=de.width/de.height,lt=300,Bt=300,St=de.width,Oe=de.height;St>lt&&(St=lt,Oe=St/ze),Oe>Bt&&(Oe=Bt,St=Oe*ze),r(ce());let Ke=l?.left||800-St/2,sa=l?.top||450-Oe/2;r(ui({id:v4(),src:de.src,x:Ke,y:sa,width:St,height:Oe,draggable:true,rotation:0}));};},Se.readAsDataURL(Ee);}),P.target.value="");},sn=async P=>{let oe=P.target.files;if(!(!oe||oe.length===0)){console.log("files",P),r(ra("select")),r(Ct(false)),G(false);for(let Ee of Array.from(oe))try{let Se=URL.createObjectURL(Ee),le=document.createElement("video");console.log("video",le),le.src=Se,le.muted=!0,le.playsInline=!0,le.preload="auto",le.load(),await new Promise((mt,se)=>{let Lt=setTimeout(()=>se(new Error("Metadata load timeout")),1e4);le.onloadedmetadata=()=>{clearTimeout(Lt),mt();},le.onerror=()=>{clearTimeout(Lt),se(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:le.duration,width:le.videoWidth,height:le.videoHeight}),await new Promise((mt,se)=>{let Lt=setTimeout(()=>se(new Error("Video load timeout")),1e4);le.readyState>=2?(clearTimeout(Lt),mt()):le.onloadeddata=()=>{clearTimeout(Lt),mt();};});let de=Math.min(.8,le.duration/2);console.log("Seeking to:",de),le.currentTime=de,await new Promise(mt=>{let se=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),mt();},5e3);le.onseeked=()=>{clearTimeout(se),console.log("Seek completed"),mt();};});let ze=document.createElement("canvas"),lt=le.videoWidth/le.videoHeight,Bt=400,St=400,Oe=le.videoWidth,Ke=le.videoHeight;Oe>Bt&&(Oe=Bt,Ke=Oe/lt),Ke>St&&(Ke=St,Oe=Ke*lt),ze.width=Oe,ze.height=Ke;let sa=ze.getContext("2d",{willReadFrequently:!1});if(!sa)throw new Error("Failed to get canvas context");if(await new Promise(mt=>setTimeout(mt,100)),le.videoWidth===0||le.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Oe,height:Ke}),sa.drawImage(le,0,0,Oe,Ke);let wa=ze.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",wa.length),r(ce());let Qs=800-Oe/2,ei=450-Ke/2,pn=v4();await ua(pn,Ee,wa),r(Io({id:pn,objectUrl:Se,thumbnailDataUrl:wa,videoBlob:Ee,x:Qs,y:ei,width:Oe,height:Ke,draggable:!0,isPlaying:!1,rotation:0})),le.src="",le.load(),console.log(`Video uploaded: ${Ee.name}`);}catch(Se){console.error("Error processing video:",Se),alert(`Failed to process video: ${Ee.name}`);}P.target.value="";}},ln=(P,oe,Ee)=>{r(ce()),r(ra("select")),r(Ct(false));let Se=300,le=300,de=800-Se/2,ze=450-le/2;r(Ee?Co({id:Ee,images:P,order:oe,x:de,y:ze,width:Se,height:le,rotation:0,draggable:true}):mi({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:P,currentIndex:0,order:oe,x:de,y:ze,width:Se,height:le,rotation:0,draggable:true})),r(Ja(false));},dn=()=>{r(ce()),r(ra("select")),r(Ct(false));let P=400,oe=300,Ee=800-P/2,Se=450-oe/2;r(gi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ee,y:Se,width:P,height:oe,rotation:0,draggable:true,isCapturing:false})),G(false);},un=P=>{let de={};switch(P.name){case "rectangle":P.label==="Rectangle"?(de.width=120,de.height=80):(de.width=100,de.height=100);break;case "circle":case "ring":case "wedge":case "arc":de.radius=50,(P.name==="ring"||P.name==="arc")&&(de.innerRadius=25,de.outerRadius=50),(P.name==="wedge"||P.name==="arc")&&(de.angle=P.name==="wedge"?60:90);break;case "ellipse":de.radiusX=60,de.radiusY=40;break;case "triangle":de.radius=50,de.sides=3;break;case "polygon":de.radius=50,de.sides=6;break;case "star":de.innerRadius=25,de.outerRadius=50,de.numPoints=5;break;case "arrow":case "line":de.points=[0,0,100,0],P.name==="arrow"&&(de.pointerLength=10,de.pointerWidth=10);break}let ze={id:`shape-${Date.now()}`,type:P.name,x:750,y:400,width:100,height:100,rotation:0,color:f,...de};r(ce()),r(Ct(false)),r(ra(P.name)),r(ci(ze)),V(false);},ja=P=>{if(r(ra(P)),P==="select")r(Ct(false));else if(P==="text"){r(Ct(false)),r(ce());let oe=200,Ee=50,Se=800-oe/2,le=450-Ee/2,ze=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:Se,y:le,width:oe,height:Ee,rotation:0,draggable:true,fontSize:ze,fontFamily:I,fontStyle:R,fontWeight:C,textDecoration:w,fill:k,align:"left"})),setTimeout(()=>{r(br(lt));},100),t&&t(lt);}else r(Ct(true));},_s=()=>{r(xr()),r(Ct(false));},$s=()=>{e?e():o?M(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Xs=()=>{B(true);},Ys=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:dn,enabled:re.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>xe.current?.click(),enabled:re.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>ne.current?.click(),enabled:re.video}],ya=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(ko()),enabled:x.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(To()),enabled:x.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:$s,enabled:x.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:Xs,enabled:x.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:_s,enabled:x.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],cn=async(P,oe)=>{try{r(ra("select")),r(Ct(!1));let Ee=URL.createObjectURL(P),Se=document.createElement("video");Se.src=Ee,Se.muted=!0,Se.playsInline=!0,Se.preload="auto",await new Promise((Ke,sa)=>{let wa=setTimeout(()=>sa(new Error("Metadata load timeout")),1e4);Se.onloadedmetadata=()=>{clearTimeout(wa),Ke();},Se.onerror=()=>{clearTimeout(wa),sa(new Error("Failed to load video"));};});let le=640,de=Se.videoWidth/Se.videoHeight,ze=le,lt=ze/de;r(ce());let Bt=800-ze/2,St=450-lt/2,Oe=v4();await ua(Oe,P,oe),r(Io({id:Oe,objectUrl:Ee,thumbnailDataUrl:oe,videoBlob:P,x:Bt,y:St,width:ze,height:lt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),M(!1),B(!1);}catch(Ee){console.error("Error adding recorded video to canvas:",Ee),alert("Failed to add video to canvas. Please try again.");}},Zs=P=>{r(ra("select")),r(Ct(false)),r(hr(null)),P&&r(Ti(P)),r(Ia(!m)),j(false);},vo=()=>{r(pr(null)),r(Ja(true)),j(false);},fn=()=>{V(!E);},Js=()=>{G(!W);},sr=()=>{j(!H);},yo=()=>{K(!ie);},mn=()=>{let P=!ee;P||(V(false),G(false),j(false),K(false),J(false),z(false)),X(P),n?.(P);};return useEffect(()=>{if(!U)return;let P=oe=>{p.current&&!p.current.contains(oe.target)&&J(false);};return document.addEventListener("mousedown",P),()=>{document.removeEventListener("mousedown",P);}},[U]),g?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:mn,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:"fixed top-[168px] left-4 z-50 flex flex-col gap-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(Wa,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:Pe.map((P,oe)=>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"?(Js(),V(false),j(false),K(false),ja(P.name)):P.name==="shapes"?(fn(),G(false),j(false),K(false),ja(P.name)):P.name==="activities"?(ja(P.name),sr(),V(false),G(false),K(false)):P.name==="style"?(yo(),V(false),G(false),j(false),ja(P.name)):(ja(P.name),V(false),G(false),j(false),K(false));},children:jsx(P.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},oe))}),E&&jsx(Wa,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:it.map((P,oe)=>jsx("div",{title:P.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>un(P),children:jsx(P.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},oe))}),W&&jsx(Wa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:Ys.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))}),H&&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:[rn&&jsx("div",{title:"Flashcard",onClick:()=>vo(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),Ve.map((P,oe)=>jsx("div",{title:P.label,onClick:()=>Zs(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"})},oe))]}),ie&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Vs,{value:[d],onValueChange: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:[we.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(pa(P.value)),K(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(pa(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(mr(P.target.value)),K(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"})]})]})]})]})]}),ya.some(P=>P.enabled)&&jsx(Wa,{type:"single",className:"hidden flex-col border bg-white p-1 shadow-xl md:flex",children:ya.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:xe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:nn}),jsx("input",{ref:ne,type:"file",accept:"video/*",className:"hidden",onChange:sn}),!e&&v&&o&&jsx(Qa,{onClose:()=>M(false),stageRef:o,onRecordingComplete:cn}),A&&jsx(Os,{onClose:()=>B(false),onRecordingComplete:cn}),h&&jsx(Kf,{editingFlashcard:i,onConfirm:ln,onCancel:()=>r(Ja(false))}),O&&jsx(os,{defaultColor:f,onConfirm:P=>{r(pa(P)),z(false);},onCancel:()=>z(false)})]})},cS=uS;var ud=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let n=Re(ka),r=Re(Oi),s=a?r:n,u=Re(yr),f=(Re(x=>x.canvas.slides.find(g=>g.id===x.canvas.currentSlideId))?.videos||[]).some(x=>x.isRecorded&&x.isPlaying),[d,l]=useState(false),[m,h]=useState(null),[p,b]=useState(null),y=async()=>{if(n.length===0){b({type:"error",message:"No slides to publish"});return}if(!e){b({type:"error",message:"No publish handler provided"});return}l(true),b(null);try{let x=await e(s,u,g=>{h(g);});x.success?b({type:"success",message:x.message}):b({type:"error",message:x.message});}catch(x){b({type:"error",message:x instanceof Error?x.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),b(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 gS=({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=Ye(),p=Re(yr),b=Re(Ni),y=e??(b?p.title:"")??"Untitled",x=o??(b?p.description:"")??"Add a description...",[g,L]=useState(false),[I,R]=useState(false),[C,w]=useState(y),[k,v]=useState(x),M=useRef(null),A=useRef(null);useEffect(()=>{w(y);},[y]),useEffect(()=>{v(x);},[x]),useEffect(()=>{g&&M.current&&(M.current.focus(),M.current.select());},[g]),useEffect(()=>{I&&A.current&&(A.current.focus(),A.current.select());},[I]);let B=()=>{i&&L(true);},E=()=>{c&&R(true);},V=()=>{L(false),C.trim()&&C!==y?n?n(C.trim()):h(Ri(C.trim())):C.trim()||w(y);},W=()=>{R(false),k.trim()&&k!==x?r?r(k.trim()):h(Fi(k.trim())):k.trim()||v(x);},G=j=>{j.key==="Enter"?V():j.key==="Escape"&&(w(y),L(false));},H=j=>{j.key==="Enter"?W():j.key==="Escape"&&(v(x),R(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:M,type:"text",value:C,onChange:j=>w(j.target.value),onBlur:V,onKeyDown:G,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:B,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:A,type:"text",value:k,onChange:j=>v(j.target.value),onBlur:W,onKeyDown:H,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:E,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(ud,{onPublish:a,includeInactiveSlides:m})]})};var SS=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],LS=({colors:e=SS,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:n=""})=>{let[r,s]=useState(true),u=Q(ye),i=Q(l=>l.toolbar.penColor),c=Q(l=>l.toolbar.strokeWidth),f=u?.backgroundColor,d=Le();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(Vs,{defaultValue:[20],max:36,min:8,step:2,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[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(pa(l.value))},l.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>d(pa("#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(pa(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(mr(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 vm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),IS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),fd=e=>{let o=IS(e);return o.charAt(0).toUpperCase()+o.slice(1)},Ks=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),ym=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var wm={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 Lm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:n="",children:r,iconNode:s,...u},i)=>createElement("svg",{ref:i,...wm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Ks("lucide",n),...!r&&!ym(u)&&{"aria-hidden":"true"},...u},[...s.map(([c,f])=>createElement(c,f)),...Array.isArray(r)?r:[r]]));var Gs=(e,o)=>{let t=forwardRef(({className:a,...n},r)=>createElement(Lm,{ref:r,iconNode:o,className:Ks(`lucide-${vm(fd(e))}`,`lucide-${e}`,a),...n}));return t.displayName=fd(e),t};var MS=[["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=Gs("copy",MS);var AS=[["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=Gs("trash-2",AS);var Cm=({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 RS=({softDelete:e=false})=>{let o=Ye(),t=Re(ka),a=Re(Ca),n=Re(vr),[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(dr());},d=h=>{o(fr(h));},l=h=>{o(cr(h));},m=h=>{t.length>1&&o(ur({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(Cm,{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 or=20,US=({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]})]}),WS=({softDelete:e=false})=>{let o=Ye(),t=Re(ka),a=Re(Ca),n=Re(vr),[r,s]=useState(false),[u,i]=useState(false),[c,f]=useState(false),d=useRef(null),h=(Re(I=>I.canvas.slides.find(R=>R.id===I.canvas.currentSlideId))?.videos||[]).some(I=>I.isRecorded&&I.isPlaying),p=()=>{n&&t.length<or&&o(dr());},b=I=>{o(fr(I));},y=I=>{t.length<or&&o(cr(I));},x=I=>{t.length>1&&o(ur({id:I,softDelete:e}));},g=()=>{if(!d.current)return;let{scrollLeft:I,scrollWidth:R,clientWidth:C}=d.current,w=R>C+5;i(w&&I>5),f(w&&I<R-C-5);},L=I=>{if(!d.current)return;let R=177,C=I==="left"?d.current.scrollLeft-R:d.current.scrollLeft+R;d.current.scrollTo({left:C,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,"/",or,")"]})]}),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,R)=>jsx(US,{slide:I,index:R,isSelected:I.id===a,isSingleSlide:t.length===1,onSelect:()=>b(I.id),onDuplicate:()=>y(I.id),onDelete:()=>x(I.id)},I.id))})]}),jsx("button",{onClick:p,disabled:!n||t.length>=or,className:`px-4 pb-4 text-base font-bold ${n&&t.length<or?"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,"/",or,")"]})]}),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")]})})},pd=WS;var ZS=({stageRef:e,onScreenRecord:o,visible:t=true,config:a={}})=>{let n=Ye(),[r,s]=useState(false),[u,i]=useState(false),c=Re(L=>L.canvas.slides.find(I=>I.id===L.canvas.currentSlideId)),f=Re(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);},b=()=>{n(xr());},y=async(L,I)=>{let R=v4(),C=URL.createObjectURL(L),w=document.createElement("video");w.src=C,w.muted=true,w.playsInline=true,w.preload="auto",await new Promise((B,E)=>{let V=setTimeout(()=>E(new Error("Metadata load timeout")),1e4);w.onloadedmetadata=()=>{clearTimeout(V),B();},w.onerror=()=>{clearTimeout(V),E(new Error("Failed to load video"));};});let k=640,v=w.videoWidth/w.videoHeight,M=k,A=M/v;await ua(R,L,I),n(Io({id:R,objectUrl:C,thumbnailDataUrl:I,videoBlob:L,x:100,y:100,width:M,height:A,draggable:true,isPlaying:false,rotation:0,isRecorded:true}));},g=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>n(ko()),enabled:m.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>n(To()),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:b,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(L=>L.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(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(Qa,{onClose:()=>s(false),stageRef:e,onRecordingComplete:y}),u&&jsx(Os,{onClose:()=>i(false),onRecordingComplete:y})]})},hd=ZS;var eL=({stageRef:e,onScreenRecord:o,softDelete:t=false,actionButtonsVisible:a=true,actionButtonsConfig:n})=>jsxs(Fragment,{children:[jsx(hd,{stageRef:e,onScreenRecord:o,visible:a,config:n}),jsx(pd,{softDelete:t})]}),tL=eL;var rL="SchooplaEditorDB",nL=1,Ka="slides",Ga="metadata",gd="schoopla_current_slide_id",Rm="presentation_metadata",on=()=>new Promise((e,o)=>{let t=indexedDB.open(rL,nL);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"});};}),xd=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);}}},bd=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}}},js=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(gd),localStorage.removeItem("schoopla_presentation_metadata"),await jc(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},vd=e=>{try{localStorage.setItem(gd,e);}catch(o){console.error("Error saving current slide ID:",o);}},yd=()=>{try{return localStorage.getItem(gd)}catch(e){return console.error("Error loading current slide ID:",e),null}},wd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Sd=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:Rm,...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);}}},Ld=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(Rm);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 sL=["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"],iL=["canvas/clearCanvas"],lL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],dL=wd((e,o)=>{xd(e),vd(o);},500),uL=wd(e=>{Sd(e);},500),cL=(e,o)=>{xd(e),vd(o);},Id=false,Fm=(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&&ua(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&&iL.includes(t.type)){if(!Id){Id=true;try{let{slides:r,currentSlideId:s}=n.canvas;cL(r,s);}finally{setTimeout(()=>{Id=false;},0);}}}else if(t.type&&sL.includes(t.type)){let{slides:r,currentSlideId:s}=n.canvas;dL(r,s);}else if(t.type&&lL.includes(t.type)){let{presentationMetadata:r}=n.canvas;uL(r);}return a});new QueryClient;var mL=configureStore({reducer:{toolbar:Yl,canvas:Hi},middleware:e=>e({serializableCheck:false}).concat(Fm)}),pL=()=>configureStore({reducer:{toolbar:Yl,canvas:Hi},middleware:e=>e({serializableCheck:false})});var hL=(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")}},gL=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);}})},xL=(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 bL=(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))},Cd=(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=bL(e[s],n,r);u>t&&(t=u,a=s);}if(t>o){let s=Cd(e.slice(0,a+1),o),u=Cd(e.slice(a),o);return [...s.slice(0,-1),...u]}return [n,r]},vL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},yL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Om=(e,o=1.5)=>{if(e.length<=4)return e;let t=vL(e),a=Cd(t,o);return yL(a)},Nm=(e,o=1.5)=>({...e,points:Om(e.points,o)}),wL=(e,o=1.5)=>e.map(t=>Nm(t,o)),SL=(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 LL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Hm=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=LL(e),m=f.toDataURL(l,n);r(m);},u.onerror=s,u.src=e;})};var bo=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},rr=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",nr=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",IL=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 Hm(m,{maxWidth:a,maxHeight:n,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(m.startsWith("data:")){let h=bo(m),p=rr(m);u+=h.byteLength;let b={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=bo(l.audioData),x=rr(l.audioData);u+=y.byteLength,b.audioBuffer=y,b.audioMimeType=x;}c.push(b);}}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=bo(l.videoData),h=rr(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 b=bo(l.audioData),y=rr(l.audioData);u+=b.byteLength,p.audioBuffer=b,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=bo(l.capturedImageUrl),p=rr(l.capturedImageUrl);u+=h.byteLength,m.buffer=h,m.mimeType=p;}if(l.audioData&&l.audioData.startsWith("data:")){let h=bo(l.audioData),p=rr(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}},CL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},kL=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}.${nr(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.${nr(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}.${nr(r.mimeType)}`;if(o.append(`slide_${n}_video_${s}`,u,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let c=bo(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.${nr(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}.${nr(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.${nr(r.audioMimeType)}`;o.append(`slide_${n}_photoframe_${s}_audio`,u,i);}});}),o};var AL=()=>{let e=Ye(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let n=await bd(),r=yd(),s=await Ld();if(n&&n.length>0){let u=await Gc(),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(So({slides:i,currentSlideId:c}));}e(s?Bi({title:s.title,description:s.description}):Xn(!0));}catch(n){console.error("Error loading persisted slides:",n),e(Xn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var Vm=e=>e.map(o=>({...o,lines:o.lines||[],shapes:o.shapes||[],images:o.images||[],videos:o.videos||[],flashcards:o.flashcards||[],photoFrames:o.photoFrames||[],texts:o.texts||[],multipleChoices:o.multipleChoices||[],trueFalses:o.trueFalses||[],shortAnswers:o.shortAnswers||[],LongAnswer:o.LongAnswer||[],fillInTheBlanks:o.fillInTheBlanks||[],createdAt:o.createdAt||Date.now(),updatedAt:o.updatedAt||Date.now(),showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,activityType:o.activityType||""})),zm=new WeakSet,Um=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 ua(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},PL=()=>{let e=Ye(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||zm.has(a))return;zm.add(a);let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await js(),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=Vm(n);e(So({slides:i,currentSlideId:u})),await Um(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 js(),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=Vm(n);e(So({slides:i,currentSlideId:u})),await Um(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{
|
|
20
|
+
*/export{ww as BASIC_EDITOR_TOOLBAR_CONFIG,LS as BottomToolbar,Cv as Canvas,vw as DEFAULT_CONTEXT_MENU_CONFIG,Ns as DEFAULT_TOOLBAR_CONFIG,Tg as EditorRoot,hd as MobileActionButtons,tL as MobileBottomSection,pd as MobilePrevPanel,ud as PublishButton,Qa as ScreenRecorder,RS as SlideNavigation,cS as Toolbar,gS as TopNavBar,yw 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,dr as addSlide,fi as addText,Li as addTrueFalse,Io as addVideo,CL as arrayBufferToBase64,Mi as bringToFront,xr as clearCanvas,Lp as clearImageAnnotations,js as clearLocalData,Cp as clearPhotoFrameAnnotations,ii as createEmptySlide,pL as createViewerStore,Un as deleteFillInTheBlanks,Pn as deleteFlashcard,wn as deleteImage,$n as deleteLineById,Vn as deleteLongAnswer,Fn as deleteMultipleChoice,Dn as deletePhotoFrame,Tn as deleteShape,Hn as deleteShortAnswer,ur as deleteSlide,Mn as deleteText,On as deleteTrueFalse,In as deleteVideo,Wn as duplicateFillInTheBlanks,En as duplicateFlashcard,Sn as duplicateImage,Di as duplicateLine,zn as duplicateLongAnswer,Bn as duplicateMultipleChoice,Rn as duplicatePhotoFrame,kn as duplicateShape,qn as duplicateShortAnswer,cr as duplicateSlide,An as duplicateText,Nn as duplicateTrueFalse,Cn as duplicateVideo,pr as editFlashcard,kp as editMultipleChoice,gL as exportSlideAsBlob,hL as exportSlideAsImage,Ei as finalizeDrawing,SL as getCompressionStats,xL as getSlideDataURL,yd as loadCurrentSlideId,bd as loadFromIndexedDB,Bi as loadPresentationMetadata,Ld as loadPresentationMetadataFromDB,So as loadSlides,Ql as mergeToolbarConfig,pi as nextFlashcard,kL as prepareFormData,IL as prepareSlidesForPublishing,hi as previousFlashcard,To as redo,yn as removeLine,wp as reorderSlides,Sd as savePresentationMetadata,ce as saveToHistory,ka as selectAllSlides,Oi as selectAllSlidesIncludingInactive,vr as selectCanAddSlide,ye as selectCurrentSlide,Ca as selectCurrentSlideId,Ni as selectMetadataLoaded,yr as selectPresentationMetadata,Ep as selectSlideById,Ai as sendToBack,Ti as setActivityType,Gn as setAltText,jn as setAudioData,mr as setBackgroundColor,fr as setCurrentSlide,hr as setEditingActivity,br as setEditingTextId,Mp as setLines,Kn as setLink,Xn as setMetadataLoaded,pa as setPenColor,Fi as setPresentationDescription,Ri as setPresentationTitle,Ja as setShowFlashcardForm,Ia as setShowMcqForm,Ct as setSketchMode,Zr as setStrokeWidth,ra as setTool,yp as setViewerMode,Om as simplifyFlatPoints,Nm as simplifyLine,wL as simplifyLines,mL as store,xi as toggleImageDrawingMode,Pi as toggleLock,vi as togglePhotoFrameDrawingMode,Pp as toggleSketchMode,$a as toggleVideoPlaying,ko as undo,gr as updateElementOrder,La as updateFillInTheBlanks,Co as updateFlashcard,Lo as updateImage,Sp as updateImageAnnotation,Tp as updateLastLine,Ap as updateLinePosition,_n as updateLineTransform,Za as updateLongAnswer,Ht as updateMultipleChoice,Ya as updatePhotoFrame,Ip as updatePhotoFrameAnnotation,Xa as updateShape,ia as updateShortAnswer,li as updateSlideThumbnail,Nt as updateText,gt as updateTrueFalse,Ln as updateVideo,Le as useDispatch,PL as useInitialSlides,sl as useModalPortal,Q as useSelector,AL as useSlidesPersistence};//# sourceMappingURL=index.js.map
|
|
21
21
|
//# sourceMappingURL=index.js.map
|