@turnix-co/konva-editor 3.0.56 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use client";
2
- export{default as Konva}from'konva';import*as 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:
2
+ export{default as Konva}from'konva';import*as Le from'react';import Le__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,createContext,useState,useMemo,createElement,useContext,useId,useLayoutEffect}from'react';import {createPortal}from'react-dom';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {CameraPlus,Camera,Stop,X,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Palette,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Rectangle,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,List,Plus,Export,CaretLeft,CaretDown,CaretUp,SidebarSimple,CaretRight,ArrowsOut,SpeakerHifiIcon,NotePencilIcon,FrameCorners,PencilSimple,CopySimple,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,TextUnderline,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Copy,Pen}from'@phosphor-icons/react/dist/ssr';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import _d from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import Xu from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {Stack as Stack$1,X as X$1,DotsSixVertical,Question,FrameCorners as FrameCorners$1,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Od=e=>{throw TypeError(e)};var Nd=(e,o,t)=>o.has(e)||Od("Cannot "+t);var $=(e,o,t)=>(Nd(e,o,"read from private field"),t?t.call(e):o.get(e)),Ne=(e,o,t)=>o.has(e)?Od("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),De=(e,o,t,a)=>(Nd(e,o,"write to private field"),o.set(e,t),t);var Hd=(e,o,t,a)=>({set _(n){De(e,o,n);},get _(){return $(e,o,a)}});var Se=()=>useDispatch(),J=e=>useSelector(e),_e=Se,Re=J;var oi=20,dt=(()=>{let e=0;return o=>`${o}-${Date.now()}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`})();function wp(e){let o=JSON.parse(JSON.stringify(e));return o.id=dt("slide"),o.name=`${e.name} (Copy)`,o.createdAt=Date.now(),o.updatedAt=Date.now(),o.isActive=true,o.showMcqForm=false,o.showFlashcardForm=false,o.editingActivity=null,o.editingFlashcard=null,o.lines=o.lines.map(t=>({...t,id:dt("line")})),o.shapes=o.shapes.map(t=>({...t,id:dt("shape")})),o.images=o.images.map(t=>({...t,id:dt("img"),annotations:t.annotations?.map(a=>({...a,id:dt("line")}))??[]})),o.videos=o.videos.map(t=>({...t,id:dt("vid"),isPlaying:false,videoBlob:void 0})),o.flashcards=o.flashcards.map(t=>({...t,id:dt("flashcard")})),o.photoFrames=o.photoFrames.map(t=>({...t,id:dt("photoframe"),isCapturing:false,annotations:t.annotations?.map(a=>({...a,id:dt("line")}))??[]})),o.texts=o.texts.map(t=>({...t,id:dt("text")})),o.multipleChoices=o.multipleChoices.map(t=>({...t,id:dt("mcq"),data:{...t.data,responseOptions:{...t.data.responseOptions,selectedIndices:void 0,isCorrect:void 0,attempts:void 0}}})),o.trueFalses=o.trueFalses.map(t=>({...t,id:dt("truefalse"),data:{...t.data,responseOptions:{...t.data.responseOptions,selectedResponse:void 0,isCorrect:void 0,attempts:void 0}}})),o.shortAnswers=o.shortAnswers.map(t=>({...t,id:dt("shortAnswer"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0,isCorrect:void 0,attempts:void 0}}})),o.LongAnswer=o.LongAnswer.map(t=>({...t,id:dt("longAnswer"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0}}})),o.fillInTheBlanks=o.fillInTheBlanks.map(t=>({...t,id:dt("fillInTheBlank"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0,isCorrect:void 0,attempts:void 0}}})),o}var ni=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now(),isActive:true}),ai=ni("Page 1"),Sp={slides:[ai],currentSlideId:ai.id,history:{[ai.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false,editingOverlayPosition:null,zoomLevel:1},qd=createSlice({name:"canvas",initialState:Sp,reducers:{addSlide:e=>{if(e.slides.length>=oi)return;let o=ni(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(u=>u.isActive).length<=1)return;let r=e.slides.findIndex(u=>u.id===t);if(r===-1)return;let s=e.slides[r];if(a?(s.isActive=false,s.updatedAt=Date.now()):(e.slides.splice(r,1),delete e.history[t]),e.currentSlideId===t){let u=e.slides.filter(i=>i.isActive);u.length>0&&(e.currentSlideId=u[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=oi)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],n=wp(a);e.slides.splice(t+1,0,n),e.currentSlideId=n.id,e.history[n.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},setViewerMode:(e,o)=>{e.viewerMode=o.payload;},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[n]=e.slides.splice(t,1);e.slides.splice(a,0,n);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(n=>n.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload);if(a){let n={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(n),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,newTimestamp:r}=o.payload;switch(n){case "image":let s=t.images.find(b=>b.id===a);s&&(s.timestamp=r);break;case "video":let u=t.videos.find(b=>b.id===a);u&&(u.timestamp=r);break;case "shape":let i=t.shapes.find(b=>b.id===a);i&&(i.timestamp=r);break;case "text":let c=t.texts.find(b=>b.id===a);c&&(c.timestamp=r);break;case "flashcard":let f=t.flashcards.find(b=>b.id===a);f&&(f.timestamp=r);break;case "photoFrame":let d=t.photoFrames.find(b=>b.id===a);d&&(d.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(b=>b.id===a);l&&(l.timestamp=r);break;case "trueFalse":let m=t.trueFalses.find(b=>b.id===a);m&&(m.timestamp=r);break;case "shortAnswer":let h=t.shortAnswers.find(b=>b.id===a);h&&(h.timestamp=r);break;case "longAnswer":let p=t.LongAnswer.find(b=>b.id===a);p&&(p.timestamp=r);break;case "fillInTheBlanks":let v=t.fillInTheBlanks.find(b=>b.id===a);v&&(v.timestamp=r);break;case "line":let y=t.lines.find(b=>b.id===a);y&&(y.timestamp=r);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);if(a){let n={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(n),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(n=>n.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(n=>n.id===o.payload);if(a){let n={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(n),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(n=>n.id===o.payload);if(a){let n={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(n),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let n=t.multipleChoices[t.multipleChoices.length-1];a.x=n.x+20,a.y=n.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},updateMultipleChoiceDragAndDrop(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a].dragDropPos=o.payload.dragDropPos,t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(n=>n.id===o.payload);if(a){let n={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(n),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let n=t.trueFalses[t.trueFalses.length-1];a.x=n.x+20,a.y=n.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(n=>n.id===o.payload);if(a){let n={...JSON.parse(JSON.stringify(a)),id:`truefalse-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(n),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let n=t.shortAnswers[t.shortAnswers.length-1];a.x=n.x+20,a.y=n.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(n=>n.id===o.payload);if(a){let n={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(n),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let n=t.LongAnswer[t.LongAnswer.length-1];a.x=n.x+20,a.y=n.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload);if(a){let n={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(n),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let n=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=n.x+20,a.y=n.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(n=>n.id===o.payload);if(a){let n={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(n),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.images.splice(r,1);t.images.push(s);}}else if(n==="video"){let r=t.videos.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.videos.splice(r,1);t.videos.push(s);}}else if(n==="shape"){let r=t.shapes.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shapes.splice(r,1);t.shapes.push(s);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.flashcards.splice(r,1);t.flashcards.push(s);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.photoFrames.splice(r,1);t.photoFrames.push(s);}}else if(n==="text"){let r=t.texts.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.texts.splice(r,1);t.texts.push(s);}}else if(n==="trueFalse"){let r=t.trueFalses.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.trueFalses.splice(r,1);t.trueFalses.push(s);}}else if(n==="shortAnswer"){let r=t.shortAnswers.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shortAnswers.splice(r,1);t.shortAnswers.push(s);}}else if(n==="fillInTheBlanks"){let r=t.fillInTheBlanks.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.fillInTheBlanks.splice(r,1);t.fillInTheBlanks.push(s);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.images.splice(r,1);t.images.unshift(s);}}else if(n==="video"){let r=t.videos.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.videos.splice(r,1);t.videos.unshift(s);}}else if(n==="shape"){let r=t.shapes.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shapes.splice(r,1);t.shapes.unshift(s);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.flashcards.splice(r,1);t.flashcards.unshift(s);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.photoFrames.splice(r,1);t.photoFrames.unshift(s);}}else if(n==="text"){let r=t.texts.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.texts.splice(r,1);t.texts.unshift(s);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload,s=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);s&&(s.locked=!s.locked,"draggable"in s&&(s.draggable=!s.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,link:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="mcq"?t.multipleChoices:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.link=r,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,altText:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.altText=r,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,audioData:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.audioData=r,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},editingOverlayPosition:(e,o)=>{e.editingOverlayPosition=o.payload;},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(n=>n.id===o.payload);if(a){let n={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(n),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);if(a){let n={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(n),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let n=a.images.map((r,s)=>s).filter(r=>r!==a.currentIndex);if(n.length>0){let r=n[Math.floor(Math.random()*n.length)];a.navigationHistory.push(r),a.currentIndex=r;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);if(a){let n={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(n),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let n=o.past.pop();e.slides[t]=n;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let n=o.future.shift();e.slides[t]=n;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let n=JSON.parse(JSON.stringify(t));a.past.push(n),a.future=[],a.past.length>20&&a.past.shift();}catch(n){console.warn("Failed to save to history - data too large:",n),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;},setZoomLevel:(e,o)=>{e.zoomLevel=Math.max(.5,Math.min(2,o.payload));},zoomIn:e=>{e.zoomLevel=Math.min(2,e.zoomLevel+.25);},zoomOut:e=>{e.zoomLevel=Math.max(.5,e.zoomLevel-.25);},resetZoom:e=>{e.zoomLevel=1;}}}),{addSlide:ur,deleteSlide:cr,duplicateSlide:fr,setCurrentSlide:mr,setViewerMode:Lp,updateSlideThumbnail:si,setBackgroundColor:pr,reorderSlides:Ip,loadSlides:Io,addLine:ii,removeLine:xn,addImage:li,updateImage:Co,deleteImage:bn,duplicateImage:vn,addVideo:ko,updateVideo:yn,deleteVideo:wn,duplicateVideo:Sn,toggleVideoPlaying:Xa,addShape:di,updateShape:Ya,duplicateShape:Ln,deleteShape:In,addText:ui,editingOverlayPosition:Vd,updateText:Ft,deleteText:Cn,duplicateText:kn,addFlashcard:ci,updateFlashcard:To,deleteFlashcard:Tn,duplicateFlashcard:Mn,editFlashcard:hr,nextFlashcard:fi,previousFlashcard:mi,addPhotoFrame:pi,updatePhotoFrame:Za,deletePhotoFrame:An,duplicatePhotoFrame:Pn,toggleImageDrawingMode:hi,addImageAnnotation:gi,updateImageAnnotation:Cp,clearImageAnnotations:kp,togglePhotoFrameDrawingMode:xi,addPhotoFrameAnnotation:bi,updatePhotoFrameAnnotation:Tp,clearPhotoFrameAnnotations:Mp,addMultipleChoice:vi,updateMultipleChoice:gt,updateMultipleChoiceDragAndDrop:yi,editMultipleChoice:Ap,deleteMultipleChoice:En,duplicateMultipleChoice:Dn,addTrueFalse:wi,updateTrueFalse:ot,deleteTrueFalse:Rn,duplicateTrueFalse:Fn,addShortAnswer:Si,updateShortAnswer:sa,deleteShortAnswer:Bn,duplicateShortAnswer:On,addLongAnswer:Li,updateLongAnswer:Ja,deleteLongAnswer:Nn,duplicateLongAnswer:Hn,addFillInTheBlanks:Ii,updateFillInTheBlanks:Sa,deleteFillInTheBlanks:qn,duplicateFillInTheBlanks:Vn,setShowMcqForm:La,setShowFlashcardForm:Qa,setActivityType:Ci,setEditingActivity:gr,bringToFront:ki,sendToBack:Ti,toggleLock:Mi,setLink:zn,setAltText:Wn,setAudioData:Un,updateLastLine:Pp,finalizeDrawing:Ai,setLines:Ep,updateLinePosition:Dp,updateLineTransform:Kn,deleteLineById:Gn,duplicateLine:Pi,updateElementOrder:xr,clearCanvas:br,undo:Mo,redo:Ao,saveToHistory:de,toggleSketchMode:Rp,setSketchMode:It,setEditingTextId:vr,setPresentationTitle:Ei,setPresentationDescription:Di,loadPresentationMetadata:Ri,setMetadataLoaded:jn,setZoomLevel:WL,zoomIn:UL,zoomOut:KL,resetZoom:zd}=qd.actions;var Wd=e=>e.canvas.slides,Ia=e=>e.canvas.currentSlideId,ve=createSelector([Wd,Ia],(e,o)=>e.find(t=>t.id===o)),Ca=createSelector([Wd],e=>e.filter(o=>o.isActive!==false)),Fi=e=>e.canvas.slides,yr=createSelector([Ca],e=>e.length<oi),Fp=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},wr=e=>e.canvas.presentationMetadata,Bi=e=>e.canvas.metadataLoaded,_n=e=>e.canvas.viewerMode,Oi=qd.reducer;var Kd=e=>{let o=Se(),t=useRef(null),a=useRef(false),n=J(m=>m.toolbar.selectedTool),r=J(m=>m.toolbar.penColor),s=J(m=>m.toolbar.strokeWidth),u=J(m=>m.canvas.isSketchMode),i=J(m=>m.canvas.slides.find(p=>p.id===m.canvas.currentSlideId)?.lines||[]),c=useCallback(m=>{t.current=m;},[]),f=useCallback(m=>{n==="pen"&&t.current&&(o(de()),t.current.startDrawing(m),a.current=true);},[n,o]),d=useCallback(m=>{!t.current||!a.current||t.current.draw(m);},[]),l=useCallback(()=>{if(!t.current||!a.current)return;let m=t.current.stopDrawing();a.current=false,m&&m.points.length>=4&&o(ii(m)),o(Ai()),e?.();},[o,e]);return {lines:i,tool:n,color:r,strokeWidth:s,isSketchMode:u,setCanvasRef:c,startDrawing:f,draw:d,stopDrawing:l}};var $d=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:n,isSketchMode:r,style:s,xOffset:u=0,yOffset:i=0},c)=>{let f=useRef(null),d=useRef(false),l=useRef([]),m=useRef([]),h=useRef(null),p=useRef(t),v=useRef(a),y=useRef(n),b=useRef(r),g=useRef(u),C=useRef(i);useEffect(()=>{p.current=t,v.current=a,y.current=n,b.current=r,g.current=u,C.current=i;},[t,a,n,r,u,i]);let I=useCallback(()=>{let k=f.current;if(!k)return;let x=k.getContext("2d");x&&x.clearRect(0,0,k.width,k.height);},[]),B=useCallback(()=>{let k=f.current,x=m.current;if(!k||x.length<1)return;let S=k.getContext("2d");if(!S)return;if(S.clearRect(0,0,k.width,k.height),p.current==="eraser"?(S.globalCompositeOperation="destination-out",S.fillStyle="rgba(0,0,0,1)"):(S.globalCompositeOperation="source-over",S.fillStyle=v.current),x.length===1){S.beginPath(),S.arc(x[0].x,x[0].y,y.current/2,0,Math.PI*2),S.fill();return}let T=_d(x,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:q=>q,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(T.length<2)){S.beginPath(),S.moveTo(T[0][0],T[0][1]);for(let q=1;q<T.length;q++)S.lineTo(T[q][0],T[q][1]);S.closePath(),S.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:k=>{d.current=true;let x={x:k.x-g.current,y:k.y-C.current};l.current=[{x:k.x,y:k.y}],m.current=[x],h.current=k,B();},draw:k=>{if(!d.current||!h.current)return;let x=k.x-h.current.x,S=k.y-h.current.y;if(Math.sqrt(x*x+S*S)<2)return;let T={x:k.x-g.current,y:k.y-C.current};l.current.push({x:k.x,y:k.y}),m.current.push(T),h.current=k,B();},stopDrawing:()=>{if(!d.current)return null;if(d.current=false,l.current.length<2)return l.current=[],m.current=[],h.current=null,I(),null;let x=_d(l.current,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:w=>w,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(w=>[w[0],w[1]]),S={tool:p.current,points:x,color:v.current,strokeWidth:y.current,isSketch:true};return l.current=[],m.current=[],h.current=null,I(),S},clear:()=>{I(),l.current=[],m.current=[],h.current=null,d.current=false;},isDrawing:()=>d.current,getCanvasElement:()=>f.current}),[I,B]),useEffect(()=>{let k=f.current;k&&(k.width=e,k.height=o);},[e,o]),jsx("canvas",{ref:f,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});$d.displayName="DirectDrawingCanvas";var Xd=$d;var Zd=e=>{let o=Se(),a=J(ve)?.images||[],n=useRef(new Map),r=useRef(new Map),s=useRef(new Set);useEffect(()=>{let f=new Set(a.map(d=>d.id));s.current.forEach(d=>{if(!f.has(d)){let l=r.current.get(d);l&&(l.src="",r.current.delete(d)),n.current.delete(d);}}),s.current=f;},[a]),useEffect(()=>()=>{r.current.forEach(f=>{f.src="";}),r.current.clear(),n.current.clear();},[]);let u=useCallback(f=>{if(r.current.has(f.id))return r.current.get(f.id);let d=new window.Image;return (f.src.startsWith("http://")||f.src.startsWith("https://"))&&(d.crossOrigin="anonymous"),d.src=f.src,r.current.set(f.id,d),d},[]),i=useCallback((f,d)=>{let l=f.target,m=l.id();a.find(p=>p.id===m)&&(o(Co({id:m,x:l.x(),y:l.y(),width:l.width(),height:l.height(),rotation:l.rotation()})),d?.());},[a,o]),c=useCallback((f,d)=>{let l=d.target,m=n.current.get(f);if(!m){console.error("\u274C Image node not found for id:",f);return}let h=l.scaleX(),p=l.scaleY(),v=l.rotation(),y=m.width(),b=m.height(),g=Math.max(5,y*h),C=Math.max(5,b*p);l.scaleX(1),l.scaleY(1),m.width(g),m.height(C),o(Co({id:f,width:g,height:C,x:l.x(),y:l.y(),rotation:v})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:u,imageRefs:n,handleDragEnd:i,handleImageTransformEnd:c}};var Jd=e=>{let o=useDispatch(),t=useSelector(ve),a=useRef(new Map),n=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((u,i)=>{let c=i.target,f=c.scaleX(),d=c.scaleY(),l=c.rotation();o(gt({id:u,scaleX:f,scaleY:d,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:n,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(u,i)=>{o(gt({id:i,x:u.target.x(),y:u.target.y()})),e?.();}}};var Qd=e=>{let o=useDispatch(),t=useSelector(ve),a=useRef(new Map),n=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((u,i)=>{let c=i.target,f=c.scaleX(),d=c.scaleY(),l=c.rotation(),m=Math.max(5,c.width()*f),h=Math.max(5,c.height()*d);c.scaleX(1),c.scaleY(1),c.width(m),c.height(h),o(ot({id:u,width:m,height:h,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:n,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(u,i)=>{o(ot({id:i,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var eu=e=>{let o=Se(),a=J(ve)?.videos||[],n=useRef(new Map),r=useCallback(i=>{o(Xa(i));},[o]),s=useCallback((i,c)=>{let f=c.target;o(yn({id:i,x:f.x(),y:f.y()})),e?.();},[o,e]),u=useCallback((i,c)=>{let f=c.target,d=f.scaleX(),l=f.scaleY(),m=f.rotation(),h=Math.max(5,f.width()*d),p=Math.max(5,f.height()*l);f.scaleX(1),f.scaleY(1),f.width(h),f.height(p),o(yn({id:i,width:h,height:p,x:f.x(),y:f.y(),rotation:m})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:n,handleVideoClick:r,handleVideoDragEnd:s,handleVideoTransformEnd:u}};var ou=e=>{let o=Se(),a=J(ve)?.shapes||[],n=useRef(new Map),r=useRef(new Map),[s,u]=useState(false),i=useCallback((f,d)=>{let l=d.target;o(Ya({id:f,x:l.x(),y:l.y()})),e?.();},[o,e]),c=useCallback((f,d)=>{let l=d.target,m=a.find(g=>g.id===f);if(!m)return;let h=l.scaleX(),p=l.scaleY(),v=m.type?.toLowerCase();v==="arrow"||v==="line"||(l.scaleX(1),l.scaleY(1));let b={id:f,x:l.x(),y:l.y(),width:Math.max(5,l.width()*h),height:Math.max(5,l.height()*p),rotation:l.rotation()};switch(v){case "circle":b.radius=l.width()*h/2;break;case "star":b.innerRadius=l.width()*h/4,b.outerRadius=l.width()*h/2;break;case "triangle":b.radius=l.width()*h/2;break;case "ellipse":b.radiusX=l.width()*h/2,b.radiusY=l.height()*p/2;break;case "polygon":b.radius=l.width()*h/2;break;case "ring":let g=h;b.innerRadius=m.innerRadius&&m.innerRadius*g,b.outerRadius=m.outerRadius&&m.outerRadius*g;break;case "wedge":b.radius=m.radius&&m.radius*h;break;case "arc":b.innerRadius=m.innerRadius&&m.innerRadius*h,b.outerRadius=m.outerRadius&&m.outerRadius*h;break;case "arrow":case "line":{b.scaleX=h,b.scaleY=p,delete b.width,delete b.height;break}}o(Ya(b)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:n,isDragging:s,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:c}};var nu=(e,o)=>{let t=_e(),n=J(ve)?.texts||[],r=useRef(new Map),[s,u]=useState(null),[i,c]=useState("");return {texts:n,textRefs:r,handleDragEnd:(v,y)=>{let b=v.target;t(de()),t(Ft({id:y,x:b.x(),y:b.y()})),e();},handleTransformEnd:v=>{let y=r.current.get(v);if(!y)return;let b=y.scaleX(),g=y.scaleY(),C=n.find(B=>B.id===v);if(!C)return;let I=(b+g)/2;y.scaleX(1),y.scaleY(1),t(de()),t(Ft({id:v,x:y.x(),y:y.y(),width:Math.max(5,(C.width||100)*b),height:Math.max(5,(C.height||50)*g),fontSize:Math.round(Math.max(8,C.fontSize*I)),rotation:y.rotation()})),e();},handleDoubleClick:v=>{let y=n.find(b=>b.id===v);y&&!y.locked&&(u(v),c(y.text));},startEditing:v=>{let y=n.find(b=>b.id===v);y&&!y.locked&&(u(v),c(y.text));},editingTextId:s,editingValue:i,handleEditingChange:v=>{c(v);},finishEditing:()=>{if(s){let v=r.current.get(s),y=n.find(g=>g.id===s);t(de());let b={id:s,text:i};if(y&&(y.fontWeight!==void 0&&(b.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(b.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(b.textDecoration=y.textDecoration)),o?.current&&i.trim()){let g=o.current,C=g.offsetWidth,I=g.offsetHeight,B=1;if(v){let V=v.getStage();V&&(B=V.scaleX());}let k=14,x=(C-k)/B,S=(I-k)/B,w=i.split(`
3
+ `).length,q=n.find(V=>V.id===s)?.fontSize||24,F=w*q*1.2+10;b.width=Math.max(200,x),b.height=Math.max(50,S,F);}else if(v&&i.trim()){let g=v.text(),C=v.width();v.text(i),v.width(void 0);let I=v.width(),B=v.height();v.text(g),v.width(C),b.width=Math.max(200,I+20),b.height=Math.max(50,B+20);}t(Ft(b)),u(null),c(""),t(vr(null)),e();}}}};var su=e=>{let o=useDispatch(),a=useSelector(ve)?.shortAnswers||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(sa({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:n,handleShortAnswerDragEnd:r}};var iu=e=>{let o=useDispatch(),t=useSelector(ve),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),n=useCallback((r,s)=>{let u=r.target;o(Ja({id:s,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:n}};var du=e=>{let o=Se(),a=J(ve)?.flashcards||[],n=useRef(new Map),r=useRef(new Map),s=useCallback((d,l)=>{if(r.current.has(l))return r.current.get(l);let m=new window.Image;return (d.startsWith("http://")||d.startsWith("https://"))&&(m.crossOrigin="anonymous"),m.src=d,r.current.set(l,m),m},[]),u=useCallback(d=>{let l=d.target,m=l.id();a.find(p=>p.id===m)&&(o(To({id:m,x:l.x(),y:l.y()})),e?.());},[a,o,e]),i=useCallback((d,l)=>{let m=l.target,h=m.scaleX(),p=m.scaleY(),v=m.rotation(),y=Math.max(50,m.width()*h),b=Math.max(50,m.height()*p);m.scaleX(1),m.scaleY(1),m.width(y),m.height(b),o(To({id:d,width:y,height:b,x:m.x(),y:m.y(),rotation:v})),m.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(d=>{o(fi(d)),e?.();},[o,e]),f=useCallback(d=>{o(mi(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:n,handleDragEnd:u,handleFlashcardTransformEnd:i,handleNext:c,handlePrevious:f}};var fu=e=>{let o=Se(),a=J(ve)?.photoFrames||[],n=useRef(new Map),[r,s]=useState(new Map),u=useCallback((m,h)=>{console.log("handleDragEnd"),o(Za({id:h,x:m.target.x(),y:m.target.y()})),e?.();},[o,e]),i=useCallback((m,h)=>{let p=h.target,v=p.scaleX(),y=p.scaleY(),b=p.rotation(),g=a.find(B=>B.id===m);if(!g)return;let C=Math.max(100,g.width*v),I=Math.max(100,g.height*y);p.scaleX(1),p.scaleY(1),o(Za({id:m,width:C,height:I,x:p.x(),y:p.y(),rotation:b})),p.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async m=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(p=>{let v=new Map(p);return v.set(m,h),v}),o(Za({id:m,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),f=useCallback(m=>{let h=r.get(m);h&&(h.getTracks().forEach(p=>p.stop()),s(p=>{let v=new Map(p);return v.delete(m),v}),o(Za({id:m,isCapturing:false})),e?.());},[r,o,e]),d=useCallback((m,h)=>{let p=document.createElement("canvas");p.width=h.videoWidth,p.height=h.videoHeight;let v=p.getContext("2d");if(v){v.drawImage(h,0,0,p.width,p.height);let y=p.toDataURL("image/jpeg",.8);return o(Za({id:m,capturedImageUrl:y,isCapturing:false})),f(m),e?.(),y}return null},[o,f,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(m=>{m.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:n,handleDragEnd:u,handlePhotoFrameTransformEnd:i,startCamera:c,stopCamera:f,capturePhoto:d,cameraStreams:r}};var mu=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,s)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...s,width:Math.max(o.minWidth,Math.min(s.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(s.height,o.maxHeight))}:s,[o]),a=useCallback((r,s,u,i,c,f,d,l=[])=>{if(e.current){if(r&&!l.find(p=>p.id===r)?.isPlaying){let p=s.get(r)||u.get(r)||i.get(r)||c.get(r)||f.get(r)||(d?d.get(r):null);if(p){e.current.boundBoxFunc(t),e.current.nodes([p]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),n=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:n,boundBoxFunc:t}};var lh=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},xu=(e,o)=>{let t=_e(),a=Re(_n),n=useRef(e);useEffect(()=>{n.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(si({id:n.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),s=lh(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var uh=e=>e.flatMap(o=>[o[0],o[1]]),Xn=(e,o)=>{let t=_d(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:a=>a,start:{taper:0,cap:true},end:{taper:0,cap:true}});return uh(t)};var bu=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null),u=J(g=>g.toolbar.selectedTool),i=J(g=>g.toolbar.penColor),c=J(g=>g.toolbar.strokeWidth),f=J(g=>g.canvas.isSketchMode),d=J(g=>g.canvas.slides.find(I=>I.id===g.canvas.currentSlideId)?.images.find(I=>I.id===e)),l=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(g=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,n.current=[{x:g.x,y:g.y}];let C=g.x/h,I=g.y/p;s({tool:u,points:[C,I],color:i,strokeWidth:c/h,isSketch:f});},[u,i,c,f,h,p]),y=useCallback(g=>{if(!t.current||!r)return;a.current=true;let C=n.current[n.current.length-1];if(Math.sqrt(Math.pow(g.x-C.x,2)+Math.pow(g.y-C.y,2))<2)return;n.current.push({x:g.x,y:g.y});let B;if(f)B=Xn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,S)=>S%2===0?x/h:x/p);else {let k=g.x/h,x=g.y/p;B=[...r.points,k,x];}s(k=>k?{...k,points:B}:null);},[f,c,r,h,p]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(gi({imageId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:m,startDrawing:v,draw:y,stopDrawing:b,tool:u}};function Ve({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),n=useRef(null);return {createHandlers:useCallback((s,u)=>({onTouchStart:i=>{let c=i.evt.touches[0];n.current={x:c.clientX,y:c.clientY},a.current=setTimeout(()=>{e(s,u)(i.evt);},o);},onTouchMove:i=>{if(!n.current)return;let c=i.evt.touches[0],f=Math.abs(c.clientX-n.current.x),d=Math.abs(c.clientY-n.current.y);(f>t||d>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),n.current=null;}}),[e,o,t])}}var Lu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u})=>{let{annotations:i,activeLine:c,stopDrawing:l,tool:m}=bu(e.id),{createHandlers:h}=Ve({onLongPress:u});useEffect(()=>{let g=t.current.get(e.id);g&&(g.width()!==e.width||g.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:g.width(),konvaHeight:g.height()}),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[l,p]);let v=g=>{{r(e.id);return}},y=g=>{return;},b=g=>{};return jsxs(Group,{listening:m!=="pen"&&m!=="eraser",children:[jsx(Image$1,{id:e.id,ref:g=>{if(g)t.current.set(e.id,g),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw();else {let C=t.current.get(e.id);C?._contextMenuCleanup&&C._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:m!=="pen"&&m!=="eraser",onDragEnd:a,onTransformEnd:g=>n(e.id,g),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:g=>{g.evt.preventDefault();let C=g.evt;s(C,e.id,"image");},...m!=="pen"&&m!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onMouseMove:y,onMouseUp:b,...h(e.id,"image")}:{}}),i?.map((g,C)=>{let I=g.points.map((k,x)=>x%2===0?k*e.width+e.x:k*e.height+e.y),B=g.strokeWidth*e.width;return jsx(Line,{points:I,stroke:g.tool==="eraser"?"white":g.color,strokeWidth:B,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:g.tool==="eraser"?"destination-out":"source-over",fill:g.isSketch?g.color:void 0,closed:g.isSketch,listening:false},C)}),c&&jsx(Line,{points:c.points.map((g,C)=>C%2===0?g*e.width+e.x:g*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});Lu.displayName="ImageWithDrawing";var Ui=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u})=>jsx(Fragment,{children:e.map(i=>{let c=o(i);return c?jsx(Lu,{img:i,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u},i.id):null})}));Ui.displayName="ImageLayer";var wh=({src:e,x:o,id:t,y:a,width:n,height:r,isSelected:s,rotation:u=0,onTransformEnd:i,onDragEnd:c})=>{let f=Se(),d=useRef(null),l=m=>{f(Xa(m));};return jsxs(Group,{draggable:true,x:o,y:a,width:n,height:r,rotation:u,onDragEnd:c,onTransformEnd:i,children:[jsx(Rect,{width:n,height:r,fill:"black",stroke:s?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${n}px`,height:`${r}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>l(t),onSeeking:m=>m.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Iu=wh;var Ah=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,nodeRef:s})=>{let[u,i]=useState(null),c=useSelector(p=>p.toolbar.selectedTool),f=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let p=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(p.crossOrigin="anonymous"),p.src=e.thumbnailDataUrl,p.onload=()=>{i(p);};}},[e.thumbnailDataUrl]),!u)return null;let d=e.width/2,l=e.height/2,m=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(m,80));return jsxs(Group,{draggable:!f,listening:!f,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...f?{}:{onDragEnd:a,onTransformEnd:n},ref:p=>{if(s(p),p){let v=p.getStage()?.container();if(v){let y=b=>{let g=p.getStage()?.getPointerPosition();if(g){let C={x:e.x,y:e.y,width:e.width,height:e.height};g.x>=C.x&&g.x<=C.x+C.width&&g.y>=C.y&&g.y<=C.y+C.height&&r(b);}};v.addEventListener("contextmenu",y),p._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",y);};}}},children:[jsx(Image$1,{image:u,width:e.width,height:e.height,listening:!f,...f?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:d,y:l,radius:h,fill:"white",listening:!f,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...f?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:l,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!f,...f?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:l,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!f,...f?{}:{onClick:t,onTap:t}})]})},ku=Ah;var ji=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:n,onTransformEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(u=>jsxs(Le__default.Fragment,{children:[jsx(ku,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>a(u.id),onDragEnd:i=>n(u.id,i),onTransformEnd:i=>r(u.id,i),onContextMenu:i=>s(i,u.id,"video"),nodeRef:i=>{i?t.current.set(u.id,i):t.current.delete(u.id);}}),u.isPlaying&&!u.isRecorded&&jsx(Iu,{id:u.id,src:u.objectUrl,x:u.x,y:u.y,width:u.width,height:u.height,isSelected:false,rotation:u.rotation,onTransformEnd:i=>r(u.id,i),onDragEnd:i=>n(u.id,i)})]},u.id))}));ji.displayName="VideoLayer";var _i=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:n,handleShapeDragStart:r,onContextMenu:s,onLongPress:u})=>{let i=useSelector(d=>d.toolbar.selectedTool),c=i==="pen"||i==="eraser",{createHandlers:f}=Ve({onLongPress:u});return jsx(Fragment,{children:e.map((d,l)=>{let m=d.id||l,h={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!c,listening:!c,fill:d.color||"#096B76",stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?2:0,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radius:d.radius||d.width/2,width:d.width,height:d.width},m);case "star":return jsx(Star,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},m);case "triangle":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},sides:3,radius:d.radius||d.width/2},m);case "polygon":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},sides:d.sides||6,radius:d.radius||d.width/2},m);case "ellipse":return jsx(Ellipse,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},m);case "ring":return jsx(Ring,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},m);case "wedge":return jsx(Wedge,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radius:d.radius||d.width/2,angle:d.angle||60},m);case "arrow":return jsx(Arrow,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?d.strokeWidth||3:0,fill:"transparent"},m);case "line":return jsx(Line,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},points:d.points||[0,0,d.width,0],stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?d.strokeWidth||3:0,fill:"transparent"},m);case "arc":return jsx(Arc,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},m);case "rectangle":default:return jsx(Rect,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},m)}})})});_i.displayName="ShapeLayer";var Au=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:n,onContextMenu:r,onDoubleClick:s,editingTextId:u,onLongPress:i})=>{useEffect(()=>{e.forEach(l=>{let m=o.current.get(l.id);m&&(m.cache(),m.getLayer()?.batchDraw());});},[e,o]);let c=useSelector(l=>l.toolbar.selectedTool),f=c==="pen"||c==="eraser",{createHandlers:d}=Ve({onLongPress:i});return jsx(Fragment,{children:e.map(l=>{let m=l.id===u,h=l.fontWeight==="bold",p=h?Math.max(1,l.fontSize/25):0;return jsx(Text,{id:l.id,ref:v=>{v?o.current.set(l.id,v):o.current.delete(l.id);},text:l.text,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:!l.locked&&!m&&!f,listening:!f,fontSize:l.fontSize,fontFamily:l.fontFamily,fontStyle:l.fontStyle,fontWeight:l.fontWeight,textDecoration:l.textDecoration,fill:l.fill,stroke:h?l.fill:void 0,strokeWidth:p,align:l.align,wrap:"word",lineHeight:1.2,opacity:m?0:1,visible:!m,...f?{}:{onClick:()=>n(l.id),onTap:()=>n(l.id),onDblClick:()=>s(l.id),onDblTap:()=>s(l.id),onDragEnd:v=>t(v,l.id),onTransformEnd:()=>a(l.id),onContextMenu:v=>{v.evt.preventDefault();let y=v.evt;r(y,l.id,"text");},...d(l.id,"text")}},l.id)})})};var tg=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onNext:s,onPrevious:u,nodeRef:i,touchHandlers:c,currentTool:f})=>{let[d,l]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let b=new window.Image,g=e.images[e.currentIndex];(g.startsWith("http://")||g.startsWith("https://"))&&(b.crossOrigin="anonymous"),b.src=g,b.onload=()=>{l(b);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let m=8,h=2,p=Math.min(e.width,e.height)*.08,v=Math.max(16,Math.min(p,32)),y=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked&&f==="select",x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:n,...c,ref:b=>{if(i(b),b){let g=b.getStage()?.container();if(g){let C=I=>{let B=b.getStage()?.getPointerPosition();if(B){let k={x:e.x,y:e.y,width:e.width,height:e.height};B.x>=k.x&&B.x<=k.x+k.width&&B.y>=k.y&&B.y<=k.y+k.height&&r(I);}};g.addEventListener("contextmenu",C),b._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",C);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:m,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:m,stroke:"#E5E7EB",strokeWidth:h,listening:false}),jsx(Image$1,{x:h+4,y:h+4,image:d,width:e.width-(h+4)*2,height:e.height-(h+4)*2,cornerRadius:m-h,onClick:t,onTap:t}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:y+v,y:e.height/2,onClick:b=>{b.cancelBubble=true,u();},onTap:b=>{b.cancelBubble=true,u();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-y-v,y:e.height/2,onClick:b=>{b.cancelBubble=true,s();},onTap:b=>{b.cancelBubble=true,s();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Du=tg;var Zi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onNext:s,onPrevious:u,onContextMenu:i,onLongPress:c})=>{let{createHandlers:f}=Ve({onLongPress:c}),d=J(l=>l.toolbar.selectedTool);return jsx(Fragment,{children:e.map(l=>jsx(Du,{flashcard:l,isSelected:t===l.id,onClick:()=>r(l.id),currentTool:d,onDragEnd:a,onTransformEnd:m=>n(l.id,m),onContextMenu:m=>i(m,l.id,"flashcard"),onNext:()=>s(l.id),onPrevious:()=>u(l.id),touchHandlers:f(l.id,"flashcard"),nodeRef:m=>{m?o.current.set(l.id,m):o.current.delete(l.id);}},l.id))})});Zi.displayName="FlashcardLayer";var Fu=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null);J(g=>g.toolbar.selectedTool);let i=J(g=>g.toolbar.penColor),c=J(g=>g.toolbar.strokeWidth),f=J(g=>g.canvas.isSketchMode),d=J(g=>g.canvas.slides.find(I=>I.id===g.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),l=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(g=>{if(!m)return;t.current=true,a.current=false,n.current=[{x:g.x,y:g.y}];let C=g.x/h,I=g.y/p;s({tool:"pen",points:[C,I],color:i,strokeWidth:c/h,isSketch:f});},[m,i,c,f,h,p]),y=useCallback(g=>{if(!t.current||!r)return;a.current=true;let C=n.current[n.current.length-1];if(Math.sqrt(Math.pow(g.x-C.x,2)+Math.pow(g.y-C.y,2))<2)return;n.current.push({x:g.x,y:g.y});let B;if(f)B=Xn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,S)=>S%2===0?x/h:x/p);else {let k=g.x/h,x=g.y/p;B=[...r.points,k,x];}s(k=>k?{...k,points:B}:null);},[f,c,r,h,p]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(bi({frameId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:m,startDrawing:v,draw:y,stopDrawing:b}};var dg=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onStartCamera:s,onCapture:u,cameraStream:i,nodeRef:c,touchHandlers:f})=>{let[d,l]=useState(null),[m,h]=useState(null),p=useRef(null),v=useRef(null),y=useRef(null),b=useRef(null),g=useRef(0),C=33,I=useSelector(P=>P.toolbar.selectedTool),B=I==="pen"||I==="eraser",{annotations:k,activeLine:x,isDrawingMode:S,startDrawing:w,draw:T,stopDrawing:q}=Fu(e.id);useEffect(()=>{if(!S)return;let P=()=>{q();},N=()=>{q();};return window.addEventListener("mouseup",P),window.addEventListener("touchend",N),()=>{window.removeEventListener("mouseup",P),window.removeEventListener("touchend",N);}},[q,S]),useEffect(()=>{if(e.capturedImageUrl){let P=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(P.crossOrigin="anonymous"),P.src=e.capturedImageUrl,P.onload=()=>{l(P);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),v.current||(v.current=document.createElement("canvas"));let P=p.current,N=v.current;P.srcObject=i;let _=()=>{N.width=P.videoWidth||640,N.height=P.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",N.width,N.height);let Q=re=>{if(re-g.current<C){y.current=requestAnimationFrame(Q);return}g.current=re;let j=N.getContext("2d");if(j&&P.readyState===P.HAVE_ENOUGH_DATA){j.drawImage(P,0,0,N.width,N.height);let pe=N.toDataURL("image/jpeg",.6),ge=new window.Image;ge.onload=()=>{h(ge);},ge.src=pe;}y.current=requestAnimationFrame(Q);};y.current=requestAnimationFrame(Q);};return P.onloadedmetadata=_,P.readyState>=P.HAVE_METADATA&&_(),P.play().catch(Q=>console.error("Error playing video:",Q)),()=>{y.current&&(cancelAnimationFrame(y.current),y.current=null);}}return ()=>{h(null),b.current&&(b.current.src="");}},[e.isCapturing,i]);let H=()=>{p.current&&e.isCapturing&&u(p.current);},F=P=>{if(e.capturedImageUrl){if(!S){t();return}let N=P.currentTarget,_=N.getAbsoluteTransform().copy(),re=N.getStage()?.getPointerPosition();if(re){_.invert();let j=_.point(re);w(j);}P.cancelBubble=true;}else t();},V=P=>{if(!S||!e.capturedImageUrl)return;let N=P.currentTarget,_=N.getAbsoluteTransform().copy(),re=N.getStage()?.getPointerPosition();if(re){_.invert();let j=_.point(re);T(j);}},U=()=>{!S||!e.capturedImageUrl||q();},K=e.isCapturing?m:d,R=Math.min(e.width,e.height)*.12,z=Math.max(25,Math.min(R,50)),ne=e.width/2,X=e.height/2;return jsxs(Group,{id:e.id,draggable:!S&&!B,listening:true,onClick:t,onTap:t,x:e.x,y:e.y,...f,...B?{}:{onDragEnd:a,onTransformEnd:n},rotation:e.rotation,width:e.width,height:e.height,ref:P=>{if(c(P),P){let N=P.getStage()?.container();if(N){let _=Q=>{let re=P.getStage()?.getPointerPosition();if(re){let j={x:e.x,y:e.y,width:e.width,height:e.height};re.x>=j.x&&re.x<=j.x+j.width&&re.y>=j.y&&re.y<=j.y+j.height&&r(Q);}};N.addEventListener("contextmenu",_),P._contextMenuCleanup=()=>{N.removeEventListener("contextmenu",_);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:K?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),K&&jsx(Image$1,{image:K,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:F,onTap:F,onMouseDown:F,onTouchStart:F,onMouseMove:V,onTouchMove:V,onMouseUp:U,onTouchEnd:U,...B?{}:{onDragEnd:a,onTransformEnd:n}}),k?.map((P,N)=>{let _=P.points.map((re,j)=>j%2===0?re*e.width:re*e.height),Q=P.strokeWidth*e.width;return jsx(Line,{points:_,stroke:P.tool==="eraser"?"white":P.color,strokeWidth:Q,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:P.tool==="eraser"?"destination-out":"source-over",fill:P.isSketch?P.color:void 0,closed:P.isSketch,listening:false},N)}),x&&jsx(Line,{points:x.points.map((P,N)=>N%2===0?P*e.width:P*e.height),stroke:x.tool==="eraser"?"white":x.color,strokeWidth:x.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},"active"),!K&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:X-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:ne-z+6,y:X-60,width:z*1.6,height:z*1.6,radius:z,fill:"white",cornerRadius:8,listening:true,onClick:P=>{P.cancelBubble=true,e.isCapturing?H():s();},onTap:P=>{P.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:ne-12,y:X-40,width:z*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:P=>{P.stopPropagation(),e.isCapturing?H():s();}})})]}),jsx(Text,{x:0,y:X,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:X+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:ne-24,y:X+104,width:z*1.6,height:z*1.6,radius:z,fill:"#096B76",cornerRadius:z,listening:true,onClick:P=>{P.cancelBubble=true,e.isCapturing?H():s();},onTap:P=>{P.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:ne-8,y:X+120,width:z*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:P=>{P.stopPropagation(),e.isCapturing?H():s();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:ne-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:P=>{P.stopPropagation(),H();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},Hu=dg;var ol=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onStartCamera:s,onCapture:u,cameraStreams:i,onContextMenu:c,onLongPress:f})=>{let{createHandlers:d}=Ve({onLongPress:f});return jsx(Fragment,{children:e.map(l=>jsx(Hu,{photoFrame:l,isSelected:t===l.id,onClick:()=>r(l.id),onDragEnd:m=>a(m,l.id),onContextMenu:m=>c(m,l.id,"photoFrame"),onStartCamera:()=>s(l.id),onCapture:m=>u(l.id,m),cameraStream:i.get(l.id),touchHandlers:d(l.id,"photoFrame"),nodeRef:m=>{m?o.current.set(l.id,m):o.current.delete(l.id);}},l.id))})});ol.displayName="PhotoFrameLayer";var Wu=({x:e,y:o,onAction:t,onClose:a,type:n,isDrawingMode:r,menuRef:s})=>{useEffect(()=>{let f=l=>{s?.current&&!s.current.contains(l.target)&&a();},d=l=>{l.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",d);}},[a]);let u=useMemo(()=>[{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"border",label:"Toggle Border",icon:jsx(FrameCorners,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"draw",label:r?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line","video"]},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(d=>!(d.showForTypes&&!d.showForTypes.includes(n)||d.hideForTypes&&d.hideForTypes.includes(n))),[n,r]),i=(f,d)=>{f==="order"||f==="lock"?t(f,d):(t(f),a());},c=jsx("div",{ref:s,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:u.map((f,d)=>jsxs("button",{onClick:l=>i(f.action,l),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${f.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[f.icon,jsx("span",{className:`font-medium ${f.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:f.label})]}),f.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},d))})});return createPortal(c,document.body)};var Uu=({x:e,y:o,items:t,onClose:a})=>{let n=useRef(null);return useEffect(()=>{let r=s=>{n.current&&!n.current.contains(s.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:n,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((r,s)=>jsx("button",{onClick:()=>{r.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:r.label})},s))})})};var Gu=createContext(null),rl=()=>useContext(Gu);function Pg({children:e,className:o="",style:t}){let a=useRef(null),[n,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Gu.Provider,{value:n,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function ze(){let e=rl();return typeof document>"u"?null:e||document.body}var ju=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:n,onClose:r})=>{let[s,u]=useState(a),i=useRef(null),c=ze();useEffect(()=>{i.current?.focus();},[]);let f=()=>{n(s),r();},d=m=>{m.key==="Enter"?f():m.key==="Escape"&&r();};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:i,type:"text",value:s,onChange:m=>u(m.target.value),onKeyDown:d,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:r,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:f,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),c):null};var es=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,n]=useState(e),r=useRef(null),s=ze();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let u=d=>{d.preventDefault(),o(a);},i=(d,l,m)=>{m/=100;let h=l*Math.min(m,1-m)/100,p=v=>{let y=(v+d/30)%12,b=m-h*Math.max(Math.min(y-3,9-y,1),-1);return Math.round(255*b).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!s)return null;let f=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:r,className:"max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:u,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:d=>n(d.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:d=>n(d.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:d=>{let l=parseInt(d.target.value),m=i(l,100,50);n(m);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(d=>jsx("button",{type:"button",onClick:()=>n(d),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===d.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:d},title:d},d))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(f,s)};var Xg=({imageSrc:e,onCrop:o})=>{let[t]=Xu(e),a=useRef(null),n=useRef(null),r=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),u=useMemo(()=>{let l=s.width*.5,m=s.height*.5,h=(s.width-l)/2,p=(s.height-m)/2;return {x:h,y:p,width:l,height:m}},[s]),[i,c]=useState(u);useEffect(()=>{c(u);},[u]),useEffect(()=>{r.current&&n.current&&(r.current.nodes([n.current]),r.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let f=()=>{let l=n.current;if(!l)return;let m=l.scaleX(),h=l.scaleY();l.scaleX(1),l.scaleY(1),c({x:l.x(),y:l.y(),width:Math.max(20,l.width()*m),height:Math.max(20,l.height()*h)});},d=()=>{let l=n.current;l&&c({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:s.width,height:s.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:s.width,height:s.height}),jsx(Rect,{x:0,y:0,width:s.width,height:s.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:n,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:f,dragBoundFunc:l=>{let m=Math.max(0,Math.min(l.x,s.width-i.width)),h=Math.max(0,Math.min(l.y,s.height-i.height));return {x:m,y:h}}}),jsx(Transformer,{ref:r,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(l,m)=>m.width<20||m.height<20||m.x<0||m.y<0||m.x+m.width>s.width||m.y+m.height>s.height?l:m})]})})},Yu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[n,r]=useState({x:0,y:0,width:0,height:0}),[s]=Xu(e),u=ze();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let i=(d,l,m,h)=>{r({x:d,y:l,width:m,height:h});},c=()=>{if(!s)return;let m=Math.min(600/s.width,400/s.height),h=n.x/m,p=n.y/m,v=n.width/m,y=n.height/m,b=document.createElement("canvas");b.width=v,b.height=y;let g=b.getContext("2d");if(!g)return;g.drawImage(s,h,p,v,y,0,0,v,y);let C=b.toDataURL("image/png");o(C);};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(Xg,{imageSrc:e,onCrop:i})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:c,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),u):null};var eo=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let n=ze(),[r,s]=useState(false),[u,i]=useState(null),[c,f]=useState(0),[d,l]=useState(true),m=useRef(null),h=useRef([]),p=useRef(null),v=useRef(null),y=useRef(null),b=useRef(null),g=useRef(null),C=useRef(null);useEffect(()=>()=>{y.current&&cancelAnimationFrame(y.current),p.current&&clearInterval(p.current),v.current&&v.current.getTracks().forEach(w=>w.stop());},[]);let I=async()=>{try{let w,T=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let U=o.current.getLayers();console.log("Konva layers:",U.length),U.forEach((_,Q)=>{let re=_.getChildren();console.log(`Layer ${Q} children count:`,re.length);});let K=document.createElement("canvas");K.width=o.current.width(),K.height=o.current.height();let R=K.getContext("2d",{willReadFrequently:!1});if(!R){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",K.width,"x",K.height),g.current=K;let z=()=>{if(R.clearRect(0,0,K.width,K.height),U.forEach(_=>{let Q=_.getCanvas()._canvas;Q&&R.drawImage(Q,0,0);}),a?.current){let _=a.current;R.drawImage(_,0,0);}};C.current=z,o.current.draw(),z(),await new Promise(_=>setTimeout(_,100)),console.log("Creating captureStream..."),w=K.captureStream(30),console.log("Canvas stream created, tracks:",w.getTracks().length);let X=w.getVideoTracks()[0];X&&console.log("Video track:",X.label,"state:",X.readyState);let P=0,N=()=>{z(),o?.current&&(o.current.getLayers().forEach(Q=>{Q.batchDraw();}),P++,P%60===0&&console.log("Drawing frame:",P)),y.current=requestAnimationFrame(N);};N();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{T=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let q=[...w.getVideoTracks()];T&&q.push(...T.getAudioTracks());let H=new MediaStream(q);v.current=H;let F="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?F="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?F="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?F="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(F="video/webm;codecs=vp8"),console.log("Using mimeType:",F);let V=new MediaRecorder(H,{mimeType:F,videoBitsPerSecond:25e5});m.current=V,h.current=[],V.ondataavailable=U=>{console.log("Data available, size:",U.data.size),U.data.size>0&&h.current.push(U.data);},V.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let U=new Blob(h.current,{type:F});console.log("Final blob size:",U.size),o?.current&&C.current&&g.current&&(o.current.draw(),o.current.getLayers().forEach(R=>{R.batchDraw();}),C.current(),b.current=g.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",b.current.length)),H.getTracks().forEach(K=>K.stop()),p.current&&clearInterval(p.current),y.current&&(cancelAnimationFrame(y.current),y.current=null),i(U);},V.onerror=U=>{console.error("MediaRecorder error:",U);},console.log("Starting recording..."),V.start(1e3),s(!0),f(0),p.current=setInterval(()=>{f(U=>U+1);},1e3);}catch(w){console.error("Error starting screen recording:",w),alert("Failed to start recording. Please ensure you granted permission.");}},B=()=>{m.current&&r&&(console.log("Stopping recording, state:",m.current.state),m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),s(false));},k=()=>{if(u){let w=URL.createObjectURL(u),T=document.createElement("a");T.href=w,T.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(w);}},x=w=>{let T=Math.floor(w/60),q=w%60;return `${T.toString().padStart(2,"0")}:${q.toString().padStart(2,"0")}`};if(!n)return null;if(r){let w=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:x(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:B,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(w,n)}let S=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!u&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>l(!d),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${d?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:d?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:I,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),u&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(u),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",x(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&b.current&&(t(u,b.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:k,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),f(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})});return createPortal(S,n)};var ec=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:n})=>{let r=ze(),[s,u]=useState(false),[i,c]=useState(null),[f,d]=useState(false),[l,m]=useState(0),h=useRef(null),p=useRef([]),v=useRef(null),y=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(w=>w.blob()).then(w=>c(w)).catch(w=>console.error("Error loading audio:",w));},[o,i]);let b=async()=>{try{let w=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),T=new MediaRecorder(w);h.current=T,p.current=[],T.ondataavailable=q=>{q.data.size>0&&p.current.push(q.data);},T.onstop=()=>{let q=new Blob(p.current,{type:"audio/webm"});c(q),w.getTracks().forEach(H=>H.stop()),v.current&&clearInterval(v.current);},T.start(),u(!0),m(0),v.current=setInterval(()=>{m(q=>q+1);},1e3);}catch(w){console.error("Error starting audio recording:",w),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{h.current&&s&&(h.current.stop(),u(false));},C=()=>{if(i){let w=URL.createObjectURL(i),T=new Audio(w);y.current=T,T.onended=()=>{d(false),URL.revokeObjectURL(w);},T.play(),d(true);}},I=()=>{y.current&&(y.current.pause(),y.current.currentTime=0,d(false));},B=async()=>{if(i){let w=new FileReader;w.onloadend=()=>{let T=w.result;t(T),n();},w.readAsDataURL(i);}},k=()=>{c(null),a();},x=w=>{let T=Math.floor(w/60),q=w%60;return `${T.toString().padStart(2,"0")}:${q.toString().padStart(2,"0")}`};if(!r)return null;if(s){let w=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:x(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:g,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(w,r)}let S=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:b,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:f?I:C,className:"flex w-full cursor-pointer items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),f?"Playing...":"Play Audio"]}),jsxs("button",{onClick:k,className:"flex w-full cursor-pointer items-center gap-2 rounded-lg border border-red-300 bg-red-600 px-4 py-3 text-white transition-colors hover:bg-red-700",children:[jsx(Trash,{className:"h-5 w-5",weight:"fill"}),"Delete Audio"]})]}),jsx("button",{onClick:B,className:"w-full cursor-pointer rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:n,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})});return createPortal(S,r)};var Nt=({audioData:e,x:o,y:t,width:a,scale:n=1,offsetX:r=0,offsetY:s=0,containerTop:u=90,containerRight:i=320})=>{let[c,f]=useState(false),d=useRef(null),l=p=>{if(p.stopPropagation(),c&&d.current)d.current.pause(),d.current.currentTime=0,f(false);else {let v=new Audio(e);d.current=v,v.onended=()=>{f(false);},v.onerror=()=>{console.error("Error playing audio"),f(false);},v.play(),f(true);}},m=(o+a)*n+r-15,h=t*n+s+u-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${c?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${m}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var oc=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=Se(),n=J(ve),r=ze(),s=useMemo(()=>{if(!n)return [];let y=[];return n.images?.forEach(b=>{y.push({id:b.id,type:"image",name:"Image",timestamp:b.timestamp||0});}),n.videos?.forEach(b=>{y.push({id:b.id,type:"video",name:"Video",timestamp:b.timestamp||0});}),n.shapes?.forEach(b=>{y.push({id:b.id,type:"shape",name:`${b.type} Shape`,timestamp:b.timestamp||0});}),n.texts?.forEach(b=>{y.push({id:b.id,type:"text",name:b.text.substring(0,20)+(b.text.length>20?"...":""),timestamp:b.timestamp||0});}),n.flashcards?.forEach(b=>{y.push({id:b.id,type:"flashcard",name:`Flashcard (${b.images.length} images)`,timestamp:b.timestamp||0});}),n.photoFrames?.forEach(b=>{y.push({id:b.id,type:"photoFrame",name:"Photo Frame",timestamp:b.timestamp||0});}),n.multipleChoices?.forEach(b=>{y.push({id:b.id,type:"mcq",name:"Multiple Choice",timestamp:b.timestamp||0});}),n.trueFalses?.forEach(b=>{y.push({id:b.id,type:"trueFalse",name:"True/False",timestamp:b.timestamp||0});}),n.shortAnswers?.forEach(b=>{y.push({id:b.id,type:"shortAnswer",name:"Short Answer",timestamp:b.timestamp||0});}),n.LongAnswer?.forEach(b=>{y.push({id:b.id,type:"longAnswer",name:"Long Answer",timestamp:b.timestamp||0});}),n.fillInTheBlanks?.forEach(b=>{y.push({id:b.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:b.timestamp||0});}),n.lines?.forEach(b=>{b.id&&y.push({id:b.id,type:"line",name:"Drawn Line",timestamp:b.timestamp||0});}),y.sort((b,g)=>g.timestamp-b.timestamp)},[n]),[u,i]=useState(s),[c,f]=useState(false);useEffect(()=>{c||i(s);},[s]);let d=y=>{let b="h-5 w-5";switch(y){case "image":return jsx(Image$3,{className:b});case "video":return jsx(VideoCamera,{className:b});case "shape":return jsx(Shapes$1,{className:b});case "text":return jsx(TextT,{className:b});case "flashcard":return jsx(Cards$1,{className:b});case "photoFrame":return jsx(FrameCorners$1,{className:b});case "line":return jsx(Pen,{className:b});default:return jsx(Question,{className:b})}},h=y=>{f(true),i(y);},p=()=>{f(false);let y=Date.now();u.forEach((b,g)=>{let C=y-g;a(xr({id:b.id,type:b.type,newTimestamp:C}));});};if(!r)return null;let v=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-50 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-50 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:u.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:u,onReorder:h,className:"space-y-1",children:u.map(y=>{let b=y.id===e;return jsxs(Reorder.Item,{value:y,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${b?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(y.id,y.type),className:`font-medium ${b?"text-[#096B76]":"text-[#00000099]"}`,children:y.name})}),jsx("div",{className:`${b?"text-[#096B76]":"text-[#00000099]"}`,children:d(y.type)})]},y.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[u.length," Layers"]})]})]})]});return createPortal(v,r)};var ss=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},rc=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,touchHandlers:s,onUpdate:u})=>{let i=useSelector(F=>F.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(null),l=e.data.responseOptions.attempts||0,m=useRef(null),h=useDispatch(),[p,v]=useState(new Set(e.data.responseOptions.selectedIndices||[])),[y,b]=useState(false);useEffect(()=>{let F=m.current;if(F)return a.current.set(e.id,F),()=>{a.current.delete(e.id);}},[e.id,a]);let g=new Set(e.data.responseOptions.correctIndex),C=g.size>1,I=F=>{if(y)return;let V;C?(V=new Set(p),V.has(F)?V.delete(F):V.add(F)):V=new Set([F]),v(V);let U=Array.from(V),K=U.length===e.data.responseOptions.correctIndex.length&&U.every(R=>e.data.responseOptions.correctIndex.includes(R));h(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:U,isCorrect:K}}})),u?.();},B=()=>{p.size>0&&(b(true),h(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},k=()=>{b(false),v(new Set);},x=p.size===g.size&&Array.from(p).every(F=>g.has(F)),S=Array.from(p).filter(F=>g.has(F)),w=C&&S.length>0&&!x,T=()=>x?"\u2713 Correct! Great job! \u{1F389}":w?`\u26A0 Partially correct (${S.length}/${g.size})`:"\u2717 Try again!",q=()=>x?{bg:"#dcfce7",text:"#166534"}:w?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},H=useMemo(()=>{let X=e.data.feedbackMode==="practice"?48:0,P=12,N=e.width-48,_=N-80,Q=Math.max(60,ss(e.data.question,20,N,"bold")+20),re=`Select ${g.size} answers (${p.size}/${g.size} selected)`,j=C&&!y&&e.data.feedbackMode==="practice"?ss(re,14,N)+10:0,pe=y&&e.data.feedbackMode==="practice"?Math.max(60,ss(T(),16,N-40)+30):0,ge=e.data.responseOptions.options.map(xe=>{let St=ss(xe,16,_);return Math.max(55,St+20)}),le=Q+j+pe,ye=ge.reduce((xe,St)=>xe+St+8,-8),we=le+ye+P+X+24;return {padding:24,questionHeight:Q,instructionHeight:j,feedbackHeight:pe,optionsStartY:le,optionHeights:ge,totalHeight:we,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:X,buttonTopMargin:P,availableWidth:N,optionTextWidth:_}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,y,p.size,g.size,C,T]);return jsxs(Group,{ref:m,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:H.totalHeight,onTransformEnd:F=>o(e.id,F),...s,...c?{}:{onDragEnd:n,onClick:F=>t&&t(e.id),onTap:F=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:H.totalHeight,width:e.width,onContextMenu:F=>{F.cancelBubble=true,r(F.evt,e.id,"mcq");}}),jsx(Text,{x:H.padding+8,y:H.padding,text:e.data.question,fontSize:H.questionFontSize,fontStyle:"bold",fill:"#111827",width:H.availableWidth,height:H.questionHeight-H.padding,wrap:"word",ellipsis:true,listening:false}),H.instructionHeight>0&&jsx(Text,{x:H.padding,y:H.questionHeight,text:`Select ${g.size} answers (${p.size}/${g.size} selected)`,fontSize:H.instructionFontSize,fill:"#6b7280",width:H.availableWidth,wrap:"word",listening:false}),y&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:H.padding+24,y:H.questionHeight+H.instructionHeight+10,width:H.availableWidth-40,height:H.feedbackHeight-20,fill:q().bg,cornerRadius:8}),jsx(Text,{x:H.padding+24,y:H.questionHeight+H.instructionHeight+10,width:H.availableWidth-40,height:H.feedbackHeight-20,text:T()+` (${l} attempts)`,fontSize:H.feedbackFontSize,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((F,V)=>{let U=g.has(V),K=p.has(V),R=H.optionsStartY;for(let N=0;N<V;N++)R+=H.optionHeights[N]+H.optionGap;let z=H.optionHeights[V],ne="#e5e7eb",X="#ffffff",P="#111827";return y&&K&&!U?(ne="#ef4444",X="#fee2e2",P="#ef4444"):K&&(ne="#096B76",X="#ECFFF8",P="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:H.padding+12,y:R+(z-20)/2,width:20,height:20,fill:K?"#096B76":"white",stroke:K?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:C?4:10,onClick:N=>{N.cancelBubble=true,I(V);},onTap:N=>{N.cancelBubble=true,I(V);}}),K&&jsx(Text,{x:H.padding+12,y:R+(z-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:H.padding+44,y:R,width:H.availableWidth-60,height:z,fill:X,stroke:ne,strokeWidth:2,cornerRadius:8,onClick:N=>{N.cancelBubble=true,I(V);},onTap:N=>{N.cancelBubble=true,I(V);}}),jsx(Text,{x:H.padding+60,y:R+10,width:H.optionTextWidth,height:z-20,text:F,fontSize:H.optionFontSize,fill:P,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},V)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:H.optionsStartY+H.optionHeights.reduce((F,V)=>F+V+H.optionGap,-H.optionGap)+H.buttonTopMargin,children:[jsxs(Group,{onMouseDown:F=>{F.cancelBubble=true,d("check");},onMouseUp:F=>{F.cancelBubble=true,d(null),B();},onMouseLeave:F=>{F.cancelBubble=true,d(null);},onTouchStart:F=>{F.cancelBubble=true,d("check");},onTouchEnd:F=>{F.cancelBubble=true,d(null),B();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:H.padding+14,width:(H.availableWidth-24)/(y?2:1),height:H.buttonHeight,fill:p.size===0||y?"#9ca3af":"#096B76",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:H.padding+14,width:(H.availableWidth-24)/(y?2:1),height:H.buttonHeight,text:y?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),y&&jsxs(Group,{x:(e.width-H.padding*2)/2+8,onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),k();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),k();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:H.padding,width:(H.availableWidth-8)/2,height:H.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:H.padding,width:(H.availableWidth-8)/2,height:H.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});rc.displayName="MultipleChoice";var nc=rc;var Vx=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},dl=({multipleChoice:e,onContextMenu:o,handleSelect:t,mcqRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(R=>R.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,f]=useState(false),d=e.data.responseOptions.selectedIndices??[],l=useMemo(()=>new Set(d),[d]),m=e.data.responseOptions.attempts??0,h=m>0,[p,v]=useState(false),[y,b]=useState(0),g=new Set(e.data.responseOptions.correctIndex),C=Array.from(l).filter(R=>g.has(R)),I=l.size===g.size&&Array.from(l).every(R=>g.has(R)),B=C.length>0&&!I,k=()=>I?"\u2713 Correct! Great job!":B?`\u26A0 Partially correct (${C.length}/${g.size})`:"\u2717 Try again!",x=useCallback(R=>{let z=R.target;s(yi({id:e.id,dragDropPos:{x:z.x(),y:z.y()}})),r?.();},[s,e.id,r]),S=useMemo(()=>{let z=Math.max(window.innerWidth*.3,500),ne=20,X=18,P=28,N=40,_=50,Q=20,re=60,j=Math.max(z-40,400),pe=Math.max(60,Vx(e.data.question,ne,j,"bold")),ge=Math.max(z-Q*2,400),le=Math.max(150,window.innerHeight*.2),ye=e.data.feedbackMode==="practice",we=pe+20+le+(h?re+18:0)+(ye?N+(h?_:0)+20:0),xe=we+100;return {screenWidth:z,screenHeight:xe,dropZoneWidth:ge,dropZoneHeight:le,questionFontSize:ne,questionHeight:pe,feedbackFontSize:X,feedbackHeight:re,dropHereFontSize:P,buttonHeight:N,buttonGap:_,padding:Q,contentWidth:j,totalContentHeight:we,isPracticeMode:ye}},[e.data.question,e.data.feedbackMode,h]),w=useRef(null);useEffect(()=>{let R=w.current;if(R)return a.current.set(e.id,R),()=>{a.current.delete(e.id);}},[e.id,a]);let T=R=>{s(yi({id:e.id,dragDropPos:{x:R.target.x(),y:R.target.y()}})),r?.();},q=R=>{let z=R.target,ne=z.x(),X=z.y(),P=window.innerWidth*.2,N=50,_=S.padding,Q=S.padding+S.dropZoneWidth,re=S.questionHeight+20,j=S.questionHeight+20+S.dropZoneHeight,pe=ne+P>_&&ne<Q&&X+N>re&&X<j;f(pe),r?.();},H=(R,z)=>{let ne=z.target,X=ne.x(),P=ne.y(),N=window.innerWidth*.2,_=50;s(gt({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[R]:{x:X,y:P}}}));let Q=S.padding,re=S.padding+S.dropZoneWidth,j=S.questionHeight+20,pe=S.questionHeight+20+S.dropZoneHeight,ge=X+N>Q&&X<re&&P+_>j&&P<pe,le;ge?le=new Set(l).add(R):(le=new Set(l),le.delete(R)),f(false);let ye=Array.from(le),we=ye.length===g.size&&ye.every(xe=>g.has(xe));s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:ye,isCorrect:we}}})),r?.();},F=()=>{s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},V=()=>{s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),f(false),b(R=>R+1),r?.();},U=()=>I?{bg:"#dcfce7",text:"#166534"}:B?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},K=()=>h?I?"#4CAF50":B?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:w,x:e.dragDropPos?.x,y:e.dragDropPos?.y,name:"mcq-element",width:S.screenWidth,height:S.screenHeight,draggable:!i,listening:!i,onDragMove:x,...n,...i?{}:{onClick:R=>t&&t(e.id),onTap:R=>t&&t(e.id),onContextMenu:R=>{R.evt.preventDefault(),o(R.evt,e.id,"mcq");}},children:[jsxs(Group,{rotation:e.rotation,onDragEnd:T,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:S.totalContentHeight+20,width:S.screenWidth,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:S.padding,y:S.padding,width:S.contentWidth,height:S.questionHeight-S.padding,text:e.data.question,fontSize:S.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:S.padding,y:S.questionHeight+20,width:S.dropZoneWidth,height:S.dropZoneHeight,fill:"#EBF6F7",stroke:K(),strokeWidth:3,dash:[10,10],cornerRadius:8}),h&&jsxs(Fragment,{children:[jsx(Rect,{x:S.padding+3,y:S.questionHeight+20+S.dropZoneHeight+18,width:S.dropZoneWidth-5,height:S.feedbackHeight,fill:U().bg,cornerRadius:8}),jsx(Text,{x:S.padding,y:S.questionHeight+20+S.dropZoneHeight+20,width:S.dropZoneWidth,height:S.feedbackHeight,text:k()+` (${m} attempts)`,fontSize:S.feedbackFontSize,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),l.size===0&&!h&&jsx(Text,{x:S.padding,y:S.questionHeight+20,width:S.dropZoneWidth,height:S.dropZoneHeight,text:g.size>1?`Drop ${g.size} Correct Answers Here`:"Drop Here",fontSize:S.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),S.isPracticeMode?jsxs(Group,{x:S.padding,y:S.questionHeight+20+S.dropZoneHeight+(h?S.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,!(h||l.size===0)&&(v(true),F());},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),F();},onTouchEnd:()=>v(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:h||l.size===0?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:S.buttonHeight,width:S.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:h||l.size===0?"#9ca3af":"white",width:S.dropZoneWidth,height:S.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),h&&jsxs(Group,{y:S.buttonGap,onMouseDown:V,onTouchStart:V,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:S.buttonHeight,width:S.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:S.dropZoneWidth,height:S.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((R,z)=>{let ne=z%2,X=Math.floor(z/2),P=S.dropZoneWidth/2+25,N=50,_=10,Q=l.has(z),re=g.has(z),j=h&&Q,pe="transparent";j?pe=re?"#4CAF50":"#ef4444":Q&&(pe="#4CAF50");let ge=h&&!Q?0:1,le=e.optionDragDropPos?.[z],ye=le?.x??ne*(P+_),we=le?.y??S.totalContentHeight+30+X*(N+_);return jsxs(Group,{x:ye,y:we,draggable:!h,onDragStart:xe=>{xe.cancelBubble=true;},onDragMove:xe=>{xe.cancelBubble=true,q(xe);},onDragEnd:xe=>{xe.cancelBubble=true,H(z,xe);},opacity:ge,children:[jsx(Rect,{width:P-20,height:N,fill:"white",stroke:pe,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:P-20,height:N,text:R,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${z}-${y}`)})]})};dl.displayName="MultipleChoiceDragAndDrop";var ic=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(nc,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:f=>n(f,c.id),onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id):jsx(dl,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id))})};var lc=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},dc=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s,onUpdate:u})=>{let i=useSelector(T=>T.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(false),l=e.data.responseOptions.attempts||0,[m,h]=useState(null),p=useDispatch(),[v,y]=useState(e.data.responseOptions.selectedResponse??null),b=useRef(null);useEffect(()=>{let T=b.current;if(T)return a.current.set(e.id,T),()=>{a.current.delete(e.id);}},[e.id]);let g=()=>{v!==null&&d(true),p(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},C=()=>{d(false),y(null);},I=e.data.responseOptions.correctAnswer,B=v===I,k=T=>{if(f)return;y(T);let q=T===e.data.responseOptions.correctAnswer;p(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:T,isCorrect:q}}})),u?.();},x=()=>B?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",S=()=>B?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},w=useMemo(()=>{let K=e.data.feedbackMode==="practice"?48:0,R=12,z=e.width-48,ne=Math.max(60,lc(e.data.question,20,z,"bold")+20),X=f&&e.data.feedbackMode==="practice"?Math.max(60,lc(x(),16,z-40)+30):0,P=ne+X,N=164,_=P+N+R+K+24;return {padding:24,questionHeight:ne,feedbackHeight:X,optionsStartY:P,optionsHeight:N,totalHeight:_,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:K,buttonTopMargin:R,availableWidth:z}},[e.width,e.data.question,e.data.feedbackMode,f,x]);return jsxs(Group,{ref:b,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:w.totalHeight,...s,...c?{}:{onDragEnd:T=>r(T,e.id),onClick:T=>t&&t(e.id),onTap:T=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:w.totalHeight,width:e.width,onTransformEnd:T=>o(e.id,T),onContextMenu:T=>{T.cancelBubble=true,n(T.evt,e.id,"trueFalse");}}),jsx(Text,{x:w.padding+8,y:w.padding,text:e.data.question,fontSize:w.questionFontSize,fontStyle:"bold",fill:"#111827",width:w.availableWidth,height:w.questionHeight-w.padding,wrap:"word",ellipsis:true,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:w.padding+24,y:w.questionHeight+10,width:w.availableWidth-40,height:w.feedbackHeight-20,fill:S().bg,cornerRadius:8}),jsx(Text,{x:w.padding+24,y:w.questionHeight+10,width:w.availableWidth-40,height:w.feedbackHeight-20,text:x()+` (${l} attempts)`,fontSize:w.feedbackFontSize,fontStyle:"bold",fill:S().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((T,q)=>{let H=I===T.value,F=v===T.value,V=(e.width-w.padding*3)/2,U=w.padding+q*(V+w.padding),K=w.optionsStartY,R=T.value===true,z=R?"#10b981":"#ef4444",ne="#ffffff",X="#ffffff",P="#e5e7eb";return f&&F&&(H?(X=R?"#f0fdf4":"#fef2f2",P=R?"#86efac":"#fecaca"):(X="#fee2e2",P="#ef4444")),F&&!f&&(P="#096B76",X="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:U,y:K,width:V,height:w.optionHeight+50,fill:X,stroke:P,strokeWidth:2,cornerRadius:12,onClick:N=>{N.cancelBubble=true,k(T.value);},onTap:N=>{N.cancelBubble=true,k(T.value);}}),jsx(Circle,{x:U+V/2,y:K+40,radius:28,fill:z,listening:false}),R?jsx(Text,{x:U+V/2-14,y:K+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:ne,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:U+V/2-14,y:K+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:ne,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:U,y:K+85,width:V,height:30,text:T.label,fontSize:w.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},T.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:w.optionsStartY+2*(w.optionHeight+w.optionGap)+w.buttonTopMargin,children:[jsxs(Group,{onMouseDown:T=>{T.cancelBubble=true,h("check");},onMouseUp:T=>{T.cancelBubble=true,h(null),g();},onMouseLeave:T=>{T.cancelBubble=true,h(null);},onTouchStart:T=>{T.cancelBubble=true,h("check");},onTouchEnd:T=>{T.cancelBubble=true,h(null),g();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:w.padding+14,width:(w.availableWidth-24)/(f?2:1),height:w.buttonHeight,fill:v===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:w.padding+14,width:(w.availableWidth-24)/(f?2:1),height:w.buttonHeight,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-w.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),C();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),C();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:w.padding,width:(w.availableWidth-8)/2,height:w.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:w.padding,width:(w.availableWidth-8)/2,height:w.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});dc.displayName="TrueFalse";var uc=dc;var ab="#FFFFFF",ml=({trueFalse:e,onContextMenu:o,handleSelect:t,trueFalseRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(P=>P.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,f]=useState(false),d=e.data.responseOptions.selectedResponse??null,l=(e.data.responseOptions.attempts??0)>0,[m,h]=useState(false),[p,v]=useState(0),y=e.data.responseOptions.attempts||0,b=340,g=100,C=Math.max(window.innerWidth*.3,400),I=window.innerHeight*.5,B=useRef(null);useEffect(()=>{let P=B.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id]);let x=Math.max(60,((P,N,_,Q)=>{let j=document.createElement("canvas").getContext("2d");if(!j)return N;j.font=`${Q} ${N}px Arial, sans-serif`;let pe=P.split(" "),ge=[],le="";return pe.forEach(ye=>{let we=le?`${le} ${ye}`:ye;j.measureText(we).width>_&&le!==""?(ge.push(le),le=ye):le=we;}),le&&ge.push(le),ge.length*N*1.2})(e.data.question,20,C-40,"bold")+20),S=x+10,w=C-40,T=I-x-250,q=useCallback(P=>{let N=P.target;s(ot({id:e.id,dragDropPos:{x:N.x(),y:N.y()}})),r?.();},[s,e.id,r]),H=P=>{s(ot({id:e.id,dragDropPos:{x:P.target.x(),y:P.target.y()}})),r?.();},F=P=>{let N=P.target,_=N.x(),Q=N.y(),re=window.innerWidth*.2-40,j=50,pe=20,ge=20+w,le=S,ye=S+T,we=_+re>pe&&_<ge&&Q+j>le&&Q<ye;f(we),r?.();},V=(P,N)=>{let _=P?"true":"false",Q=N.target;s(ot({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[_]:{x:Q.x(),y:Q.y()}}}));let re=Q.x(),j=Q.y(),pe=window.innerWidth*.2-40,ge=50,le=20,ye=20+w,we=S,xe=S+T;if(!(re+pe>le&&re<ye&&j+ge>we&&j<xe)){f(false);return}f(false);let ae=P===e.data.responseOptions.correctAnswer;s(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:P,isCorrect:ae}}}));},U=()=>{s(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},K=()=>{s(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),f(false),v(P=>P+1),r?.();},R=e.data.responseOptions.correctAnswer,z=d===R,ne=()=>z?"\u2713 Correct! Great job!":"\u2717 Try again!",X=()=>z?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:B,name:"trueFalse-element",width:C,height:I,x:e.dragDropPos?.x,y:e.dragDropPos?.y,draggable:!i,listening:!i,onDragMove:q,...n,...i?{}:{onClick:P=>t&&t(e.id),onTap:P=>t&&t(e.id),onContextMenu:P=>{P.evt.preventDefault(),o(P.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:g,rotation:e.rotation,onDragEnd:H,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:l?I:e.data.feedbackMode==="practice"?I-50:I-100,width:C,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:C-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:S,width:w,height:T,fill:"transparent",stroke:c?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:S,width:w,height:60,fill:X().bg,cornerRadius:8}),jsx(Text,{x:20,y:S,width:w,height:60,text:ne()+" ("+y+" attempts)",fontSize:18,fontStyle:"bold",fill:X().text,align:"center",verticalAlign:"middle"})]}),d===null&&!l&&jsx(Text,{x:20,y:S,width:w,height:T,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),[{value:true,label:"True"},{value:false,label:"False"}].map((P,N)=>{let _=w/2+20,Q=50,re=10,j=d===P.value,pe=R===P.value,ge=l&&j,le=P.value?"true":"false",ye=16+N*(_+re),we=g+I-300,xe=e.optionDragDropPos?.[le],St="transparent";return ge?St=pe?"#4CAF50":"#ef4444":j&&(St="#4CAF50"),jsxs(Group,{x:xe?.x??ye,y:xe?.y??we,draggable:!l,onDragStart:ae=>{ae.cancelBubble=true;},onDragMove:ae=>{ae.cancelBubble=true,F(ae);},onDragEnd:ae=>{ae.cancelBubble=true,V(P.value,ae);},opacity:l&&!j?.5:1,children:[jsx(Rect,{width:_-40,height:Q,fill:"#075560",stroke:St,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:_-40,height:Q,text:P.label,fontSize:18,fontStyle:"bold",fill:ab,align:"center",verticalAlign:"middle",listening:false})]},`${P.value}-${p}`)}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:I-100,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,!(l||d===null)&&d!==null&&(h(true),U());},onMouseUp:()=>h(false),onMouseLeave:()=>h(false),onTouchStart:()=>{d!==null&&(h(true),U());},onTouchEnd:()=>h(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:l||d===null?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:w}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:l||d===null?"#9ca3af":"white",width:w,height:40,align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{y:50,onMouseDown:K,onTouchStart:K,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:w}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:w,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]})})};ml.displayName="TrueFalseDragAndDrop";var cc=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(uc,{trueFalse:c,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id):jsx(ml,{trueFalse:c,handleSelect:t,trueFalseRefs:a,onContextMenu:r,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id))})};var Aa=new WeakMap,zo=new WeakMap,Rr={current:[]},hl=false,Dr=0,Er=new Set,is=new Map;function fc(e){let o=Array.from(e).sort((t,a)=>t instanceof jt&&t.options.deps.includes(a)?1:a instanceof jt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(Rr.current.includes(t))continue;Rr.current.push(t),t.recompute();let a=zo.get(t);if(a)for(let n of a){let r=Aa.get(n);r&&fc(r);}}}function nb(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function sb(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function ls(e){if(Dr>0&&!is.has(e)&&is.set(e,e.prevState),Er.add(e),!(Dr>0)&&!hl)try{for(hl=!0;Er.size>0;){let o=Array.from(Er);Er.clear();for(let t of o){let a=is.get(t)??t.prevState;t.prevState=a,nb(t);}for(let t of o){let a=Aa.get(t);a&&(Rr.current.push(t),fc(a));}for(let t of o){let a=Aa.get(t);if(a)for(let n of a)sb(n);}}}finally{hl=false,Rr.current=[],is.clear();}}function Mt(e){Dr++;try{e();}finally{if(Dr--,Dr===0){let o=Er.values().next().value;o&&ls(o);}}}function mc(e){return typeof e=="function"}var ea=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var n,r;this.listeners.add(a);let s=(r=(n=this.options)==null?void 0:n.onSubscribe)==null?void 0:r.call(n,a,this);return ()=>{this.listeners.delete(a),s?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,n;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):mc(o)?this.state=o(this.prevState):this.state=o,(n=(a=this.options)==null?void 0:a.onUpdate)==null||n.call(a),ls(this);}};var jt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),n=new Array(t);for(let r=0;r<t;r++){let s=this.options.deps[r];a[r]=s.prevState,n[r]=s.state;}return this.lastSeenDepValues=n,{prevDepVals:a,currDepVals:n,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let n=this.getDepVals();this.state=this.options.fn(n),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let r of this.options.deps)r instanceof e&&r.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:n}=this.getDepVals();for(let r=0;r<n.length;r++)if(n[r]!==a[r]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,n;this.listeners.add(t);let r=(n=(a=this.options).onSubscribe)==null?void 0:n.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof ea){let a=Aa.get(t);a||(a=new Set,Aa.set(t,a)),a.add(this);let n=zo.get(this);n||(n=new Set,zo.set(this,n)),n.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof ea){let a=Aa.get(t);a&&a.delete(this);let n=zo.get(this);n&&n.delete(t);}}};function ib(e){return typeof e=="function"}function gl(e,...o){return ib(e)?e(...o):e}function pc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Pa,bt,ft,Fr,Ea,ro,la,Wo,Br,ds,Or,Uo,no=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:n=1e3}){Ne(this,Pa,true);Ne(this,bt);Ne(this,ft);Ne(this,Fr);Ne(this,Ea);Ne(this,ro);Ne(this,la);Ne(this,Wo);Ne(this,Br,0);Ne(this,ds,5);Ne(this,Or,()=>{this.debugLog("Connected to event bus"),De(this,ro,true),this.debugLog("Emitting queued events",$(this,Ea)),$(this,Ea).forEach(o=>this.emitEventToBus(o)),De(this,Ea,[]),this.stopConnectLoop(),$(this,ft).call(this).removeEventListener("tanstack-connect-success",$(this,Or));});Ne(this,Uo,()=>{if($(this,ft).call(this).addEventListener("tanstack-connect-success",$(this,Or)),$(this,Br)<$(this,ds)){Hd(this,Br)._++,this.dispatchCustomEvent("tanstack-connect",{});return}$(this,ft).call(this).removeEventListener("tanstack-connect",$(this,Uo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});De(this,bt,o),De(this,Pa,a),De(this,ft,this.getGlobalTarget),De(this,Fr,t),this.debugLog(" Initializing event subscription for plugin",$(this,bt)),De(this,Ea,[]),De(this,ro,false),De(this,la,null),De(this,Wo,n);}startConnectLoop(){$(this,la)!==null||$(this,ro)||(this.debugLog(`Starting connect loop (every ${$(this,Wo)}ms)`),De(this,la,setInterval($(this,Uo),$(this,Wo))));}stopConnectLoop(){$(this,la)!==null&&(clearInterval($(this,la)),De(this,la,null),this.debugLog("Stopped connect loop"));}debugLog(...o){$(this,Fr)&&console.log(`\u{1F334} [tanstack-devtools:${$(this,bt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return $(this,bt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});$(this,ft).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{$(this,ft).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!$(this,Pa)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!$(this,ro)){this.debugLog("Bus not available, will be pushed as soon as connected"),$(this,Ea).push({type:`${$(this,bt)}:${o}`,payload:t,pluginId:$(this,bt)}),typeof CustomEvent<"u"&&($(this,Uo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${$(this,bt)}:${o}`,payload:t,pluginId:$(this,bt)})}on(o,t){let a=`${$(this,bt)}:${o}`;if(!$(this,Pa))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let n=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return $(this,ft).call(this).addEventListener(a,n),this.debugLog("Registered event to bus",a),()=>{$(this,ft).call(this).removeEventListener(a,n);}}onAll(o){if(!$(this,Pa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;o(n);};return $(this,ft).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,ft).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!$(this,Pa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;$(this,bt)&&n.pluginId!==$(this,bt)||o(n);};return $(this,ft).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,ft).call(this).removeEventListener("tanstack-devtools-global",t)}};Pa=new WeakMap,bt=new WeakMap,ft=new WeakMap,Fr=new WeakMap,Ea=new WeakMap,ro=new WeakMap,la=new WeakMap,Wo=new WeakMap,Br=new WeakMap,ds=new WeakMap,Or=new WeakMap,Uo=new WeakMap;var xl=class extends no{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},hc=(e,o)=>{bl.emit(e,o);},bl=new xl;function gc(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var lb={enabled:true,leading:true,trailing:true,wait:0},Da,At,so,io,lo,Ko,us=class{constructor(o,t){Ne(this,Da);Ne(this,At);Ne(this,so);Ne(this,io);Ne(this,lo);Ne(this,Ko);this.fn=o,this.store=new ea(gc()),this.setOptions=a=>{this.options={...this.options,...a},$(this,so).call(this)||this.cancel();},De(this,At,a=>{this.store.setState(n=>{let r={...n,...a},{isPending:s}=r;return {...r,status:$(this,so).call(this)?s?"pending":"idle":"disabled"}}),hc("Throttler",this);}),De(this,so,()=>!!gl(this.options.enabled,this)),De(this,io,()=>gl(this.options.wait,this)),this.maybeExecute=(...a)=>{$(this,At).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let n=Date.now(),r=n-this.store.state.lastExecutionTime,s=$(this,io).call(this);if(this.options.leading&&r>=s)$(this,lo).call(this,...a);else if($(this,At).call(this,{lastArgs:a}),!$(this,Da)&&this.options.trailing){let u=this.store.state.lastExecutionTime?n-this.store.state.lastExecutionTime:0,i=s-u;$(this,At).call(this,{isPending:true}),De(this,Da,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&$(this,lo).call(this,...c);},i));}},De(this,lo,(...a)=>{if(!$(this,so).call(this))return;this.fn(...a);let n=Date.now(),r=n+$(this,io).call(this);$(this,Ko).call(this),$(this,At).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:n,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||$(this,At).call(this,{nextExecutionTime:void 0});},$(this,io).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&$(this,lo).call(this,...this.store.state.lastArgs);},De(this,Ko,()=>{$(this,Da)&&(clearTimeout($(this,Da)),De(this,Da,void 0));}),this.cancel=()=>{$(this,Ko).call(this),$(this,At).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{$(this,At).call(this,gc());},this.key=pc(t.key),this.options={...lb,...t},$(this,At).call(this,this.options.initialState??{}),bl.on("d-Throttler",a=>{a.payload.key===this.key&&($(this,At).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Da=new WeakMap,At=new WeakMap,so=new WeakMap,io=new WeakMap,lo=new WeakMap,Ko=new WeakMap;function vl(e,o){return new us(e,o).maybeExecute}function Ra(e,o){return typeof e=="function"?e(o):e}function Fa(e,o){return ps(o).reduce((a,n)=>{if(a===null)return null;if(typeof a<"u")return a[n]},e)}function Go(e,o,t){let a=ps(o);function n(r){if(!a.length)return Ra(t,r);let s=a.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[s]:n(r[s])}):{[s]:n()};if(Array.isArray(r)&&typeof s=="number"){let u=r.slice(0,s);return [...u.length?u:new Array(s),n(r[s]),...r.slice(s+1)]}return [...new Array(s),n()]}return n(e)}function wl(e,o){let t=ps(o);function a(n){if(!n)return;if(t.length===1){let s=t[0];if(Array.isArray(n)&&typeof s=="number")return n.filter((c,f)=>f!==s);let{[s]:u,...i}=n;return i}let r=t.shift();if(typeof r=="string"&&typeof n=="object")return {...n,[r]:a(n[r])};if(typeof r=="number"&&Array.isArray(n)){if(r>=n.length)return n;let s=n.slice(0,r);return [...s.length?s:new Array(r),a(n[r]),...n.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var db=/^(\d+)$/gm,ub=/\.(\d+)(?=\.)/gm,cb=/^(\d+)\./gm,fb=/\.(\d+$)/gm,mb=/\.{2,}/gm,yl="__int__",cs=`${yl}$1`;function ps(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(db,cs).replace(ub,`.${cs}.`).replace(cb,`${cs}.`).replace(fb,`.${cs}`).replace(mb,".").split(".").map(o=>{if(o.startsWith(yl)){let t=o.substring(yl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Sl(e){return !(Array.isArray(e)&&e.length===0)}function jo(e,o){let t=a=>a.validators.filter(Boolean).map(n=>({cause:n.cause,validate:n.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function _o(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:n,onDynamicAsyncDebounceMs:r}=o.validators||{},s=t??0,u=i=>i.validators.filter(Boolean).map(c=>{let f=c?.cause||e,d=s;switch(f){case "change":d=n??s;break;case "blur":d=a??s;break;case "dynamic":d=r??s;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:f,validate:c.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var Nr=e=>!!e&&typeof e=="object"&&"fields"in e;function Ba(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[n,r]of e)if(!o.has(n)||!Object.is(r,o.get(n)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let n of e)if(!o.has(n))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let n of t)if(!a.includes(n)||!Ba(e[n],o[n]))return false;return true}var hs=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},gs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Qe(e,o){return e==null?o:{...e,...o}}var uo=256,ms=[],fs;for(;uo--;)ms[uo]=(uo+256).toString(16).substring(1);function Ll(){let e=0,o,t="";if(!fs||uo+16>256){for(fs=new Array(256),e=256;e--;)fs[e]=256*Math.random()|0;e=0,uo=0;}for(;e<16;e++)o=fs[uo+e],e===6?t+=ms[o&15|64]:e===8?t+=ms[o&63|128]:t+=ms[o],e&1&&e>1&&e<11&&(t+="-");return uo++,t}var Oa=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},n={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},s=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,n,r,s],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[n,s],form:e.form});case "change":return e.runValidation({validators:[a,s],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function pb(e,o){let t=new Map;for(let a of e){let n=a.path??[],r=o,s="";for(let u=0;u<n.length;u++){let i=n[u];if(i===void 0)continue;let c=typeof i=="object"?i.key:i,f=Number(c);Array.isArray(r)&&!Number.isNaN(f)?s+=`[${f}]`:s+=(u>0?".":"")+String(c),typeof r=="object"&&r!==null?r=r[c]:r=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var xc=(e,o)=>{let t=pb(e,o);return {form:t,fields:t}},Na={validate({value:e,validationSource:o},t){let a=t["~standard"].validate(e);if(a instanceof Promise)throw new Error("async function passed to sync validator");if(a.issues)return o==="field"?a.issues:xc(a.issues,e)},async validateAsync({value:e,validationSource:o},t){let a=await t["~standard"].validate(e);if(a.issues)return o==="field"?a.issues:xc(a.issues,e)}},xs=e=>!!e&&"~standard"in e;var $o={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function Hr(e){function o(d,l,m,h){let p=a(d,l,m,h);({insert:()=>u(p,d,l),remove:()=>i(p),swap:()=>h!==void 0&&f(p,d,l,h),move:()=>h!==void 0&&c(p,d,l,h)})[m]();}function t(d,l){return `${d}[${l}]`}function a(d,l,m,h){let p=[t(d,l)];if(m==="swap")p.push(t(d,h));else if(m==="move"){let[v,y]=[Math.min(l,h),Math.max(l,h)];for(let b=v;b<=y;b++)p.push(t(d,b));}else {let v=e.getFieldValue(d),y=Array.isArray(v)?v.length:0;for(let b=l+1;b<y;b++)p.push(t(d,b));}return Object.keys(e.fieldInfo).filter(v=>p.some(y=>v.startsWith(y)))}function n(d,l){return d.replace(/\[(\d+)\]/,(m,h)=>{let p=parseInt(h,10);return `[${l==="up"?p+1:Math.max(0,p-1)}]`})}function r(d,l){(l==="up"?d:[...d].reverse()).forEach(h=>{let p=n(h.toString(),l),v=e.getFieldMeta(p);v?e.setFieldMeta(h,v):e.setFieldMeta(h,s());});}let s=()=>$o,u=(d,l,m)=>{r(d,"down"),d.forEach(h=>{h.toString().startsWith(t(l,m))&&e.setFieldMeta(h,s());});},i=d=>{r(d,"up");},c=(d,l,m,h)=>{let p=new Map(Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,m))).map(v=>[v,e.getFieldMeta(v)]));r(d,m<h?"up":"down"),Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,h))).forEach(v=>{let y=v.replace(t(l,h),t(l,m)),b=p.get(y);b&&e.setFieldMeta(v,b);});},f=(d,l,m,h)=>{d.forEach(p=>{if(!p.toString().startsWith(t(l,m)))return;let v=p.toString().replace(t(l,m),t(l,h)),[y,b]=[e.getFieldMeta(p),e.getFieldMeta(v)];y&&e.setFieldMeta(v,y),b&&e.setFieldMeta(p,b);});};return {handleArrayFieldMetaShift:o}}var Il=class extends no{constructor(){super({pluginId:"form-devtools"});}},Pt=new Il;function Cl(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var Vr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),n=this.store.mount(),r=()=>{a(),n(),Pt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return Pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),s&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let n=this.options;this.options=a;let r=!!a.transform?.deps?.some((i,c)=>i!==this.prevTransformArray[c]),s=a.defaultValues&&!Ba(a.defaultValues,n.defaultValues)&&!this.state.isTouched,u=!Ba(a.defaultState,n.defaultState)&&!this.state.isTouched;!s&&!u&&!r||(Mt(()=>{this.baseStore.setState(()=>Cl(Object.assign({},this.state,u?a.defaultState:{},s?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),Pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,n)=>{let{fieldMeta:r}=this.state,s=this.resetFieldMeta(r);a&&!n?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Cl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let n=[];return Mt(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;let u=s.instance;n.push(Promise.resolve().then(()=>u.validate(a,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(n)).flat()},this.validateArrayFieldsStartingFrom=async(a,n,r)=>{let s=this.getFieldValue(a),u=Array.isArray(s)?Math.max(s.length-1,0):null,i=[`${a}[${n}]`];for(let l=n+1;l<=(u??0);l++)i.push(`${a}[${l}]`);let c=Object.keys(this.fieldInfo).filter(l=>i.some(m=>l.startsWith(m))),f=[];return Mt(()=>{c.forEach(l=>{f.push(Promise.resolve().then(()=>this.validateField(l,r)));});}),(await Promise.all(f)).flat()},this.validateField=(a,n)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(s=>({...s,isTouched:true})),r.validate(n)):[]},this.validateSync=a=>{let n=jo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Oa}),r=false,s={};return Mt(()=>{for(let c of n){if(!c.validate)continue;let f=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:l}=bs(f),m=qr(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let p=this.getFieldMeta(h);if(!p)continue;let{errorMap:v,errorSourceMap:y}=p,b=l?.[h],{newErrorValue:g,newSource:C}=hs({newFormValidatorError:b,isPreviousErrorFromFormValidator:y?.[m]==="form",previousErrorValue:v?.[m]});C==="form"&&(s[h]={...s[h],[m]:b}),v?.[m]!==g&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[m]:g},errorSourceMap:{...I.errorSourceMap,[m]:C}}));}this.state.errorMap?.[m]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[m]:d}})),(d||l)&&(r=!0);}let u=qr("submit");this.state.errorMap?.[u]&&a!=="submit"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let i=qr("server");this.state.errorMap?.[i]&&a!=="server"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[i]:void 0}}));}),{hasErrored:r,fieldsErrorMap:s}},this.validateAsync=async a=>{let n=_o(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Oa});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let r=[],s;for(let c of n){if(!c.validate)continue;let f=qr(c.cause);this.state.validationMetaMap[f]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[f]={lastAbortController:l},r.push(new Promise(async m=>{let h;try{h=await new Promise((b,g)=>{setTimeout(async()=>{if(l.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(C){g(C);}},c.debounceMs);});}catch(b){h=b;}let{formError:p,fieldErrors:v}=bs(h);v&&(s=s?{...s,...v}:v);let y=qr(c.cause);for(let b of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[b]===void 0)continue;let g=this.getFieldMeta(b);if(!g)continue;let{errorMap:C,errorSourceMap:I}=g,B=s?.[b],{newErrorValue:k,newSource:x}=hs({newFormValidatorError:B,isPreviousErrorFromFormValidator:I?.[y]==="form",previousErrorValue:C?.[y]});C?.[y]!==k&&this.setFieldMeta(b,S=>({...S,errorMap:{...S.errorMap,[y]:k},errorSourceMap:{...S.errorSourceMap,[y]:x}}));}this.baseStore.setState(b=>({...b,errorMap:{...b.errorMap,[y]:p}})),m(s?{fieldErrors:s,errorMapKey:y}:void 0);}));}let u=[],i={};if(r.length){u=await Promise.all(r);for(let c of u)if(c?.fieldErrors){let{errorMapKey:f}=c;for(let[d,l]of Object.entries(c.fieldErrors)){let h={...i[d]||{},[f]:l};i[d]=h;}}}return this.baseStore.setState(c=>({...c,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(a);return n&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Fa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var n;return (n=this.fieldInfo)[a]||(n[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,n)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Ra(n,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((n,r)=>{let s=r;return n[s]=$o,n},{}),this.setFieldValue=(a,n,r)=>{let s=r?.dontUpdateMeta??false,u=r?.dontRunListeners??false,i=r?.dontValidate??false;Mt(()=>{s||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:Go(c.values,a,n)}));}),u||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(s=>{let u=a.toString();return s!==u&&s.startsWith(u)}),a];this.baseStore.setState(s=>{let u={...s};return r.forEach(i=>{u.values=wl(u.values,i),delete this.fieldInfo[i],delete u.fieldMetaBase[i];}),u});},this.pushFieldValue=(a,n,r)=>{this.setFieldValue(a,s=>[...Array.isArray(s)?s:[],n],r);},this.insertFieldValue=async(a,n,r,s)=>{this.setFieldValue(a,i=>[...i.slice(0,n),r,...i.slice(n)],Qe(s,{dontValidate:true}));let u=s?.dontValidate??false;u||await this.validateField(a,"change"),Hr(this).handleArrayFieldMetaShift(a,n,"insert"),u||await this.validateArrayFieldsStartingFrom(a,n,"change");},this.replaceFieldValue=async(a,n,r,s)=>{this.setFieldValue(a,i=>i.map((c,f)=>f===n?r:c),Qe(s,{dontValidate:true})),(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.removeFieldValue=async(a,n,r)=>{let s=this.getFieldValue(a),u=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,c=>c.filter((f,d)=>d!==n),Qe(r,{dontValidate:true})),Hr(this).handleArrayFieldMetaShift(a,n,"remove"),u!==null){let c=`${a}[${u}]`;this.deleteField(c);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.swapFieldValues=(a,n,r,s)=>{this.setFieldValue(a,i=>{let c=i[n],f=i[r];return Go(Go(i,`${n}`,f),`${r}`,c)},Qe(s,{dontValidate:true})),Hr(this).handleArrayFieldMetaShift(a,n,"swap",r),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,n,r,s)=>{this.setFieldValue(a,i=>{let c=[...i];return c.splice(r,0,c.splice(n,1)[0]),c},Qe(s,{dontValidate:true})),Hr(this).handleArrayFieldMetaShift(a,n,"move",r),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,n)=>{let r=this.getFieldValue(a),s=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],Qe(n,{dontValidate:true})),s!==null)for(let i=0;i<=s;i++){let c=`${a}[${i}]`;this.deleteField(c);}(n?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:$o},values:this.options.defaultValues?Go(n.values,a,Fa(this.options.defaultValues,a)):n.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[n,r])=>(Object.keys(r).length&&r.errors.length&&(a[n]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Na.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Na.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Ll(),this._devtoolsSubmissionOverride=false,this.baseStore=new ea(Cl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new jt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=0,f={};for(let d of Object.keys(i.fieldMetaBase)){let l=i.fieldMetaBase[d],m=u?.fieldMetaBase[d],h=s?.[d],p=Fa(i.values,d),v=h?.errors;if(!m||l.errorMap!==m.errorMap){v=Object.values(l.errorMap??{}).filter(I=>I!==void 0);let C=this.getFieldInfo(d)?.instance;C&&!C.options.disableErrorFlat&&(v=v?.flat(1));}let y=!Sl(v??[]),b=!l.isDirty,g=Ba(p,Fa(this.options.defaultValues,d))||Ba(p,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===b&&h.isValid===y&&h.isDefaultValue===g&&h.errors===v&&l===m){f[d]=h,c++;continue}f[d]={...l,errors:v,isPristine:b,isValid:y,isDefaultValue:g};}return Object.keys(i.fieldMetaBase).length&&s&&c===Object.keys(i.fieldMetaBase).length?s:f}}),this.store=new jt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=n[1],f=Object.values(c).filter(Boolean),d=f.some(F=>F.isValidating),l=f.every(F=>F.isValid),m=f.some(F=>F.isTouched),h=f.some(F=>F.isBlurred),p=f.every(F=>F.isDefaultValue),v=m&&i.errorMap?.onMount,y=f.some(F=>F.isDirty),b=!y,g=!!(i.errorMap?.onMount||f.some(F=>F?.errorMap?.onMount)),C=!!d,I=s?.errors??[];(!u||i.errorMap!==u.errorMap)&&(I=Object.values(i.errorMap).reduce((F,V)=>V===void 0?F:V&&Nr(V)?(F.push(V.form),F):(F.push(V),F),[]));let B=I.length===0,k=l&&B,x=this.options.canSubmitWhenInvalid??false,S=i.submissionAttempts===0&&!m&&!g||!C&&!i.isSubmitting&&k||x,w=i.errorMap;if(v&&(I=I.filter(F=>F!==i.errorMap.onMount),w=Object.assign(w,{onMount:void 0})),s&&u&&s.errorMap===w&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===I&&s.isFieldsValidating===d&&s.isFieldsValid===l&&s.isFormValid===B&&s.isValid===k&&s.canSubmit===S&&s.isTouched===m&&s.isBlurred===h&&s.isPristine===b&&s.isDefaultValue===p&&s.isDirty===y&&Ba(u,i))return s;let T={...i,errorMap:w,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:l,isFormValid:B,isValid:k,canSubmit:S,isTouched:m,isBlurred:h,isPristine:b,isDefaultValue:p,isDirty:y},q=this.options.transform?.deps??[];if(q.length!==this.prevTransformArray.length||q.some((F,V)=>F!==this.prevTransformArray[V])){let F=Object.assign({},this,{state:T});this.options.transform?.fn(F),T=F.state,this.prevTransformArray=q;}return T}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=vl(a=>Pt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),Pt.on("request-form-state",a=>{a.payload.id===this._formId&&Pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Pt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),Pt.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return xs(o.validate)?Na[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(n=>({...n,isSubmitted:false,submissionAttempts:n.submissionAttempts+1,isSubmitSuccessful:false})),Mt(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance&&(n.instance.state.meta.isTouched||n.instance.setMeta(r=>({...r,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(n=>({...n,isSubmitting:true}));let a=()=>{this.baseStore.setState(n=>({...n,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(n=>n.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}Mt(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance?.options.listeners?.onSubmit?.({value:n.instance.state.value,fieldApi:n.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),Mt(()=>{this.baseStore.setState(n=>({...n,isSubmitted:!0,isSubmitSuccessful:!0})),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(n){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:n}),a(),n}}setErrorMap(o){Mt(()=>{Object.entries(o).forEach(([t,a])=>{let n=t;if(Nr(a)){let{formError:r,fieldErrors:s}=bs(a);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,c=>({...c,errorMap:{...c.errorMap,[n]:s?.[u]},errorSourceMap:{...c.errorSourceMap,[n]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[n]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[n]:a}}));});});}};function bs(e){if(e){if(Nr(e)){let o=bs(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function qr(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}var zr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:n}=this.options.validators||{};if(n){let r=this.runValidator({validate:n,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:r},errorSourceMap:{...s?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let n=Fa(t.form.options.defaultValues,t.name),r=t.defaultValue??n;a?this.setValue(s=>s||r,{dontUpdateMeta:true}):r!==void 0&&this.setValue(r,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Qe(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Qe(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,n)=>{this.form.insertFieldValue(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,n)=>{this.form.replaceFieldValue(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Qe(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,n)=>{this.form.swapFieldValues(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,n)=>{this.form.moveFieldValues(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Qe(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),n=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:s,onBlurListenTo:u}=r.instance.options.validators||{};t==="change"&&s?.includes(this.name)&&n.push(r.instance),t==="blur"&&u?.includes(this.name)&&n.push(r.instance);}return n},this.validateSync=(t,a)=>{let n=jo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Oa}),s=this.getLinkedFields(t).reduce((c,f)=>{let d=jo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Oa});return d.forEach(l=>{l.field=f;}),c.concat(d)},[]),u=false;Mt(()=>{let c=(f,d)=>{let l=vs(d.cause),m=d.validate?bc(f.runValidator({validate:d.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,h=a[l],{newErrorValue:p,newSource:v}=gs({formLevelError:h,fieldLevelError:m});f.state.meta.errorMap?.[l]!==p&&f.setMeta(y=>({...y,errorMap:{...y.errorMap,[l]:p},errorSourceMap:{...y.errorSourceMap,[l]:v}})),p&&(u=!0);};for(let f of n)c(this,f);for(let f of s)f.validate&&c(f.field,f);});let i=vs("submit");return this.state.meta.errorMap?.[i]&&t!=="submit"&&!u&&this.setMeta(c=>({...c,errorMap:{...c.errorMap,[i]:void 0},errorSourceMap:{...c.errorSourceMap,[i]:void 0}})),{hasErrored:u}},this.validateAsync=async(t,a)=>{let n=_o(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Oa}),r=await a,s=this.getLinkedFields(t),u=s.reduce((l,m)=>{let h=_o(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Oa});return h.forEach(p=>{p.field=m;}),l.concat(h)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of s)l.setMeta(m=>({...m,isValidating:true}));let i=[],c=[],f=(l,m,h)=>{let p=vs(m.cause);l.getInfo().validationMetaMap[p]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:y},h.push(new Promise(async b=>{let g;try{g=await new Promise((x,S)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(y.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:m.validate,value:{value:l.store.state.value,fieldApi:l,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(w){S(w);}},m.debounceMs);});}catch(x){g=x;}if(y.signal.aborted)return b(void 0);let C=bc(g),I=r[this.name]?.[p],{newErrorValue:B,newSource:k}=gs({formLevelError:I,fieldLevelError:C});l.setMeta(x=>({...x,errorMap:{...x?.errorMap,[p]:B},errorSourceMap:{...x.errorSourceMap,[p]:k}})),b(B);}));};for(let l of n)l.validate&&f(this,l,i);for(let l of u)l.validate&&f(l.field,l,c);let d=[];(i.length||c.length)&&(d=await Promise.all(i),await Promise.all(c)),this.setMeta(l=>({...l,isValidating:false}));for(let l of s)l.setMeta(m=>({...m,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:n}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,n[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[vs(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Na.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Na.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new jt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...$o,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return xs(o.validate)?Na[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function bc(e){if(e)return e}function vs(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function ys(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,gb)}function gb(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,n]of e)if(!o.has(a)||!Object.is(n,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=vc(e);if(t.length!==vc(o).length)return false;for(let a=0;a<t.length;a++)if(!Object.prototype.hasOwnProperty.call(o,t[a])||!Object.is(e[t[a]],o[t[a]]))return false;return true}function vc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Xo=typeof window<"u"?useLayoutEffect:useEffect;function Lb(e){let[o]=useState(()=>{let a=new zr({...e,form:e.form,name:e.name});return a.Field=kl,a});return Xo(o.mount,[o]),Xo(()=>{o.update(e);}),ys(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var kl=(({children:e,...o})=>{let t=Lb(o),a=useMemo(()=>Ra(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function kb({form:e,selector:o,children:t}){let a=ys(e.store,o);return Ra(t,a)}function Tl(e){let o=useId(),[t]=useState(()=>{let a=new Vr({...e,formId:o}),n=a;return n.Field=function(s){return jsx(kl,{...s,form:a})},n.Subscribe=function(s){return jsx(kb,{form:a,selector:s.selector,children:s.children})},n});return Xo(t.mount,[]),Xo(()=>{t.update(e);}),t}function Ml({field:e}){return jsxs(Fragment,{children:[e.state.meta.isTouched&&!e.state.meta.isValid?jsx("em",{children:e.state.meta.errors.join(", ")}):null,e.state.meta.isValidating?"Validating...":null]})}var Ob=({editElement:e})=>{let o=useDispatch(),t=useSelector(ve),a=useRef(null),n=ze(),r=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[u,i]=useState(s),c=Tl({defaultValues:{questionType:s,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:l})=>{if(l.questionType==="true-false"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctAnswer:l.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,dragDropPos:{x:r&&"dragDropPos"in e?e.dragDropPos?.x??400:200,y:r&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?ot(m):wi(m));}else if(l.questionType==="multiple-choice"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctIndex:l.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,dragDropPos:{x:r&&"dragDropPos"in e?e.dragDropPos?.x??400:400,y:r&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?gt(m):vi(m));}else if(l.questionType==="short-answer"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?sa(m):Si(m));}else if(l.questionType==="fill-in-the-blank"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Sa(m):Ii(m));}else if(l.questionType==="long-answer"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctLongAnswer:l.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Ja(m):Li(m));}o(La(false));}}),f=()=>{o(La(false));};if(!n)return null;let d=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:l=>{l.preventDefault(),l.stopPropagation(),c.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{f();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(c.Field,{name:"questionType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:m=>{l.handleChange(m.target.value),i(m.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(Ml,{field:l})]})}),u&&!["short-answer","fill-in-the-blank","long-answer"].includes(u)&&jsx(c.Field,{name:"responseType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:m=>l.handleChange(m.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(Ml,{field:l})]})})]}),jsx(c.Field,{name:"feedbackMode",children:l=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${u==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>l.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>l.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),u==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(Ml,{field:l})]})}),jsx(c.Field,{name:"question",validators:{onChange:({value:l})=>l?void 0:"A question is required"},children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:l.state.value,onChange:m=>l.handleChange(m.target.value),onBlur:l.handleBlur,placeholder:"Enter Your Question"})}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),u==="true-false"&&jsx(c.Field,{name:"responseOptions.correctAnswer",children:l=>{let m=l.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>l.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${m===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),m===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>l.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${m===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),m===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value:l})=>{if(l.options.filter(h=>!h.trim()).length>0)return "All options must have text";if(!l.correctIndex||l.correctIndex.length===0)return "Please select at least one correct answer"}},children:l=>{let m=(y,b)=>{let g=[...l.state.value.options];g[y]=b,l.handleChange({...l.state.value,options:g});},h=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},p=y=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let b=l.state.value.options.filter((C,I)=>I!==y),g=l.state.value.correctIndex?.filter(C=>C!==y).map(C=>C>y?C-1:C);l.handleChange({...l.state.value,options:b,correctIndex:g});},v=y=>{let b=l.state.value.correctIndex||[];if(b.includes(y))l.handleChange({...l.state.value,correctIndex:b.filter(C=>C!==y)});else {if(b.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...b,y]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:l.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:l.state.value.options.map((y,b)=>{let g=!y.trim(),C=l.state.value.correctIndex?.includes(b),I=l.state.meta.isTouched&&g;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>v(b),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${C?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:C&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${I?"border-red-500 bg-red-50":C?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${b+1}`,value:y,onChange:B=>m(b,B.target.value),onBlur:l.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),l.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>p(b),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},b)})}),jsx("button",{type:"button",onClick:h,disabled:l.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),l.state.value.correctIndex.length===0||l.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:l.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.Field,{name:"responseOptions.correctShortAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:l.state.value,onChange:m=>{l.handleChange(m.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),u==="long-answer"&&jsx(c.Field,{name:"responseOptions.correctLongAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:l.state.value,onChange:m=>{l.handleChange(m.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),jsx(c.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,m])=>jsx("button",{type:"submit",disabled:!l,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:m?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(d,n)},Sc=Ob;var kc=({text:e,position:o})=>{let t=Se(),a=(f,d,l,m,h)=>{let v=document.createElement("canvas").getContext("2d");if(!v)return {width:e.width,height:e.height};v.font=`${h} ${m} ${d}px ${l}`;let y=f.split(`
4
+ `),b=0;for(let I of y){let B=v.measureText(I||" ");B.width>b&&(b=B.width);}let C=y.length*d*1.2;return {width:Math.max(200,b+40),height:Math.max(50,C+20)}},n=f=>{let d=Math.max(12,Math.min(72,e.fontSize+f)),l=a(e.text,d,e.fontFamily,e.fontWeight,e.fontStyle);t(de()),t(Ft({id:e.id,fontSize:d,width:l.width,height:l.height}));},r=f=>{t(de()),t(Ft({id:e.id,fill:f}));},s=()=>{let f=e.fontWeight==="bold"?"normal":"bold",d=a(e.text,e.fontSize,e.fontFamily,f,e.fontStyle);t(de()),t(Ft({id:e.id,fontWeight:f,width:d.width,height:d.height}));},u=()=>{let f=e.fontStyle==="italic"?"normal":"italic",d=a(e.text,e.fontSize,e.fontFamily,e.fontWeight,f);t(de()),t(Ft({id:e.id,fontStyle:f,width:d.width,height:d.height}));},i=()=>{t(de()),t(Ft({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},c=f=>{let d=a(e.text,e.fontSize,f,e.fontWeight,e.fontStyle);t(de()),t(Ft({id:e.id,fontFamily:f,width:d.width,height:d.height}));};return jsxs("div",{className:"absolute z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:"50%",top:100,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:f=>f.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:f=>c(f.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>n(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>n(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:s,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:[jsx(TextB,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextB,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:u,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:i,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:[jsx(TextUnderline,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextUnderline,{size:16,weight:"bold",className:"hidden sm:block"})]})]}),jsx("div",{className:"border-l border-gray-200 pl-1",children:jsx("input",{type:"color",value:e.fill,onChange:f=>r(f.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var Mc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:n,scale:r,textareaRef:s})=>{let u=useRef(null),i=useMemo(()=>({fontSize:`${e.fontSize*r}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,r]),c=useCallback(f=>{f.style.height="auto",f.style.height=`${f.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(f).font,d.style.fontSize=f.style.fontSize,d.style.fontFamily=f.style.fontFamily,d.style.fontWeight=f.style.fontWeight,d.style.fontStyle=f.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let l=f.value.split(`
5
+ `),m=0;document.body.appendChild(d);for(let p of l){d.textContent=p||" ";let v=d.offsetWidth;v>m&&(m=v);}document.body.removeChild(d);let h=10;f.style.width=`${Math.max(200,m+h+20)}px`;},[]);return useEffect(()=>{let f=u.current;f&&(f.style.fontSize=`${e.fontSize*r}px`,f.style.fontFamily=e.fontFamily,f.style.fontStyle=e.fontStyle,f.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",f.style.textDecoration=e.textDecoration,f.style.color=e.fill,c(f));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,c]),jsx("div",{style:{position:"absolute",top:`${n.top}px`,left:`${n.left}px`,zIndex:1e3},children:jsx("textarea",{ref:f=>{if(u.current=f,s.current=f,f){f.focus();let d=f.value.length;f.setSelectionRange(d,d),c(f);}},value:o,onChange:f=>{t(f.target.value);},onKeyDown:f=>{f.key==="Escape"&&a();},style:i},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Xb=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},Ac=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s})=>{let u=useSelector(w=>w.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useDispatch(),f=useRef(null),[d,l]=useState(null),m=e.data.responseOptions.attempts||0,[h,p]=useState(e.data.responseOptions.userAnswer||""),[v,y]=useState(false);useEffect(()=>{let w=f.current;if(w)return a.current.set(e.id,w),()=>{a.current.delete(e.id);}},[e.id,a]);let b=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=v&&h.trim().toLowerCase()===b,C=w=>{p(w);let T=w.trim(),q=T.toLowerCase()===b;c(sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:T,isCorrect:q}}}));},I=()=>{y(false),p(""),c(sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:"",isCorrect:false}}}));},B=()=>g?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",k=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},x=e.data.feedbackMode==="practice",S=useMemo(()=>{let V=x?48:0,U=12,K=30,R=e.width-48,z=Math.max(60,Xb(e.data.question,18,R,"bold")+20),ne=v?40:0,X=v?54:20,P=z+ne+K+50+12+U+V+24;return {padding:24,questionHeight:z,questionFontSize:18,feedbackHeight:ne,feedbackFontSize:12,inputY:X,inputHeight:50,inputMargin:12,buttonHeight:V,buttonTopMargin:U,placeholderHeight:K,contentWidth:R,totalHeight:P}},[e.width,e.data.question,v,g,x,B]);return jsxs(Group,{ref:f,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:S.totalHeight,name:"sa-element",...s,...i?{}:{onDragEnd:r,onClick:()=>o&&o(e.id),onTap:()=>o&&o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:S.totalHeight,onTransformEnd:w=>t(e.id,w),onContextMenu:w=>{w.cancelBubble=true,n(w.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:S.padding+8,y:S.padding,fontSize:S.questionFontSize,fontStyle:"bold",fill:"#111827",width:S.contentWidth,height:S.questionHeight-S.padding,wrap:"word",listening:false}),jsx(Rect,{x:S.padding,y:S.questionHeight+S.feedbackHeight+S.placeholderHeight-S.inputY,width:S.contentWidth+4,height:S.inputHeight+6,fill:"#ffffff",stroke:g?"#22c55e":v?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:S.padding,y:S.questionHeight+S.feedbackHeight+S.placeholderHeight-S.inputY},divProps:{style:{width:`${S.contentWidth-4}px`,height:`${S.inputHeight}px`,pointerEvents:v?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:w=>C(w.target.value),disabled:v,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:v?"none":"auto"}})}),v&&jsxs(Fragment,{children:[jsx(Rect,{x:S.padding,y:S.questionHeight+80,width:S.contentWidth,height:S.feedbackHeight,fill:k().bg,cornerRadius:8}),jsx(Text,{x:36,y:S.questionHeight+80,width:S.contentWidth,height:S.feedbackHeight,text:B()+` (${m} attempts)`,fontSize:S.feedbackFontSize,fontStyle:"bold",fill:k().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:S.questionHeight+S.feedbackHeight+S.placeholderHeight+S.inputHeight+S.inputMargin+S.buttonTopMargin,children:[jsxs(Group,{onMouseDown:w=>{w.cancelBubble=true,l("check");},onMouseUp:w=>{w.cancelBubble=true,l(null),h.length>0&&(y(true),c(sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},onMouseLeave:w=>{w.cancelBubble=true,l(null);},onTouchStart:w=>{w.cancelBubble=true,l("check");},onTouchEnd:w=>{w.cancelBubble=true,l(null),h.length>0&&y(true);},scaleX:d==="check"?.95:1,scaleY:d==="check"?.95:1,children:[jsx(Rect,{x:S.padding+14,width:(S.contentWidth-24)/(v?2:1),height:S.buttonHeight,fill:h.length===0||v?"#9ca3af":"#096B76",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:S.padding+14,width:(S.contentWidth-24)/(v?2:1),height:S.buttonHeight,text:v?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),v&&jsxs(Group,{x:(e.width-S.padding*2)/2+8,onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),I();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),I();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:S.padding,width:(S.contentWidth-8)/2,height:S.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:S.padding,width:(S.contentWidth-8)/2,height:S.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ac.displayName="ShortAnswer";var Pc=Ac;var Dc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Pc,{shortAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"shortAnswer")},i.id))})};var Rc=e=>{let o=useDispatch(),a=useSelector(ve)?.fillInTheBlanks||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(Sa({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:n,handleFillInTheBlanksDragEnd:r}};var El=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},Fc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:n,fibRefs:r,touchHandlers:s})=>{let u=useSelector(w=>w.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),f=useDispatch(),[d,l]=useState(null),m=e.data.responseOptions.attempts||0,[h,p]=useState(e.data.responseOptions.userAnswer||""),[v,y]=useState(false);useEffect(()=>{let w=c.current;if(w)return r.current.set(e.id,w),()=>{r.current.delete(e.id);}},[e.id,r]);let b=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=v&&h.trim().toLowerCase()===b,C=w=>{p(w);let T=w.trim(),q=T.toLowerCase()===b;f(Sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:T,isCorrect:q}}}));},I=()=>{y(false),p("");},B=()=>{h.length>0&&(y(true),f(Sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},k=e.data.feedbackMode==="practice",x=useMemo(()=>{let K=e.width-48,R=(K-15)/2,z=24,ne=z,X=Math.max(60,El(e.data.question.replace("_____","________"),24,K,"bold")+20);z+=X;let P=z,N=Math.max(35,El("Enter your answer in the blank.",16,K)+10);z+=N;let _=z;z+=67;let Q=z,re=v?Math.max(32,El(g?"Right Answer, Great Job!":"Wrong Answer",14,K-40)+16):0;v&&(z+=re+16);let j=z;return k&&(z+=64),z+=24,{padding:24,questionY:ne,questionHeight:X,questionFontSize:24,helperTextY:P,helperTextHeight:N,helperTextFontSize:16,inputY:_,inputHeight:51,feedbackY:Q,feedbackHeight:re,feedbackFontSize:14,buttonsY:j,buttonHeight:64,buttonGap:15,buttonWidth:R,contentWidth:K,totalHeight:z}},[e.width,e.data.question,v,g,k]),S=()=>v?g?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...s,...i?{}:{onDragEnd:w=>a(w,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:x.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:w=>t(e.id,w),onContextMenu:w=>{w.cancelBubble=true,n?.(w.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:x.padding,y:x.questionY,fontSize:x.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:x.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:x.padding,y:x.helperTextY,fontSize:x.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:x.contentWidth,height:x.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:x.padding,y:x.inputY,width:x.contentWidth,height:x.inputHeight,fill:"#ffffff",stroke:S(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:x.padding,y:x.inputY},divProps:{style:{width:`${x.contentWidth}px`,height:`${x.inputHeight}px`,pointerEvents:v?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:w=>C(w.target.value),disabled:v,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),v&&jsxs(Group,{y:x.feedbackY,children:[jsx(Rect,{x:x.padding,width:x.contentWidth,height:x.feedbackHeight,fill:g?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:g?"\u2713":"\u2717",x:x.padding+10,y:0,width:16,height:x.feedbackHeight,fontSize:x.feedbackFontSize,fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:g?`Right Answer, Great Job! (${m} attempts)`:`Wrong Answer (${m} attempts)`,x:x.padding+30,y:0,height:x.feedbackHeight,fontSize:x.feedbackFontSize,fontStyle:"600",fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),k&&jsxs(Group,{y:x.buttonsY,children:[jsxs(Group,{x:x.padding,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true,onMouseDown:w=>{w.cancelBubble=true,l("reset");},onMouseUp:w=>{w.cancelBubble=true,l(null),I();},onMouseLeave:w=>{w.cancelBubble=true,l(null);},onTouchStart:w=>{w.cancelBubble=true,l("reset");},onTouchEnd:w=>{w.cancelBubble=true,l(null),I();},scaleX:d==="reset"?.98:1,scaleY:d==="reset"?.98:1,children:[jsx(Rect,{width:x.buttonWidth,height:x.buttonHeight,fill:v?"#096b76":"#9ca3af",cornerRadius:8}),jsx(Text,{width:x.buttonWidth,height:x.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:x.padding+x.buttonWidth+x.buttonGap,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true,onMouseDown:w=>{w.cancelBubble=true,!v&&l("submit");},onMouseUp:w=>{w.cancelBubble=true,!v&&(l(null),B());},onMouseLeave:w=>{w.cancelBubble=true,l(null);},onTouchStart:w=>{w.cancelBubble=true,!v&&l("submit");},onTouchEnd:w=>{w.cancelBubble=true,!v&&(l(null),B());},scaleX:d==="submit"?.98:1,scaleY:d==="submit"?.98:1,children:[jsx(Rect,{width:x.buttonWidth,height:x.buttonHeight,fill:h.length===0||v?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:x.buttonWidth,height:x.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Fc.displayName="FillInTheBlanks";var Bc=Fc;var Nc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,onLongPress:r,fibRefs:s})=>{let{createHandlers:u}=Ve({onLongPress:r});return jsx(Fragment,{children:e.map(i=>jsx(Bc,{fillInTheBlank:i,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,fibRefs:s,touchHandlers:u(i.id,"fillInTheBlanks")},i.id))})};var Fl=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},Ol=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,touchHandlers:r,handleDragEnd:s})=>{let u=useSelector(x=>x.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),f=useDispatch(),[d,l]=useState(null),[m,h]=useState(e.data.responseOptions.userAnswer||""),[p,v]=useState(false);useEffect(()=>{let x=c.current;if(x)return a.current.set(e.id,x),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",b=p&&m.trim().toLowerCase()===y,g=x=>{h(x);let S=x.trim();S.toLowerCase()===y;f(Ja({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:S}}}));},C=()=>{v(false),h("");},I=()=>b?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",B=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},k=useMemo(()=>{let U=e.width-48,K=Math.max(60,Fl(e.data.question,20,U,"bold")+20),R=p?Math.max(60,Fl(I(),14,U)+30):0,ne=Math.max(30,Fl("Answer (Extended response):",14,U)+10),X=K+R+ne+120+12+12+48+24;return {padding:24,questionHeight:K,questionFontSize:20,feedbackHeight:R,feedbackFontSize:14,placeholderHeight:ne,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:U,totalHeight:X}},[e.width,e.data.question,p,b,I]);return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:k.totalHeight,...r,name:"la-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:x=>{let S=c.current?.getStage()?.getPointerPosition();if(!S||!n)return;let w={x:e.x,y:e.y,width:e.width,height:k.totalHeight};S.x>=w.x&&S.x<=w.x+w.width&&S.y>=w.y&&S.y<=w.y+w.height&&n(x.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:k.totalHeight-50,onTransformEnd:x=>t(e.id,x)}),jsx(Text,{text:e.data.question,x:k.padding+8,y:k.padding,fontSize:k.questionFontSize,fontStyle:"bold",fill:"#111827",width:k.contentWidth,wrap:"word",listening:false}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:k.padding,y:k.questionHeight,width:k.contentWidth,height:k.feedbackHeight,fill:B().bg,cornerRadius:8}),jsx(Text,{x:k.padding,y:k.questionHeight,width:k.contentWidth,height:k.feedbackHeight,text:I(),fontSize:k.feedbackFontSize,fontStyle:"bold",fill:B().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),jsx(Text,{text:"Answer:",x:k.padding,y:k.questionHeight+k.feedbackHeight+k.textareaMargin,fontSize:k.placeholderFontSize,fill:"#6b7280",width:k.contentWidth,wrap:"word",listening:false}),jsx(Rect,{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight,width:k.contentWidth,height:k.textareaHeight,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight},divProps:{style:{width:`${k.contentWidth}px`,height:`${k.textareaHeight}px`,pointerEvents:p?"none":"auto"}},children:jsx("textarea",{value:m,onChange:x=>g(x.target.value),disabled:p,placeholder:"Type your extended answer here...",className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"18px",pointerEvents:p?"none":"auto"}})}),jsx(Group,{y:k.questionHeight+k.feedbackHeight+k.placeholderHeight+k.textareaHeight+k.textareaMargin+k.buttonTopMargin,children:p&&jsxs(Group,{onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),C();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),C();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:k.padding,width:k.contentWidth,height:k.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:x=>x.cancelBubble=true,onTap:x=>x.cancelBubble=true}),jsx(Text,{x:k.padding,width:k.contentWidth,height:k.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Ol.displayName="LongAnswer";var qc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Ol,{longAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"longAnswer")},i.id))})};var fo=1600,mo=900,Uc=3200,Kc=1800,Iv=e=>{let o=0,t=0,a=fo,n=mo;if(!e)return {minX:o,minY:t,maxX:a,maxY:n,width:fo,height:mo};let r=(i,c,f,d)=>{o=Math.min(o,i),t=Math.min(t,c),a=Math.max(a,i+f),n=Math.max(n,c+d);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let c=i.x||0,f=i.y||0,d=i.scaleX||1,l=i.scaleY||1;for(let m=0;m<i.points.length;m+=2){let h=c+i.points[m]*d,p=f+i.points[m+1]*l;o=Math.min(o,h),t=Math.min(t,p),a=Math.max(a,h),n=Math.max(n,p);}}}),e.images?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>r(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>r(i.x,i.y,i.width,i.height));let s=Math.min(a-o,Uc),u=Math.min(n-t,Kc);return o=Math.max(o,a-Uc),t=Math.max(t,n-Kc),{minX:o,minY:t,maxX:a,maxY:n,width:s,height:u}},Cv=(e,o,t={minX:0,minY:0,maxX:fo,maxY:mo,width:fo,height:mo})=>{let a=Math.max(t.width,fo),n=Math.max(t.height,mo),r=e/o,s=a/n,u,i,c,f=0;if(r>s)i=n,u=Math.round(i*r),c=o/i;else {u=a,i=Math.round(u/r),c=e/u;let d=n*c;f=(o-d)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:u,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},Gc=(e,o,t=1)=>{let a=o.contentOffsetX||0,n=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/(o.scale*t)+a,y:(e.y-o.offsetY)/(o.scale*t)+n}},kv=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:n={enabled:true}}={})=>{let r=_e(),s=ze(),u=J(L=>L.toolbar.selectedTool),i=J(ve),c=J(Ia),f=J(_n),d=J(L=>L.canvas.zoomLevel),m=(i?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),h=!!m,p=useCallback(()=>{m&&r(Xa(m.id));},[r,m]),v=i?.editingActivity,y=i?.showMcqForm,b=i?.lines||[],g=useRef(null),C=useRef(null),[I,B]=useState(null),k=useRef(null),[x,S]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:fo,stageHeight:mo,offsetX:0,offsetY:0,baseWidth:fo,baseHeight:mo,contentOffsetX:0,contentOffsetY:0}),w=useMemo(()=>Iv(i||null),[c]),[T,q]=useState(null),[H,F]=useState(null),[V,U]=useState(null),[K,R]=useState(null),[z,ne]=useState(null),[X$1,P]=useState(null),[N,_]=useState(null),[Q,re]=useState(false),[j,pe]=useState(null),[ge,le]=useState(false),ye=useRef(null),we=useRef(null),xe=useRef(null),{debouncedGenerateThumbnail:St}=xu(c,g);useEffect(()=>{let L=()=>{if(C.current){let E=C.current.getBoundingClientRect(),O=Cv(E.width,E.height,w);S(O);}};L();let M=new ResizeObserver(L);return C.current&&M.observe(C.current),window.addEventListener("resize",L),()=>{M.disconnect(),window.removeEventListener("resize",L);}},[w]),useEffect(()=>{if(g.current){let L=g.current.container();L&&(L.style.cursor="");}},[u]);let ae=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(M=>M.batchDraw()),!f)try{St();}catch(M){console.warn("Preview generation failed (CORS):",M);}});},[St,f]),rn=useRef(c);useEffect(()=>{rn.current!==c&&(rn.current=c,ae());},[c,ae]);let yo=useRef(null),nn=useRef(true);useEffect(()=>{if(!i)return;let L=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),M=yo.current?.count!==L;!nn.current&&M&&setTimeout(()=>{ae();},100),yo.current={slideId:c,count:L},nn.current=false;},[i,c,ae]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{xe.current&&a&&a(xe);},[a]);let{startDrawing:sn,draw:ln,stopDrawing:dn,setCanvasRef:Ks,tool:Gs,color:Ga,strokeWidth:js,isSketchMode:_s}=Kd(ae),ja=useRef(new Map),{images:$s,getLoadedImage:un,imageRefs:_a,handleDragEnd:cn,handleImageTransformEnd:Xs}=Zd(ae),{videos:ir,videoRefs:wo,handleVideoClick:fn,handleVideoDragEnd:Ys,handleVideoTransformEnd:Zs}=eu(ae),{multipleChoice:A,handleMcqTransform:te,mcqRefs:ke,handleDragEnd:Ie}=Jd(ae),{trueFalse:ce,handleTrueFalseTransform:se,trueFalseRefs:Ee,handleTrueFalseDragEnd:it}=Qd(ae),{shortAnswers:ra,saRefs:Ye,handleShortAnswerDragEnd:Oe}=su(ae),{longAnswers:lt,handleLongAnswerDragEnd:na}=iu(ae),{fillInTheBlanks:va,handleFillInTheBlanksDragEnd:Js,fibRefs:So}=Rc(ae),{transformerRef:ie,boundBoxFunc:Ze}=mu(),{shapes:ya,shapeRefs:Jt,isDragging:Cd,handleShapeDragEnd:_m,handleShapeResizeEnd:$m}=ou(ae),{texts:lr,textRefs:wa,handleDragEnd:Xm,handleTransformEnd:Ym,handleDoubleClick:Zm,startEditing:mn,editingTextId:be,editingValue:kd,handleEditingChange:Td,finishEditing:Qs}=nu(ae,ye);useEffect(()=>{t&&t(mn);},[t,mn]);let pn=J(L=>L.canvas.editingTextId);useEffect(()=>{pn&&pn!==be&&mn(pn);},[pn,be,mn]);let{flashcards:Jm,flashcardRefs:hn,handleDragEnd:Qm,handleFlashcardTransformEnd:ep,handleNext:tp,handlePrevious:ap}=du(ae),{photoFrames:Md,photoFrameRefs:gn,handleDragEnd:op,handlePhotoFrameTransformEnd:rp,startCamera:np,capturePhoto:sp,cameraStreams:ip}=fu(ae);useEffect(()=>{if(ie.current){if(be){ie.current.nodes([]),ie.current.getLayer()?.batchDraw();return}if(I&&!ir.find(E=>E.id===I)?.isPlaying){let E=ja.current.get(I)||_a.current.get(I)||wo.current.get(I)||Jt.current.get(I)||wa.current.get(I)||ke.current.get(I)||hn.current.get(I)||gn.current.get(I)||Ye.current.get(I)||Ee.current.get(I)||So.current.get(I);if(E){let O=E.attrs?.locked;if(E.visible()&&O!==true){ie.current.nodes([E]),ie.current.getLayer()?.batchDraw();return}}}ie.current.nodes([]),ie.current.getLayer()?.batchDraw();}},[I,be,ir,ja,_a,wo,Jt,wa,hn,gn,Md,ke,Ee,So,ie]);let We=useCallback(L=>{B(L),o?.(L);},[o]),Lo=useCallback(()=>{B(null),o?.(null),ie.current&&(ie.current.nodes([]),ie.current.getLayer()?.batchDraw());},[ie,o]),Ad=useCallback(L=>i?i.lines?.some(M=>M.id===L)?"line":i.images?.some(M=>M.id===L)?"image":i.videos?.some(M=>M.id===L)?"video":i.shapes?.some(M=>M.id===L)?"shape":i.texts?.some(M=>M.id===L)?"text":i.flashcards?.some(M=>M.id===L)?"flashcard":i.photoFrames?.some(M=>M.id===L)?"photoFrame":i.multipleChoices?.some(M=>M.id===L)?"mcq":i.trueFalses?.some(M=>M.id===L)?"trueFalse":i.shortAnswers?.some(M=>M.id===L)?"shortAnswer":i.LongAnswer?.some(M=>M.id===L)?"longAnswer":i.fillInTheBlanks?.some(M=>M.id===L)?"fillInTheBlanks":null:null,[i]),Pd=useCallback((L,M)=>{switch(r(de()),M){case "line":r(Gn(L));break;case "image":r(bn(L));break;case "video":r(wn(L));break;case "shape":r(In(L));break;case "text":r(Cn(L));break;case "flashcard":r(Tn(L));break;case "photoFrame":r(An(L));break;case "mcq":r(En(L));break;case "trueFalse":r(Rn(L));break;case "shortAnswer":r(Bn(L));break;case "longAnswer":r(Nn(L));break;case "fillInTheBlanks":r(qn(L));break}Lo(),ae();},[r,Lo,ae]);useEffect(()=>{let L=M=>{if(M.key!=="Delete"&&M.key!=="Backspace"||!I||be)return;let E=document.activeElement;if(E instanceof HTMLInputElement||E instanceof HTMLTextAreaElement||E?.getAttribute("contenteditable")==="true")return;M.preventDefault();let Ce=Ad(I);Ce&&Pd(I,Ce);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[I,be,Ad,Pd]),useEffect(()=>{let L=ie.current;return ()=>{L&&L.nodes([]);}},[c]),useEffect(()=>{let L=M=>{be&&M.target.tagName!=="TEXTAREA"&&Qs();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[be,Qs]),useEffect(()=>{let L=be||I;if(!L||I&&be){F(null);return}let M=wa.current.get(L),E=g.current;if(!M||!E){F(null);return}let O=E.container().getBoundingClientRect(),Ce=M.absolutePosition(),he=E.scaleX();F({x:O.left+(Ce.x+M.width()*he/2)*he+x.offsetX,y:O.top+Ce.y*he+x.offsetY-70});},[I,be,lr,wa,x.offsetX,x.offsetY]),useEffect(()=>{if(!be){U(null);return}let L=wa.current.get(be),M=g.current;if(!L||!M){U(null);return}let E=L.getClientRect({relativeTo:M}),O=M.container().getBoundingClientRect(),Ce=M.scaleX(),he=M.position(),oe={top:O.top+he.y+E.y*Ce,left:O.left+he.x+E.x*Ce,scale:Ce};U(oe),r(Vd(oe));},[be,lr,wa,x.offsetY,x.offsetX]);let Ed=useCallback(L=>{let M=L.target.getClassName(),E=L.target===L.target.getStage(),O=M==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",Ce=M==="Image",he=M==="Text",oe=M==="Group"||L.target.getParent()?.getClassName()==="Group",pt=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&L.target.attrs.id,ht=M==="Group";if(E&&!O&&!Ce&&!he&&!oe&&!pt&&!ht&&Lo(),!(u==="pen"||u==="eraser")&&(Ce||he||O||oe||pt||ht))return;let Ue=L.target.getStage()?.getPointerPosition();if(!Ue)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let W=Gc(Ue,x,d);sn(W);}},[u,sn,Lo,x,d]),Dd=useCallback(L=>{if(Cd)return;let M=L.target.getStage()?.getPointerPosition();if(!M)return;let E=Gc(M,x,d);ln(E);},[ln,Cd,x,d]),Rd=useCallback(()=>{dn();},[dn]),lp=useCallback(L=>{cn(L,ae);},[cn,ae]),dp=useCallback(L=>{fn(L),We(L);},[fn,We]),Rt=useCallback((L,M,E)=>{if(L.preventDefault(),!n.enabled)return;let O=L.clientX,Ce=L.clientY,he=k.current?.offsetHeight||250,oe=k.current?.offsetWidth||200,pt=window.innerHeight,ht=window.innerWidth,tt=O,Ue=Ce;Ce+he>pt&&(Ue=Ce-he),O+oe>ht&&(tt=O-oe),We(M),q({x:tt,y:Ue,elementId:M,elementType:E});},[We,n.enabled]),$a=useRef(null),dr=useRef(null),Lt=useCallback((L,M)=>E=>{if(!n.enabled)return;E.preventDefault();let O=E.changedTouches[0];if(!O)return;let Ce=O.clientX,he=O.clientY,oe=k.current?.offsetHeight||200,pt=k.current?.offsetWidth||200,ht=window.innerHeight,tt=window.innerWidth,Ue=Ce,at=he;he+oe>ht&&(at=he-oe),Ce+pt>tt&&(Ue=Ce-pt),We(L),q({x:Ue,y:at,elementId:L,elementType:M});},[We,n.enabled]),up=useCallback((L,M)=>({onTouchStart:E=>{let O=E.evt.touches[0];dr.current={x:O.clientX,y:O.clientY},$a.current=setTimeout(()=>{Lt(L,M)(E.evt);},500);},onTouchMove:E=>{if(!dr.current)return;let O=E.evt.touches[0],Ce=Math.abs(O.clientX-dr.current.x),he=Math.abs(O.clientY-dr.current.y);(Ce>10||he>10)&&$a.current&&(clearTimeout($a.current),$a.current=null);},onTouchEnd:()=>{$a.current&&(clearTimeout($a.current),$a.current=null),dr.current=null;}}),[Lt]),Fd=useCallback(L=>{r(gr(L)),r(La(true));},[r]),Bd=useCallback(L=>{r(hr(L)),r(Qa(true));},[r]),cp=useCallback((L,M)=>{if(!T)return;let{elementId:E,elementType:O}=T;switch(L){case "order":if(M){let D=M.target.getBoundingClientRect();R({x:D.right+5,y:D.top,type:"order"});}break;case "lock":if(M){let D=M.target.getBoundingClientRect();R({x:D.right+5,y:D.top,type:"lock"});}break;case "link":if(q(null),O==="line")break;let Ce=i?O==="image"?i.images.find(D=>D.id===E):i.videos.find(D=>D.id===E):null;ne({type:"link",defaultValue:Ce?.link||""});break;case "voice":if(q(null),O==="line")break;let he=i?O==="image"?i.images.find(D=>D.id===E):O==="video"?i.videos.find(D=>D.id===E):O==="text"?i.texts.find(D=>D.id===E):O==="flashcard"?i.flashcards.find(D=>D.id===E):O==="photoFrame"?i.photoFrames.find(D=>D.id===E):O==="mcq"?i.multipleChoices.find(D=>D.id===E):O==="fillInTheBlanks"?i.fillInTheBlanks.find(D=>D.id===E):O==="longAnswer"?i.LongAnswer.find(D=>D.id===E):O==="shortAnswer"?i.shortAnswers.find(D=>D.id===E):O==="trueFalse"?i.trueFalses.find(D=>D.id===E):O==="shape"?i.shapes.find(D=>D.id===E):null:null;pe({elementId:E,elementType:O,existingAudio:he?.audioData});break;case "edit":q(null);let oe=null;O==="mcq"?oe=i?.multipleChoices.find(D=>D.id===E):O==="trueFalse"?oe=i?.trueFalses.find(D=>D.id===E):O==="shortAnswer"?oe=i?.shortAnswers.find(D=>D.id===E):O==="longAnswer"?oe=i?.LongAnswer.find(D=>D.id===E):O==="fillInTheBlanks"&&(oe=i?.fillInTheBlanks.find(D=>D.id===E)),oe&&Fd(oe);break;case "editFlashcard":q(null);let pt=i?.flashcards.find(D=>D.id===E);pt&&Bd(pt);break;case "color":q(null);let ht=i?.shapes.find(D=>D.id===E);P({elementId:E,elementType:"shape",defaultColor:ht?.color||"#096B76"});break;case "border":if(q(null),O==="shape"){r(de());let D=i?.shapes.find(ti=>ti.id===E);D&&r(Ya({id:E,hasBorder:!D.hasBorder})),ae();}break;case "crop":if(q(null),O==="image"){let D=i?.images.find(ti=>ti.id===E);D&&_({elementId:E,imageSrc:D.src});}break;case "draw":q(null),O==="image"?r(hi(E)):O==="photoFrame"&&r(xi(E));break;case "duplicate":r(de()),O==="line"?r(Pi(E)):O==="image"?r(vn(E)):O==="video"?r(Sn(E)):O==="shape"?r(Ln(E)):O==="text"?r(kn(E)):O==="flashcard"?r(Mn(E)):O==="photoFrame"?r(Pn(E)):O==="mcq"?r(Dn(E)):O==="trueFalse"?r(Fn(E)):O==="shortAnswer"?r(On(E)):O==="fillInTheBlanks"?r(Vn(E)):O==="longAnswer"&&r(Hn(E)),ae();break;case "infinite-clone":r(de());let tt=5;for(let D=0;D<tt;D++)O==="image"?r(vn(E)):O==="video"?r(Sn(E)):O==="shape"?r(Ln(E)):O==="text"?r(kn(E)):O==="flashcard"?r(Mn(E)):O==="photoFrame"?r(Pn(E)):O==="mcq"?r(Dn(E)):O==="trueFalse"?r(Fn(E)):O==="shortAnswer"?r(On(E)):O==="fillInTheBlanks"?r(Vn(E)):O==="longAnswer"&&r(Hn(E));ae();break;case "make-response":if(q(null),O==="line")break;let Ue=`#response-${E}`;r(de()),r(zn({id:E,type:O,link:Ue})),(i?O==="image"?i.images.find(D=>D.id===E):O==="video"?i.videos.find(D=>D.id===E):O==="shape"?i.shapes.find(D=>D.id===E):O==="flashcard"?i.flashcards.find(D=>D.id===E):O==="photoFrame"?i.photoFrames.find(D=>D.id===E):i.multipleChoices.find(D=>D.id===E):null)?.altText||r(Wn({id:E,type:O,altText:"Interactive response area"})),ae(),console.log(`Element ${E} marked as interactive response area`);break;case "accessibility":if(q(null),O==="line")break;let W=i?O==="image"?i.images.find(D=>D.id===E):O==="video"?i.videos.find(D=>D.id===E):O==="shape"?i.shapes.find(D=>D.id===E):null:null;ne({type:"altText",defaultValue:W?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),q(null),le(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(de()),O==="line"?r(Gn(E)):O==="image"?r(bn(E)):O==="video"?r(wn(E)):O==="shape"?r(In(E)):O==="text"?r(Cn(E)):O==="flashcard"?r(Tn(E)):O==="photoFrame"?r(An(E)):O==="mcq"?r(En(E)):O==="trueFalse"?r(Rn(E)):O==="shortAnswer"?r(Bn(E)):O==="longAnswer"?r(Nn(E)):O==="fillInTheBlanks"&&r(qn(E)),Lo(),ae();break}},[T,r,ae,Lo,i,Fd,Bd]),fp=useCallback(()=>{q(null),R(null);},[]),ei=useCallback(L=>{if(!T)return;let{elementId:M,elementType:E}=T;switch(r(de()),L){case "bring-to-front":E!=="line"&&r(ki({id:M,type:E}));break;case "send-to-back":E!=="line"&&r(Ti({id:M,type:E}));break;case "lock":case "unlock":E!=="line"&&r(Mi({id:M,type:E}));break}ae(),q(null),R(null);},[T,r,ae]),mp=useCallback(L=>{if(!T||!z)return;let{elementId:M,elementType:E}=T;r(de()),z.type==="link"&&E!=="line"?r(zn({id:M,type:E,link:L})):z.type==="altText"&&E!=="line"&&r(Wn({id:M,type:E,altText:L})),ae(),ne(null);},[T,z,r,ae]),pp=useCallback(L=>{if(!j)return;let{elementId:M,elementType:E}=j;r(de()),r(Un({id:M,type:E,audioData:L})),ae(),pe(null);},[j,r,ae]),hp=useCallback(()=>{if(!j)return;let{elementId:L,elementType:M}=j;r(de()),r(Un({id:L,type:M,audioData:""})),ae();},[j,r,ae]),gp=useCallback(L=>{if(!X$1)return;let{elementId:M}=X$1;r(de()),r(Ya({id:M,color:L})),ae(),P(null);},[X$1,r,ae]),xp=useCallback(L=>{if(!N)return;let{elementId:M}=N;r(de()),r(Co({id:M,src:L})),ae(),_(null);},[N,r,ae]);return jsxs("div",{ref:C,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Xd,{ref:L=>{if(we.current=L,Ks(L),L){let M=L.getCanvasElement();M&&(xe.current=M,a&&a(xe));}},width:x.baseWidth,height:x.baseHeight,tool:Gs,color:Ga,strokeWidth:js/(x.scale*d),isSketchMode:_s,xOffset:x.contentOffsetX,yOffset:x.contentOffsetY-x.offsetY/x.scale,style:{width:x.stageWidth,height:x.stageHeight}}),jsxs(Stage,{ref:g,width:x.stageWidth,height:x.stageHeight,scaleX:x.scaleX*d,scaleY:x.scaleY*d,x:x.offsetX,y:0,onMouseDown:Ed,onMouseMove:Dd,onMouseUp:Rd,onTouchStart:Ed,onTouchMove:Dd,onTouchEnd:Rd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:x.baseWidth,height:x.stageHeight/x.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-x.contentOffsetX,y:x.offsetY/x.scale-x.contentOffsetY,children:(()=>{let L=[];return b.forEach((M,E)=>{L.push({type:"line",timestamp:M.timestamp||E,element:{...M,id:M.id??`line-${E}`},index:E});}),ya.forEach(M=>{L.push({type:"shape",timestamp:M.timestamp||0,element:M});}),$s.forEach(M=>{L.push({type:"image",timestamp:M.timestamp||0,element:M});}),ir.forEach(M=>{L.push({type:"video",timestamp:M.timestamp||0,element:M});}),lr.forEach(M=>{L.push({type:"text",timestamp:M.timestamp||0,element:M});}),Jm.forEach(M=>{L.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Md.forEach(M=>{L.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),A.forEach(M=>{L.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),ce.forEach(M=>{L.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),ra.forEach(M=>{L.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),lt.forEach(M=>{L.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),va.forEach(M=>{L.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),L.sort((M,E)=>M.timestamp-E.timestamp),L.map((M,E)=>{let O=`${M.type}-${"id"in M.element&&M.element.id||M.index||E}`,Ce="id"in M.element?M.element.id:void 0,he=Ce&&I===Ce;switch(M.type){case "line":let oe=M.element,pt=M.index||0,ht=oe.tool==="eraser",tt=oe.isSketch&&oe.tool==="pen",Ue=oe.isSketch&&ht,at=oe.id||`line-${pt}`;return oe.x===void 0&&(oe.x=0),oe.y===void 0&&(oe.y=0),oe.scaleX===void 0&&(oe.scaleX=1),oe.scaleY===void 0&&(oe.scaleY=1),oe.rotation===void 0&&(oe.rotation=0),u==="eraser"?jsx(Group,{x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,children:jsx(Line,{points:oe.points||[],stroke:tt||Ue?void 0:oe.color,strokeWidth:tt||Ue?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Ue?ht?"black":oe.color:void 0,closed:tt||Ue,tension:0,globalCompositeOperation:ht?"destination-out":"source-over",listening:true,onClick:()=>{r(de()),r(xn(pt));},onTap:()=>{r(de()),r(xn(pt));},hitStrokeWidth:Math.max(20,(oe.strokeWidth??0)*2),onMouseEnter:W=>{let D=W.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:W=>{let D=W.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},O):jsxs(Le__default.Fragment,{children:[jsx(Group,{id:at,ref:W=>{W?ja.current.set(at,W):ja.current.delete(at);},x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",at),We(at));},onTap:()=>{u==="select"&&(console.log("Line tapped:",at),We(at));},onDragEnd:W=>{r(de()),r(Kn({id:at,x:W.target.x(),y:W.target.y(),scaleX:W.target.scaleX(),scaleY:W.target.scaleY(),rotation:W.target.rotation()})),ae();},onTransformEnd:W=>{r(de()),r(Kn({id:at,x:W.target.x(),y:W.target.y(),scaleX:W.target.scaleX(),scaleY:W.target.scaleY(),rotation:W.target.rotation()})),ae();},onMouseEnter:W=>{if(u==="select"){let D=W.target.getStage();D&&(D.container().style.cursor="move");}},onMouseLeave:W=>{if(u==="select"){let D=W.target.getStage();D&&(D.container().style.cursor="default");}},onContextMenu:W=>{let D=W.evt;D.preventDefault(),Rt(D,at,"line");},...up(at,"line"),children:jsx(Line,{points:oe.points||[],stroke:tt||Ue?void 0:oe.color,strokeWidth:tt||Ue?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Ue?ht?"black":oe.color:void 0,closed:tt||Ue,tension:0,globalCompositeOperation:ht?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=ja.current.get(I);console.log("Line Transformer - selectedId:",I,"node found:",!!D),D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shape":return jsxs(Le__default.Fragment,{children:[jsx(_i,{onSelect:We,shapes:[M.element],shapeRefs:Jt,handleShapeDragEnd:_m,handleShapeResizeEnd:$m,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Jt.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "image":return jsxs(Le__default.Fragment,{children:[jsx(Ui,{images:[M.element],getLoadedImage:un,imageRefs:_a,onDragEnd:lp,onTransform:Xs,onSelect:We,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=_a.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "video":return jsxs(Le__default.Fragment,{children:[jsx(ji,{videos:[M.element],selectedId:I,videoRefs:wo,onVideoClick:dp,onDragEnd:Ys,onTransformEnd:Zs,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=wo.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "text":return jsxs(Le__default.Fragment,{children:[jsx(Au,{texts:[M.element],textRefs:wa,onDragEnd:Xm,onTransformEnd:Ym,onSelect:We,onContextMenu:Rt,onLongPress:Lt,onDoubleClick:Zm,editingTextId:be,editingValue:kd,onEditingChange:Td}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=wa.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "flashcard":return jsxs(Le__default.Fragment,{children:[jsx(Zi,{flashcards:[M.element],flashcardRefs:hn,selectedId:I,onDragEnd:Qm,onTransform:ep,onSelect:We,onNext:tp,onPrevious:ap,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=hn.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "photoFrame":return jsxs(Le__default.Fragment,{children:[jsx(ol,{photoFrames:[M.element],photoFrameRefs:gn,selectedId:I,onDragEnd:op,onTransform:rp,onSelect:We,onStartCamera:np,onCapture:sp,cameraStreams:ip,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=gn.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "mcq":return jsxs(Le__default.Fragment,{children:[jsx(ic,{handleMcqTransform:te,multipleChoice:[M.element],handleSelect:We,mcqRefs:ke,handleDragEnd:Ie,onContextMenu:Rt,onLongPress:Lt,onUpdate:ae}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=ke.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "trueFalse":return jsxs(Le__default.Fragment,{children:[jsx(cc,{trueFalses:[M.element],handleTrueFalseTransform:se,handleSelect:We,trueFalseRefs:Ee,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:it,onUpdate:ae}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Ee.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shortAnswer":return jsxs(Le__default.Fragment,{children:[jsx(Dc,{shortAnswers:[M.element],handleSelect:We,handleTransform:te,saRefs:Ye,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:Oe}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Ye.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "longAnswer":return jsxs(Le__default.Fragment,{children:[jsx(qc,{longAnswer:[M.element],handleSelect:We,handleTransform:te,saRefs:Ye,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:na}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Ye.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "fillInTheBlanks":return jsxs(Le__default.Fragment,{children:[jsx(Nc,{fillInTheBlanks:[M.element],handleSelect:We,handleTransform:te,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:Js,fibRefs:So}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=So.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);default:return null}})})()})]}),T&&jsx(Wu,{menuRef:k,x:T.x,y:T.y,type:T.elementType,onAction:cp,onClose:fp,isDrawingMode:T.elementType==="image"?i?.images.find(L=>L.id===T.elementId)?.isDrawingMode:T.elementType==="photoFrame"?i?.photoFrames.find(L=>L.id===T.elementId)?.isDrawingMode:false}),K&&T&&jsx(Uu,{x:K.x,y:K.y,items:K.type==="order"?[{label:"Bring to Front",onClick:()=>ei("bring-to-front")},{label:"Send to Back",onClick:()=>ei("send-to-back")}]:[{label:i&&(T.elementType==="image"?i.images.find(L=>L.id===T.elementId)?.locked:i.videos.find(L=>L.id===T.elementId)?.locked)?"Unlock":"Lock",onClick:()=>ei(i&&(T.elementType==="image"?i.images.find(L=>L.id===T.elementId)?.locked:i.videos.find(L=>L.id===T.elementId)?.locked)?"unlock":"lock")}],onClose:()=>R(null)}),z&&jsx(ju,{title:z.type==="link"?"Add Link":"Add Alt Text",label:z.type==="link"?"URL":"Alternative Text",placeholder:z.type==="link"?"https://example.com":"Describe this image/video",defaultValue:z.defaultValue,onSave:mp,onClose:()=>ne(null)}),X$1&&jsx(es,{defaultColor:X$1.defaultColor,onConfirm:gp,onCancel:()=>P(null)}),N&&jsx(Yu,{imageSrc:N.imageSrc,onConfirm:xp,onCancel:()=>_(null)}),Q&&jsx(eo,{onClose:()=>re(false),stageRef:g}),j&&jsx(ec,{elementId:j.elementId,elementType:j.elementType,existingAudio:j.existingAudio,onSave:pp,onDelete:hp,onClose:()=>pe(null)}),ge&&jsx(oc,{selectedElementId:I||void 0,onClose:()=>le(false),onSelectElement:L=>{We(L),le(false);}}),i?.images.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.videos.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.shapes?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.texts?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),y&&jsx(Sc,{editElement:v}),H&&(()=>{let L=be||I;if(!L)return null;let M=lr.find(E=>E.id===L);return M?jsx(kc,{text:M,position:H}):null})(),V&&be&&(()=>{let L=lr.find(M=>M.id===be);return L?jsx(Mc,{text:L,editingValue:kd,onEditingChange:Td,onFinish:Qs,position:{top:V.top,left:V.left},scale:V.scale,textareaRef:ye},be):null})(),h&&s&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:m?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:p})}),jsx("button",{onClick:p,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),s)]})},Tv=kv;var Av="SchooplaVideoStorage";var ta="videos",Cs=()=>new Promise((e,o)=>{let t=indexedDB.open(Av,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(ta)||n.createObjectStore(ta,{keyPath:"id"});};}),da=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Cs(),r=a.transaction([ta],"readwrite").objectStore(ta),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,i)=>{let c=r.put(s);c.onsuccess=()=>u(!0),c.onerror=()=>i(c.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var jc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Cs(),t=e.transaction([ta],"readonly").objectStore(ta);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let s=r.result,u=new Map;s.forEach(i=>{u.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),a(u);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Nl=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Cs(),a=o.transaction([ta],"readwrite").objectStore(ta);await new Promise((n,r)=>{let s=a.delete(e);s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},_c=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Cs(),t=e.transaction([ta],"readwrite").objectStore(ta);await new Promise((a,n)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>n(r.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},$c=e=>URL.createObjectURL(e);function Ha(e,o=[]){let t=[];function a(r,s){let u=Le.createContext(s),i=t.length;t=[...t,s];let c=d=>{let{scope:l,children:m,...h}=d,p=l?.[e]?.[i]||u,v=Le.useMemo(()=>h,Object.values(h));return jsx(p.Provider,{value:v,children:m})};c.displayName=r+"Provider";function f(d,l){let m=l?.[e]?.[i]||u,h=Le.useContext(m);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${r}\``)}return [c,f]}let n=()=>{let r=t.map(s=>Le.createContext(s));return function(u){let i=u?.[e]||r;return Le.useMemo(()=>({[`__scope${e}`]:{...u,[e]:i}}),[u,i])}};return n.scopeName=e,[a,Ev(n,...o)]}function Ev(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(n=>({useScope:n(),scopeName:n.scopeName}));return function(r){let s=a.reduce((u,{useScope:i,scopeName:c})=>{let d=i(r)[`__scope${c}`];return {...u,...d}},{});return Le.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function Xc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function $r(...e){return o=>{let t=false,a=e.map(n=>{let r=Xc(n,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let n=0;n<a.length;n++){let r=a[n];typeof r=="function"?r():Xc(e[n],null);}}}}function Ut(...e){return Le.useCallback($r(...e),e)}function Jc(e){let o=Dv(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Fv);if(i){let c=i.props.children,f=u.map(d=>d===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Dv(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Ov(n),u=Bv(r,n.props);return n.type!==Le.Fragment&&(u.ref=a?$r(a,s):s),Le.cloneElement(n,u)}return Le.Children.count(n)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Rv=Symbol("radix.slottable");function Fv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Rv}function Bv(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let i=r(...u);return n(...u),i}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function Ov(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var qv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],yt=qv.reduce((e,o)=>{let t=Jc(`Primitive.${o}`),a=Le.forwardRef((n,r)=>{let{asChild:s,...u}=n,i=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...u,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function nt(e,o,{checkForDefaultPrevented:t=true}={}){return function(n){if(e?.(n),t===false||!n.defaultPrevented)return o?.(n)}}function Hl(e){let o=Vv(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Wv);if(i){let c=i.props.children,f=u.map(d=>d===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Vv(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Kv(n),u=Uv(r,n.props);return n.type!==Le.Fragment&&(u.ref=a?$r(a,s):s),Le.cloneElement(n,u)}return Le.Children.count(n)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var zv=Symbol("radix.slottable");function Wv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===zv}function Uv(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let i=r(...u);return n(...u),i}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function Kv(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function ks(e){let o=e+"CollectionProvider",[t,a]=Ha(o),[n,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=p=>{let{scope:v,children:y}=p,b=Le__default.useRef(null),g=Le__default.useRef(new Map).current;return jsx(n,{scope:v,itemMap:g,collectionRef:b,children:y})};s.displayName=o;let u=e+"CollectionSlot",i=Hl(u),c=Le__default.forwardRef((p,v)=>{let{scope:y,children:b}=p,g=r(u,y),C=Ut(v,g.collectionRef);return jsx(i,{ref:C,children:b})});c.displayName=u;let f=e+"CollectionItemSlot",d="data-radix-collection-item",l=Hl(f),m=Le__default.forwardRef((p,v)=>{let{scope:y,children:b,...g}=p,C=Le__default.useRef(null),I=Ut(v,C),B=r(f,y);return Le__default.useEffect(()=>(B.itemMap.set(C,{ref:C,...g}),()=>void B.itemMap.delete(C))),jsx(l,{[d]:"",ref:I,children:b})});m.displayName=f;function h(p){let v=r(e+"CollectionConsumer",p);return Le__default.useCallback(()=>{let b=v.collectionRef.current;if(!b)return [];let g=Array.from(b.querySelectorAll(`[${d}]`));return Array.from(v.itemMap.values()).sort((B,k)=>g.indexOf(B.ref.current)-g.indexOf(k.ref.current))},[v.collectionRef,v.itemMap])}return [{Provider:s,Slot:c,ItemSlot:m},h,a]}var Zo=globalThis?.document?Le.useLayoutEffect:()=>{};var Gv=Le[" useId ".trim().toString()]||(()=>{}),jv=0;function af(e){let[o,t]=Le.useState(Gv());return Zo(()=>{t(a=>a??String(jv++));},[e]),(o?`radix-${o}`:"")}function of(e){let o=Le.useRef(e);return Le.useEffect(()=>{o.current=e;}),Le.useMemo(()=>(...t)=>o.current?.(...t),[])}var _v=Le[" useInsertionEffect ".trim().toString()]||Zo;function ca({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[n,r,s]=$v({defaultProp:o,onChange:t}),u=e!==void 0,i=u?e:n;{let f=Le.useRef(e!==void 0);Le.useEffect(()=>{let d=f.current;d!==u&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${u?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=u;},[u,a]);}let c=Le.useCallback(f=>{if(u){let d=Xv(f)?f(e):f;d!==e&&s.current?.(d);}else r(f);},[u,e,r,s]);return [i,c]}function $v({defaultProp:e,onChange:o}){let[t,a]=Le.useState(e),n=Le.useRef(t),r=Le.useRef(o);return _v(()=>{r.current=o;},[o]),Le.useEffect(()=>{n.current!==t&&(r.current?.(t),n.current=t);},[t,n]),[t,a,r]}function Xv(e){return typeof e=="function"}var Yv=Le.createContext(void 0);function Qo(e){let o=Le.useContext(Yv);return e||o||"ltr"}var zl="rovingFocusGroup.onEntryFocus",Zv={bubbles:false,cancelable:true},Xr="RovingFocusGroup",[Wl,rf,Jv]=ks(Xr),[Qv,Ul]=Ha(Xr,[Jv]),[ey,ty]=Qv(Xr),nf=Le.forwardRef((e,o)=>jsx(Wl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Wl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(ay,{...e,ref:o})})}));nf.displayName=Xr;var ay=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:n=false,dir:r,currentTabStopId:s,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:i,onEntryFocus:c,preventScrollOnEntryFocus:f=false,...d}=e,l=Le.useRef(null),m=Ut(o,l),h=Qo(r),[p,v]=ca({prop:s,defaultProp:u??null,onChange:i,caller:Xr}),[y,b]=Le.useState(false),g=of(c),C=rf(t),I=Le.useRef(false),[B,k]=Le.useState(0);return Le.useEffect(()=>{let x=l.current;if(x)return x.addEventListener(zl,g),()=>x.removeEventListener(zl,g)},[g]),jsx(ey,{scope:t,orientation:a,dir:h,loop:n,currentTabStopId:p,onItemFocus:Le.useCallback(x=>v(x),[v]),onItemShiftTab:Le.useCallback(()=>b(true),[]),onFocusableItemAdd:Le.useCallback(()=>k(x=>x+1),[]),onFocusableItemRemove:Le.useCallback(()=>k(x=>x-1),[]),children:jsx(yt.div,{tabIndex:y||B===0?-1:0,"data-orientation":a,...d,ref:m,style:{outline:"none",...e.style},onMouseDown:nt(e.onMouseDown,()=>{I.current=true;}),onFocus:nt(e.onFocus,x=>{let S=!I.current;if(x.target===x.currentTarget&&S&&!y){let w=new CustomEvent(zl,Zv);if(x.currentTarget.dispatchEvent(w),!w.defaultPrevented){let T=C().filter(U=>U.focusable),q=T.find(U=>U.active),H=T.find(U=>U.id===p),V=[q,H,...T].filter(Boolean).map(U=>U.ref.current);df(V,f);}}I.current=false;}),onBlur:nt(e.onBlur,()=>b(false))})})}),sf="RovingFocusGroupItem",lf=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:n=false,tabStopId:r,children:s,...u}=e,i=af(),c=r||i,f=ty(sf,t),d=f.currentTabStopId===c,l=rf(t),{onFocusableItemAdd:m,onFocusableItemRemove:h,currentTabStopId:p}=f;return Le.useEffect(()=>{if(a)return m(),()=>h()},[a,m,h]),jsx(Wl.ItemSlot,{scope:t,id:c,focusable:a,active:n,children:jsx(yt.span,{tabIndex:d?0:-1,"data-orientation":f.orientation,...u,ref:o,onMouseDown:nt(e.onMouseDown,v=>{a?f.onItemFocus(c):v.preventDefault();}),onFocus:nt(e.onFocus,()=>f.onItemFocus(c)),onKeyDown:nt(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){f.onItemShiftTab();return}if(v.target!==v.currentTarget)return;let y=ny(v,f.orientation,f.dir);if(y!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let g=l().filter(C=>C.focusable).map(C=>C.ref.current);if(y==="last")g.reverse();else if(y==="prev"||y==="next"){y==="prev"&&g.reverse();let C=g.indexOf(v.currentTarget);g=f.loop?sy(g,C+1):g.slice(C+1);}setTimeout(()=>df(g));}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:p!=null}):s})})});lf.displayName=sf;var oy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ry(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ny(e,o,t){let a=ry(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return oy[a]}function df(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function sy(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var uf=nf,cf=lf;var mf="Toggle",Kl=Le.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:n,...r}=e,[s,u]=ca({prop:t,onChange:n,defaultProp:a??false,caller:mf});return jsx(yt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:nt(e.onClick,()=>{e.disabled||u(!s);})})});Kl.displayName=mf;var qa="ToggleGroup",[hf]=Ha(qa,[Ul]),gf=Ul(),Gl=Le__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(dy,{...a,ref:o});if(t==="multiple")return jsx(uy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${qa}\``)});Gl.displayName=qa;var[xf,bf]=hf(qa),dy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=ca({prop:t,defaultProp:a??"",onChange:n,caller:qa});return jsx(xf,{scope:e.__scopeToggleGroup,type:"single",value:Le__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:u,onItemDeactivate:Le__default.useCallback(()=>u(""),[u]),children:jsx(vf,{...r,ref:o})})}),uy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=ca({prop:t,defaultProp:a??[],onChange:n,caller:qa}),i=Le__default.useCallback(f=>u((d=[])=>[...d,f]),[u]),c=Le__default.useCallback(f=>u((d=[])=>d.filter(l=>l!==f)),[u]);return jsx(xf,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:c,children:jsx(vf,{...r,ref:o})})});Gl.displayName=qa;var[cy,fy]=hf(qa),vf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:n=true,orientation:r,dir:s,loop:u=true,...i}=e,c=gf(t),f=Qo(s),d={role:"group",dir:f,...i};return jsx(cy,{scope:t,rovingFocus:n,disabled:a,children:n?jsx(uf,{asChild:true,...c,orientation:r,dir:f,loop:u,children:jsx(yt.div,{...d,ref:o})}):jsx(yt.div,{...d,ref:o})})}),As="ToggleGroupItem",my=Le__default.forwardRef((e,o)=>{let t=bf(As,e.__scopeToggleGroup),a=fy(As,e.__scopeToggleGroup),n=gf(e.__scopeToggleGroup),r=t.value.includes(e.value),s=a.disabled||e.disabled,u={...e,pressed:r,disabled:s},i=Le__default.useRef(null);return a.rovingFocus?jsx(cf,{asChild:true,...n,focusable:!s,active:r,ref:i,children:jsx(pf,{...u,ref:o})}):jsx(pf,{...u,ref:o})});my.displayName=As;var pf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...n}=e,r=bf(As,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=r.type==="single"?s:void 0;return jsx(Kl,{...u,...n,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),yf=Gl;function wf(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var n=e.length;for(o=0;o<n;o++)e[o]&&(t=wf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Ps(){for(var e,o,t=0,a="",n=arguments.length;t<n;t++)(e=arguments[t])&&(o=wf(e))&&(a&&(a+=" "),a+=o);return a}var hy=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},gy=(e,o)=>({classGroupId:e,validator:o}),kf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Sf=[],xy="arbitrary..",by=e=>{let o=yy(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return vy(s);let u=s.split("-"),i=u[0]===""&&u.length>1?1:0;return Tf(u,i,o)},getConflictingClassGroupIds:(s,u)=>{if(u){let i=a[s],c=t[s];return i?c?hy(c,i):i:c||Sf}return t[s]||Sf}}},Tf=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let n=e[o],r=t.nextPart.get(n);if(r){let c=Tf(e,o+1,r);if(c)return c}let s=t.validators;if(s===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),i=s.length;for(let c=0;c<i;c++){let f=s[c];if(f.validator(u))return f.classGroupId}},vy=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?xy+a:void 0})(),yy=e=>{let{theme:o,classGroups:t}=e;return wy(t,o)},wy=(e,o)=>{let t=kf();for(let a in e){let n=e[a];$l(n,t,a,o);}return t},$l=(e,o,t,a)=>{let n=e.length;for(let r=0;r<n;r++){let s=e[r];Sy(s,o,t,a);}},Sy=(e,o,t,a)=>{if(typeof e=="string"){Ly(e,o,t);return}if(typeof e=="function"){Iy(e,o,t,a);return}Cy(e,o,t,a);},Ly=(e,o,t)=>{let a=e===""?o:Mf(o,e);a.classGroupId=t;},Iy=(e,o,t,a)=>{if(ky(e)){$l(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(gy(t,e));},Cy=(e,o,t,a)=>{let n=Object.entries(e),r=n.length;for(let s=0;s<r;s++){let[u,i]=n[s];$l(i,Mf(o,u),t,a);}},Mf=(e,o)=>{let t=e,a=o.split("-"),n=a.length;for(let r=0;r<n;r++){let s=a[r],u=t.nextPart.get(s);u||(u=kf(),t.nextPart.set(s,u)),t=u;}return t},ky=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Ty=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),n=(r,s)=>{t[r]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let s=t[r];if(s!==void 0)return s;if((s=a[r])!==void 0)return n(r,s),s},set(r,s){r in t?t[r]=s:n(r,s);}}};var My=[],Lf=(e,o,t,a,n)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:n}),Ay=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=n=>{let r=[],s=0,u=0,i=0,c,f=n.length;for(let p=0;p<f;p++){let v=n[p];if(s===0&&u===0){if(v===":"){r.push(n.slice(i,p)),i=p+1;continue}if(v==="/"){c=p;continue}}v==="["?s++:v==="]"?s--:v==="("?u++:v===")"&&u--;}let d=r.length===0?n:n.slice(i),l=d,m=false;d.endsWith("!")?(l=d.slice(0,-1),m=true):d.startsWith("!")&&(l=d.slice(1),m=true);let h=c&&c>i?c-i:void 0;return Lf(r,m,l,h)};if(o){let n=o+":",r=a;a=s=>s.startsWith(n)?r(s.slice(n.length)):Lf(My,false,s,void 0,true);}if(t){let n=a;a=r=>t({className:r,parseClassName:n});}return a},Py=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],n=[];for(let r=0;r<t.length;r++){let s=t[r],u=s[0]==="[",i=o.has(s);u||i?(n.length>0&&(n.sort(),a.push(...n),n=[]),a.push(s)):n.push(s);}return n.length>0&&(n.sort(),a.push(...n)),a}},Ey=e=>({cache:Ty(e.cacheSize),parseClassName:Ay(e),sortModifiers:Py(e),...by(e)}),Dy=/\s+/,Ry=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:n,sortModifiers:r}=o,s=[],u=e.trim().split(Dy),i="";for(let c=u.length-1;c>=0;c-=1){let f=u[c],{isExternal:d,modifiers:l,hasImportantModifier:m,baseClassName:h,maybePostfixModifierPosition:p}=t(f);if(d){i=f+(i.length>0?" "+i:i);continue}let v=!!p,y=a(v?h.substring(0,p):h);if(!y){if(!v){i=f+(i.length>0?" "+i:i);continue}if(y=a(h),!y){i=f+(i.length>0?" "+i:i);continue}v=false;}let b=l.length===0?"":l.length===1?l[0]:r(l).join(":"),g=m?b+"!":b,C=g+y;if(s.indexOf(C)>-1)continue;s.push(C);let I=n(y,v);for(let B=0;B<I.length;++B){let k=I[B];s.push(g+k);}i=f+(i.length>0?" "+i:i);}return i},Fy=(...e)=>{let o=0,t,a,n="";for(;o<e.length;)(t=e[o++])&&(a=Af(t))&&(n&&(n+=" "),n+=a);return n},Af=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Af(e[a]))&&(t&&(t+=" "),t+=o);return t},By=(e,...o)=>{let t,a,n,r,s=i=>{let c=o.reduce((f,d)=>d(f),e());return t=Ey(c),a=t.cache.get,n=t.cache.set,r=u,u(i)},u=i=>{let c=a(i);if(c)return c;let f=Ry(i,t);return n(i,f),f};return r=s,(...i)=>r(Fy(...i))},Oy=[],je=e=>{let o=t=>t[e]||Oy;return o.isThemeGetter=true,o},Pf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Ef=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Ny=/^\d+\/\d+$/,Hy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,qy=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Vy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,zy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Wy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,er=e=>Ny.test(e),ue=e=>!!e&&!Number.isNaN(Number(e)),Va=e=>!!e&&Number.isInteger(Number(e)),jl=e=>e.endsWith("%")&&ue(e.slice(0,-1)),fa=e=>Hy.test(e),Uy=()=>true,Ky=e=>qy.test(e)&&!Vy.test(e),Df=()=>false,Gy=e=>zy.test(e),jy=e=>Wy.test(e),_y=e=>!Y(e)&&!Z(e),$y=e=>tr(e,Bf,Df),Y=e=>Pf.test(e),go=e=>tr(e,Of,Ky),_l=e=>tr(e,Qy,ue),If=e=>tr(e,Rf,Df),Xy=e=>tr(e,Ff,jy),Es=e=>tr(e,Nf,Gy),Z=e=>Ef.test(e),Yr=e=>ar(e,Of),Yy=e=>ar(e,ew),Cf=e=>ar(e,Rf),Zy=e=>ar(e,Bf),Jy=e=>ar(e,Ff),Ds=e=>ar(e,Nf,true),tr=(e,o,t)=>{let a=Pf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},ar=(e,o,t=false)=>{let a=Ef.exec(e);return a?a[1]?o(a[1]):t:false},Rf=e=>e==="position"||e==="percentage",Ff=e=>e==="image"||e==="url",Bf=e=>e==="length"||e==="size"||e==="bg-size",Of=e=>e==="length",Qy=e=>e==="number",ew=e=>e==="family-name",Nf=e=>e==="shadow";var tw=()=>{let e=je("color"),o=je("font"),t=je("text"),a=je("font-weight"),n=je("tracking"),r=je("leading"),s=je("breakpoint"),u=je("container"),i=je("spacing"),c=je("radius"),f=je("shadow"),d=je("inset-shadow"),l=je("text-shadow"),m=je("drop-shadow"),h=je("blur"),p=je("perspective"),v=je("aspect"),y=je("ease"),b=je("animate"),g=()=>["auto","avoid","all","avoid-page","page","left","right","column"],C=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...C(),Z,Y],B=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],x=()=>[Z,Y,i],S=()=>[er,"full","auto",...x()],w=()=>[Va,"none","subgrid",Z,Y],T=()=>["auto",{span:["full",Va,Z,Y]},Va,Z,Y],q=()=>[Va,"auto",Z,Y],H=()=>["auto","min","max","fr",Z,Y],F=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],V=()=>["start","end","center","stretch","center-safe","end-safe"],U=()=>["auto",...x()],K=()=>[er,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...x()],R=()=>[e,Z,Y],z=()=>[...C(),Cf,If,{position:[Z,Y]}],ne=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",Zy,$y,{size:[Z,Y]}],P=()=>[jl,Yr,go],N=()=>["","none","full",c,Z,Y],_=()=>["",ue,Yr,go],Q=()=>["solid","dashed","dotted","double"],re=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],j=()=>[ue,jl,Cf,If],pe=()=>["","none",h,Z,Y],ge=()=>["none",ue,Z,Y],le=()=>["none",ue,Z,Y],ye=()=>[ue,Z,Y],we=()=>[er,"full",...x()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[fa],breakpoint:[fa],color:[Uy],container:[fa],"drop-shadow":[fa],ease:["in","out","in-out"],font:[_y],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[fa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[fa],shadow:[fa],spacing:["px",ue],text:[fa],"text-shadow":[fa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",er,Y,Z,v]}],container:["container"],columns:[{columns:[ue,Y,Z,u]}],"break-after":[{"break-after":g()}],"break-before":[{"break-before":g()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:I()}],overflow:[{overflow:B()}],"overflow-x":[{"overflow-x":B()}],"overflow-y":[{"overflow-y":B()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:S()}],"inset-x":[{"inset-x":S()}],"inset-y":[{"inset-y":S()}],start:[{start:S()}],end:[{end:S()}],top:[{top:S()}],right:[{right:S()}],bottom:[{bottom:S()}],left:[{left:S()}],visibility:["visible","invisible","collapse"],z:[{z:[Va,"auto",Z,Y]}],basis:[{basis:[er,"full","auto",u,...x()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ue,er,"auto","initial","none",Y]}],grow:[{grow:["",ue,Z,Y]}],shrink:[{shrink:["",ue,Z,Y]}],order:[{order:[Va,"first","last","none",Z,Y]}],"grid-cols":[{"grid-cols":w()}],"col-start-end":[{col:T()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":w()}],"row-start-end":[{row:T()}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":H()}],"auto-rows":[{"auto-rows":H()}],gap:[{gap:x()}],"gap-x":[{"gap-x":x()}],"gap-y":[{"gap-y":x()}],"justify-content":[{justify:[...F(),"normal"]}],"justify-items":[{"justify-items":[...V(),"normal"]}],"justify-self":[{"justify-self":["auto",...V()]}],"align-content":[{content:["normal",...F()]}],"align-items":[{items:[...V(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...V(),{baseline:["","last"]}]}],"place-content":[{"place-content":F()}],"place-items":[{"place-items":[...V(),"baseline"]}],"place-self":[{"place-self":["auto",...V()]}],p:[{p:x()}],px:[{px:x()}],py:[{py:x()}],ps:[{ps:x()}],pe:[{pe:x()}],pt:[{pt:x()}],pr:[{pr:x()}],pb:[{pb:x()}],pl:[{pl:x()}],m:[{m:U()}],mx:[{mx:U()}],my:[{my:U()}],ms:[{ms:U()}],me:[{me:U()}],mt:[{mt:U()}],mr:[{mr:U()}],mb:[{mb:U()}],ml:[{ml:U()}],"space-x":[{"space-x":x()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":x()}],"space-y-reverse":["space-y-reverse"],size:[{size:K()}],w:[{w:[u,"screen",...K()]}],"min-w":[{"min-w":[u,"screen","none",...K()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[s]},...K()]}],h:[{h:["screen","lh",...K()]}],"min-h":[{"min-h":["screen","lh","none",...K()]}],"max-h":[{"max-h":["screen","lh",...K()]}],"font-size":[{text:["base",t,Yr,go]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,Z,_l]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",jl,Y]}],"font-family":[{font:[Yy,Y,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[n,Z,Y]}],"line-clamp":[{"line-clamp":[ue,"none",Z,_l]}],leading:[{leading:[r,...x()]}],"list-image":[{"list-image":["none",Z,Y]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Z,Y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:R()}],"text-color":[{text:R()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Q(),"wavy"]}],"text-decoration-thickness":[{decoration:[ue,"from-font","auto",Z,go]}],"text-decoration-color":[{decoration:R()}],"underline-offset":[{"underline-offset":[ue,"auto",Z,Y]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:x()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Z,Y]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Z,Y]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:ne()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Va,Z,Y],radial:["",Z,Y],conic:[Va,Z,Y]},Jy,Xy]}],"bg-color":[{bg:R()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:R()}],"gradient-via":[{via:R()}],"gradient-to":[{to:R()}],rounded:[{rounded:N()}],"rounded-s":[{"rounded-s":N()}],"rounded-e":[{"rounded-e":N()}],"rounded-t":[{"rounded-t":N()}],"rounded-r":[{"rounded-r":N()}],"rounded-b":[{"rounded-b":N()}],"rounded-l":[{"rounded-l":N()}],"rounded-ss":[{"rounded-ss":N()}],"rounded-se":[{"rounded-se":N()}],"rounded-ee":[{"rounded-ee":N()}],"rounded-es":[{"rounded-es":N()}],"rounded-tl":[{"rounded-tl":N()}],"rounded-tr":[{"rounded-tr":N()}],"rounded-br":[{"rounded-br":N()}],"rounded-bl":[{"rounded-bl":N()}],"border-w":[{border:_()}],"border-w-x":[{"border-x":_()}],"border-w-y":[{"border-y":_()}],"border-w-s":[{"border-s":_()}],"border-w-e":[{"border-e":_()}],"border-w-t":[{"border-t":_()}],"border-w-r":[{"border-r":_()}],"border-w-b":[{"border-b":_()}],"border-w-l":[{"border-l":_()}],"divide-x":[{"divide-x":_()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":_()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Q(),"hidden","none"]}],"divide-style":[{divide:[...Q(),"hidden","none"]}],"border-color":[{border:R()}],"border-color-x":[{"border-x":R()}],"border-color-y":[{"border-y":R()}],"border-color-s":[{"border-s":R()}],"border-color-e":[{"border-e":R()}],"border-color-t":[{"border-t":R()}],"border-color-r":[{"border-r":R()}],"border-color-b":[{"border-b":R()}],"border-color-l":[{"border-l":R()}],"divide-color":[{divide:R()}],"outline-style":[{outline:[...Q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ue,Z,Y]}],"outline-w":[{outline:["",ue,Yr,go]}],"outline-color":[{outline:R()}],shadow:[{shadow:["","none",f,Ds,Es]}],"shadow-color":[{shadow:R()}],"inset-shadow":[{"inset-shadow":["none",d,Ds,Es]}],"inset-shadow-color":[{"inset-shadow":R()}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:R()}],"ring-offset-w":[{"ring-offset":[ue,go]}],"ring-offset-color":[{"ring-offset":R()}],"inset-ring-w":[{"inset-ring":_()}],"inset-ring-color":[{"inset-ring":R()}],"text-shadow":[{"text-shadow":["none",l,Ds,Es]}],"text-shadow-color":[{"text-shadow":R()}],opacity:[{opacity:[ue,Z,Y]}],"mix-blend":[{"mix-blend":[...re(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":re()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ue]}],"mask-image-linear-from-pos":[{"mask-linear-from":j()}],"mask-image-linear-to-pos":[{"mask-linear-to":j()}],"mask-image-linear-from-color":[{"mask-linear-from":R()}],"mask-image-linear-to-color":[{"mask-linear-to":R()}],"mask-image-t-from-pos":[{"mask-t-from":j()}],"mask-image-t-to-pos":[{"mask-t-to":j()}],"mask-image-t-from-color":[{"mask-t-from":R()}],"mask-image-t-to-color":[{"mask-t-to":R()}],"mask-image-r-from-pos":[{"mask-r-from":j()}],"mask-image-r-to-pos":[{"mask-r-to":j()}],"mask-image-r-from-color":[{"mask-r-from":R()}],"mask-image-r-to-color":[{"mask-r-to":R()}],"mask-image-b-from-pos":[{"mask-b-from":j()}],"mask-image-b-to-pos":[{"mask-b-to":j()}],"mask-image-b-from-color":[{"mask-b-from":R()}],"mask-image-b-to-color":[{"mask-b-to":R()}],"mask-image-l-from-pos":[{"mask-l-from":j()}],"mask-image-l-to-pos":[{"mask-l-to":j()}],"mask-image-l-from-color":[{"mask-l-from":R()}],"mask-image-l-to-color":[{"mask-l-to":R()}],"mask-image-x-from-pos":[{"mask-x-from":j()}],"mask-image-x-to-pos":[{"mask-x-to":j()}],"mask-image-x-from-color":[{"mask-x-from":R()}],"mask-image-x-to-color":[{"mask-x-to":R()}],"mask-image-y-from-pos":[{"mask-y-from":j()}],"mask-image-y-to-pos":[{"mask-y-to":j()}],"mask-image-y-from-color":[{"mask-y-from":R()}],"mask-image-y-to-color":[{"mask-y-to":R()}],"mask-image-radial":[{"mask-radial":[Z,Y]}],"mask-image-radial-from-pos":[{"mask-radial-from":j()}],"mask-image-radial-to-pos":[{"mask-radial-to":j()}],"mask-image-radial-from-color":[{"mask-radial-from":R()}],"mask-image-radial-to-color":[{"mask-radial-to":R()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":C()}],"mask-image-conic-pos":[{"mask-conic":[ue]}],"mask-image-conic-from-pos":[{"mask-conic-from":j()}],"mask-image-conic-to-pos":[{"mask-conic-to":j()}],"mask-image-conic-from-color":[{"mask-conic-from":R()}],"mask-image-conic-to-color":[{"mask-conic-to":R()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:ne()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Z,Y]}],filter:[{filter:["","none",Z,Y]}],blur:[{blur:pe()}],brightness:[{brightness:[ue,Z,Y]}],contrast:[{contrast:[ue,Z,Y]}],"drop-shadow":[{"drop-shadow":["","none",m,Ds,Es]}],"drop-shadow-color":[{"drop-shadow":R()}],grayscale:[{grayscale:["",ue,Z,Y]}],"hue-rotate":[{"hue-rotate":[ue,Z,Y]}],invert:[{invert:["",ue,Z,Y]}],saturate:[{saturate:[ue,Z,Y]}],sepia:[{sepia:["",ue,Z,Y]}],"backdrop-filter":[{"backdrop-filter":["","none",Z,Y]}],"backdrop-blur":[{"backdrop-blur":pe()}],"backdrop-brightness":[{"backdrop-brightness":[ue,Z,Y]}],"backdrop-contrast":[{"backdrop-contrast":[ue,Z,Y]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ue,Z,Y]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ue,Z,Y]}],"backdrop-invert":[{"backdrop-invert":["",ue,Z,Y]}],"backdrop-opacity":[{"backdrop-opacity":[ue,Z,Y]}],"backdrop-saturate":[{"backdrop-saturate":[ue,Z,Y]}],"backdrop-sepia":[{"backdrop-sepia":["",ue,Z,Y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":x()}],"border-spacing-x":[{"border-spacing-x":x()}],"border-spacing-y":[{"border-spacing-y":x()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Z,Y]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ue,"initial",Z,Y]}],ease:[{ease:["linear","initial",y,Z,Y]}],delay:[{delay:[ue,Z,Y]}],animate:[{animate:["none",b,Z,Y]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,Z,Y]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:ge()}],"rotate-x":[{"rotate-x":ge()}],"rotate-y":[{"rotate-y":ge()}],"rotate-z":[{"rotate-z":ge()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":["scale-3d"],skew:[{skew:ye()}],"skew-x":[{"skew-x":ye()}],"skew-y":[{"skew-y":ye()}],transform:[{transform:[Z,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:we()}],"translate-x":[{"translate-x":we()}],"translate-y":[{"translate-y":we()}],"translate-z":[{"translate-z":we()}],"translate-none":["translate-none"],accent:[{accent:R()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:R()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Z,Y]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":x()}],"scroll-mx":[{"scroll-mx":x()}],"scroll-my":[{"scroll-my":x()}],"scroll-ms":[{"scroll-ms":x()}],"scroll-me":[{"scroll-me":x()}],"scroll-mt":[{"scroll-mt":x()}],"scroll-mr":[{"scroll-mr":x()}],"scroll-mb":[{"scroll-mb":x()}],"scroll-ml":[{"scroll-ml":x()}],"scroll-p":[{"scroll-p":x()}],"scroll-px":[{"scroll-px":x()}],"scroll-py":[{"scroll-py":x()}],"scroll-ps":[{"scroll-ps":x()}],"scroll-pe":[{"scroll-pe":x()}],"scroll-pt":[{"scroll-pt":x()}],"scroll-pr":[{"scroll-pr":x()}],"scroll-pb":[{"scroll-pb":x()}],"scroll-pl":[{"scroll-pl":x()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Z,Y]}],fill:[{fill:["none",...R()]}],"stroke-w":[{stroke:[ue,Yr,go,_l]}],stroke:[{stroke:["none",...R()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var Hf=By(tw);function za(...e){return Hf(Ps(e))}var ow=Le.createContext({size:"default",variant:"default",spacing:0});function Wa({className:e,variant:o,size:t,spacing:a=1,children:n,...r}){return jsx(yf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:za("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(ow.Provider,{value:{variant:o,size:t,spacing:a},children:n})})}var nw={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Uf=createSlice({name:"toolbar",initialState:nw,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:aa,setPenColor:ma,setStrokeWidth:Zr,setFontSize:zD,setFontFamily:WD,setFontStyle:UD,setFontWeight:KD,setTextDecoration:GD,setTextColor:jD}=Uf.actions,Yl=Uf.reducer;var Gf=e=>jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",...e,children:jsx("ellipse",{cx:"12",cy:"12",rx:"10.5",ry:"7.5"})});var _f=e=>jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",...e,children:[jsx("circle",{cx:"12",cy:"12",r:"10",fill:"currentColor"}),jsx("circle",{cx:"12",cy:"12",r:"6",fill:"white"})]});var Rs=({onClose:e,onRecordingComplete:o})=>{let t=ze(),[a,n]=useState(false),[r,s]=useState(null),[u,i]=useState(0),[c,f]=useState(null),[d,l]=useState(false),m=useRef(null),h=useRef([]),p=useRef(null),v=useRef(null),y=useRef(null);useEffect(()=>((async()=>{try{let S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});f(S),l(!0),y.current&&(y.current.srcObject=S);}catch(S){console.error("Error accessing camera:",S),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),c&&c.getTracks().forEach(S=>S.stop());}),[]);let b=()=>{c&&(c.getTracks().forEach(x=>x.stop()),f(null),l(false));},g=async()=>{try{let x=null,S=null;try{x=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(F){console.error("Error accessing camera for recording:",F),alert("Failed to access camera for recording.");return}try{S=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(F){console.warn("Microphone access denied:",F);}let w=[...x.getVideoTracks()];S&&w.push(...S.getAudioTracks());let T=new MediaStream(w),q="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?q="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?q="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?q="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(q="video/webm;codecs=vp8");let H=new MediaRecorder(T,{mimeType:q,videoBitsPerSecond:25e5});m.current=H,h.current=[],H.ondataavailable=F=>{F.data.size>0&&h.current.push(F.data);},H.onstop=()=>{let F=new Blob(h.current,{type:q}),V=document.createElement("video");V.src=URL.createObjectURL(F),V.muted=!0,V.currentTime=.1,V.onseeked=()=>{let U=document.createElement("canvas");U.width=V.videoWidth,U.height=V.videoHeight;let K=U.getContext("2d");K&&(K.drawImage(V,0,0),v.current=U.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(V.src);},T.getTracks().forEach(U=>U.stop()),x&&x.getTracks().forEach(U=>U.stop()),S&&S.getTracks().forEach(U=>U.stop()),p.current&&clearInterval(p.current),s(F),b();},H.onerror=F=>{console.error("MediaRecorder error:",F);},H.start(1e3),n(!0),i(0),p.current=setInterval(()=>{i(F=>F+1);},1e3);}catch(x){console.error("Error starting camera recording:",x),alert("Failed to start recording. Please check permissions.");}},C=()=>{m.current&&a&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),n(false));},I=()=>{if(r){let x=URL.createObjectURL(r),S=document.createElement("a");S.href=x,S.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(S),S.click(),document.body.removeChild(S),URL.revokeObjectURL(x);}},B=x=>{let S=Math.floor(x/60),w=x%60;return `${S.toString().padStart(2,"0")}:${w.toString().padStart(2,"0")}`};if(!t)return null;let k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:x=>{x.target===x.currentTarget&&e(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:x=>x.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:y,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:g,disabled:!d,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!d&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:C,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:B(u)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",B(u)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{s(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&v.current&&(o(r,v.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(k,t)};var pa=40,Xf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,n]=useState(t?.images||[]),[r,s]=useState(t?.order||"sequential"),[u,i]=useState(false),c=useRef(null),f=ze(),d=useRef(null);useEffect(()=>{let g=C=>{C.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let l=g=>{let C=g.target.files;if(!C||C.length===0)return;let I=pa-a.length;if(I<=0){alert(`You can only upload a maximum of ${pa} images`);return}let B=Array.from(C).slice(0,I);B.length<C.length&&alert(`Only ${I} more images can be added (max ${pa} total)`);let k=B.map(x=>new Promise((S,w)=>{let T=new FileReader;T.onload=q=>{q.target?.result?S(q.target.result):w(new Error("Failed to read file"));},T.onerror=w,T.readAsDataURL(x);}));Promise.all(k).then(x=>{n(S=>[...S,...x]),d.current&&(d.current.value="");});},m=g=>{g.preventDefault(),i(false);let C=Array.from(g.dataTransfer.files).filter(x=>x.type.startsWith("image/"));if(C.length===0)return;let I=pa-a.length;if(I<=0){alert(`You can only upload a maximum of ${pa} images`);return}let B=C.slice(0,I);B.length<C.length&&alert(`Only ${I} more images can be added (max ${pa} total)`);let k=B.map(x=>new Promise((S,w)=>{let T=new FileReader;T.onload=q=>{q.target?.result?S(q.target.result):w(new Error("Failed to read file"));},T.onerror=w,T.readAsDataURL(x);}));Promise.all(k).then(x=>{n(S=>[...S,...x]);});},h=g=>{g.preventDefault(),i(true);},p=()=>{i(false);},v=g=>{n(C=>C.filter((I,B)=>B!==g));},y=g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!f)return null;let b=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:y,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=pa?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",pa," images"]}):jsxs("span",{children:[a.length,"/",pa," images"]})})]}),jsx("input",{ref:d,type:"file",accept:"image/*",multiple:true,onChange:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:h,onDragLeave:p,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>s("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>s("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,C)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${C+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(C),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:C+1})]},C))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(b,f)};var Fs={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},Sw={enabled:true};function Ql(e){return e?{tools:{...Fs.tools,...e.tools},actions:{...Fs.actions,...e.actions}}:Fs}var Lw={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Iw={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};function ed(e,[o,t]){return Math.min(t,Math.max(o,e))}function Yf(e){let o=Le.useRef({value:e,previous:e});return Le.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Jf(e){let[o,t]=Le.useState(void 0);return Zo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(n=>{if(!Array.isArray(n)||!n.length)return;let r=n[0],s,u;if("borderBoxSize"in r){let i=r.borderBoxSize,c=Array.isArray(i)?i[0]:i;s=c.inlineSize,u=c.blockSize;}else s=e.offsetWidth,u=e.offsetHeight;t({width:s,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var Qf=["PageUp","PageDown"],em=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],tm={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},or="Slider",[td,kw,Tw]=ks(or),[am]=Ha(or,[Tw]),[Mw,Os]=am(or),om=Le.forwardRef((e,o)=>{let{name:t,min:a=0,max:n=100,step:r=1,orientation:s="horizontal",disabled:u=false,minStepsBetweenThumbs:i=0,defaultValue:c=[a],value:f,onValueChange:d=()=>{},onValueCommit:l=()=>{},inverted:m=false,form:h,...p}=e,v=Le.useRef(new Set),y=Le.useRef(0),g=s==="horizontal"?Aw:Pw,[C=[],I]=ca({prop:f,defaultProp:c,onChange:T=>{[...v.current][y.current]?.focus(),d(T);}}),B=Le.useRef(C);function k(T){let q=Bw(C,T);w(T,q);}function x(T){w(T,y.current);}function S(){let T=B.current[y.current];C[y.current]!==T&&l(C);}function w(T,q,{commit:H}={commit:false}){let F=qw(r),V=Vw(Math.round((T-a)/r)*r+a,F),U=ed(V,[a,n]);I((K=[])=>{let R=Rw(K,U,q);if(Hw(R,i*r)){y.current=R.indexOf(U);let z=String(R)!==String(K);return z&&H&&l(R),z?R:K}else return K});}return jsx(Mw,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:n,valueIndexToChangeRef:y,thumbs:v.current,values:C,orientation:s,form:h,children:jsx(td.Provider,{scope:e.__scopeSlider,children:jsx(td.Slot,{scope:e.__scopeSlider,children:jsx(g,{"aria-disabled":u,"data-disabled":u?"":void 0,...p,ref:o,onPointerDown:nt(p.onPointerDown,()=>{u||(B.current=C);}),min:a,max:n,inverted:m,onSlideStart:u?void 0:k,onSlideMove:u?void 0:x,onSlideEnd:u?void 0:S,onHomeKeyDown:()=>!u&&w(a,0,{commit:true}),onEndKeyDown:()=>!u&&w(n,C.length-1,{commit:true}),onStepKeyDown:({event:T,direction:q})=>{if(!u){let V=Qf.includes(T.key)||T.shiftKey&&em.includes(T.key)?10:1,U=y.current,K=C[U],R=r*V*q;w(K+R,U,{commit:true});}}})})})})});om.displayName=or;var[rm,nm]=am(or,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Aw=Le.forwardRef((e,o)=>{let{min:t,max:a,dir:n,inverted:r,onSlideStart:s,onSlideMove:u,onSlideEnd:i,onStepKeyDown:c,...f}=e,[d,l]=Le.useState(null),m=Ut(o,g=>l(g)),h=Le.useRef(void 0),p=Qo(n),v=p==="ltr",y=v&&!r||!v&&r;function b(g){let C=h.current||d.getBoundingClientRect(),I=[0,C.width],k=rd(I,y?[t,a]:[a,t]);return h.current=C,k(g-C.left)}return jsx(rm,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx(sm,{dir:p,"data-orientation":"horizontal",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:g=>{let C=b(g.clientX);s?.(C);},onSlideMove:g=>{let C=b(g.clientX);u?.(C);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:g=>{let I=tm[y?"from-left":"from-right"].includes(g.key);c?.({event:g,direction:I?-1:1});}})})}),Pw=Le.forwardRef((e,o)=>{let{min:t,max:a,inverted:n,onSlideStart:r,onSlideMove:s,onSlideEnd:u,onStepKeyDown:i,...c}=e,f=Le.useRef(null),d=Ut(o,f),l=Le.useRef(void 0),m=!n;function h(p){let v=l.current||f.current.getBoundingClientRect(),y=[0,v.height],g=rd(y,m?[a,t]:[t,a]);return l.current=v,g(p-v.top)}return jsx(rm,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:jsx(sm,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:p=>{let v=h(p.clientY);r?.(v);},onSlideMove:p=>{let v=h(p.clientY);s?.(v);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:p=>{let y=tm[m?"from-bottom":"from-top"].includes(p.key);i?.({event:p,direction:y?-1:1});}})})}),sm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:n,onSlideEnd:r,onHomeKeyDown:s,onEndKeyDown:u,onStepKeyDown:i,...c}=e,f=Os(or,t);return jsx(yt.span,{...c,ref:o,onKeyDown:nt(e.onKeyDown,d=>{d.key==="Home"?(s(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):Qf.concat(em).includes(d.key)&&(i(d),d.preventDefault());}),onPointerDown:nt(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),f.thumbs.has(l)?l.focus():a(d);}),onPointerMove:nt(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&n(d);}),onPointerUp:nt(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),r(d));})})}),im="SliderTrack",lm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Os(im,t);return jsx(yt.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...a,ref:o})});lm.displayName=im;var ad="SliderRange",dm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Os(ad,t),r=nm(ad,t),s=Le.useRef(null),u=Ut(o,s),i=n.values.length,c=n.values.map(l=>fm(l,n.min,n.max)),f=i>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(yt.span,{"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,...a,ref:u,style:{...e.style,[r.startEdge]:f+"%",[r.endEdge]:d+"%"}})});dm.displayName=ad;var od="SliderThumb",um=Le.forwardRef((e,o)=>{let t=kw(e.__scopeSlider),[a,n]=Le.useState(null),r=Ut(o,u=>n(u)),s=Le.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(Ew,{...e,ref:r,index:s})}),Ew=Le.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:n,...r}=e,s=Os(od,t),u=nm(od,t),[i,c]=Le.useState(null),f=Ut(o,b=>c(b)),d=i?s.form||!!i.closest("form"):true,l=Jf(i),m=s.values[a],h=m===void 0?0:fm(m,s.min,s.max),p=Fw(a,s.values.length),v=l?.[u.size],y=v?Ow(v,h,u.direction):0;return Le.useEffect(()=>{if(i)return s.thumbs.add(i),()=>{s.thumbs.delete(i);}},[i,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${y}px)`},children:[jsx(td.ItemSlot,{scope:e.__scopeSlider,children:jsx(yt.span,{role:"slider","aria-label":e["aria-label"]||p,"aria-valuemin":s.min,"aria-valuenow":m,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...r,ref:f,style:m===void 0?{display:"none"}:e.style,onFocus:nt(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),d&&jsx(cm,{name:n??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:m},a)]})});um.displayName=od;var Dw="RadioBubbleInput",cm=Le.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let n=Le.useRef(null),r=Ut(n,a),s=Yf(o);return Le.useEffect(()=>{let u=n.current;if(!u)return;let i=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==o&&f){let d=new Event("input",{bubbles:true});f.call(u,o),u.dispatchEvent(d);}},[s,o]),jsx(yt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});cm.displayName=Dw;function Rw(e=[],o,t){let a=[...e];return a[t]=o,a.sort((n,r)=>n-r)}function fm(e,o,t){let r=100/(t-o)*(e-o);return ed(r,[0,100])}function Fw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Bw(e,o){if(e.length===1)return 0;let t=e.map(n=>Math.abs(n-o)),a=Math.min(...t);return t.indexOf(a)}function Ow(e,o,t){let a=e/2,r=rd([0,50],[0,a]);return (a-r(o)*t)*t}function Nw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Hw(e,o){if(o>0){let t=Nw(e);return Math.min(...t)>=o}return true}function rd(e,o){return t=>{if(e[0]===e[1]||o[0]===o[1])return o[0];let a=(o[1]-o[0])/(e[1]-e[0]);return o[0]+a*(t-e[0])}}function qw(e){return (String(e).split(".")[1]||"").length}function Vw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var mm=om,pm=lm,hm=dm,gm=um;function Ns({className:e,defaultValue:o,value:t,min:a=0,max:n=100,rangeClassName:r,trackClassName:s,thumbClassName:u,...i}){let c=Le.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,n],[t,o,a,n]);return jsxs(mm,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:n,className:za("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[jsx(pm,{"data-slot":"slider-track",className:za("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",s),children:jsx(hm,{"data-slot":"slider-range",className:za("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(f,d)=>jsx(gm,{"data-slot":"slider-thumb",className:za("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",u)},d))]})}var gS=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a,onVisibilityChange:n}={})=>{let r=Se(),s=J(A=>A.canvas.slides.find(te=>te.id===A.canvas.currentSlideId)),u=s?.videos||[],i=s?.editingFlashcard,c=J(A=>A.toolbar.selectedTool),f=J(A=>A.toolbar.penColor),d=J(A=>A.toolbar.strokeWidth),l=J(A=>A.canvas.editingOverlayPosition),m=s?.showMcqForm,h=s?.showFlashcardForm,p=useRef(null);useEffect(()=>{let A=te=>{(te.ctrlKey||te.metaKey)&&te.key==="z"&&!te.shiftKey&&(te.preventDefault(),r(Mo())),(te.ctrlKey&&te.shiftKey&&te.key==="Z"||te.ctrlKey&&te.key==="y")&&(te.preventDefault(),r(Ao()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[r]);let v=useMemo(()=>Ql(a),[a]),{tools:y,actions:b}=v,g=u.some(A=>A.isRecorded&&A.isPlaying),C=J(A=>A.toolbar.fontSize),I=J(A=>A.toolbar.fontFamily),B=J(A=>A.toolbar.fontStyle),k=J(A=>A.toolbar.fontWeight),x=J(A=>A.toolbar.textDecoration),S=J(A=>A.toolbar.textColor),[w,T]=useState(false),[q,H]=useState(false),[F,V]=useState(false),[U,K]=useState(false),[R,z]=useState(false),[ne,X]=useState(false),[P,N]=useState(false),[_,Q]=useState(false),[re,j]=useState(true),pe=useRef(null),ge=useRef(null),le=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],ye=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"style",icon:Palette,label:"Style",configKey:"style"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),we=useMemo(()=>[{name:"rectangle",icon:Square,label:"Square"},{name:"rectangle",icon:Rectangle,label:"Rectangle"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Gf,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:_f,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),xe=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),St=useMemo(()=>ye.filter(A=>{let te=y[A.configKey];return typeof te=="boolean"?te:Array.isArray(te)?te.length>0:true}),[y,ye]),ae=useMemo(()=>{let A=y.shapes;return A===false?[]:A===true?we:Array.isArray(A)?we.filter(te=>A.includes(te.name)):we},[y.shapes,we]),rn=useMemo(()=>{let A=y.activities;return A===false?[]:A===true?xe:Array.isArray(A)?xe.filter(te=>A.includes(te.name)):xe},[y.activities,xe]),yo=useMemo(()=>{let A=y.media;return A===false?{photoFrame:false,image:false,video:false}:A===true?{photoFrame:true,image:true,video:true}:Array.isArray(A)?{photoFrame:A.includes("photo-frame"),image:A.includes("image"),video:A.includes("video")}:{photoFrame:true,image:true,video:true}},[y.media]),nn=useMemo(()=>{let A=y.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[y.activities]),sn=A=>{let te=A.target.files;!te||te.length===0||(r(aa("select")),r(It(false)),K(false),Array.from(te).forEach(ke=>{let Ie=new FileReader;Ie.onload=ce=>{let se=new window.Image;se.src=ce.target?.result,se.onload=()=>{let Ee=se.width/se.height,it=300,ra=300,Ye=se.width,Oe=se.height;Ye>it&&(Ye=it,Oe=Ye/Ee),Oe>ra&&(Oe=ra,Ye=Oe*Ee),r(de());let lt=l?.left||800-Ye/2,na=l?.top||450-Oe/2;r(li({id:v4(),src:se.src,x:lt,y:na,width:Ye,height:Oe,draggable:true,rotation:0}));};},Ie.readAsDataURL(ke);}),A.target.value="");},ln=async A=>{let te=A.target.files;if(!(!te||te.length===0)){console.log("files",A),r(aa("select")),r(It(false)),K(false);for(let ke of Array.from(te))try{let Ie=URL.createObjectURL(ke),ce=document.createElement("video");console.log("video",ce),ce.src=Ie,ce.muted=!0,ce.playsInline=!0,ce.preload="auto",ce.load(),await new Promise((Ze,ya)=>{let Jt=setTimeout(()=>ya(new Error("Metadata load timeout")),1e4);ce.onloadedmetadata=()=>{clearTimeout(Jt),Ze();},ce.onerror=()=>{clearTimeout(Jt),ya(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ce.duration,width:ce.videoWidth,height:ce.videoHeight}),await new Promise((Ze,ya)=>{let Jt=setTimeout(()=>ya(new Error("Video load timeout")),1e4);ce.readyState>=2?(clearTimeout(Jt),Ze()):ce.onloadeddata=()=>{clearTimeout(Jt),Ze();};});let se=Math.min(.8,ce.duration/2);console.log("Seeking to:",se),ce.currentTime=se,await new Promise(Ze=>{let ya=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ze();},5e3);ce.onseeked=()=>{clearTimeout(ya),console.log("Seek completed"),Ze();};});let Ee=document.createElement("canvas"),it=ce.videoWidth/ce.videoHeight,ra=400,Ye=400,Oe=ce.videoWidth,lt=ce.videoHeight;Oe>ra&&(Oe=ra,lt=Oe/it),lt>Ye&&(lt=Ye,Oe=lt*it),Ee.width=Oe,Ee.height=lt;let na=Ee.getContext("2d",{willReadFrequently:!1});if(!na)throw new Error("Failed to get canvas context");if(await new Promise(Ze=>setTimeout(Ze,100)),ce.videoWidth===0||ce.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Oe,height:lt}),na.drawImage(ce,0,0,Oe,lt);let va=Ee.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",va.length),r(de());let Js=800-Oe/2,So=450-lt/2,ie=v4();await da(ie,ke,va),r(ko({id:ie,objectUrl:Ie,thumbnailDataUrl:va,videoBlob:ke,x:Js,y:So,width:Oe,height:lt,draggable:!0,isPlaying:!1,rotation:0})),ce.src="",ce.load(),console.log(`Video uploaded: ${ke.name}`);}catch(Ie){console.error("Error processing video:",Ie),alert(`Failed to process video: ${ke.name}`);}A.target.value="";}},dn=(A,te,ke)=>{r(de()),r(aa("select")),r(It(false));let Ie=300,ce=300,se=800-Ie/2,Ee=450-ce/2;r(ke?To({id:ke,images:A,order:te,x:se,y:Ee,width:Ie,height:ce,rotation:0,draggable:true}):ci({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:te,x:se,y:Ee,width:Ie,height:ce,rotation:0,draggable:true})),r(Qa(false));},Ks=()=>{r(de()),r(aa("select")),r(It(false));let A=400,te=300,ke=800-A/2,Ie=450-te/2;r(pi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ke,y:Ie,width:A,height:te,rotation:0,draggable:true,isCapturing:false})),K(false);},Gs=A=>{let se={};switch(A.name){case "rectangle":A.label==="Rectangle"?(se.width=120,se.height=80):(se.width=100,se.height=100);break;case "circle":case "ring":case "wedge":case "arc":se.radius=50,(A.name==="ring"||A.name==="arc")&&(se.innerRadius=25,se.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(se.angle=A.name==="wedge"?60:90);break;case "ellipse":se.radiusX=60,se.radiusY=40;break;case "triangle":se.radius=50,se.sides=3;break;case "polygon":se.radius=50,se.sides=6;break;case "star":se.innerRadius=25,se.outerRadius=50,se.numPoints=5;break;case "arrow":case "line":se.points=[0,0,100,0],A.name==="arrow"&&(se.pointerLength=10,se.pointerWidth=10);break}let Ee={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:f,...se};r(de()),r(It(false)),r(aa(A.name)),r(di(Ee)),V(false);},Ga=A=>{if(r(aa(A)),A==="select")r(It(false));else if(A==="text"){r(It(false)),r(de());let te=200,ke=50,Ie=800-te/2,ce=450-ke/2,Ee=window.innerWidth<768?Math.max(C,32):C,it=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(ui({id:it,text:"",x:Ie,y:ce,width:te,height:ke,rotation:0,draggable:true,fontSize:Ee,fontFamily:I,fontStyle:B,fontWeight:k,textDecoration:x,fill:S,align:"left"})),setTimeout(()=>{r(vr(it));},100),t&&t(it);}else r(It(true));},js=()=>{r(br()),r(It(false));},_s=()=>{e?e():o?T(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},ja=()=>{H(true);},$s=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:Ks,enabled:yo.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>pe.current?.click(),enabled:yo.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>ge.current?.click(),enabled:yo.video}],un=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Mo()),enabled:b.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(Ao()),enabled:b.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:_s,enabled:b.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:ja,enabled:b.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:js,enabled:b.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],_a=async(A,te)=>{try{r(aa("select")),r(It(!1));let ke=URL.createObjectURL(A),Ie=document.createElement("video");Ie.src=ke,Ie.muted=!0,Ie.playsInline=!0,Ie.preload="auto",await new Promise((lt,na)=>{let va=setTimeout(()=>na(new Error("Metadata load timeout")),1e4);Ie.onloadedmetadata=()=>{clearTimeout(va),lt();},Ie.onerror=()=>{clearTimeout(va),na(new Error("Failed to load video"));};});let ce=640,se=Ie.videoWidth/Ie.videoHeight,Ee=ce,it=Ee/se;r(de());let ra=800-Ee/2,Ye=450-it/2,Oe=v4();await da(Oe,A,te),r(ko({id:Oe,objectUrl:ke,thumbnailDataUrl:te,videoBlob:A,x:ra,y:Ye,width:Ee,height:it,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),T(!1),H(!1);}catch(ke){console.error("Error adding recorded video to canvas:",ke),alert("Failed to add video to canvas. Please try again.");}},cn=A=>{r(aa("select")),r(It(false)),r(gr(null)),A&&r(Ci(A)),r(La(!m)),z(false);},Xs=()=>{r(hr(null)),r(Qa(true)),z(false);},ir=()=>{V(!F);},wo=()=>{K(!U);},fn=()=>{z(!R);},Ys=()=>{X(!ne);},Zs=()=>{let A=!re;A||(V(false),K(false),z(false),X(false),Q(false),N(false)),j(A),n?.(A);};return useEffect(()=>{if(!_)return;let A=te=>{p.current&&!p.current.contains(te.target)&&Q(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[_]),g?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:Zs,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:re?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),re&&jsxs("div",{className:"fixed scrollbar-hide top-[168px] bottom-4 left-4 z-50 flex flex-col gap-4 overflow-y-auto",children:[jsxs("div",{className:"flex items-center",children:[jsx(Wa,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:St.map((A,te)=>jsx("div",{title:A.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.name===c?"bg-primary/10":A.name==="style"?"md:hidden":""}`,onClick:()=>{A.name==="image"?(wo(),V(false),z(false),X(false),Ga(A.name)):A.name==="shapes"?(ir(),K(false),z(false),X(false),Ga(A.name)):A.name==="activities"?(Ga(A.name),fn(),V(false),K(false),X(false)):A.name==="style"?(Ys(),V(false),K(false),z(false),Ga(A.name)):(Ga(A.name),V(false),K(false),z(false),X(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},te))}),F&&jsx(Wa,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:ae.map((A,te)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Gs(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},te))}),U&&jsx(Wa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:$s.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),R&&jsxs(Wa,{type:"single",className:"mx-1 mt-auto mb-10 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl lg:mb-11",children:[nn&&jsx("div",{title:"Flashcard",onClick:()=>Xs(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),rn.map((A,te)=>jsx("div",{title:A.label,onClick:()=>cn(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},te))]}),ne&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Ns,{value:[d],onValueChange:A=>{r(Zr(A[0]));},max:28,min:6,step:1,className:"w-28",rangeClassName:"bg-gray-300",thumbClassName:"bg-gray-600 border-none h-4 w-4"}),jsx("div",{className:"h-5 w-5 rounded-full bg-gray-800"})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"COLOR"}),jsxs("div",{className:"flex flex-wrap gap-1",children:[le.map(A=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${f===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{r(ma(A.value)),X(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:f,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>r(ma(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:f,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{r(pr(A.target.value)),X(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),un.some(A=>A.enabled)&&jsx(Wa,{type:"single",className:"hidden flex-col border bg-white p-1 shadow-xl md:flex",children:un.filter(A=>A.enabled).map(A=>jsx("button",{onClick:A.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.colorClass}`,title:A.title,children:jsx(A.icon,{weight:A.iconWeight,className:"text-lg md:text-xl"})},A.key))})]}),jsx("input",{ref:pe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:sn}),jsx("input",{ref:ge,type:"file",accept:"video/*",className:"hidden",onChange:ln}),!e&&w&&o&&jsx(eo,{onClose:()=>T(false),stageRef:o,onRecordingComplete:_a}),q&&jsx(Rs,{onClose:()=>H(false),onRecordingComplete:_a}),h&&jsx(Xf,{editingFlashcard:i,onConfirm:dn,onCancel:()=>r(Qa(false))}),P&&jsx(es,{defaultColor:f,onConfirm:A=>{r(ma(A)),N(false);},onCancel:()=>N(false)})]})},xS=gS;var dd=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let n=Re(Ca),r=Re(Fi),s=a?r:n,u=Re(wr),f=(Re(b=>b.canvas.slides.find(g=>g.id===b.canvas.currentSlideId))?.videos||[]).some(b=>b.isRecorded&&b.isPlaying),[d,l]=useState(false),[m,h]=useState(null),[p,v]=useState(null),y=async()=>{if(n.length===0){v({type:"error",message:"No slides to publish"});return}if(!e){v({type:"error",message:"No publish handler provided"});return}l(true),v(null);try{let b=await e(s,u,g=>{h(g);});b.success?v({type:"success",message:b.message}):v({type:"error",message:b.message});}catch(b){v({type:"error",message:b instanceof Error?b.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),v(null);},3e3);}console.log("For checking>>>>>>>>>>>",s,"<<<<<<<<<<<<<");};return f?null:jsxs("button",{onClick:y,disabled:d||n.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var SS=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:n,onDescriptionChange:r,showPublishButton:s=true,showBackButton:u=true,editableTitle:i=true,editableDescription:c=true,className:f="",rightContent:d,leftContent:l,includeInactiveSlides:m=false})=>{let h=_e(),p=Re(wr),v=Re(Bi),y=e??(v?p.title:"")??"Untitled",b=o??(v?p.description:"")??"Add a description...",[g,C]=useState(false),[I,B]=useState(false),[k,x]=useState(y),[S,w]=useState(b),T=useRef(null),q=useRef(null);useEffect(()=>{x(y);},[y]),useEffect(()=>{w(b);},[b]),useEffect(()=>{g&&T.current&&(T.current.focus(),T.current.select());},[g]),useEffect(()=>{I&&q.current&&(q.current.focus(),q.current.select());},[I]);let H=()=>{i&&C(true);},F=()=>{c&&B(true);},V=()=>{C(false),k.trim()&&k!==y?n?n(k.trim()):h(Ei(k.trim())):k.trim()||x(y);},U=()=>{B(false),S.trim()&&S!==b?r?r(S.trim()):h(Di(S.trim())):S.trim()||w(b);},K=z=>{z.key==="Enter"?V():z.key==="Escape"&&(x(y),C(false));},R=z=>{z.key==="Enter"?U():z.key==="Escape"&&(w(b),B(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${f}`,children:[l||jsxs("div",{className:"flex items-center gap-4",children:[u&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[g?jsx("input",{ref:T,type:"text",value:k,onChange:z=>x(z.target.value),onBlur:V,onKeyDown:K,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:H,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${i?"hover:border-primary cursor-text":""}`,children:k}),I?jsx("input",{ref:q,type:"text",value:S,onChange:z=>w(z.target.value),onBlur:U,onKeyDown:R,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:F,title:S,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${c?"hover:border-primary cursor-text":""}`,children:S})]})]}),d||s&&a&&jsx(dd,{onPublish:a,includeInactiveSlides:m})]})};var MS=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],AS=({colors:e=MS,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:n=""})=>{let[r,s]=useState(true),u=J(ve),i=J(l=>l.toolbar.penColor),c=J(l=>l.toolbar.strokeWidth),f=u?.backgroundColor,d=Se();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:r?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-16 left-1/2 z-50 hidden w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-3 shadow-2xl md:bottom-6 md:flex md:p-5 2xl:px-8 2xl:py-6 ${n}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-black md:h-3 md:w-3"}),jsx(Ns,{defaultValue:[20],max:36,min:8,step:2,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:l=>d(Zr(l[0]))}),jsx("div",{className:"h-5 w-5 rounded-full bg-black md:h-7 md:w-7 lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"COLOR"}),jsxs(Wa,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${i===l.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:l.value},onClick:()=>d(ma(l.value))},l.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>d(ma("#2D2F50"))}),jsxs("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] md:h-10 md:w-10 lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(ma(l.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:f},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(pr(l.target.value))})})]})}),jsx("div",{className:"absolute -top-6 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2 md:-top-4",children:jsx("button",{onClick:()=>s(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{weight:"bold",className:"text-gray-600 md:text-xl"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>s(true),className:"fixed bottom-20 left-1/2 z-50 hidden -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl md:bottom-3 md:flex","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var Lm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),PS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),cd=e=>{let o=PS(e);return o.charAt(0).toUpperCase()+o.slice(1)},zs=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Im=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Cm={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var Tm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:n="",children:r,iconNode:s,...u},i)=>createElement("svg",{ref:i,...Cm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:zs("lucide",n),...!r&&!Im(u)&&{"aria-hidden":"true"},...u},[...s.map(([c,f])=>createElement(c,f)),...Array.isArray(r)?r:[r]]));var Ws=(e,o)=>{let t=forwardRef(({className:a,...n},r)=>createElement(Tm,{ref:r,iconNode:o,className:zs(`lucide-${Lm(cd(e))}`,`lucide-${e}`,a),...n}));return t.displayName=cd(e),t};var FS=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],en=Ws("copy",FS);var BS=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],tn=Ws("trash-2",BS);var Am=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:s})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:n,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(en,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),s();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(tn,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var qS=({softDelete:e=false})=>{let o=_e(),t=Re(Ca),a=Re(Ia),n=Re(yr),[r,s]=useState(true),c=(Re(h=>h.canvas.slides.find(p=>p.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),f=()=>{n&&o(ur());},d=h=>{o(mr(h));},l=h=>{o(fr(h));},m=h=>{t.length>1&&o(cr({id:h,softDelete:e}));};return c?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>s(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((h,p)=>jsx(Am,{slide:h,index:p,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>l(h.id),onDelete:()=>m(h.id)},h.id))}),jsxs("button",{onClick:f,disabled:!n,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${n?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>s(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var rr=20,$S=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:s})=>jsxs("div",{className:`relative h-[122px] w-[166px] shrink-0 cursor-pointer rounded-lg border bg-[#fafafa] transition-all ${t?"border-[#096b76]":"border-black/10"}`,onClick:n,children:[jsx("div",{className:"absolute top-1 right-1 bottom-1 left-1 overflow-hidden rounded bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"size-full object-contain"}):jsx("div",{className:"flex size-full items-center justify-center",children:jsx("span",{className:"text-xs text-black/20",children:"No preview"})})}),jsx("div",{className:"absolute top-3 left-3 flex h-5 w-5 items-center justify-center rounded-full bg-[#333c48]",children:jsx("span",{className:"text-xs font-bold text-white",children:o+1})}),jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"absolute top-3 right-3 flex cursor-pointer items-center justify-center rounded-md bg-[#3B75E0] p-1.5 text-white transition-colors hover:bg-[#2d5fc0]",title:"Duplicate Page",children:jsx(Copy,{size:18,weight:"bold"})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),s();},className:"absolute right-3 bottom-6 flex cursor-pointer items-center justify-center rounded-md bg-[#E53935] p-1.5 text-white transition-colors hover:bg-[#c62828]",title:"Delete Page",children:jsx(Trash,{size:18,weight:"bold"})}),jsxs("p",{className:"absolute bottom-2 left-3 text-sm text-black/40",children:["Page ",o+1]})]}),XS=({softDelete:e=false})=>{let o=_e(),t=Re(Ca),a=Re(Ia),n=Re(yr),[r,s]=useState(false),[u,i]=useState(false),[c,f]=useState(false),d=useRef(null),h=(Re(I=>I.canvas.slides.find(B=>B.id===I.canvas.currentSlideId))?.videos||[]).some(I=>I.isRecorded&&I.isPlaying),p=()=>{n&&t.length<rr&&o(ur());},v=I=>{o(mr(I));},y=I=>{t.length<rr&&o(fr(I));},b=I=>{t.length>1&&o(cr({id:I,softDelete:e}));},g=()=>{if(!d.current)return;let{scrollLeft:I,scrollWidth:B,clientWidth:k}=d.current,x=B>k+5;i(x&&I>5),f(x&&I<B-k-5);},C=I=>{if(!d.current)return;let B=177,k=I==="left"?d.current.scrollLeft-B:d.current.scrollLeft+B;d.current.scrollTo({left:k,behavior:"smooth"});};return useEffect(()=>{if(r){let I=setTimeout(()=>{requestAnimationFrame(()=>{g();});},350);return ()=>clearTimeout(I)}},[t,r]),useEffect(()=>{let I=d.current;if(!(!I||!r))return I.addEventListener("scroll",g),window.addEventListener("resize",g),()=>{I.removeEventListener("scroll",g),window.removeEventListener("resize",g);}},[r]),h?null:jsx("div",{className:"fixed bottom-0 left-1/2 z-50 flex w-full -translate-x-1/2 flex-col gap-4 md:hidden",children:jsxs(AnimatePresence,{mode:"wait",children:[r&&jsxs(motion.div,{initial:{y:230,opacity:0},animate:{y:0,opacity:1},exit:{y:230,opacity:0},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},onAnimationComplete:()=>g(),className:"border bg-white md:hidden",children:[jsxs("div",{className:"flex w-full items-center justify-between px-4 py-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Cards,{size:24,weight:"fill",className:"text-[#096b76]"}),jsx("span",{className:"text-base font-bold text-black/80",children:"Pages"}),jsxs("span",{className:"text-base font-bold text-black/80",children:["(",t.length,"/",rr,")"]})]}),jsx("button",{onClick:()=>s(false),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretDown,{size:16,weight:"bold",className:"text-black/60"})})]}),jsxs("div",{className:"relative",children:[u&&jsx("button",{onClick:()=>C("left"),className:"absolute top-1/2 left-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll left",children:jsx(CaretLeft,{size:20,weight:"bold",className:"text-black/80"})}),c&&jsx("button",{onClick:()=>C("right"),className:"absolute top-1/2 right-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll right",children:jsx(CaretRight,{size:20,weight:"bold",className:"text-black/80"})}),jsx("div",{ref:d,className:"scrollbar-hide flex gap-[11px] overflow-x-auto px-4 pb-4",children:t.map((I,B)=>jsx($S,{slide:I,index:B,isSelected:I.id===a,isSingleSlide:t.length===1,onSelect:()=>v(I.id),onDuplicate:()=>y(I.id),onDelete:()=>b(I.id)},I.id))})]}),jsx("button",{onClick:p,disabled:!n||t.length>=rr,className:`px-4 pb-4 text-base font-bold ${n&&t.length<rr?"cursor-pointer text-[#096b76]":"cursor-not-allowed text-black/30"}`,children:"+ Add Page"})]},"open"),!r&&jsxs(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{type:"tween",duration:.2},className:"flex cursor-pointer items-center justify-between gap-2 border border-black/10 bg-white px-4 py-3 shadow-lg md:hidden",children:[jsxs("div",{className:"flex gap-2",children:[jsx(Cards,{size:20,weight:"fill",className:"text-[#096b76]"}),jsxs("span",{className:"text-sm font-bold text-black/80",children:["Pages (",t.length,"/",rr,")"]})]}),jsx("button",{onClick:()=>s(true),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretUp,{size:16,weight:"bold",className:"text-black/60"})})]},"close")]})})},md=XS;var oL=({stageRef:e,onScreenRecord:o,visible:t=true,config:a={}})=>{let n=_e(),[r,s]=useState(false),[u,i]=useState(false),c=Re(C=>C.canvas.slides.find(I=>I.id===C.canvas.currentSlideId)),f=Re(C=>C.canvas.zoomLevel),l=(c?.videos||[]).some(C=>C.isRecorded&&C.isPlaying),m={undo:a.undo??true,redo:a.redo??true,screenRecord:a.screenRecord??true,cameraRecord:a.cameraRecord??true,clear:a.clear??true,zoomOut:a.zoomOut??true,zoomIn:a.zoomIn??true,resetZoom:a.resetZoom??true},h=()=>{o?o():s(true);},p=()=>{i(true);},v=()=>{n(br());},y=async(C,I)=>{let B=v4(),k=URL.createObjectURL(C),x=document.createElement("video");x.src=k,x.muted=true,x.playsInline=true,x.preload="auto",await new Promise((H,F)=>{let V=setTimeout(()=>F(new Error("Metadata load timeout")),1e4);x.onloadedmetadata=()=>{clearTimeout(V),H();},x.onerror=()=>{clearTimeout(V),F(new Error("Failed to load video"));};});let S=640,w=x.videoWidth/x.videoHeight,T=S,q=T/w;await da(B,C,I),n(ko({id:B,objectUrl:k,thumbnailDataUrl:I,videoBlob:C,x:100,y:100,width:T,height:q,draggable:true,isPlaying:false,rotation:0,isRecorded:true}));},g=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>n(Mo()),enabled:m.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>n(Ao()),enabled:m.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:h,enabled:m.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:p,enabled:m.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:v,enabled:m.clear,iconWeight:"fill",colorClass:"text-[#E92222]"},{key:"resetZoom",title:"Reset Zoom",icon:ArrowsOut,onClick:()=>n(zd()),enabled:m.resetZoom&&f!==1,iconWeight:"bold",colorClass:"text-primary"}].filter(C=>C.enabled);return !t||l||g.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fixed bottom-[74px] left-1/2 z-50 flex w-11/12 -translate-x-1/2 items-center justify-between rounded-md border bg-white px-4 py-1 shadow-lg md:hidden",children:g.map(C=>jsx("button",{onClick:C.onClick,className:`flex size-10 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-black/5 ${C.colorClass}`,title:C.title,children:jsx(C.icon,{weight:C.iconWeight,className:"text-xl"})},C.key))}),!o&&r&&e&&jsx(eo,{onClose:()=>s(false),stageRef:e,onRecordingComplete:y}),u&&jsx(Rs,{onClose:()=>i(false),onRecordingComplete:y})]})},pd=oL;var sL=({stageRef:e,onScreenRecord:o,softDelete:t=false,actionButtonsVisible:a=true,actionButtonsConfig:n})=>jsxs(Fragment,{children:[jsx(pd,{stageRef:e,onScreenRecord:o,visible:a,config:n}),jsx(md,{softDelete:t})]}),iL=sL;var uL="SchooplaEditorDB",cL=1,Ua="slides",Ka="metadata",hd="schoopla_current_slide_id",Nm="presentation_metadata",on=()=>new Promise((e,o)=>{let t=indexedDB.open(uL,cL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(Ua)||n.createObjectStore(Ua,{keyPath:"id"}),n.objectStoreNames.contains(Ka)||n.createObjectStore(Ka,{keyPath:"id"});};}),gd=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await on(),a=o.transaction([Ua],"readwrite").objectStore(Ua);await new Promise((n,r)=>{let s=a.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);});for(let n of e)await new Promise((r,s)=>{let u=a.add(n);u.onsuccess=()=>r(!0),u.onerror=()=>s(u.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},xd=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await on(),t=e.transaction([Ua],"readonly").objectStore(Ua);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let s=r.result;console.log("\u2705 Loaded from IndexedDB:",s.length,"slides"),s.length>0&&s[0].images&&console.log("First slide images:",s[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(s.length>0?s:null);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Us=async()=>{try{let e=await on(),o=e.transaction([Ua,Ka],"readwrite"),t=o.objectStore(Ua),a=o.objectStore(Ka);await new Promise((n,r)=>{let s=t.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),await new Promise((n,r)=>{let s=a.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(hd),localStorage.removeItem("schoopla_presentation_metadata"),await _c(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},bd=e=>{try{localStorage.setItem(hd,e);}catch(o){console.error("Error saving current slide ID:",o);}},vd=()=>{try{return localStorage.getItem(hd)}catch(e){return console.error("Error loading current slide ID:",e),null}},yd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},wd=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await on(),a=o.transaction([Ka],"readwrite").objectStore(Ka);await new Promise((n,r)=>{let s=a.put({id:Nm,...e});s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Sd=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await on(),t=e.transaction([Ka],"readonly").objectStore(Ka);return new Promise((a,n)=>{let r=t.get(Nm);r.onsuccess=()=>{e.close();let s=r.result;if(s){let{id:u,...i}=s;console.log("\u2705 Loaded presentation metadata:",i),a(i);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var fL=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides","canvas/updateSlideThumbnail"],mL=["canvas/clearCanvas"],pL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],hL=yd((e,o)=>{gd(e),bd(o);},500),gL=yd(e=>{wd(e);},500),xL=(e,o)=>{gd(e),bd(o);},Ld=false,Hm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Nl(r).catch(s=>{console.error("Error deleting video blob:",s);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,u=e.getState().canvas.slides.find(i=>i.id===r);u&&u.videos&&u.videos.length>0&&u.videos.forEach(i=>{Nl(i.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,s=e.getState(),i=s.canvas.slides.find(c=>c.id===s.canvas.currentSlideId)?.videos.find(c=>c.id===r);i&&i.videoBlob&&setTimeout(()=>{let c=e.getState(),d=c.canvas.slides.find(l=>l.id===c.canvas.currentSlideId)?.videos.find(l=>l.id!==r&&l.x===i.x+20&&l.y===i.y+20);d&&i.videoBlob&&da(d.id,i.videoBlob,d.thumbnailDataUrl).catch(l=>{console.error("Error saving duplicated video blob:",l);});},0);}let a=o(t),n=e.getState();if(n.canvas.viewerMode)return a;if(t.type&&mL.includes(t.type)){if(!Ld){Ld=true;try{let{slides:r,currentSlideId:s}=n.canvas;xL(r,s);}finally{setTimeout(()=>{Ld=false;},0);}}}else if(t.type&&fL.includes(t.type)){let{slides:r,currentSlideId:s}=n.canvas;hL(r,s);}else if(t.type&&pL.includes(t.type)){let{presentationMetadata:r}=n.canvas;gL(r);}return a});new QueryClient;var vL=configureStore({reducer:{toolbar:Yl,canvas:Oi},middleware:e=>e({serializableCheck:false}).concat(Hm)}),yL=()=>configureStore({reducer:{toolbar:Yl,canvas:Oi},middleware:e=>e({serializableCheck:false})});var wL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2,fileName:r=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:s,quality:a,pixelRatio:n}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=u,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},SL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o;return new Promise((r,s)=>{try{let u=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:u,quality:a,pixelRatio:n});fetch(i).then(c=>c.blob()).then(c=>r(c)).catch(c=>s(c));}catch(u){s(u);}})},LL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:n})};var IL=(e,o,t)=>{let a=t.x-o.x,n=t.y-o.y;if(a===0&&n===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+n*n,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*n)/r)),u=o.x+s*a,i=o.y+s*n;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-i,2))},Id=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,n=e[0],r=e[e.length-1];for(let s=1;s<e.length-1;s++){let u=IL(e[s],n,r);u>t&&(t=u,a=s);}if(t>o){let s=Id(e.slice(0,a+1),o),u=Id(e.slice(a),o);return [...s.slice(0,-1),...u]}return [n,r]},CL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},kL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Vm=(e,o=1.5)=>{if(e.length<=4)return e;let t=CL(e),a=Id(t,o);return kL(a)},zm=(e,o=1.5)=>({...e,points:Vm(e.points,o)}),TL=(e,o=1.5)=>e.map(t=>zm(t,o)),ML=(e,o)=>{let t=e.length/2,a=o.length/2,n=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${n}%`}};var AL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Wm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:n=.85}=o;return new Promise((r,s)=>{let u=new Image;u.onload=()=>{let{width:i,height:c}=u;if(i>t||c>a){let h=i/c;i>c?(i=Math.min(i,t),c=i/h):(c=Math.min(c,a),i=c*h);}let f=document.createElement("canvas");f.width=i,f.height=c;let d=f.getContext("2d");if(!d){s(new Error("Failed to get canvas context"));return}d.drawImage(u,0,0,i,c);let l=AL(e),m=f.toDataURL(l,n);r(m);},u.onerror=s,u.src=e;})};var vo=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let n=0;n<t.length;n++)a[n]=t.charCodeAt(n);return a.buffer},nr=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",sr=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",PL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:n=1080,imageQuality:r=.85}=o,s=[],u=0;for(let i of e){let c=[],f=[],d=[];for(let l of i.images){let m=l.src;if(t&&m.startsWith("data:"))try{m=await Wm(m,{maxWidth:a,maxHeight:n,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(m.startsWith("data:")){let h=vo(m),p=nr(m);u+=h.byteLength;let v={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,buffer:h,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let y=vo(l.audioData),b=nr(l.audioData);u+=y.byteLength,v.audioBuffer=y,v.audioMimeType=b;}c.push(v);}}for(let l of i.videos){let m,h;if(l.videoBlob)m=await l.videoBlob.arrayBuffer(),h=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))m=vo(l.videoData),h=nr(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}u+=m.byteLength;let p={id:l.id,thumbnailDataUrl:l.thumbnailDataUrl,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,isPlaying:l.isPlaying,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isRecorded:l.isRecorded,buffer:m,mimeType:h};if(l.audioData&&l.audioData.startsWith("data:")){let v=vo(l.audioData),y=nr(l.audioData);u+=v.byteLength,p.audioBuffer=v,p.audioMimeType=y;}f.push(p);}for(let l of i.photoFrames){let m={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:l.draggable,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isCapturing:l.isCapturing};if(l.capturedImageUrl&&l.capturedImageUrl.startsWith("data:")){let h=vo(l.capturedImageUrl),p=nr(l.capturedImageUrl);u+=h.byteLength,m.buffer=h,m.mimeType=p;}if(l.audioData&&l.audioData.startsWith("data:")){let h=vo(l.audioData),p=nr(l.audioData);u+=h.byteLength,m.audioBuffer=h,m.audioMimeType=p;}d.push(m);}s.push({...i,images:c,videos:f,photoFrames:d});}return {slides:s,totalSize:u}},EL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},DL=e=>{let o=new FormData,t=e.slides.map((a,n)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,mimeType:r.mimeType,fileKey:`slide_${n}_image_${s}`,audioFileKey:r.audioBuffer?`slide_${n}_image_${s}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,isPlaying:r.isPlaying,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isRecorded:r.isRecorded,mimeType:r.mimeType,fileKey:`slide_${n}_video_${s}`,thumbnailFileKey:`slide_${n}_video_${s}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${n}_video_${s}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,rotation:r.rotation,draggable:r.draggable,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isCapturing:r.isCapturing,mimeType:r.mimeType,fileKey:r.buffer?`slide_${n}_photoframe_${s}`:void 0,audioFileKey:r.audioBuffer?`slide_${n}_photoframe_${s}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,n)=>{a.images.forEach((r,s)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${sr(r.mimeType)}`;if(o.append(`slide_${n}_image_${s}`,u,i),r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),f=`${r.id}_audio.${sr(r.audioMimeType)}`;o.append(`slide_${n}_image_${s}_audio`,c,f);}}),a.videos.forEach((r,s)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${sr(r.mimeType)}`;if(o.append(`slide_${n}_video_${s}`,u,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let c=vo(r.thumbnailDataUrl),f=new Blob([c],{type:"image/jpeg"}),d=`${r.id}_thumbnail.jpg`;o.append(`slide_${n}_video_${s}_thumbnail`,f,d);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),f=`${r.id}_audio.${sr(r.audioMimeType)}`;o.append(`slide_${n}_video_${s}_audio`,c,f);}}),a.photoFrames.forEach((r,s)=>{if(r.buffer&&r.mimeType){let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${sr(r.mimeType)}`;o.append(`slide_${n}_photoframe_${s}`,u,i);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${sr(r.audioMimeType)}`;o.append(`slide_${n}_photoframe_${s}_audio`,u,i);}});}),o};var BL=()=>{let e=_e(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let n=await xd(),r=vd(),s=await Sd();if(n&&n.length>0){let u=await jc(),i=n.map(f=>{if(f.videos&&f.videos.length>0){let d=f.videos.map(l=>{let m=u.get(l.id);if(m){let h=$c(m.blob);return {...l,objectUrl:h,thumbnailDataUrl:m.thumbnailDataUrl,videoBlob:m.blob}}else return l});return {...f,videos:d}}return f}),c=r&&i.find(f=>f.id===r)?r:i[0].id;e(Io({slides:i,currentSlideId:c}));}e(s?Ri({title:s.title,description:s.description}):jn(!0));}catch(n){console.error("Error loading persisted slides:",n),e(jn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var Km=e=>e.map(o=>({...o,lines:o.lines||[],shapes:o.shapes||[],images:o.images||[],videos:o.videos||[],flashcards:o.flashcards||[],photoFrames:o.photoFrames||[],texts:o.texts||[],multipleChoices:o.multipleChoices||[],trueFalses:o.trueFalses||[],shortAnswers:o.shortAnswers||[],LongAnswer:o.LongAnswer||[],fillInTheBlanks:o.fillInTheBlanks||[],createdAt:o.createdAt||Date.now(),updatedAt:o.updatedAt||Date.now(),showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,activityType:o.activityType||""})),Gm=new WeakSet,jm=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await da(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},OL=()=>{let e=_e(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Gm.has(a))return;Gm.add(a);let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await Us(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,i=Km(n);e(Io({slides:i,currentSlideId:u})),await jm(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await Us(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,i=Km(n);e(Io({slides:i,currentSlideId:u})),await jm(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
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{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
20
+ */export{Iw as BASIC_EDITOR_TOOLBAR_CONFIG,AS as BottomToolbar,Tv as Canvas,Sw as DEFAULT_CONTEXT_MENU_CONFIG,Fs as DEFAULT_TOOLBAR_CONFIG,Pg as EditorRoot,pd as MobileActionButtons,iL as MobileBottomSection,md as MobilePrevPanel,dd as PublishButton,eo as ScreenRecorder,qS as SlideNavigation,xS as Toolbar,SS as TopNavBar,Lw as VIEWER_TOOLBAR_CONFIG,Ii as addFillInTheBlanks,ci as addFlashcard,li as addImage,gi as addImageAnnotation,ii as addLine,Li as addLongAnswer,vi as addMultipleChoice,pi as addPhotoFrame,bi as addPhotoFrameAnnotation,di as addShape,Si as addShortAnswer,ur as addSlide,ui as addText,wi as addTrueFalse,ko as addVideo,EL as arrayBufferToBase64,ki as bringToFront,br as clearCanvas,kp as clearImageAnnotations,Us as clearLocalData,Mp as clearPhotoFrameAnnotations,ni as createEmptySlide,yL as createViewerStore,qn as deleteFillInTheBlanks,Tn as deleteFlashcard,bn as deleteImage,Gn as deleteLineById,Nn as deleteLongAnswer,En as deleteMultipleChoice,An as deletePhotoFrame,In as deleteShape,Bn as deleteShortAnswer,cr as deleteSlide,Cn as deleteText,Rn as deleteTrueFalse,wn as deleteVideo,Vn as duplicateFillInTheBlanks,Mn as duplicateFlashcard,vn as duplicateImage,Pi as duplicateLine,Hn as duplicateLongAnswer,Dn as duplicateMultipleChoice,Pn as duplicatePhotoFrame,Ln as duplicateShape,On as duplicateShortAnswer,fr as duplicateSlide,kn as duplicateText,Fn as duplicateTrueFalse,Sn as duplicateVideo,hr as editFlashcard,Ap as editMultipleChoice,SL as exportSlideAsBlob,wL as exportSlideAsImage,Ai as finalizeDrawing,ML as getCompressionStats,LL as getSlideDataURL,vd as loadCurrentSlideId,xd as loadFromIndexedDB,Ri as loadPresentationMetadata,Sd as loadPresentationMetadataFromDB,Io as loadSlides,Ql as mergeToolbarConfig,fi as nextFlashcard,DL as prepareFormData,PL as prepareSlidesForPublishing,mi as previousFlashcard,Ao as redo,xn as removeLine,Ip as reorderSlides,wd as savePresentationMetadata,de as saveToHistory,Ca as selectAllSlides,Fi as selectAllSlidesIncludingInactive,yr as selectCanAddSlide,ve as selectCurrentSlide,Ia as selectCurrentSlideId,Bi as selectMetadataLoaded,wr as selectPresentationMetadata,Fp as selectSlideById,Ti as sendToBack,Ci as setActivityType,Wn as setAltText,Un as setAudioData,pr as setBackgroundColor,mr as setCurrentSlide,gr as setEditingActivity,vr as setEditingTextId,Ep as setLines,zn as setLink,jn as setMetadataLoaded,ma as setPenColor,Di as setPresentationDescription,Ei as setPresentationTitle,Qa as setShowFlashcardForm,La as setShowMcqForm,It as setSketchMode,Zr as setStrokeWidth,aa as setTool,Lp as setViewerMode,Vm as simplifyFlatPoints,zm as simplifyLine,TL as simplifyLines,vL as store,hi as toggleImageDrawingMode,Mi as toggleLock,xi as togglePhotoFrameDrawingMode,Rp as toggleSketchMode,Xa as toggleVideoPlaying,Mo as undo,xr as updateElementOrder,Sa as updateFillInTheBlanks,To as updateFlashcard,Co as updateImage,Cp as updateImageAnnotation,Pp as updateLastLine,Dp as updateLinePosition,Kn as updateLineTransform,Ja as updateLongAnswer,gt as updateMultipleChoice,Za as updatePhotoFrame,Tp as updatePhotoFrameAnnotation,Ya as updateShape,sa as updateShortAnswer,si as updateSlideThumbnail,Ft as updateText,ot as updateTrueFalse,yn as updateVideo,Se as useDispatch,OL as useInitialSlides,rl as useModalPortal,J as useSelector,BL as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
21
  //# sourceMappingURL=index.js.map