@turnix-co/konva-editor 3.0.37 → 3.0.40
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 +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
export{default as Konva}from'konva';import*as ye from'react';import ye__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,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,Export,CaretLeft,Plus,CaretDown,CaretUp,SidebarSimple,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,TextUnderline,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,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 Pd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {EyeIcon,Stack as Stack$1,X as X$1,DotsSixVertical,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import Du from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var wd=e=>{throw TypeError(e)};var Ld=(e,o,t)=>o.has(e)||wd("Cannot "+t);var j=(e,o,t)=>(Ld(e,o,"read from private field"),t?t.call(e):o.get(e)),Re=(e,o,t)=>o.has(e)?wd("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Te=(e,o,t,a)=>(Ld(e,o,"write to private field"),o.set(e,t),t);var Sd=(e,o,t,a)=>({set _(s){Te(e,o,s);},get _(){return j(e,o,a)}});var ve=()=>useDispatch(),Q=e=>useSelector(e),ft=ve,ot=Q;var Wn=20,Gn=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}),Kn=Gn("Slide 1"),ap={slides:[Kn],currentSlideId:Kn.id,history:{[Kn.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false},Id=createSlice({name:"canvas",initialState:ap,reducers:{addSlide:e=>{if(e.slides.length>=Wn)return;let o=Gn(`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 n=e.slides[r];if(a?(n.isActive=false,n.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>=Wn)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],s={...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,s),e.currentSlideId=s.id,e.history[s.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[s]=e.slides.splice(t,1);e.slides.splice(a,0,s);},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(s=>s.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(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,newTimestamp:r}=o.payload;switch(s){case "image":let n=t.images.find(g=>g.id===a);n&&(n.timestamp=r);break;case "video":let u=t.videos.find(g=>g.id===a);u&&(u.timestamp=r);break;case "shape":let i=t.shapes.find(g=>g.id===a);i&&(i.timestamp=r);break;case "text":let c=t.texts.find(g=>g.id===a);c&&(c.timestamp=r);break;case "flashcard":let p=t.flashcards.find(g=>g.id===a);p&&(p.timestamp=r);break;case "photoFrame":let d=t.photoFrames.find(g=>g.id===a);d&&(d.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(g=>g.id===a);l&&(l.timestamp=r);break;case "trueFalse":let f=t.trueFalses.find(g=>g.id===a);f&&(f.timestamp=r);break;case "shortAnswer":let h=t.shortAnswers.find(g=>g.id===a);h&&(h.timestamp=r);break;case "longAnswer":let m=t.LongAnswer.find(g=>g.id===a);m&&(m.timestamp=r);break;case "fillInTheBlanks":let v=t.fillInTheBlanks.find(g=>g.id===a);v&&(v.timestamp=r);break;case "line":let x=t.lines.find(g=>g.id===a);x&&(x.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.multipleChoices[t.multipleChoices.length-1];a.x=s.x+20,a.y=s.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(s=>s.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.trueFalses[t.trueFalses.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.shortAnswers[t.shortAnswers.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.LongAnswer[t.LongAnswer.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(s),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 s=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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:s}=o.payload;if(s==="image"){let r=t.images.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.images.splice(r,1);t.images.push(n);}}else if(s==="video"){let r=t.videos.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.videos.splice(r,1);t.videos.push(n);}}else if(s==="shape"){let r=t.shapes.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shapes.splice(r,1);t.shapes.push(n);}}else if(s==="flashcard"){let r=t.flashcards.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.flashcards.splice(r,1);t.flashcards.push(n);}}else if(s==="photoFrame"){let r=t.photoFrames.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.photoFrames.splice(r,1);t.photoFrames.push(n);}}else if(s==="text"){let r=t.texts.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.texts.splice(r,1);t.texts.push(n);}}else if(s==="trueFalse"){let r=t.trueFalses.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.trueFalses.splice(r,1);t.trueFalses.push(n);}}else if(s==="shortAnswer"){let r=t.shortAnswers.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shortAnswers.splice(r,1);t.shortAnswers.push(n);}}else if(s==="fillInTheBlanks"){let r=t.fillInTheBlanks.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.fillInTheBlanks.splice(r,1);t.fillInTheBlanks.push(n);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s}=o.payload;if(s==="image"){let r=t.images.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.images.splice(r,1);t.images.unshift(n);}}else if(s==="video"){let r=t.videos.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.videos.splice(r,1);t.videos.unshift(n);}}else if(s==="shape"){let r=t.shapes.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shapes.splice(r,1);t.shapes.unshift(n);}}else if(s==="flashcard"){let r=t.flashcards.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.flashcards.splice(r,1);t.flashcards.unshift(n);}}else if(s==="photoFrame"){let r=t.photoFrames.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.photoFrames.splice(r,1);t.photoFrames.unshift(n);}}else if(s==="text"){let r=t.texts.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.texts.splice(r,1);t.texts.unshift(n);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s}=o.payload,n=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);n&&(n.locked=!n.locked,"draggable"in n&&(n.draggable=!n.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,link:r}=o.payload,u=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="mcq"?t.multipleChoices:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="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:s,altText:r}=o.payload,u=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="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:s,audioData:r}=o.payload,u=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="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();}},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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 s=a.images.map((r,n)=>n).filter(r=>r!==a.currentIndex);if(s.length>0){let r=s[Math.floor(Math.random()*s.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(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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 s=o.past.pop();e.slides[t]=s;}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 s=o.future.shift();e.slides[t]=s;}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 s=JSON.parse(JSON.stringify(t));a.past.push(s),a.future=[],a.past.length>20&&a.past.shift();}catch(s){console.warn("Failed to save to history - data too large:",s),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;}}}),{addSlide:jn,deleteSlide:_n,duplicateSlide:Xn,setCurrentSlide:$n,setViewerMode:op,updateSlideThumbnail:Yn,setBackgroundColor:Jn,reorderSlides:rp,loadSlides:co,addLine:Zn,removeLine:as,addImage:Qn,updateImage:fo,deleteImage:os,duplicateImage:rs,addVideo:ss,updateVideo:ns,deleteVideo:is,duplicateVideo:ls,toggleVideoPlaying:qa,addShape:ei,updateShape:mo,duplicateShape:ds,deleteShape:us,addText:ti,updateText:Dt,deleteText:cs,duplicateText:fs,addFlashcard:ai,updateFlashcard:po,deleteFlashcard:ms,duplicateFlashcard:ps,editFlashcard:Qo,nextFlashcard:oi,previousFlashcard:ri,addPhotoFrame:si,updatePhotoFrame:Ha,deletePhotoFrame:hs,duplicatePhotoFrame:gs,toggleImageDrawingMode:ni,addImageAnnotation:ii,updateImageAnnotation:sp,clearImageAnnotations:np,togglePhotoFrameDrawingMode:li,addPhotoFrameAnnotation:di,updatePhotoFrameAnnotation:ip,clearPhotoFrameAnnotations:lp,addMultipleChoice:ui,updateMultipleChoice:pa,editMultipleChoice:dp,deleteMultipleChoice:xs,duplicateMultipleChoice:bs,addTrueFalse:ci,updateTrueFalse:ha,deleteTrueFalse:vs,duplicateTrueFalse:ys,addShortAnswer:fi,updateShortAnswer:er,deleteShortAnswer:ws,duplicateShortAnswer:Ls,addLongAnswer:mi,updateLongAnswer:tr,deleteLongAnswer:Ss,duplicateLongAnswer:Is,addFillInTheBlanks:pi,updateFillInTheBlanks:ar,deleteFillInTheBlanks:Cs,duplicateFillInTheBlanks:ks,setShowMcqForm:ga,setShowFlashcardForm:Ua,setActivityType:hi,setEditingActivity:or,bringToFront:gi,sendToBack:xi,toggleLock:bi,setLink:Ts,setAltText:Ms,setAudioData:As,updateLastLine:up,finalizeDrawing:vi,setLines:cp,updateLinePosition:fp,updateLineTransform:Ps,deleteLineById:Es,duplicateLine:yi,updateElementOrder:rr,clearCanvas:wi,undo:Ds,redo:Rs,saveToHistory:ue,toggleSketchMode:mp,setSketchMode:wt,setEditingTextId:sr,setPresentationTitle:Li,setPresentationDescription:Si,loadPresentationMetadata:Ii,setMetadataLoaded:Fs}=Id.actions;var Cd=e=>e.canvas.slides,ho=e=>e.canvas.currentSlideId,ge=createSelector([Cd,ho],(e,o)=>e.find(t=>t.id===o)),go=createSelector([Cd],e=>e.filter(o=>o.isActive!==false)),Ci=e=>e.canvas.slides,ki=createSelector([go],e=>e.length<Wn),pp=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},nr=e=>e.canvas.presentationMetadata,Ti=e=>e.canvas.metadataLoaded,Bs=e=>e.canvas.viewerMode,Mi=Id.reducer;var Td=e=>{let o=ve(),t=useRef(null),a=useRef(false),s=Q(f=>f.toolbar.selectedTool),r=Q(f=>f.toolbar.penColor),n=Q(f=>f.toolbar.strokeWidth),u=Q(f=>f.canvas.isSketchMode),i=Q(f=>f.canvas.slides.find(m=>m.id===f.canvas.currentSlideId)?.lines||[]),c=useCallback(f=>{t.current=f;},[]),p=useCallback(f=>{s==="pen"&&t.current&&(o(ue()),t.current.startDrawing(f),a.current=true);},[s,o]),d=useCallback(f=>{!t.current||!a.current||t.current.draw(f);},[]),l=useCallback(()=>{if(!t.current||!a.current)return;let f=t.current.stopDrawing();a.current=false,f&&f.points.length>=4&&o(Zn(f)),o(vi()),e?.();},[o,e]);return {lines:i,tool:s,color:r,strokeWidth:n,isSketchMode:u,setCanvasRef:c,startDrawing:p,draw:d,stopDrawing:l}};var Ed=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:s,isSketchMode:r,style:n,xOffset:u=0,yOffset:i=0},c)=>{let p=useRef(null),d=useRef(false),l=useRef([]),f=useRef([]),h=useRef(null),m=useRef(t),v=useRef(a),x=useRef(s),g=useRef(r),b=useRef(u),w=useRef(i);useEffect(()=>{m.current=t,v.current=a,x.current=s,g.current=r,b.current=u,w.current=i;},[t,a,s,r,u,i]);let I=useCallback(()=>{let k=p.current;if(!k)return;let S=k.getContext("2d");S&&S.clearRect(0,0,k.width,k.height);},[]),P=useCallback(()=>{let k=p.current,S=f.current;if(!k||S.length<1)return;let y=k.getContext("2d");if(!y)return;if(y.clearRect(0,0,k.width,k.height),m.current==="eraser"?(y.globalCompositeOperation="destination-out",y.fillStyle="rgba(0,0,0,1)"):(y.globalCompositeOperation="source-over",y.fillStyle=v.current),S.length===1){y.beginPath(),y.arc(S[0].x,S[0].y,x.current/2,0,Math.PI*2),y.fill();return}let B=Pd(S,{size:x.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:T=>T,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(B.length<2)){y.beginPath(),y.moveTo(B[0][0],B[0][1]);for(let T=1;T<B.length;T++)y.lineTo(B[T][0],B[T][1]);y.closePath(),y.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:k=>{d.current=true;let S={x:k.x-b.current,y:k.y-w.current};l.current=[{x:k.x,y:k.y}],f.current=[S],h.current=k,P();},draw:k=>{if(!d.current||!h.current)return;let S=k.x-h.current.x,y=k.y-h.current.y;if(Math.sqrt(S*S+y*y)<2)return;let B={x:k.x-b.current,y:k.y-w.current};l.current.push({x:k.x,y:k.y}),f.current.push(B),h.current=k,P();},stopDrawing:()=>{if(!d.current)return null;if(d.current=false,l.current.length<2)return l.current=[],f.current=[],h.current=null,I(),null;let S=Pd(l.current,{size:x.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:E=>E,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(E=>[E[0],E[1]]),y={tool:m.current,points:S,color:v.current,strokeWidth:x.current,isSketch:true};return l.current=[],f.current=[],h.current=null,I(),y},clear:()=>{I(),l.current=[],f.current=[],h.current=null,d.current=false;},isDrawing:()=>d.current,getCanvasElement:()=>p.current}),[I,P]),useEffect(()=>{let k=p.current;k&&(k.width=e,k.height=o);},[e,o]),jsx("canvas",{ref:p,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...n}})});Ed.displayName="DirectDrawingCanvas";var Dd=Ed;var Fd=e=>{let o=ve(),a=Q(ge)?.images||[],s=useRef(new Map),r=useRef(new Map),n=useRef(new Set);useEffect(()=>{let p=new Set(a.map(d=>d.id));n.current.forEach(d=>{if(!p.has(d)){let l=r.current.get(d);l&&(l.src="",r.current.delete(d)),s.current.delete(d);}}),n.current=p;},[a]),useEffect(()=>()=>{r.current.forEach(p=>{p.src="";}),r.current.clear(),s.current.clear();},[]);let u=useCallback(p=>{if(r.current.has(p.id))return r.current.get(p.id);let d=new window.Image;return (p.src.startsWith("http://")||p.src.startsWith("https://"))&&(d.crossOrigin="anonymous"),d.src=p.src,r.current.set(p.id,d),d},[]),i=useCallback((p,d)=>{let l=p.target,f=l.id();a.find(m=>m.id===f)&&(o(fo({id:f,x:l.x(),y:l.y(),width:l.width(),height:l.height(),rotation:l.rotation()})),d?.());},[a,o]),c=useCallback((p,d)=>{let l=d.target,f=s.current.get(p);if(!f){console.error("\u274C Image node not found for id:",p);return}let h=l.scaleX(),m=l.scaleY(),v=l.rotation(),x=f.width(),g=f.height(),b=Math.max(5,x*h),w=Math.max(5,g*m);l.scaleX(1),l.scaleY(1),f.width(b),f.height(w),o(fo({id:p,width:b,height:w,x:l.x(),y:l.y(),rotation:v})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:u,imageRefs:s,handleDragEnd:i,handleImageTransformEnd:c}};var Bd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),s=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((u,i)=>{let c=i.target,p=c.scaleX(),d=c.scaleY(),l=c.rotation(),f=Math.max(5,c.width()*p),h=Math.max(5,c.height()*d);c.scaleX(1),c.scaleY(1),c.width(f),c.height(h),o(pa({id:u,width:f,height:h,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:s,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(u,i)=>{o(pa({id:i,x:u.target.x(),y:u.target.y()})),e?.();}}};var Od=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),s=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((u,i)=>{let c=i.target,p=c.scaleX(),d=c.scaleY(),l=c.rotation(),f=Math.max(5,c.width()*p),h=Math.max(5,c.height()*d);c.scaleX(1),c.scaleY(1),c.width(f),c.height(h),o(ha({id:u,width:f,height:h,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:s,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(u,i)=>{o(ha({id:i,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var Nd=e=>{let o=ve(),a=Q(ge)?.videos||[],s=useRef(new Map),r=useCallback(i=>{o(qa(i));},[o]),n=useCallback((i,c)=>{let p=c.target;o(ns({id:i,x:p.x(),y:p.y()})),e?.();},[o,e]),u=useCallback((i,c)=>{let p=c.target,d=p.scaleX(),l=p.scaleY(),f=p.rotation(),h=Math.max(5,p.width()*d),m=Math.max(5,p.height()*l);p.scaleX(1),p.scaleY(1),p.width(h),p.height(m),o(ns({id:i,width:h,height:m,x:p.x(),y:p.y(),rotation:f})),p.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:s,handleVideoClick:r,handleVideoDragEnd:n,handleVideoTransformEnd:u}};var Hd=e=>{let o=ve(),a=Q(ge)?.shapes||[],s=useRef(new Map),r=useRef(new Map),[n,u]=useState(false),i=useCallback((p,d)=>{let l=d.target;o(mo({id:p,x:l.x(),y:l.y()})),e?.();},[o,e]),c=useCallback((p,d)=>{let l=d.target,f=a.find(b=>b.id===p);if(!f)return;let h=l.scaleX(),m=l.scaleY(),v=f.type?.toLowerCase();v==="arrow"||v==="line"||(l.scaleX(1),l.scaleY(1));let g={id:p,x:l.x(),y:l.y(),width:Math.max(5,l.width()*h),height:Math.max(5,l.height()*m),rotation:l.rotation()};switch(v){case "circle":g.radius=l.width()*h/2;break;case "star":g.innerRadius=l.width()*h/4,g.outerRadius=l.width()*h/2;break;case "triangle":g.radius=l.width()*h/2;break;case "ellipse":g.radiusX=l.width()*h/2,g.radiusY=l.height()*m/2;break;case "polygon":g.radius=l.width()*h/2;break;case "ring":let b=h;g.innerRadius=f.innerRadius&&f.innerRadius*b,g.outerRadius=f.outerRadius&&f.outerRadius*b;break;case "wedge":g.radius=f.radius&&f.radius*h;break;case "arc":g.innerRadius=f.innerRadius&&f.innerRadius*h,g.outerRadius=f.outerRadius&&f.outerRadius*h;break;case "arrow":case "line":{g.scaleX=h,g.scaleY=m,delete g.width,delete g.height;break}}o(mo(g)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:s,isDragging:n,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:c}};var Kd=(e,o)=>{let t=ft(),s=Q(ge)?.texts||[],r=useRef(new Map),[n,u]=useState(null),[i,c]=useState("");return {texts:s,textRefs:r,handleDragEnd:(v,x)=>{let g=v.target;t(ue()),t(Dt({id:x,x:g.x(),y:g.y()})),e();},handleTransformEnd:v=>{let x=r.current.get(v);if(!x)return;let g=x.scaleX(),b=x.scaleY(),w=s.find(P=>P.id===v);if(!w)return;let I=(g+b)/2;x.scaleX(1),x.scaleY(1),t(ue()),t(Dt({id:v,x:x.x(),y:x.y(),width:Math.max(5,(w.width||100)*g),height:Math.max(5,(w.height||50)*b),fontSize:Math.round(Math.max(8,w.fontSize*I)),rotation:x.rotation()})),e();},handleDoubleClick:v=>{let x=s.find(g=>g.id===v);x&&!x.locked&&(u(v),c(x.text));},startEditing:v=>{let x=s.find(g=>g.id===v);x&&!x.locked&&(u(v),c(x.text));},editingTextId:n,editingValue:i,handleEditingChange:v=>{c(v);},finishEditing:()=>{if(n){let v=r.current.get(n),x=s.find(b=>b.id===n);t(ue());let g={id:n,text:i};if(x&&(x.fontWeight!==void 0&&(g.fontWeight=x.fontWeight),x.fontStyle!==void 0&&(g.fontStyle=x.fontStyle),x.textDecoration!==void 0&&(g.textDecoration=x.textDecoration)),o?.current&&i.trim()){let b=o.current,w=b.offsetWidth,I=b.offsetHeight,P=1;if(v){let O=v.getStage();O&&(P=O.scaleX());}let k=14,S=(w-k)/P,y=(I-k)/P,E=i.split(`
|
|
3
|
-
`).length,T=s.find(O=>O.id===n)?.fontSize||24,F=E*T*1.2+10;g.width=Math.max(200,S),g.height=Math.max(50,y,F);}else if(v&&i.trim()){let b=v.text(),w=v.width();v.text(i),v.width(void 0);let I=v.width(),P=v.height();v.text(b),v.width(w),g.width=Math.max(200,I+20),g.height=Math.max(50,P+20);}t(Dt(g)),u(null),c(""),t(sr(null)),e();}}}};var Wd=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],s=useRef(new Map),r=useCallback((n,u)=>{let i=n.target;o(er({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:s,handleShortAnswerDragEnd:r}};var zd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),s=useCallback((r,n)=>{let u=r.target;o(tr({id:n,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:s}};var jd=e=>{let o=ve(),a=Q(ge)?.flashcards||[],s=useRef(new Map),r=useRef(new Map),n=useCallback((d,l)=>{if(r.current.has(l))return r.current.get(l);let f=new window.Image;return (d.startsWith("http://")||d.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=d,r.current.set(l,f),f},[]),u=useCallback((d,l)=>{let f=d.target,h=f.id();a.find(v=>v.id===h)&&(o(po({id:h,x:f.x(),y:f.y()})),l?.());},[a,o]),i=useCallback((d,l)=>{let f=l.target,h=f.scaleX(),m=f.scaleY(),v=f.rotation(),x=Math.max(50,f.width()*h),g=Math.max(50,f.height()*m);f.scaleX(1),f.scaleY(1),f.width(x),f.height(g),o(po({id:d,width:x,height:g,x:f.x(),y:f.y(),rotation:v})),f.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(d=>{o(oi(d)),e?.();},[o,e]),p=useCallback(d=>{o(ri(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:s,handleDragEnd:u,handleFlashcardTransformEnd:i,handleNext:c,handlePrevious:p}};var $d=e=>{let o=ve(),a=Q(ge)?.photoFrames||[],s=useRef(new Map),[r,n]=useState(new Map),u=useCallback((f,h)=>{console.log("handleDragEnd"),o(Ha({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),i=useCallback((f,h)=>{let m=h.target,v=m.scaleX(),x=m.scaleY(),g=m.rotation(),b=a.find(P=>P.id===f);if(!b)return;let w=Math.max(100,b.width*v),I=Math.max(100,b.height*x);m.scaleX(1),m.scaleY(1),o(Ha({id:f,width:w,height:I,x:m.x(),y:m.y(),rotation:g})),m.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(m=>{let v=new Map(m);return v.set(f,h),v}),o(Ha({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),p=useCallback(f=>{let h=r.get(f);h&&(h.getTracks().forEach(m=>m.stop()),n(m=>{let v=new Map(m);return v.delete(f),v}),o(Ha({id:f,isCapturing:false})),e?.());},[r,o,e]),d=useCallback((f,h)=>{let m=document.createElement("canvas");m.width=h.videoWidth,m.height=h.videoHeight;let v=m.getContext("2d");if(v){v.drawImage(h,0,0,m.width,m.height);let x=m.toDataURL("image/jpeg",.8);return o(Ha({id:f,capturedImageUrl:x,isCapturing:false})),p(f),e?.(),x}return null},[o,p,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:s,handleDragEnd:u,handlePhotoFrameTransformEnd:i,startCamera:c,stopCamera:p,capturePhoto:d,cameraStreams:r}};var Yd=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),a=useCallback((r,n,u,i,c,p,d,l=[])=>{if(e.current){if(r&&!l.find(m=>m.id===r)?.isPlaying){let m=n.get(r)||u.get(r)||i.get(r)||c.get(r)||p.get(r)||(d?d.get(r):null);if(m){e.current.boundBoxFunc(t),e.current.nodes([m]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),s=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:s,boundBoxFunc:t}};var Kp=(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])},eu=(e,o)=>{let t=ft(),a=ot(Bs),s=useRef(e);useEffect(()=>{s.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(Yn({id:s.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),n=Kp(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var zp=e=>e.flatMap(o=>[o[0],o[1]]),Ns=(e,o)=>{let t=Pd(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 zp(t)};var tu=e=>{let o=ve(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null),u=Q(b=>b.toolbar.selectedTool),i=Q(b=>b.toolbar.penColor),c=Q(b=>b.toolbar.strokeWidth),p=Q(b=>b.canvas.isSketchMode),d=Q(b=>b.canvas.slides.find(I=>I.id===b.canvas.currentSlideId)?.images.find(I=>I.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,m=d?.height||1,v=useCallback(b=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,s.current=[{x:b.x,y:b.y}];let w=b.x/h,I=b.y/m;n({tool:u,points:[w,I],color:i,strokeWidth:c/h,isSketch:p});},[u,i,c,p,h,m]),x=useCallback(b=>{if(!t.current||!r)return;a.current=true;let w=s.current[s.current.length-1];if(Math.sqrt(Math.pow(b.x-w.x,2)+Math.pow(b.y-w.y,2))<2)return;s.current.push({x:b.x,y:b.y});let P;if(p)P=Ns(s.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((S,y)=>y%2===0?S/h:S/m);else {let k=b.x/h,S=b.y/m;P=[...r.points,k,S];}n(k=>k?{...k,points:P}:null);},[p,c,r,h,m]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(ii({imageId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:f,startDrawing:v,draw:x,stopDrawing:g,tool:u}};function Ne({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),s=useRef(null);return {createHandlers:useCallback((n,u)=>({onTouchStart:i=>{let c=i.evt.touches[0];s.current={x:c.clientX,y:c.clientY},a.current=setTimeout(()=>{e(n,u)(i.evt);},o);},onTouchMove:i=>{if(!s.current)return;let c=i.evt.touches[0],p=Math.abs(c.clientX-s.current.x),d=Math.abs(c.clientY-s.current.y);(p>t||d>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),s.current=null;}}),[e,o,t])}}var nu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n,onLongPress:u})=>{let{annotations:i,activeLine:c,stopDrawing:l,tool:f}=tu(e.id),{createHandlers:h}=Ne({onLongPress:u});useEffect(()=>{let b=t.current.get(e.id);b&&(b.width()!==e.width||b.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:b.width(),konvaHeight:b.height()}),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let m=false;useEffect(()=>{return;},[l,m]);let v=b=>{{r(e.id);return}},x=b=>{return;},g=b=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="eraser",children:[jsx(Image$1,{id:e.id,ref:b=>{if(b)t.current.set(e.id,b),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw();else {let w=t.current.get(e.id);w?._contextMenuCleanup&&w._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:b=>s(e.id,b),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:b=>{b.evt.preventDefault();let w=b.evt;n(w,e.id,"image");},...f!=="pen"&&f!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onMouseMove:x,onMouseUp:g,...h(e.id,"image")}:{}}),i?.map((b,w)=>{let I=b.points.map((k,S)=>S%2===0?k*e.width+e.x:k*e.height+e.y),P=b.strokeWidth*e.width;return jsx(Line,{points:I,stroke:b.tool==="eraser"?"white":b.color,strokeWidth:P,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},w)}),c&&jsx(Line,{points:c.points.map((b,w)=>w%2===0?b*e.width+e.x:b*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")]})});nu.displayName="ImageWithDrawing";var Bi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n,onLongPress:u})=>jsx(Fragment,{children:e.map(i=>{let c=o(i);return c?jsx(nu,{img:i,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n,onLongPress:u},i.id):null})}));Bi.displayName="ImageLayer";var th=({src:e,x:o,id:t,y:a,width:s,height:r,isSelected:n,rotation:u=0,onTransformEnd:i,onDragEnd:c})=>{let p=ve(),d=useRef(null),l=f=>{p(qa(f));};return jsxs(Group,{draggable:true,x:o,y:a,width:s,height:r,rotation:u,onDragEnd:c,onTransformEnd:i,children:[jsx(Rect,{width:s,height:r,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${s}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:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},iu=th;var dh=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,nodeRef:n})=>{let[u,i]=useState(null),c=useSelector(m=>m.toolbar.selectedTool),p=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let m=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(m.crossOrigin="anonymous"),m.src=e.thumbnailDataUrl,m.onload=()=>{i(m);};}},[e.thumbnailDataUrl]),!u)return null;let d=e.width/2,l=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,80));return jsxs(Group,{draggable:!p,listening:!p,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...p?{}:{onDragEnd:a,onTransformEnd:s},ref:m=>{if(n(m),m){let v=m.getStage()?.container();if(v){let x=g=>{let b=m.getStage()?.getPointerPosition();if(b){let w={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=w.x&&b.x<=w.x+w.width&&b.y>=w.y&&b.y<=w.y+w.height&&r(g);}};v.addEventListener("contextmenu",x),m._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",x);};}}},children:[jsx(Image$1,{image:u,width:e.width,height:e.height,listening:!p,...p?{}:{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:!p,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...p?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:l,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!p,...p?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:l,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!p,...p?{}:{onClick:t,onTap:t}})]})},du=dh;var Vi=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:s,onTransformEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(u=>jsxs(ye__default.Fragment,{children:[jsx(du,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>a(u.id),onDragEnd:i=>s(u.id,i),onTransformEnd:i=>r(u.id,i),onContextMenu:i=>n(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=>s(u.id,i)})]},u.id))}));Vi.displayName="VideoLayer";var qi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:s,handleShapeDragStart:r,onContextMenu:n,onLongPress:u})=>{let i=useSelector(d=>d.toolbar.selectedTool),c=i==="pen"||i==="eraser",{createHandlers:p}=Ne({onLongPress:u});return jsx(Fragment,{children:e.map((d,l)=>{let f=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:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},radius:d.radius||d.width/2,width:d.width,height:d.width},f);case "star":return jsx(Star,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},sides:3,radius:d.radius||d.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},sides:d.sides||6,radius:d.radius||d.width/2},f);case "ellipse":return jsx(Ellipse,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},f);case "ring":return jsx(Ring,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "wedge":return jsx(Wedge,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},radius:d.radius||d.width/2,angle:d.angle||60},f);case "arrow":return jsx(Arrow,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "line":return jsx(Line,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},f)}})})});qi.displayName="ShapeLayer";var fu=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:s,onContextMenu:r,onDoubleClick:n,editingTextId:u,onLongPress:i})=>{let c=useSelector(l=>l.toolbar.selectedTool),p=c==="pen"||c==="eraser",{createHandlers:d}=Ne({onLongPress:i});return jsx(Fragment,{children:e.map(l=>{let f=l.id===u,h=l.fontWeight==="bold",m=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&&!f&&!p,listening:!p,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:m,align:l.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...p?{}:{onClick:()=>s(l.id),onTap:()=>s(l.id),onDblClick:()=>n(l.id),onDblTap:()=>n(l.id),onDragEnd:v=>t(v,l.id),onTransformEnd:()=>a(l.id),onContextMenu:v=>{v.evt.preventDefault();let x=v.evt;r(x,l.id,"text");},...d(l.id,"text")}},l.id)})})};var Fh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onNext:n,onPrevious:u,nodeRef:i,touchHandlers:c})=>{let[p,d]=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=()=>{d(x);};}},[e.images,e.currentIndex]),!p||e.images.length===0)return null;let l=8,f=2,h=Math.min(e.width,e.height)*.08,m=Math.max(16,Math.min(h,32)),v=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:s,...c,ref:x=>{if(i(x),x){let g=x.getStage()?.container();if(g){let b=w=>{let I=x.getStage()?.getPointerPosition();if(I){let P={x:e.x,y:e.y,width:e.width,height:e.height};I.x>=P.x&&I.x<=P.x+P.width&&I.y>=P.y&&I.y<=P.y+P.height&&r(w);}};g.addEventListener("contextmenu",b),x._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",b);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:l,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:l,stroke:"#E5E7EB",strokeWidth:f,listening:false}),jsx(Image$1,{x:f+4,y:f+4,image:p,width:e.width-(f+4)*2,height:e.height-(f+4)*2,cornerRadius:l-f,onClick:t,onTap:t}),jsx(Rect,{x:f,y:e.height-50,width:e.width-f*2,height:50,cornerRadius:[0,0,l-f,l-f],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:v+m,y:e.height/2,onClick:x=>{x.cancelBubble=true,u();},onTap:x=>{x.cancelBubble=true,u();},children:[jsx(Circle,{radius:m,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-v-m,y:e.height/2,onClick:x=>{x.cancelBubble=true,n();},onTap:x=>{x.cancelBubble=true,n();},children:[jsx(Circle,{radius:m,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"})]})},hu=Fh;var Ki=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onNext:n,onPrevious:u,onContextMenu:i,onLongPress:c})=>{let{createHandlers:p}=Ne({onLongPress:c});return jsx(Fragment,{children:e.map(d=>jsx(hu,{flashcard:d,isSelected:t===d.id,onClick:()=>r(d.id),onDragEnd:a,onTransformEnd:l=>s(d.id,l),onContextMenu:l=>i(l,d.id,"flashcard"),onNext:()=>n(d.id),onPrevious:()=>u(d.id),touchHandlers:p(d.id,"flashcard"),nodeRef:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);}},d.id))})});Ki.displayName="FlashcardLayer";var xu=e=>{let o=ve(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null);Q(b=>b.toolbar.selectedTool);let i=Q(b=>b.toolbar.penColor),c=Q(b=>b.toolbar.strokeWidth),p=Q(b=>b.canvas.isSketchMode),d=Q(b=>b.canvas.slides.find(I=>I.id===b.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,m=d?.height||1,v=useCallback(b=>{if(!f)return;t.current=true,a.current=false,s.current=[{x:b.x,y:b.y}];let w=b.x/h,I=b.y/m;n({tool:"pen",points:[w,I],color:i,strokeWidth:c/h,isSketch:p});},[f,i,c,p,h,m]),x=useCallback(b=>{if(!t.current||!r)return;a.current=true;let w=s.current[s.current.length-1];if(Math.sqrt(Math.pow(b.x-w.x,2)+Math.pow(b.y-w.y,2))<2)return;s.current.push({x:b.x,y:b.y});let P;if(p)P=Ns(s.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((S,y)=>y%2===0?S/h:S/m);else {let k=b.x/h,S=b.y/m;P=[...r.points,k,S];}n(k=>k?{...k,points:P}:null);},[p,c,r,h,m]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(di({frameId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:f,startDrawing:v,draw:x,stopDrawing:g}};var Kh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onStartCamera:n,onCapture:u,cameraStream:i,nodeRef:c,touchHandlers:p})=>{let[d,l]=useState(null),[f,h]=useState(null),m=useRef(null),v=useRef(null),x=useRef(null),g=useRef(null),b=useRef(0),w=33,I=useSelector(q=>q.toolbar.selectedTool),P=I==="pen"||I==="eraser",{annotations:k,activeLine:S,isDrawingMode:y,startDrawing:E,draw:B,stopDrawing:T}=xu(e.id);useEffect(()=>{if(!y)return;let q=()=>{T();},_=()=>{T();};return window.addEventListener("mouseup",q),window.addEventListener("touchend",_),()=>{window.removeEventListener("mouseup",q),window.removeEventListener("touchend",_);}},[T,y]),useEffect(()=>{if(e.capturedImageUrl){let q=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(q.crossOrigin="anonymous"),q.src=e.capturedImageUrl,q.onload=()=>{l(q);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){m.current||(m.current=document.createElement("video"),m.current.autoplay=true,m.current.playsInline=true),v.current||(v.current=document.createElement("canvas"));let q=m.current,_=v.current;q.srcObject=i;let K=()=>{_.width=q.videoWidth||640,_.height=q.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",_.width,_.height);let X=te=>{if(te-b.current<w){x.current=requestAnimationFrame(X);return}b.current=te;let $=_.getContext("2d");if($&&q.readyState===q.HAVE_ENOUGH_DATA){$.drawImage(q,0,0,_.width,_.height);let re=_.toDataURL("image/jpeg",.6),ie=new window.Image;ie.onload=()=>{h(ie);},ie.src=re;}x.current=requestAnimationFrame(X);};x.current=requestAnimationFrame(X);};return q.onloadedmetadata=K,q.readyState>=q.HAVE_METADATA&&K(),q.play().catch(X=>console.error("Error playing video:",X)),()=>{x.current&&(cancelAnimationFrame(x.current),x.current=null);}}return ()=>{h(null),g.current&&(g.current.src="");}},[e.isCapturing,i]);let G=()=>{m.current&&e.isCapturing&&u(m.current);},F=q=>{if(e.capturedImageUrl){if(!y){t();return}let _=q.currentTarget,K=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){K.invert();let $=K.point(te);E($);}q.cancelBubble=true;}else t();},O=q=>{if(!y||!e.capturedImageUrl)return;let _=q.currentTarget,K=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){K.invert();let $=K.point(te);B($);}},U=()=>{!y||!e.capturedImageUrl||T();},V=e.isCapturing?f:d,H=Math.min(e.width,e.height)*.12,oe=Math.max(25,Math.min(H,50)),me=e.width/2,W=e.height/2;return jsxs(Group,{id:e.id,draggable:!y&&!P,listening:true,x:e.x,y:e.y,...p,...P?{}:{onDragEnd:a,onTransformEnd:s},rotation:e.rotation,width:e.width,height:e.height,ref:q=>{if(c(q),q){let _=q.getStage()?.container();if(_){let K=X=>{let te=q.getStage()?.getPointerPosition();if(te){let $={x:e.x,y:e.y,width:e.width,height:e.height};te.x>=$.x&&te.x<=$.x+$.width&&te.y>=$.y&&te.y<=$.y+$.height&&r(X);}};_.addEventListener("contextmenu",K),q._contextMenuCleanup=()=>{_.removeEventListener("contextmenu",K);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:V?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),V&&jsx(Image$1,{image:V,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:F,onTap:F,onMouseDown:F,onTouchStart:F,onMouseMove:O,onTouchMove:O,onMouseUp:U,onTouchEnd:U,...P?{}:{onDragEnd:a,onTransformEnd:s}}),k?.map((q,_)=>{let K=q.points.map((te,$)=>$%2===0?te*e.width:te*e.height),X=q.strokeWidth*e.width;return jsx(Line,{points:K,stroke:q.tool==="eraser"?"white":q.color,strokeWidth:X,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:q.tool==="eraser"?"destination-out":"source-over",fill:q.isSketch?q.color:void 0,closed:q.isSketch,listening:false},_)}),S&&jsx(Line,{points:S.points.map((q,_)=>_%2===0?q*e.width:q*e.height),stroke:S.tool==="eraser"?"white":S.color,strokeWidth:S.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:S.tool==="eraser"?"destination-out":"source-over",fill:S.isSketch?S.color:void 0,closed:S.isSketch,listening:false},"active"),!V&&!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:W-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:me-oe+6,y:W-60,width:oe*1.6,height:oe*1.6,radius:oe,fill:"white",cornerRadius:8,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?G():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?G():n();}}),jsx(Html,{groupProps:{x:me-12,y:W-40,width:oe*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?G():n();}})})]}),jsx(Text,{x:0,y:W,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:W+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:me-24,y:W+104,width:oe*1.6,height:oe*1.6,radius:oe,fill:"#096B76",cornerRadius:oe,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?G():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?G():n();}}),jsx(Html,{groupProps:{x:me-8,y:W+120,width:oe*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?G():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:me-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:q=>{q.stopPropagation(),G();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},wu=Kh;var Xi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onStartCamera:n,onCapture:u,cameraStreams:i,onContextMenu:c,onLongPress:p})=>{let{createHandlers:d}=Ne({onLongPress:p});return jsx(Fragment,{children:e.map(l=>jsx(wu,{photoFrame:l,isSelected:t===l.id,onClick:()=>r(l.id),onDragEnd:f=>a(f,l.id),onTransformEnd:f=>s(l.id,f),onContextMenu:f=>c(f,l.id,"photoFrame"),onStartCamera:()=>n(l.id),onCapture:f=>u(l.id,f),cameraStream:i.get(l.id),touchHandlers:d(l.id,"photoFrame"),nodeRef:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);}},l.id))})});Xi.displayName="PhotoFrameLayer";var Cu=({x:e,y:o,onAction:t,onClose:a,type:s,elementId:r="",isDrawingMode:n,menuRef:u})=>{useEffect(()=>{let d=f=>{u?.current&&!u.current.contains(f.target)&&a();},l=f=>{f.key==="Escape"&&a();};return document.addEventListener("mousedown",d),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",l);}},[a]);let i=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:n?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(l=>!(l.showForTypes&&!l.showForTypes.includes(s)||l.hideForTypes&&l.hideForTypes.includes(s))),[s,n]),c=(d,l)=>{d==="order"||d==="lock"?t(d,l):(t(d),a());},p=jsx("div",{ref:u,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:i.map((d,l)=>jsxs("button",{onClick:f=>c(d.action,f),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] ${d.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[d.icon,jsx("span",{className:`font-medium ${d.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:d.label})]}),d.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},l))})});return createPortal(p,document.body)};var ku=({x:e,y:o,items:t,onClose:a})=>{let s=useRef(null);return useEffect(()=>{let r=n=>{s.current&&!s.current.contains(n.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:s,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,n)=>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})},n))})})};var Mu=createContext(null),$i=()=>useContext(Mu);function pg({children:e,className:o="",style:t}){let a=useRef(null),[s,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Mu.Provider,{value:s,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function qe(){let e=$i();return typeof document>"u"?null:e||document.body}var Au=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:s,onClose:r})=>{let[n,u]=useState(a),i=useRef(null),c=qe();useEffect(()=>{i.current?.focus();},[]);let p=()=>{s(n),r();},d=f=>{f.key==="Enter"?p():f.key==="Escape"&&r();};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{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:n,onChange:f=>u(f.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:p,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 Ws=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,s]=useState(e),r=useRef(null),n=qe();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,f)=>{f/=100;let h=l*Math.min(f,1-f)/100,m=v=>{let x=(v+d/30)%12,g=f-h*Math.max(Math.min(x-3,9-x,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return `#${m(0)}${m(8)}${m(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!n)return null;let p=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=>s(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=>s(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),f=i(l,100,50);s(f);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(d=>jsx("button",{type:"button",onClick:()=>s(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(p,n)};var Rg=({imageSrc:e,onCrop:o})=>{let[t]=Du(e),a=useRef(null),s=useRef(null),r=useRef(null),n=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=n.width*.5,f=n.height*.5,h=(n.width-l)/2,m=(n.height-f)/2;return {x:h,y:m,width:l,height:f}},[n]),[i,c]=useState(u);useEffect(()=>{c(u);},[u]),useEffect(()=>{r.current&&s.current&&(r.current.nodes([s.current]),r.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let p=()=>{let l=s.current;if(!l)return;let f=l.scaleX(),h=l.scaleY();l.scaleX(1),l.scaleY(1),c({x:l.x(),y:l.y(),width:Math.max(20,l.width()*f),height:Math.max(20,l.height()*h)});},d=()=>{let l=s.current;l&&c({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:s,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:p,dragBoundFunc:l=>{let f=Math.max(0,Math.min(l.x,n.width-i.width)),h=Math.max(0,Math.min(l.y,n.height-i.height));return {x:f,y:h}}}),jsx(Transformer,{ref:r,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(l,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>n.width||f.y+f.height>n.height?l:f})]})})},Ru=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[s,r]=useState({x:0,y:0,width:0,height:0}),[n]=Du(e),u=qe();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let i=(d,l,f,h)=>{r({x:d,y:l,width:f,height:h});},c=()=>{if(!n)return;let f=Math.min(600/n.width,400/n.height),h=s.x/f,m=s.y/f,v=s.width/f,x=s.height/f,g=document.createElement("canvas");g.width=v,g.height=x;let b=g.getContext("2d");if(!b)return;b.drawImage(n,h,m,v,x,0,0,v,x);let w=g.toDataURL("image/png");o(w);};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(Rg,{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 pr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let s=qe(),[r,n]=useState(false),[u,i]=useState(null),[c,p]=useState(0),[d,l]=useState(true),f=useRef(null),h=useRef([]),m=useRef(null),v=useRef(null),x=useRef(null),g=useRef(null),b=useRef(null),w=useRef(null);useEffect(()=>()=>{x.current&&cancelAnimationFrame(x.current),m.current&&clearInterval(m.current),v.current&&v.current.getTracks().forEach(E=>E.stop());},[]);let I=async()=>{try{let E,B=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((K,X)=>{let te=K.getChildren();console.log(`Layer ${X} children count:`,te.length);});let V=document.createElement("canvas");V.width=o.current.width(),V.height=o.current.height();let H=V.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:",V.width,"x",V.height),b.current=V;let oe=()=>{if(H.clearRect(0,0,V.width,V.height),U.forEach(K=>{let X=K.getCanvas()._canvas;X&&H.drawImage(X,0,0);}),a?.current){let K=a.current;H.drawImage(K,0,0);}};w.current=oe,o.current.draw(),oe(),await new Promise(K=>setTimeout(K,100)),console.log("Creating captureStream..."),E=V.captureStream(30),console.log("Canvas stream created, tracks:",E.getTracks().length);let W=E.getVideoTracks()[0];W&&console.log("Video track:",W.label,"state:",W.readyState);let q=0,_=()=>{oe(),o?.current&&(o.current.getLayers().forEach(X=>{X.batchDraw();}),q++,q%60===0&&console.log("Drawing frame:",q)),x.current=requestAnimationFrame(_);};_();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{B=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let T=[...E.getVideoTracks()];B&&T.push(...B.getAudioTracks());let G=new MediaStream(T);v.current=G;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 O=new MediaRecorder(G,{mimeType:F,videoBitsPerSecond:25e5});f.current=O,h.current=[],O.ondataavailable=U=>{console.log("Data available, size:",U.data.size),U.data.size>0&&h.current.push(U.data);},O.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&&w.current&&b.current&&(o.current.draw(),o.current.getLayers().forEach(H=>{H.batchDraw();}),w.current(),g.current=b.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",g.current.length)),G.getTracks().forEach(V=>V.stop()),m.current&&clearInterval(m.current),x.current&&(cancelAnimationFrame(x.current),x.current=null),i(U);},O.onerror=U=>{console.error("MediaRecorder error:",U);},console.log("Starting recording..."),O.start(1e3),n(!0),p(0),m.current=setInterval(()=>{p(U=>U+1);},1e3);}catch(E){console.error("Error starting screen recording:",E),alert("Failed to start recording. Please ensure you granted permission.");}},P=()=>{f.current&&r&&(console.log("Stopping recording, state:",f.current.state),f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),n(false));},k=()=>{if(u){let E=URL.createObjectURL(u),B=document.createElement("a");B.href=E,B.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(B),B.click(),document.body.removeChild(B),URL.revokeObjectURL(E);}},S=E=>{let B=Math.floor(E/60),T=E%60;return `${B.toString().padStart(2,"0")}:${T.toString().padStart(2,"0")}`};if(!s)return null;if(r){let E=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:S(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:P,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(E,s)}let y=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: ",S(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&g.current&&(t(u,g.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick: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),p(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(y,s)};var Nu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:s})=>{let r=qe(),[n,u]=useState(false),[i,c]=useState(null),[p,d]=useState(false),[l,f]=useState(0),h=useRef(null),m=useRef([]),v=useRef(null),x=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(E=>E.blob()).then(E=>c(E)).catch(E=>console.error("Error loading audio:",E));},[o,i]);let g=async()=>{try{let E=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),B=new MediaRecorder(E);h.current=B,m.current=[],B.ondataavailable=T=>{T.data.size>0&&m.current.push(T.data);},B.onstop=()=>{let T=new Blob(m.current,{type:"audio/webm"});c(T),E.getTracks().forEach(G=>G.stop()),v.current&&clearInterval(v.current);},B.start(),u(!0),f(0),v.current=setInterval(()=>{f(T=>T+1);},1e3);}catch(E){console.error("Error starting audio recording:",E),alert("Failed to start recording. Please allow microphone access.");}},b=()=>{h.current&&n&&(h.current.stop(),u(false));},w=()=>{if(i){let E=URL.createObjectURL(i),B=new Audio(E);x.current=B,B.onended=()=>{d(false),URL.revokeObjectURL(E);},B.play(),d(true);}},I=()=>{x.current&&(x.current.pause(),x.current.currentTime=0,d(false));},P=async()=>{if(i){let E=new FileReader;E.onloadend=()=>{let B=E.result;t(B),s();},E.readAsDataURL(i);}},k=()=>{c(null),a();},S=E=>{let B=Math.floor(E/60),T=E%60;return `${B.toString().padStart(2,"0")}:${T.toString().padStart(2,"0")}`};if(!r)return null;if(n){let E=jsx("div",{className:"pointer-events-none fixed inset-0 z-50",children:jsxs("div",{className:"pointer-events-auto fixed top-[100px] left-1/2 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:S(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: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(E,r)}let y=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:g,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:p?I:w,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),p?"Playing...":"Play Audio"]}),jsx("button",{onClick:k,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:P,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:s,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(y,r)};var Ft=({audioData:e,x:o,y:t,width:a,scale:s=1,offsetX:r=0,offsetY:n=0,containerTop:u=90,containerRight:i=320})=>{let[c,p]=useState(false),d=useRef(null),l=m=>{if(m.stopPropagation(),c&&d.current)d.current.pause(),d.current.currentTime=0,p(false);else {let v=new Audio(e);d.current=v,v.onended=()=>{p(false);},v.onerror=()=>{console.error("Error playing audio"),p(false);},v.play(),p(true);}},f=(o+a)*s+r-15,h=t*s+n+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:`${f}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var Hu=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=ve(),s=Q(ge),r=qe(),n=useMemo(()=>{if(!s)return [];let x=[];return s.images?.forEach(g=>{x.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),s.videos?.forEach(g=>{x.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),s.shapes?.forEach(g=>{x.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),s.texts?.forEach(g=>{x.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),s.flashcards?.forEach(g=>{x.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),s.photoFrames?.forEach(g=>{x.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),s.multipleChoices?.forEach(g=>{x.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),s.trueFalses?.forEach(g=>{x.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),s.shortAnswers?.forEach(g=>{x.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),s.LongAnswer?.forEach(g=>{x.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),s.fillInTheBlanks?.forEach(g=>{x.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),s.lines?.forEach(g=>{g.id&&x.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),x.sort((g,b)=>b.timestamp-g.timestamp)},[s]),[u,i]=useState(n),[c,p]=useState(false);useEffect(()=>{c||i(n);},[n]);let d=x=>{let g="h-5 w-5";switch(x){case "image":return jsx(Image$3,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes$1,{className:g});case "text":return jsx(TextT,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners,{className:g});case "line":return jsx(Pen,{className:g});default:return jsx(Question,{className:g})}},h=x=>{p(true),i(x);},m=()=>{p(false);let x=Date.now();u.forEach((g,b)=>{let w=x-b;a(rr({id:g.id,type:g.type,newTimestamp:w}));});};if(!r)return null;let v=jsxs("div",{className:"konva-editor-root",children:[jsx("div",{className:"fixed inset-0 z-9999 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-10000 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(x=>{let g=x.id===e;return jsxs(Reorder.Item,{value:x,onDragEnd:m,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${g?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(x.id,x.type),className:`font-medium ${g?"text-[#096B76]":"text-[#00000099]"}`,children:x.name})}),jsx("div",{className:`${g?"text-[#096B76]":"text-[#00000099]"}`,children:d(x.type)})]},x.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 Uu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r,touchHandlers:n})=>{let u=useSelector(W=>W.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,p]=useState(new Set),[d,l]=useState(false),[f,h]=useState(null),m=useRef(null);useEffect(()=>{let W=m.current;if(W)return a.current.set(e.id,W),()=>{a.current.delete(e.id);}},[e.id]);let v=new Set(e.data.responseOptions.correctIndex),x=v.size>1,g=W=>{d||p(x?q=>{let _=new Set(q);return _.has(W)?_.delete(W):_.add(W),_}:new Set([W]));},b=()=>{c.size>0&&l(true);},w=()=>{l(false),p(new Set);},I=c.size===v.size&&Array.from(c).every(W=>v.has(W)),P=Array.from(c).filter(W=>v.has(W)),k=x&&P.length>0&&!I,S=()=>I?"\u2713 Correct! Great job! \u{1F389}":k?`\u26A0 Partially correct (${P.length}/${v.size})`:"\u2717 Try again!",y=()=>I?{bg:"#dcfce7",text:"#166534"}:k?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},E=55,B=8,T=24,G=60,F=60,O=x&&!d?25:0,U=e.data.feedbackMode==="practice"?48:0,V=12,H=G+O+(d?F:0),oe=e.data.responseOptions.options.length*(E+B),me=H+oe+V+U+T;return jsxs(Group,{ref:m,name:"mcq-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...n,...i?{}:{onDragEnd:s,onClick:W=>t&&t(e.id),onTap:W=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:me,width:e.width,onTransformEnd:W=>o(e.id,W),onContextMenu:W=>{W.cancelBubble=true,r(W.evt,e.id,"mcq");}}),jsx(Text,{x:T+8,y:T,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-T*2,listening:false}),x&&!d&&e.data.feedbackMode==="practice"?jsx(Text,{x:T,y:T+35,text:`Select ${v.size} answers (${c.size}/${v.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-T*2,listening:false}):null,d&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:T+24,y:G+O,width:e.width-T*2-40,height:F-20,fill:y().bg,cornerRadius:8}),jsx(Text,{x:T,y:G+O,width:e.width-T*2,height:F-20,text:S(),fontSize:16,fontStyle:"bold",fill:y().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((W,q)=>{let _=v.has(q),K=c.has(q),X=H+q*(E+B),te="#e5e7eb",$="#ffffff",re="#111827";return d&&_?(te="#22c55e",$="#dcfce7",re="#1B9D2C"):d&&K&&!_?(te="#ef4444",$="#fee2e2",re="#ef4444"):K&&(te="#096B76",$="#ECFFF8",re="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:T+12,y:X+(E-20)/2,width:20,height:20,fill:K?"#096B76":"white",stroke:K?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:x?4:10,onClick:ie=>{ie.cancelBubble=true,g(q);},onTap:ie=>{ie.cancelBubble=true,g(q);}}),K&&jsx(Text,{x:T+12,y:X+(E-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:T+44,y:X,width:e.width-T*2-60,height:E,fill:$,stroke:te,strokeWidth:2,cornerRadius:8,onClick:ie=>{ie.cancelBubble=true,g(q);},onTap:ie=>{ie.cancelBubble=true,g(q);}}),jsx(Text,{x:T+60,y:X,width:e.width-T*2-80,height:E,text:W,fontSize:16,fill:re,verticalAlign:"middle",listening:false})]},q)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:H+e.data.responseOptions.options.length*(E+B)+12,children:[jsxs(Group,{onMouseDown:W=>{W.cancelBubble=true,h("check");},onMouseUp:W=>{W.cancelBubble=true,h(null),b();},onMouseLeave:W=>{W.cancelBubble=true,h(null);},onTouchStart:W=>{W.cancelBubble=true,h("check");},onTouchEnd:W=>{W.cancelBubble=true,h(null),b();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:T+14,width:(e.width-T*2-24)/(d?2:1),height:48,fill:c.size===0||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.cancelBubble=true}),jsx(Text,{x:T+14,width:(e.width-T*2-24)/(d?2:1),height:48,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-T*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),w();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),w();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:T,width:(e.width-T*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.cancelBubble=true}),jsx(Text,{x:T,width:(e.width-T*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Uu.displayName="MultipleChoice";var Ku=Uu;var Qi=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:s,touchHandlers:r})=>{let n=useDispatch(),u=useSelector(K=>K.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,p]=useState(false),[d,l]=useState(new Set),[f,h]=useState(false),[m,v]=useState(false),[x,g]=useState(0),b=340,w=100,I=window.innerWidth*.4,P=window.innerHeight*.5,k=b+20,S=w+60,y=I-40,E=P-300,B=useRef(null);useEffect(()=>{let K=B.current;if(K)return s.current.set(e.id,K),()=>{s.current.delete(e.id);}},[e.id]);let T=K=>{n(pa({id:e.id,x:K.target.x(),y:K.target.y()}));},G=K=>{let X=K.target,te=X.x(),$=X.y(),re=window.innerWidth*.2,Ae=te+re>k&&te<k+y&&$+50>S&&$<S+E;p(Ae);},F=(K,X)=>{let te=X.target,$=te.x(),re=te.y(),ie=window.innerWidth*.2,Ce=$+ie>k&&$<k+y&&re+50>S&&re<S+E;l(Ce?Ee=>new Set(Ee).add(K):Ee=>{let lt=new Set(Ee);return lt.delete(K),lt}),p(false);},O=()=>{h(true);},U=()=>{h(false),l(new Set),g(K=>K+1);},V=new Set(e.data.responseOptions.correctIndex),H=d.size===V.size&&Array.from(d).every(K=>V.has(K)),oe=Array.from(d).filter(K=>V.has(K)),me=oe.length>0&&!H,W=()=>H?"\u2713 Correct! Great job!":me?`\u26A0 Partially correct (${oe.length}/${V.size})`:"\u2717 Try again!",q=()=>H?{bg:"#dcfce7",text:"#166534"}:me?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},_=()=>f?H?"#4CAF50":me?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:B,name:"mcq-element",width:I,height:P,draggable:!i,listening:!i,...r,...i?{}:{onClick:K=>a&&a(e.id),onTap:K=>a&&a(e.id),onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"mcq");}},children:[jsxs(Group,{x:b,y:w,rotation:e.rotation,onDragEnd:T,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?P-100:P-50,width:I,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:I-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:y,height:E,fill:"#EBF6F7",stroke:_(),strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:E+18,width:y-5,height:60,fill:q().bg,cornerRadius:8}),jsx(Text,{x:20,y:E+20,width:y,height:60,text:W(),fontSize:18,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle"})]}),d.size===0&&!f&&jsx(Text,{x:20,y:60,width:y,height:E-60,text:V.size>1?`Drop ${V.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:f?P-200:P-160,children:[jsxs(Group,{onMouseDown:()=>{v(true),O();},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),O();},onTouchEnd:()=>v(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:y}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:y,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:U,onTouchStart:U,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:y}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:y,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((K,X)=>{let te=X%2,$=Math.floor(X/2),re=window.innerWidth*.2,ie=50,Ae=10,Ce=d.has(X),Ee=V.has(X),lt=f&&Ce,bt="transparent";return lt?bt=Ee?"#4CAF50":"#ef4444":Ce&&(bt="#4CAF50"),jsxs(Group,{x:340+te*(re+Ae),y:w+P-80+$*(ie+Ae),draggable:!f,onDragMove:G,onDragEnd:lo=>F(X,lo),opacity:f&&!Ce?.5:1,children:[jsx(Rect,{width:re-20,height:ie,fill:"white",stroke:bt,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:re-20,height:ie,text:K,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${X}-${x}`)})]})};Qi.displayName="MultipleChoiceDragAndDrop";var Wu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r,onLongPress:n})=>{let{createHandlers:u}=Ne({onLongPress:n});return jsx(Fragment,{children:e.map(i=>i.data.responseType==="classic"?jsx(Ku,{multipleChoice:i,handleMcqTransform:o,mcqRefs:a,handleDragEnd:c=>s(c,i.id),onContextMenu:r,touchHandlers:u(i.id,"mcq")},i.id):jsx(Qi,{multipleChoice:i,handleMcqTransform:o,mcqRefs:a,onContextMenu:r,touchHandlers:u(i.id,"mcq")},i.id))})};var zu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r,touchHandlers:n})=>{let u=useSelector(V=>V.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,p]=useState(null),[d,l]=useState(false),[f,h]=useState(null),m=useRef(null);useEffect(()=>{let V=m.current;if(V)return a.current.set(e.id,V),()=>{a.current.delete(e.id);}},[e.id]);let v=()=>{c!==null&&l(true);},x=()=>{l(false),p(null);},g=e.data.responseOptions.correctAnswer,b=c===g,w=V=>{d||p(V);},I=()=>b?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",P=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},k=70,S=12,y=24,E=60,B=60,T=e.data.feedbackMode==="practice"?48:0,G=12,F=E+(d?B:0),O=2*(k+S),U=F+O+G+T+y;return jsxs(Group,{ref:m,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...n,...i?{}:{onDragEnd:V=>r(V,e.id),onClick:V=>t&&t(e.id),onTap:V=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:U-20,width:e.width,onTransformEnd:V=>o(e.id,V),onContextMenu:V=>{V.cancelBubble=true,s(V.evt,e.id,"trueFalse");}}),jsx(Text,{x:y,y,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),d&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:y,y:E,width:e.width-y*2,height:B-10,fill:P().bg,cornerRadius:8}),jsx(Text,{x:y,y:E,width:e.width-y*2,height:B-10,text:I(),fontSize:16,fontStyle:"bold",fill:P().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((V,H)=>{let oe=g===V.value,me=c===V.value,W=(e.width-y*3)/2,q=y+H*(W+y),_=F,K=V.value===true,X=K?"#10b981":"#ef4444",te="#ffffff",$="#ffffff",re="#e5e7eb";return d&&(oe?($=K?"#f0fdf4":"#fef2f2",re=K?"#86efac":"#fecaca"):me&&!oe&&($="#fee2e2",re="#ef4444")),me&&!d&&(re="#096B76",$="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:q,y:_,width:W,height:k+50,fill:$,stroke:re,strokeWidth:2,cornerRadius:12,onClick:ie=>{ie.cancelBubble=true,w(V.value);},onTap:ie=>{ie.cancelBubble=true,w(V.value);}}),jsx(Circle,{x:q+W/2,y:_+40,radius:28,fill:X,listening:false}),K?jsx(Text,{x:q+W/2-14,y:_+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:q+W/2-14,y:_+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:q,y:_+85,width:W,height:30,text:V.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},V.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:F+2*(k+S),children:[jsxs(Group,{onMouseDown:V=>{V.cancelBubble=true,h("check");},onMouseUp:V=>{V.cancelBubble=true,h(null),v();},onMouseLeave:V=>{V.cancelBubble=true,h(null);},onTouchStart:V=>{V.cancelBubble=true,h("check");},onTouchEnd:V=>{V.cancelBubble=true,h(null),v();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:y,width:(e.width-y*2-8)/(d?2:1),height:48,fill:c===null||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:V=>V.cancelBubble=true,onTap:V=>V.cancelBubble=true}),jsx(Text,{x:y,width:(e.width-y*2-8)/(d?2:1),height:48,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-y*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),x();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),x();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:y,width:(e.width-y*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:V=>V.cancelBubble=true,onTap:V=>V.cancelBubble=true}),jsx(Text,{x:y,width:(e.width-y*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});zu.displayName="TrueFalse";var Gu=zu;var Ex="#FFFFFF",al=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t,touchHandlers:a})=>{let s=useDispatch(),r=useSelector(X=>X.toolbar.selectedTool),n=r==="pen"||r==="eraser",[u,i]=useState(false),[c,p]=useState(null),[d,l]=useState(false),[f,h]=useState(false),[m,v]=useState(0),[x,g]=useState(false),b=340,w=100,I=window.innerWidth*.4,P=window.innerHeight*.5,k=I-40,S=P-300,y=20,E=60,B=k,T=S,G=I*.2-40,F=50,O=useRef(null),U=X=>{s(ha({id:e.id,x:X.target.x(),y:X.target.y()}));},V=X=>{let te=X.target,$=te.x(),re=te.y(),ie=Math.max(0,Math.min($+G,y+B)-Math.max($,y)),Ae=Math.max(0,Math.min(re+F,E+T)-Math.max(re,E)),Ce=ie*Ae,Ee=G*F;i(Ce/Ee>=.5);},H=(X,te)=>{let $=te.target,re=$.x(),ie=$.y(),Ae=Math.max(0,Math.min(re+G,y+B)-Math.max(re,y)),Ce=Math.max(0,Math.min(ie+F,E+T)-Math.max(ie,E)),Ee=Ae*Ce,lt=G*F;if(Ee/lt>=.5)p(X);else return;i(false);},oe=()=>{l(true);},me=()=>{l(false),p(null),v(X=>X+1);},W=e.data.responseOptions.correctAnswer,q=c===W,_=()=>q?"\u2713 Correct! Great job!":"\u2717 Try again!",K=()=>q?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:O,name:"trueFalse-element",width:I,height:P,draggable:!n,listening:!n,...a,...n?{}:{onContextMenu:X=>{X.evt.preventDefault(),o(X.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:w,rotation:e.rotation,onDragEnd:U,children:[jsx(Rect,{fill:"white",stroke:u?"#4CAF50":"#e5e7eb",strokeWidth:u?4:2,cornerRadius:12,height:d?P:e.data.feedbackMode==="practice"?P-50:P-100,width:I,shadowColor:u?"#4CAF50":"transparent",shadowBlur:u?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:I-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:k,height:S,fill:"transparent",stroke:u?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:k,height:60,fill:K().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:k,height:60,text:_(),fontSize:18,fontStyle:"bold",fill:K().text,align:"center",verticalAlign:"middle"})]}),c===null&&!d&&jsx(Text,{x:20,y:60,width:k,height:S-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:P-100,children:[jsxs(Group,{onMouseDown:()=>{c!==null&&(h(true),oe());},onMouseUp:()=>h(false),onMouseLeave:()=>h(false),onTouchStart:()=>{c!==null&&(h(true),oe());},onTouchEnd:()=>h(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:c===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{y:50,onMouseDown:me,onTouchStart:me,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((X,te)=>{let $=window.innerWidth*.2,re=50,ie=10,Ae=c===X.value,Ce=W===X.value,Ee=d&&Ae,lt="transparent";return Ee?lt=Ce?"#4CAF50":"#ef4444":Ae&&(lt="#4CAF50"),jsxs(Group,{x:16+te*($+ie),y:w+P-300,draggable:!d,onDragMove:V,onDragEnd:bt=>H(X.value,bt),opacity:d&&!Ae?.5:1,children:[jsx(Rect,{width:$-40,height:re,fill:"#075560",stroke:lt,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:$-40,height:re,text:X.label,fontSize:18,fontStyle:"bold",fill:Ex,align:"center",verticalAlign:"middle",listening:false})]},`${X.value}-${m}`)})]})})};al.displayName="TrueFalseDragAndDrop";var ju=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:s,onContextMenu:r,onLongPress:n})=>{let{createHandlers:u}=Ne({onLongPress:n});return jsx(Fragment,{children:e.map(i=>i.data.responseType==="classic"?jsx(Gu,{trueFalse:i,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s,touchHandlers:u(i.id,"trueFalse")},i.id):jsx(al,{trueFalse:i,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:r,touchHandlers:u(i.id,"trueFalse")},i.id))})};var ya=new WeakMap,Ao=new WeakMap,yr={current:[]},rl=false,vr=0,br=new Set,$s=new Map;function _u(e){let o=Array.from(e).sort((t,a)=>t instanceof Gt&&t.options.deps.includes(a)?1:a instanceof Gt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(yr.current.includes(t))continue;yr.current.push(t),t.recompute();let a=Ao.get(t);if(a)for(let s of a){let r=ya.get(s);r&&_u(r);}}}function Fx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Bx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Ys(e){if(vr>0&&!$s.has(e)&&$s.set(e,e.prevState),br.add(e),!(vr>0)&&!rl)try{for(rl=!0;br.size>0;){let o=Array.from(br);br.clear();for(let t of o){let a=$s.get(t)??t.prevState;t.prevState=a,Fx(t);}for(let t of o){let a=ya.get(t);a&&(yr.current.push(t),_u(a));}for(let t of o){let a=ya.get(t);if(a)for(let s of a)Bx(s);}}}finally{rl=false,yr.current=[],$s.clear();}}function It(e){vr++;try{e();}finally{if(vr--,vr===0){let o=br.values().next().value;o&&Ys(o);}}}function Xu(e){return typeof e=="function"}var Qt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var s,r;this.listeners.add(a);let n=(r=(s=this.options)==null?void 0:s.onSubscribe)==null?void 0:r.call(s,a,this);return ()=>{this.listeners.delete(a),n?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,s;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):Xu(o)?this.state=o(this.prevState):this.state=o,(s=(a=this.options)==null?void 0:a.onUpdate)==null||s.call(a),Ys(this);}};var Gt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),s=new Array(t);for(let r=0;r<t;r++){let n=this.options.deps[r];a[r]=n.prevState,s[r]=n.state;}return this.lastSeenDepValues=s,{prevDepVals:a,currDepVals:s,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let s=this.getDepVals();this.state=this.options.fn(s),(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:s}=this.getDepVals();for(let r=0;r<s.length;r++)if(s[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,s;this.listeners.add(t);let r=(s=(a=this.options).onSubscribe)==null?void 0:s.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof Qt){let a=ya.get(t);a||(a=new Set,ya.set(t,a)),a.add(this);let s=Ao.get(this);s||(s=new Set,Ao.set(this,s)),s.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof Qt){let a=ya.get(t);a&&a.delete(this);let s=Ao.get(this);s&&s.delete(t);}}};function Ox(e){return typeof e=="function"}function sl(e,...o){return Ox(e)?e(...o):e}function $u(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var wa,pt,nt,wr,La,Ga,oa,Po,Lr,Js,Sr,Eo,ja=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:s=1e3}){Re(this,wa,true);Re(this,pt);Re(this,nt);Re(this,wr);Re(this,La);Re(this,Ga);Re(this,oa);Re(this,Po);Re(this,Lr,0);Re(this,Js,5);Re(this,Sr,()=>{this.debugLog("Connected to event bus"),Te(this,Ga,true),this.debugLog("Emitting queued events",j(this,La)),j(this,La).forEach(o=>this.emitEventToBus(o)),Te(this,La,[]),this.stopConnectLoop(),j(this,nt).call(this).removeEventListener("tanstack-connect-success",j(this,Sr));});Re(this,Eo,()=>{if(j(this,nt).call(this).addEventListener("tanstack-connect-success",j(this,Sr)),j(this,Lr)<j(this,Js)){Sd(this,Lr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}j(this,nt).call(this).removeEventListener("tanstack-connect",j(this,Eo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Te(this,pt,o),Te(this,wa,a),Te(this,nt,this.getGlobalTarget),Te(this,wr,t),this.debugLog(" Initializing event subscription for plugin",j(this,pt)),Te(this,La,[]),Te(this,Ga,false),Te(this,oa,null),Te(this,Po,s);}startConnectLoop(){j(this,oa)!==null||j(this,Ga)||(this.debugLog(`Starting connect loop (every ${j(this,Po)}ms)`),Te(this,oa,setInterval(j(this,Eo),j(this,Po))));}stopConnectLoop(){j(this,oa)!==null&&(clearInterval(j(this,oa)),Te(this,oa,null),this.debugLog("Stopped connect loop"));}debugLog(...o){j(this,wr)&&console.log(`\u{1F334} [tanstack-devtools:${j(this,pt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return j(this,pt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});j(this,nt).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{j(this,nt).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!j(this,wa)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!j(this,Ga)){this.debugLog("Bus not available, will be pushed as soon as connected"),j(this,La).push({type:`${j(this,pt)}:${o}`,payload:t,pluginId:j(this,pt)}),typeof CustomEvent<"u"&&(j(this,Eo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${j(this,pt)}:${o}`,payload:t,pluginId:j(this,pt)})}on(o,t){let a=`${j(this,pt)}:${o}`;if(!j(this,wa))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let s=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return j(this,nt).call(this).addEventListener(a,s),this.debugLog("Registered event to bus",a),()=>{j(this,nt).call(this).removeEventListener(a,s);}}onAll(o){if(!j(this,wa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;o(s);};return j(this,nt).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,nt).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!j(this,wa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;j(this,pt)&&s.pluginId!==j(this,pt)||o(s);};return j(this,nt).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,nt).call(this).removeEventListener("tanstack-devtools-global",t)}};wa=new WeakMap,pt=new WeakMap,nt=new WeakMap,wr=new WeakMap,La=new WeakMap,Ga=new WeakMap,oa=new WeakMap,Po=new WeakMap,Lr=new WeakMap,Js=new WeakMap,Sr=new WeakMap,Eo=new WeakMap;var nl=class extends ja{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Yu=(e,o)=>{il.emit(e,o);},il=new nl;function Ju(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Nx={enabled:true,leading:true,trailing:true,wait:0},Sa,Ct,_a,Xa,$a,Do,Zs=class{constructor(o,t){Re(this,Sa);Re(this,Ct);Re(this,_a);Re(this,Xa);Re(this,$a);Re(this,Do);this.fn=o,this.store=new Qt(Ju()),this.setOptions=a=>{this.options={...this.options,...a},j(this,_a).call(this)||this.cancel();},Te(this,Ct,a=>{this.store.setState(s=>{let r={...s,...a},{isPending:n}=r;return {...r,status:j(this,_a).call(this)?n?"pending":"idle":"disabled"}}),Yu("Throttler",this);}),Te(this,_a,()=>!!sl(this.options.enabled,this)),Te(this,Xa,()=>sl(this.options.wait,this)),this.maybeExecute=(...a)=>{j(this,Ct).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let s=Date.now(),r=s-this.store.state.lastExecutionTime,n=j(this,Xa).call(this);if(this.options.leading&&r>=n)j(this,$a).call(this,...a);else if(j(this,Ct).call(this,{lastArgs:a}),!j(this,Sa)&&this.options.trailing){let u=this.store.state.lastExecutionTime?s-this.store.state.lastExecutionTime:0,i=n-u;j(this,Ct).call(this,{isPending:true}),Te(this,Sa,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&j(this,$a).call(this,...c);},i));}},Te(this,$a,(...a)=>{if(!j(this,_a).call(this))return;this.fn(...a);let s=Date.now(),r=s+j(this,Xa).call(this);j(this,Do).call(this),j(this,Ct).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:s,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||j(this,Ct).call(this,{nextExecutionTime:void 0});},j(this,Xa).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&j(this,$a).call(this,...this.store.state.lastArgs);},Te(this,Do,()=>{j(this,Sa)&&(clearTimeout(j(this,Sa)),Te(this,Sa,void 0));}),this.cancel=()=>{j(this,Do).call(this),j(this,Ct).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{j(this,Ct).call(this,Ju());},this.key=$u(t.key),this.options={...Nx,...t},j(this,Ct).call(this,this.options.initialState??{}),il.on("d-Throttler",a=>{a.payload.key===this.key&&(j(this,Ct).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Sa=new WeakMap,Ct=new WeakMap,_a=new WeakMap,Xa=new WeakMap,$a=new WeakMap,Do=new WeakMap;function ll(e,o){return new Zs(e,o).maybeExecute}function Ia(e,o){return typeof e=="function"?e(o):e}function Ca(e,o){return an(o).reduce((a,s)=>{if(a===null)return null;if(typeof a<"u")return a[s]},e)}function Ro(e,o,t){let a=an(o);function s(r){if(!a.length)return Ia(t,r);let n=a.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[n]:s(r[n])}):{[n]:s()};if(Array.isArray(r)&&typeof n=="number"){let u=r.slice(0,n);return [...u.length?u:new Array(n),s(r[n]),...r.slice(n+1)]}return [...new Array(n),s()]}return s(e)}function ul(e,o){let t=an(o);function a(s){if(!s)return;if(t.length===1){let n=t[0];if(Array.isArray(s)&&typeof n=="number")return s.filter((c,p)=>p!==n);let{[n]:u,...i}=s;return i}let r=t.shift();if(typeof r=="string"&&typeof s=="object")return {...s,[r]:a(s[r])};if(typeof r=="number"&&Array.isArray(s)){if(r>=s.length)return s;let n=s.slice(0,r);return [...n.length?n:new Array(r),a(s[r]),...s.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var Vx=/^(\d+)$/gm,qx=/\.(\d+)(?=\.)/gm,Hx=/^(\d+)\./gm,Ux=/\.(\d+$)/gm,Kx=/\.{2,}/gm,dl="__int__",Qs=`${dl}$1`;function an(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(Vx,Qs).replace(qx,`.${Qs}.`).replace(Hx,`${Qs}.`).replace(Ux,`.${Qs}`).replace(Kx,".").split(".").map(o=>{if(o.startsWith(dl)){let t=o.substring(dl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function cl(e){return !(Array.isArray(e)&&e.length===0)}function Fo(e,o){let t=a=>a.validators.filter(Boolean).map(s=>({cause:s.cause,validate:s.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Bo(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:s,onDynamicAsyncDebounceMs:r}=o.validators||{},n=t??0,u=i=>i.validators.filter(Boolean).map(c=>{let p=c?.cause||e,d=n;switch(p){case "change":d=s??n;break;case "blur":d=a??n;break;case "dynamic":d=r??n;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:p,validate:c.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var Ir=e=>!!e&&typeof e=="object"&&"fields"in e;function ka(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[s,r]of e)if(!o.has(s)||!Object.is(r,o.get(s)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let s of e)if(!o.has(s))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let s of t)if(!a.includes(s)||!ka(e[s],o[s]))return false;return true}var on=({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},rn=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function $e(e,o){return e==null?o:{...e,...o}}var Ya=256,tn=[],en;for(;Ya--;)tn[Ya]=(Ya+256).toString(16).substring(1);function fl(){let e=0,o,t="";if(!en||Ya+16>256){for(en=new Array(256),e=256;e--;)en[e]=256*Math.random()|0;e=0,Ya=0;}for(;e<16;e++)o=en[Ya+e],e===6?t+=tn[o&15|64]:e===8?t+=tn[o&63|128]:t+=tn[o],e&1&&e>1&&e<11&&(t+="-");return Ya++,t}var Ta=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"},s={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,s,r,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[s,n],form:e.form});case "change":return e.runValidation({validators:[a,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Wx(e,o){let t=new Map;for(let a of e){let s=a.path??[],r=o,n="";for(let u=0;u<s.length;u++){let i=s[u];if(i===void 0)continue;let c=typeof i=="object"?i.key:i,p=Number(c);Array.isArray(r)&&!Number.isNaN(p)?n+=`[${p}]`:n+=(u>0?".":"")+String(c),typeof r=="object"&&r!==null?r=r[c]:r=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var Zu=(e,o)=>{let t=Wx(e,o);return {form:t,fields:t}},Ma={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:Zu(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:Zu(a.issues,e)}},sn=e=>!!e&&"~standard"in e;var Oo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function Cr(e){function o(d,l,f,h){let m=a(d,l,f,h);({insert:()=>u(m,d,l),remove:()=>i(m),swap:()=>h!==void 0&&p(m,d,l,h),move:()=>h!==void 0&&c(m,d,l,h)})[f]();}function t(d,l){return `${d}[${l}]`}function a(d,l,f,h){let m=[t(d,l)];if(f==="swap")m.push(t(d,h));else if(f==="move"){let[v,x]=[Math.min(l,h),Math.max(l,h)];for(let g=v;g<=x;g++)m.push(t(d,g));}else {let v=e.getFieldValue(d),x=Array.isArray(v)?v.length:0;for(let g=l+1;g<x;g++)m.push(t(d,g));}return Object.keys(e.fieldInfo).filter(v=>m.some(x=>v.startsWith(x)))}function s(d,l){return d.replace(/\[(\d+)\]/,(f,h)=>{let m=parseInt(h,10);return `[${l==="up"?m+1:Math.max(0,m-1)}]`})}function r(d,l){(l==="up"?d:[...d].reverse()).forEach(h=>{let m=s(h.toString(),l),v=e.getFieldMeta(m);v?e.setFieldMeta(h,v):e.setFieldMeta(h,n());});}let n=()=>Oo,u=(d,l,f)=>{r(d,"down"),d.forEach(h=>{h.toString().startsWith(t(l,f))&&e.setFieldMeta(h,n());});},i=d=>{r(d,"up");},c=(d,l,f,h)=>{let m=new Map(Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,f))).map(v=>[v,e.getFieldMeta(v)]));r(d,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,h))).forEach(v=>{let x=v.replace(t(l,h),t(l,f)),g=m.get(x);g&&e.setFieldMeta(v,g);});},p=(d,l,f,h)=>{d.forEach(m=>{if(!m.toString().startsWith(t(l,f)))return;let v=m.toString().replace(t(l,f),t(l,h)),[x,g]=[e.getFieldMeta(m),e.getFieldMeta(v)];x&&e.setFieldMeta(v,x),g&&e.setFieldMeta(m,g);});};return {handleArrayFieldMetaShift:o}}var ml=class extends ja{constructor(){super({pluginId:"form-devtools"});}},kt=new ml;function pl(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 Tr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),s=this.store.mount(),r=()=>{a(),s(),kt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return kt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let s=this.options;this.options=a;let r=!!a.transform?.deps?.some((i,c)=>i!==this.prevTransformArray[c]),n=a.defaultValues&&!ka(a.defaultValues,s.defaultValues)&&!this.state.isTouched,u=!ka(a.defaultState,s.defaultState)&&!this.state.isTouched;!n&&!u&&!r||(It(()=>{this.baseStore.setState(()=>pl(Object.assign({},this.state,u?a.defaultState:{},n?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),kt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,s)=>{let{fieldMeta:r}=this.state,n=this.resetFieldMeta(r);a&&!s?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>pl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let s=[];return It(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let u=n.instance;s.push(Promise.resolve().then(()=>u.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(s)).flat()},this.validateArrayFieldsStartingFrom=async(a,s,r)=>{let n=this.getFieldValue(a),u=Array.isArray(n)?Math.max(n.length-1,0):null,i=[`${a}[${s}]`];for(let l=s+1;l<=(u??0);l++)i.push(`${a}[${l}]`);let c=Object.keys(this.fieldInfo).filter(l=>i.some(f=>l.startsWith(f))),p=[];return It(()=>{c.forEach(l=>{p.push(Promise.resolve().then(()=>this.validateField(l,r)));});}),(await Promise.all(p)).flat()},this.validateField=(a,s)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(n=>({...n,isTouched:true})),r.validate(s)):[]},this.validateSync=a=>{let s=Fo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ta}),r=false,n={};return It(()=>{for(let c of s){if(!c.validate)continue;let p=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:l}=nn(p),f=kr(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let m=this.getFieldMeta(h);if(!m)continue;let{errorMap:v,errorSourceMap:x}=m,g=l?.[h],{newErrorValue:b,newSource:w}=on({newFormValidatorError:g,isPreviousErrorFromFormValidator:x?.[f]==="form",previousErrorValue:v?.[f]});w==="form"&&(n[h]={...n[h],[f]:g}),v?.[f]!==b&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[f]:b},errorSourceMap:{...I.errorSourceMap,[f]:w}}));}this.state.errorMap?.[f]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:d}})),(d||l)&&(r=!0);}let u=kr("submit");this.state.errorMap?.[u]&&a!=="submit"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let i=kr("server");this.state.errorMap?.[i]&&a!=="server"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[i]:void 0}}));}),{hasErrored:r,fieldsErrorMap:n}},this.validateAsync=async a=>{let s=Bo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ta});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let r=[],n;for(let c of s){if(!c.validate)continue;let p=kr(c.cause);this.state.validationMetaMap[p]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[p]={lastAbortController:l},r.push(new Promise(async f=>{let h;try{h=await new Promise((g,b)=>{setTimeout(async()=>{if(l.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(w){b(w);}},c.debounceMs);});}catch(g){h=g;}let{formError:m,fieldErrors:v}=nn(h);v&&(n=n?{...n,...v}:v);let x=kr(c.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let b=this.getFieldMeta(g);if(!b)continue;let{errorMap:w,errorSourceMap:I}=b,P=n?.[g],{newErrorValue:k,newSource:S}=on({newFormValidatorError:P,isPreviousErrorFromFormValidator:I?.[x]==="form",previousErrorValue:w?.[x]});w?.[x]!==k&&this.setFieldMeta(g,y=>({...y,errorMap:{...y.errorMap,[x]:k},errorSourceMap:{...y.errorSourceMap,[x]:S}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[x]:m}})),f(n?{fieldErrors:n,errorMapKey:x}:void 0);}));}let u=[],i={};if(r.length){u=await Promise.all(r);for(let c of u)if(c?.fieldErrors){let{errorMapKey:p}=c;for(let[d,l]of Object.entries(c.fieldErrors)){let h={...i[d]||{},[p]:l};i[d]=h;}}}return this.baseStore.setState(c=>({...c,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:s,fieldsErrorMap:r}=this.validateSync(a);return s&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Ca(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var s;return (s=this.fieldInfo)[a]||(s[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,s)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Ia(s,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((s,r)=>{let n=r;return s[n]=Oo,s},{}),this.setFieldValue=(a,s,r)=>{let n=r?.dontUpdateMeta??false,u=r?.dontRunListeners??false,i=r?.dontValidate??false;It(()=>{n||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:Ro(c.values,a,s)}));}),u||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(n=>{let u=a.toString();return n!==u&&n.startsWith(u)}),a];this.baseStore.setState(n=>{let u={...n};return r.forEach(i=>{u.values=ul(u.values,i),delete this.fieldInfo[i],delete u.fieldMetaBase[i];}),u});},this.pushFieldValue=(a,s,r)=>{this.setFieldValue(a,n=>[...Array.isArray(n)?n:[],s],r);},this.insertFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,i=>[...i.slice(0,s),r,...i.slice(s)],$e(n,{dontValidate:true}));let u=n?.dontValidate??false;u||await this.validateField(a,"change"),Cr(this).handleArrayFieldMetaShift(a,s,"insert"),u||await this.validateArrayFieldsStartingFrom(a,s,"change");},this.replaceFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,i=>i.map((c,p)=>p===s?r:c),$e(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.removeFieldValue=async(a,s,r)=>{let n=this.getFieldValue(a),u=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,c=>c.filter((p,d)=>d!==s),$e(r,{dontValidate:true})),Cr(this).handleArrayFieldMetaShift(a,s,"remove"),u!==null){let c=`${a}[${u}]`;this.deleteField(c);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.swapFieldValues=(a,s,r,n)=>{this.setFieldValue(a,i=>{let c=i[s],p=i[r];return Ro(Ro(i,`${s}`,p),`${r}`,c)},$e(n,{dontValidate:true})),Cr(this).handleArrayFieldMetaShift(a,s,"swap",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,s,r,n)=>{this.setFieldValue(a,i=>{let c=[...i];return c.splice(r,0,c.splice(s,1)[0]),c},$e(n,{dontValidate:true})),Cr(this).handleArrayFieldMetaShift(a,s,"move",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,s)=>{let r=this.getFieldValue(a),n=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],$e(s,{dontValidate:true})),n!==null)for(let i=0;i<=n;i++){let c=`${a}[${i}]`;this.deleteField(c);}(s?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:Oo},values:this.options.defaultValues?Ro(s.values,a,Ca(this.options.defaultValues,a)):s.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[s,r])=>(Object.keys(r).length&&r.errors.length&&(a[s]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Ma.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ma.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??fl(),this._devtoolsSubmissionOverride=false,this.baseStore=new Qt(pl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Gt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,u=a?.[0],i=s[0],c=0,p={};for(let d of Object.keys(i.fieldMetaBase)){let l=i.fieldMetaBase[d],f=u?.fieldMetaBase[d],h=n?.[d],m=Ca(i.values,d),v=h?.errors;if(!f||l.errorMap!==f.errorMap){v=Object.values(l.errorMap??{}).filter(I=>I!==void 0);let w=this.getFieldInfo(d)?.instance;w&&!w.options.disableErrorFlat&&(v=v?.flat(1));}let x=!cl(v??[]),g=!l.isDirty,b=ka(m,Ca(this.options.defaultValues,d))||ka(m,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===x&&h.isDefaultValue===b&&h.errors===v&&l===f){p[d]=h,c++;continue}p[d]={...l,errors:v,isPristine:g,isValid:x,isDefaultValue:b};}return Object.keys(i.fieldMetaBase).length&&n&&c===Object.keys(i.fieldMetaBase).length?n:p}}),this.store=new Gt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,u=a?.[0],i=s[0],c=s[1],p=Object.values(c).filter(Boolean),d=p.some(F=>F.isValidating),l=p.every(F=>F.isValid),f=p.some(F=>F.isTouched),h=p.some(F=>F.isBlurred),m=p.every(F=>F.isDefaultValue),v=f&&i.errorMap?.onMount,x=p.some(F=>F.isDirty),g=!x,b=!!(i.errorMap?.onMount||p.some(F=>F?.errorMap?.onMount)),w=!!d,I=n?.errors??[];(!u||i.errorMap!==u.errorMap)&&(I=Object.values(i.errorMap).reduce((F,O)=>O===void 0?F:O&&Ir(O)?(F.push(O.form),F):(F.push(O),F),[]));let P=I.length===0,k=l&&P,S=this.options.canSubmitWhenInvalid??false,y=i.submissionAttempts===0&&!f&&!b||!w&&!i.isSubmitting&&k||S,E=i.errorMap;if(v&&(I=I.filter(F=>F!==i.errorMap.onMount),E=Object.assign(E,{onMount:void 0})),n&&u&&n.errorMap===E&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===I&&n.isFieldsValidating===d&&n.isFieldsValid===l&&n.isFormValid===P&&n.isValid===k&&n.canSubmit===y&&n.isTouched===f&&n.isBlurred===h&&n.isPristine===g&&n.isDefaultValue===m&&n.isDirty===x&&ka(u,i))return n;let B={...i,errorMap:E,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:l,isFormValid:P,isValid:k,canSubmit:y,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:m,isDirty:x},T=this.options.transform?.deps??[];if(T.length!==this.prevTransformArray.length||T.some((F,O)=>F!==this.prevTransformArray[O])){let F=Object.assign({},this,{state:B});this.options.transform?.fn(F),B=F.state,this.prevTransformArray=T;}return B}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=ll(a=>kt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),kt.on("request-form-state",a=>{a.payload.id===this._formId&&kt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),kt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),kt.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 sn(o.validate)?Ma[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(s=>({...s,isSubmitted:false,submissionAttempts:s.submissionAttempts+1,isSubmitSuccessful:false})),It(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance&&(s.instance.state.meta.isTouched||s.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(s=>({...s,isSubmitting:true}));let a=()=>{this.baseStore.setState(s=>({...s,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),kt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(s=>s.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),kt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}It(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance?.options.listeners?.onSubmit?.({value:s.instance.state.value,fieldApi:s.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),It(()=>{this.baseStore.setState(s=>({...s,isSubmitted:!0,isSubmitSuccessful:!0})),kt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(s){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),kt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:s}),a(),s}}setErrorMap(o){It(()=>{Object.entries(o).forEach(([t,a])=>{let s=t;if(Ir(a)){let{formError:r,fieldErrors:n}=nn(a);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,c=>({...c,errorMap:{...c.errorMap,[s]:n?.[u]},errorSourceMap:{...c.errorSourceMap,[s]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[s]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[s]:a}}));});});}};function nn(e){if(e){if(Ir(e)){let o=nn(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function kr(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 Mr=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:s}=this.options.validators||{};if(s){let r=this.runValidator({validate:s,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:r},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let s=Ca(t.form.options.defaultValues,t.name),r=t.defaultValue??s;a?this.setValue(n=>n||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,$e(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,$e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,s)=>{this.form.insertFieldValue(this.name,t,a,$e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,s)=>{this.form.replaceFieldValue(this.name,t,a,$e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,$e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,s)=>{this.form.swapFieldValues(this.name,t,a,$e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,s)=>{this.form.moveFieldValues(this.name,t,a,$e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,$e(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),s=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:n,onBlurListenTo:u}=r.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&s.push(r.instance),t==="blur"&&u?.includes(this.name)&&s.push(r.instance);}return s},this.validateSync=(t,a)=>{let s=Fo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ta}),n=this.getLinkedFields(t).reduce((c,p)=>{let d=Fo(t,{...p.options,form:p.form,validationLogic:p.form.options.validationLogic||Ta});return d.forEach(l=>{l.field=p;}),c.concat(d)},[]),u=false;It(()=>{let c=(p,d)=>{let l=ln(d.cause),f=d.validate?Qu(p.runValidator({validate:d.validate,value:{value:p.store.state.value,validationSource:"field",fieldApi:p},type:"validate"})):void 0,h=a[l],{newErrorValue:m,newSource:v}=rn({formLevelError:h,fieldLevelError:f});p.state.meta.errorMap?.[l]!==m&&p.setMeta(x=>({...x,errorMap:{...x.errorMap,[l]:m},errorSourceMap:{...x.errorSourceMap,[l]:v}})),m&&(u=!0);};for(let p of s)c(this,p);for(let p of n)p.validate&&c(p.field,p);});let i=ln("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 s=Bo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ta}),r=await a,n=this.getLinkedFields(t),u=n.reduce((l,f)=>{let h=Bo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Ta});return h.forEach(m=>{m.field=f;}),l.concat(h)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of n)l.setMeta(f=>({...f,isValidating:true}));let i=[],c=[],p=(l,f,h)=>{let m=ln(f.cause);l.getInfo().validationMetaMap[m]?.lastAbortController.abort();let x=new AbortController;this.getInfo().validationMetaMap[m]={lastAbortController:x},h.push(new Promise(async g=>{let b;try{b=await new Promise((S,y)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(x.signal.aborted)return S(void 0);try{S(await this.runValidator({validate:f.validate,value:{value:l.store.state.value,fieldApi:l,signal:x.signal,validationSource:"field"},type:"validateAsync"}));}catch(E){y(E);}},f.debounceMs);});}catch(S){b=S;}if(x.signal.aborted)return g(void 0);let w=Qu(b),I=r[this.name]?.[m],{newErrorValue:P,newSource:k}=rn({formLevelError:I,fieldLevelError:w});l.setMeta(S=>({...S,errorMap:{...S?.errorMap,[m]:P},errorSourceMap:{...S.errorSourceMap,[m]:k}})),g(P);}));};for(let l of s)l.validate&&p(this,l,i);for(let l of u)l.validate&&p(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 n)l.setMeta(f=>({...f,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:s}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,s[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[ln(t)]?.lastAbortController.abort(),this.state.meta.errors;let n=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,n)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Ma.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ma.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Gt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Oo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return sn(o.validate)?Ma[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function Qu(e){if(e)return e}function ln(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 dn(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Gx)}function Gx(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,s]of e)if(!o.has(a)||!Object.is(s,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=ec(e);if(t.length!==ec(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 ec(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var No=typeof window<"u"?useLayoutEffect:useEffect;function Zx(e){let[o]=useState(()=>{let a=new Mr({...e,form:e.form,name:e.name});return a.Field=hl,a});return No(o.mount,[o]),No(()=>{o.update(e);}),dn(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var hl=(({children:e,...o})=>{let t=Zx(o),a=useMemo(()=>Ia(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function tb({form:e,selector:o,children:t}){let a=dn(e.store,o);return Ia(t,a)}function gl(e){let o=useId(),[t]=useState(()=>{let a=new Tr({...e,formId:o}),s=a;return s.Field=function(n){return jsx(hl,{...n,form:a})},s.Subscribe=function(n){return jsx(tb,{form:a,selector:n.selector,children:n.children})},s});return No(t.mount,[]),No(()=>{t.update(e);}),t}function xl({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 cb=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),s=qe(),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[u,i]=useState(n),c=gl({defaultValues:{questionType:n,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 f={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,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?ha(f):ci(f));}else if(l.questionType==="multiple-choice"){let f={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,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?pa(f):ui(f));}else if(l.questionType==="short-answer"){let f={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?er(f):fi(f));}else if(l.questionType==="fill-in-the-blank"){let f={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?ar(f):pi(f));}else if(l.questionType==="long-answer"){let f={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?tr(f):mi(f));}o(ga(false));}}),p=()=>{o(ga(false));};if(!s)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:()=>{p();},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:f=>{l.handleChange(f.target.value),i(f.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(xl,{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:f=>l.handleChange(f.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(xl,{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(xl,{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:f=>l.handleChange(f.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 f=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 ${f===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),f===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>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 ${f===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),f===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value: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 f=(x,g)=>{let b=[...l.state.value.options];b[x]=g,l.handleChange({...l.state.value,options:b});},h=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},m=x=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let g=l.state.value.options.filter((w,I)=>I!==x),b=l.state.value.correctIndex?.filter(w=>w!==x).map(w=>w>x?w-1:w);l.handleChange({...l.state.value,options:g,correctIndex:b});},v=x=>{let g=l.state.value.correctIndex||[];if(g.includes(x))l.handleChange({...l.state.value,correctIndex:g.filter(w=>w!==x)});else {if(g.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...g,x]});}};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((x,g)=>{let b=!x.trim(),w=l.state.value.correctIndex?.includes(g),I=l.state.meta.isTouched&&b;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>v(g),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${w?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:w&&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":w?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${g+1}`,value:x,onChange:P=>f(g,P.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:()=>m(g),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},g)})}),jsx("button",{type:"button",onClick:h,disabled:l.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),l.state.value.correctIndex.length===0||l.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:l.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.Field,{name:"responseOptions.correctShortAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:l.state.value,onChange:f=>{l.handleChange(f.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),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:f=>{l.handleChange(f.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),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,f])=>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:f?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(d,s)},oc=cb;var ic=({text:e,position:o})=>{let t=ve(),a=c=>{t(ue()),t(Dt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+c))}));},s=c=>{t(ue()),t(Dt({id:e.id,fill:c}));},r=()=>{t(ue()),t(Dt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ue()),t(Dt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},u=()=>{t(ue()),t(Dt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},i=c=>{t(ue()),t(Dt({id:e.id,fontFamily:c}));};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:`${o.x}px`,top:`${Math.max(60,o.y-60)}px`,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:c=>c.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:c=>i(c.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:r,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:[jsx(TextB,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextB,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:n,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:u,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:c=>s(c.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var dc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:s,scale:r,textareaRef:n})=>{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(p=>{p.style.height="auto",p.style.height=`${p.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(p).font,d.style.fontSize=p.style.fontSize,d.style.fontFamily=p.style.fontFamily,d.style.fontWeight=p.style.fontWeight,d.style.fontStyle=p.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let l=p.value.split(`
|
|
3
|
+
`).length,T=s.find(O=>O.id===n)?.fontSize||24,F=E*T*1.2+10;g.width=Math.max(200,S),g.height=Math.max(50,y,F);}else if(v&&i.trim()){let b=v.text(),w=v.width();v.text(i),v.width(void 0);let I=v.width(),P=v.height();v.text(b),v.width(w),g.width=Math.max(200,I+20),g.height=Math.max(50,P+20);}t(Dt(g)),u(null),c(""),t(sr(null)),e();}}}};var Wd=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],s=useRef(new Map),r=useCallback((n,u)=>{let i=n.target;o(er({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:s,handleShortAnswerDragEnd:r}};var zd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),s=useCallback((r,n)=>{let u=r.target;o(tr({id:n,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:s}};var jd=e=>{let o=ve(),a=Q(ge)?.flashcards||[],s=useRef(new Map),r=useRef(new Map),n=useCallback((d,l)=>{if(r.current.has(l))return r.current.get(l);let f=new window.Image;return (d.startsWith("http://")||d.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=d,r.current.set(l,f),f},[]),u=useCallback((d,l)=>{let f=d.target,h=f.id();a.find(v=>v.id===h)&&(o(po({id:h,x:f.x(),y:f.y()})),l?.());},[a,o]),i=useCallback((d,l)=>{let f=l.target,h=f.scaleX(),m=f.scaleY(),v=f.rotation(),x=Math.max(50,f.width()*h),g=Math.max(50,f.height()*m);f.scaleX(1),f.scaleY(1),f.width(x),f.height(g),o(po({id:d,width:x,height:g,x:f.x(),y:f.y(),rotation:v})),f.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(d=>{o(oi(d)),e?.();},[o,e]),p=useCallback(d=>{o(ri(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:s,handleDragEnd:u,handleFlashcardTransformEnd:i,handleNext:c,handlePrevious:p}};var $d=e=>{let o=ve(),a=Q(ge)?.photoFrames||[],s=useRef(new Map),[r,n]=useState(new Map),u=useCallback((f,h)=>{console.log("handleDragEnd"),o(Ha({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),i=useCallback((f,h)=>{let m=h.target,v=m.scaleX(),x=m.scaleY(),g=m.rotation(),b=a.find(P=>P.id===f);if(!b)return;let w=Math.max(100,b.width*v),I=Math.max(100,b.height*x);m.scaleX(1),m.scaleY(1),o(Ha({id:f,width:w,height:I,x:m.x(),y:m.y(),rotation:g})),m.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(m=>{let v=new Map(m);return v.set(f,h),v}),o(Ha({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),p=useCallback(f=>{let h=r.get(f);h&&(h.getTracks().forEach(m=>m.stop()),n(m=>{let v=new Map(m);return v.delete(f),v}),o(Ha({id:f,isCapturing:false})),e?.());},[r,o,e]),d=useCallback((f,h)=>{let m=document.createElement("canvas");m.width=h.videoWidth,m.height=h.videoHeight;let v=m.getContext("2d");if(v){v.drawImage(h,0,0,m.width,m.height);let x=m.toDataURL("image/jpeg",.8);return o(Ha({id:f,capturedImageUrl:x,isCapturing:false})),p(f),e?.(),x}return null},[o,p,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:s,handleDragEnd:u,handlePhotoFrameTransformEnd:i,startCamera:c,stopCamera:p,capturePhoto:d,cameraStreams:r}};var Yd=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),a=useCallback((r,n,u,i,c,p,d,l=[])=>{if(e.current){if(r&&!l.find(m=>m.id===r)?.isPlaying){let m=n.get(r)||u.get(r)||i.get(r)||c.get(r)||p.get(r)||(d?d.get(r):null);if(m){e.current.boundBoxFunc(t),e.current.nodes([m]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),s=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:s,boundBoxFunc:t}};var Kp=(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])},eu=(e,o)=>{let t=ft(),a=ot(Bs),s=useRef(e);useEffect(()=>{s.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(Yn({id:s.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),n=Kp(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var zp=e=>e.flatMap(o=>[o[0],o[1]]),Ns=(e,o)=>{let t=Pd(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 zp(t)};var tu=e=>{let o=ve(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null),u=Q(b=>b.toolbar.selectedTool),i=Q(b=>b.toolbar.penColor),c=Q(b=>b.toolbar.strokeWidth),p=Q(b=>b.canvas.isSketchMode),d=Q(b=>b.canvas.slides.find(I=>I.id===b.canvas.currentSlideId)?.images.find(I=>I.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,m=d?.height||1,v=useCallback(b=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,s.current=[{x:b.x,y:b.y}];let w=b.x/h,I=b.y/m;n({tool:u,points:[w,I],color:i,strokeWidth:c/h,isSketch:p});},[u,i,c,p,h,m]),x=useCallback(b=>{if(!t.current||!r)return;a.current=true;let w=s.current[s.current.length-1];if(Math.sqrt(Math.pow(b.x-w.x,2)+Math.pow(b.y-w.y,2))<2)return;s.current.push({x:b.x,y:b.y});let P;if(p)P=Ns(s.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((S,y)=>y%2===0?S/h:S/m);else {let k=b.x/h,S=b.y/m;P=[...r.points,k,S];}n(k=>k?{...k,points:P}:null);},[p,c,r,h,m]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(ii({imageId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:f,startDrawing:v,draw:x,stopDrawing:g,tool:u}};function Ne({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),s=useRef(null);return {createHandlers:useCallback((n,u)=>({onTouchStart:i=>{let c=i.evt.touches[0];s.current={x:c.clientX,y:c.clientY},a.current=setTimeout(()=>{e(n,u)(i.evt);},o);},onTouchMove:i=>{if(!s.current)return;let c=i.evt.touches[0],p=Math.abs(c.clientX-s.current.x),d=Math.abs(c.clientY-s.current.y);(p>t||d>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),s.current=null;}}),[e,o,t])}}var nu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n,onLongPress:u})=>{let{annotations:i,activeLine:c,stopDrawing:l,tool:f}=tu(e.id),{createHandlers:h}=Ne({onLongPress:u});useEffect(()=>{let b=t.current.get(e.id);b&&(b.width()!==e.width||b.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:b.width(),konvaHeight:b.height()}),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let m=false;useEffect(()=>{return;},[l,m]);let v=b=>{{r(e.id);return}},x=b=>{return;},g=b=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="eraser",children:[jsx(Image$1,{id:e.id,ref:b=>{if(b)t.current.set(e.id,b),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw();else {let w=t.current.get(e.id);w?._contextMenuCleanup&&w._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:b=>s(e.id,b),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:b=>{b.evt.preventDefault();let w=b.evt;n(w,e.id,"image");},...f!=="pen"&&f!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onMouseMove:x,onMouseUp:g,...h(e.id,"image")}:{}}),i?.map((b,w)=>{let I=b.points.map((k,S)=>S%2===0?k*e.width+e.x:k*e.height+e.y),P=b.strokeWidth*e.width;return jsx(Line,{points:I,stroke:b.tool==="eraser"?"white":b.color,strokeWidth:P,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},w)}),c&&jsx(Line,{points:c.points.map((b,w)=>w%2===0?b*e.width+e.x:b*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")]})});nu.displayName="ImageWithDrawing";var Bi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n,onLongPress:u})=>jsx(Fragment,{children:e.map(i=>{let c=o(i);return c?jsx(nu,{img:i,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n,onLongPress:u},i.id):null})}));Bi.displayName="ImageLayer";var th=({src:e,x:o,id:t,y:a,width:s,height:r,isSelected:n,rotation:u=0,onTransformEnd:i,onDragEnd:c})=>{let p=ve(),d=useRef(null),l=f=>{p(qa(f));};return jsxs(Group,{draggable:true,x:o,y:a,width:s,height:r,rotation:u,onDragEnd:c,onTransformEnd:i,children:[jsx(Rect,{width:s,height:r,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${s}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:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},iu=th;var dh=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,nodeRef:n})=>{let[u,i]=useState(null),c=useSelector(m=>m.toolbar.selectedTool),p=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let m=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(m.crossOrigin="anonymous"),m.src=e.thumbnailDataUrl,m.onload=()=>{i(m);};}},[e.thumbnailDataUrl]),!u)return null;let d=e.width/2,l=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,80));return jsxs(Group,{draggable:!p,listening:!p,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...p?{}:{onDragEnd:a,onTransformEnd:s},ref:m=>{if(n(m),m){let v=m.getStage()?.container();if(v){let x=g=>{let b=m.getStage()?.getPointerPosition();if(b){let w={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=w.x&&b.x<=w.x+w.width&&b.y>=w.y&&b.y<=w.y+w.height&&r(g);}};v.addEventListener("contextmenu",x),m._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",x);};}}},children:[jsx(Image$1,{image:u,width:e.width,height:e.height,listening:!p,...p?{}:{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:!p,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...p?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:l,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!p,...p?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:l,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!p,...p?{}:{onClick:t,onTap:t}})]})},du=dh;var Vi=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:s,onTransformEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(u=>jsxs(ye__default.Fragment,{children:[jsx(du,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>a(u.id),onDragEnd:i=>s(u.id,i),onTransformEnd:i=>r(u.id,i),onContextMenu:i=>n(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=>s(u.id,i)})]},u.id))}));Vi.displayName="VideoLayer";var qi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:s,handleShapeDragStart:r,onContextMenu:n,onLongPress:u})=>{let i=useSelector(d=>d.toolbar.selectedTool),c=i==="pen"||i==="eraser",{createHandlers:p}=Ne({onLongPress:u});return jsx(Fragment,{children:e.map((d,l)=>{let f=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:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},radius:d.radius||d.width/2,width:d.width,height:d.width},f);case "star":return jsx(Star,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},sides:3,radius:d.radius||d.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},sides:d.sides||6,radius:d.radius||d.width/2},f);case "ellipse":return jsx(Ellipse,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},f);case "ring":return jsx(Ring,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "wedge":return jsx(Wedge,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},radius:d.radius||d.width/2,angle:d.angle||60},f);case "arrow":return jsx(Arrow,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "line":return jsx(Line,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{r?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>s(d.id),onContextMenu:m=>{m.evt.preventDefault(),n(m.evt,d.id,"shape");},...p(d.id,"shape")},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},f)}})})});qi.displayName="ShapeLayer";var fu=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:s,onContextMenu:r,onDoubleClick:n,editingTextId:u,onLongPress:i})=>{let c=useSelector(l=>l.toolbar.selectedTool),p=c==="pen"||c==="eraser",{createHandlers:d}=Ne({onLongPress:i});return jsx(Fragment,{children:e.map(l=>{let f=l.id===u,h=l.fontWeight==="bold",m=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&&!f&&!p,listening:!p,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:m,align:l.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...p?{}:{onClick:()=>s(l.id),onTap:()=>s(l.id),onDblClick:()=>n(l.id),onDblTap:()=>n(l.id),onDragEnd:v=>t(v,l.id),onTransformEnd:()=>a(l.id),onContextMenu:v=>{v.evt.preventDefault();let x=v.evt;r(x,l.id,"text");},...d(l.id,"text")}},l.id)})})};var Fh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onNext:n,onPrevious:u,nodeRef:i,touchHandlers:c})=>{let[p,d]=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=()=>{d(x);};}},[e.images,e.currentIndex]),!p||e.images.length===0)return null;let l=8,f=2,h=Math.min(e.width,e.height)*.08,m=Math.max(16,Math.min(h,32)),v=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:s,...c,ref:x=>{if(i(x),x){let g=x.getStage()?.container();if(g){let b=w=>{let I=x.getStage()?.getPointerPosition();if(I){let P={x:e.x,y:e.y,width:e.width,height:e.height};I.x>=P.x&&I.x<=P.x+P.width&&I.y>=P.y&&I.y<=P.y+P.height&&r(w);}};g.addEventListener("contextmenu",b),x._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",b);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:l,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:l,stroke:"#E5E7EB",strokeWidth:f,listening:false}),jsx(Image$1,{x:f+4,y:f+4,image:p,width:e.width-(f+4)*2,height:e.height-(f+4)*2,cornerRadius:l-f,onClick:t,onTap:t}),jsx(Rect,{x:f,y:e.height-50,width:e.width-f*2,height:50,cornerRadius:[0,0,l-f,l-f],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:v+m,y:e.height/2,onClick:x=>{x.cancelBubble=true,u();},onTap:x=>{x.cancelBubble=true,u();},children:[jsx(Circle,{radius:m,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-v-m,y:e.height/2,onClick:x=>{x.cancelBubble=true,n();},onTap:x=>{x.cancelBubble=true,n();},children:[jsx(Circle,{radius:m,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"})]})},hu=Fh;var Ki=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onNext:n,onPrevious:u,onContextMenu:i,onLongPress:c})=>{let{createHandlers:p}=Ne({onLongPress:c});return jsx(Fragment,{children:e.map(d=>jsx(hu,{flashcard:d,isSelected:t===d.id,onClick:()=>r(d.id),onDragEnd:a,onTransformEnd:l=>s(d.id,l),onContextMenu:l=>i(l,d.id,"flashcard"),onNext:()=>n(d.id),onPrevious:()=>u(d.id),touchHandlers:p(d.id,"flashcard"),nodeRef:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);}},d.id))})});Ki.displayName="FlashcardLayer";var xu=e=>{let o=ve(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null);Q(b=>b.toolbar.selectedTool);let i=Q(b=>b.toolbar.penColor),c=Q(b=>b.toolbar.strokeWidth),p=Q(b=>b.canvas.isSketchMode),d=Q(b=>b.canvas.slides.find(I=>I.id===b.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,m=d?.height||1,v=useCallback(b=>{if(!f)return;t.current=true,a.current=false,s.current=[{x:b.x,y:b.y}];let w=b.x/h,I=b.y/m;n({tool:"pen",points:[w,I],color:i,strokeWidth:c/h,isSketch:p});},[f,i,c,p,h,m]),x=useCallback(b=>{if(!t.current||!r)return;a.current=true;let w=s.current[s.current.length-1];if(Math.sqrt(Math.pow(b.x-w.x,2)+Math.pow(b.y-w.y,2))<2)return;s.current.push({x:b.x,y:b.y});let P;if(p)P=Ns(s.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((S,y)=>y%2===0?S/h:S/m);else {let k=b.x/h,S=b.y/m;P=[...r.points,k,S];}n(k=>k?{...k,points:P}:null);},[p,c,r,h,m]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(di({frameId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:f,startDrawing:v,draw:x,stopDrawing:g}};var Kh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onStartCamera:n,onCapture:u,cameraStream:i,nodeRef:c,touchHandlers:p})=>{let[d,l]=useState(null),[f,h]=useState(null),m=useRef(null),v=useRef(null),x=useRef(null),g=useRef(null),b=useRef(0),w=33,I=useSelector(q=>q.toolbar.selectedTool),P=I==="pen"||I==="eraser",{annotations:k,activeLine:S,isDrawingMode:y,startDrawing:E,draw:B,stopDrawing:T}=xu(e.id);useEffect(()=>{if(!y)return;let q=()=>{T();},_=()=>{T();};return window.addEventListener("mouseup",q),window.addEventListener("touchend",_),()=>{window.removeEventListener("mouseup",q),window.removeEventListener("touchend",_);}},[T,y]),useEffect(()=>{if(e.capturedImageUrl){let q=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(q.crossOrigin="anonymous"),q.src=e.capturedImageUrl,q.onload=()=>{l(q);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){m.current||(m.current=document.createElement("video"),m.current.autoplay=true,m.current.playsInline=true),v.current||(v.current=document.createElement("canvas"));let q=m.current,_=v.current;q.srcObject=i;let K=()=>{_.width=q.videoWidth||640,_.height=q.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",_.width,_.height);let X=te=>{if(te-b.current<w){x.current=requestAnimationFrame(X);return}b.current=te;let $=_.getContext("2d");if($&&q.readyState===q.HAVE_ENOUGH_DATA){$.drawImage(q,0,0,_.width,_.height);let re=_.toDataURL("image/jpeg",.6),ie=new window.Image;ie.onload=()=>{h(ie);},ie.src=re;}x.current=requestAnimationFrame(X);};x.current=requestAnimationFrame(X);};return q.onloadedmetadata=K,q.readyState>=q.HAVE_METADATA&&K(),q.play().catch(X=>console.error("Error playing video:",X)),()=>{x.current&&(cancelAnimationFrame(x.current),x.current=null);}}return ()=>{h(null),g.current&&(g.current.src="");}},[e.isCapturing,i]);let G=()=>{m.current&&e.isCapturing&&u(m.current);},F=q=>{if(e.capturedImageUrl){if(!y){t();return}let _=q.currentTarget,K=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){K.invert();let $=K.point(te);E($);}q.cancelBubble=true;}else t();},O=q=>{if(!y||!e.capturedImageUrl)return;let _=q.currentTarget,K=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){K.invert();let $=K.point(te);B($);}},U=()=>{!y||!e.capturedImageUrl||T();},V=e.isCapturing?f:d,H=Math.min(e.width,e.height)*.12,oe=Math.max(25,Math.min(H,50)),me=e.width/2,W=e.height/2;return jsxs(Group,{id:e.id,draggable:!y&&!P,listening:true,x:e.x,y:e.y,...p,...P?{}:{onDragEnd:a,onTransformEnd:s},rotation:e.rotation,width:e.width,height:e.height,ref:q=>{if(c(q),q){let _=q.getStage()?.container();if(_){let K=X=>{let te=q.getStage()?.getPointerPosition();if(te){let $={x:e.x,y:e.y,width:e.width,height:e.height};te.x>=$.x&&te.x<=$.x+$.width&&te.y>=$.y&&te.y<=$.y+$.height&&r(X);}};_.addEventListener("contextmenu",K),q._contextMenuCleanup=()=>{_.removeEventListener("contextmenu",K);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:V?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),V&&jsx(Image$1,{image:V,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:F,onTap:F,onMouseDown:F,onTouchStart:F,onMouseMove:O,onTouchMove:O,onMouseUp:U,onTouchEnd:U,...P?{}:{onDragEnd:a,onTransformEnd:s}}),k?.map((q,_)=>{let K=q.points.map((te,$)=>$%2===0?te*e.width:te*e.height),X=q.strokeWidth*e.width;return jsx(Line,{points:K,stroke:q.tool==="eraser"?"white":q.color,strokeWidth:X,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:q.tool==="eraser"?"destination-out":"source-over",fill:q.isSketch?q.color:void 0,closed:q.isSketch,listening:false},_)}),S&&jsx(Line,{points:S.points.map((q,_)=>_%2===0?q*e.width:q*e.height),stroke:S.tool==="eraser"?"white":S.color,strokeWidth:S.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:S.tool==="eraser"?"destination-out":"source-over",fill:S.isSketch?S.color:void 0,closed:S.isSketch,listening:false},"active"),!V&&!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:W-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:me-oe+6,y:W-60,width:oe*1.6,height:oe*1.6,radius:oe,fill:"white",cornerRadius:8,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?G():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?G():n();}}),jsx(Html,{groupProps:{x:me-12,y:W-40,width:oe*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?G():n();}})})]}),jsx(Text,{x:0,y:W,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:W+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:me-24,y:W+104,width:oe*1.6,height:oe*1.6,radius:oe,fill:"#096B76",cornerRadius:oe,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?G():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?G():n();}}),jsx(Html,{groupProps:{x:me-8,y:W+120,width:oe*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?G():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:me-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:q=>{q.stopPropagation(),G();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},wu=Kh;var Xi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onStartCamera:n,onCapture:u,cameraStreams:i,onContextMenu:c,onLongPress:p})=>{let{createHandlers:d}=Ne({onLongPress:p});return jsx(Fragment,{children:e.map(l=>jsx(wu,{photoFrame:l,isSelected:t===l.id,onClick:()=>r(l.id),onDragEnd:f=>a(f,l.id),onTransformEnd:f=>s(l.id,f),onContextMenu:f=>c(f,l.id,"photoFrame"),onStartCamera:()=>n(l.id),onCapture:f=>u(l.id,f),cameraStream:i.get(l.id),touchHandlers:d(l.id,"photoFrame"),nodeRef:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);}},l.id))})});Xi.displayName="PhotoFrameLayer";var Cu=({x:e,y:o,onAction:t,onClose:a,type:s,elementId:r="",isDrawingMode:n,menuRef:u})=>{useEffect(()=>{let d=f=>{u?.current&&!u.current.contains(f.target)&&a();},l=f=>{f.key==="Escape"&&a();};return document.addEventListener("mousedown",d),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",l);}},[a]);let i=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:n?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(l=>!(l.showForTypes&&!l.showForTypes.includes(s)||l.hideForTypes&&l.hideForTypes.includes(s))),[s,n]),c=(d,l)=>{d==="order"||d==="lock"?t(d,l):(t(d),a());},p=jsx("div",{ref:u,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:i.map((d,l)=>jsxs("button",{onClick:f=>c(d.action,f),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] ${d.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[d.icon,jsx("span",{className:`font-medium ${d.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:d.label})]}),d.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},l))})});return createPortal(p,document.body)};var ku=({x:e,y:o,items:t,onClose:a})=>{let s=useRef(null);return useEffect(()=>{let r=n=>{s.current&&!s.current.contains(n.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:s,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,n)=>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})},n))})})};var Mu=createContext(null),$i=()=>useContext(Mu);function pg({children:e,className:o="",style:t}){let a=useRef(null),[s,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Mu.Provider,{value:s,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function qe(){let e=$i();return typeof document>"u"?null:e||document.body}var Au=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:s,onClose:r})=>{let[n,u]=useState(a),i=useRef(null),c=qe();useEffect(()=>{i.current?.focus();},[]);let p=()=>{s(n),r();},d=f=>{f.key==="Enter"?p():f.key==="Escape"&&r();};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{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:n,onChange:f=>u(f.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:p,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 Ws=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,s]=useState(e),r=useRef(null),n=qe();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,f)=>{f/=100;let h=l*Math.min(f,1-f)/100,m=v=>{let x=(v+d/30)%12,g=f-h*Math.max(Math.min(x-3,9-x,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return `#${m(0)}${m(8)}${m(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!n)return null;let p=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=>s(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=>s(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),f=i(l,100,50);s(f);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(d=>jsx("button",{type:"button",onClick:()=>s(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(p,n)};var Rg=({imageSrc:e,onCrop:o})=>{let[t]=Du(e),a=useRef(null),s=useRef(null),r=useRef(null),n=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=n.width*.5,f=n.height*.5,h=(n.width-l)/2,m=(n.height-f)/2;return {x:h,y:m,width:l,height:f}},[n]),[i,c]=useState(u);useEffect(()=>{c(u);},[u]),useEffect(()=>{r.current&&s.current&&(r.current.nodes([s.current]),r.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let p=()=>{let l=s.current;if(!l)return;let f=l.scaleX(),h=l.scaleY();l.scaleX(1),l.scaleY(1),c({x:l.x(),y:l.y(),width:Math.max(20,l.width()*f),height:Math.max(20,l.height()*h)});},d=()=>{let l=s.current;l&&c({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:s,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:p,dragBoundFunc:l=>{let f=Math.max(0,Math.min(l.x,n.width-i.width)),h=Math.max(0,Math.min(l.y,n.height-i.height));return {x:f,y:h}}}),jsx(Transformer,{ref:r,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(l,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>n.width||f.y+f.height>n.height?l:f})]})})},Ru=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[s,r]=useState({x:0,y:0,width:0,height:0}),[n]=Du(e),u=qe();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let i=(d,l,f,h)=>{r({x:d,y:l,width:f,height:h});},c=()=>{if(!n)return;let f=Math.min(600/n.width,400/n.height),h=s.x/f,m=s.y/f,v=s.width/f,x=s.height/f,g=document.createElement("canvas");g.width=v,g.height=x;let b=g.getContext("2d");if(!b)return;b.drawImage(n,h,m,v,x,0,0,v,x);let w=g.toDataURL("image/png");o(w);};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(Rg,{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 pr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let s=qe(),[r,n]=useState(false),[u,i]=useState(null),[c,p]=useState(0),[d,l]=useState(true),f=useRef(null),h=useRef([]),m=useRef(null),v=useRef(null),x=useRef(null),g=useRef(null),b=useRef(null),w=useRef(null);useEffect(()=>()=>{x.current&&cancelAnimationFrame(x.current),m.current&&clearInterval(m.current),v.current&&v.current.getTracks().forEach(E=>E.stop());},[]);let I=async()=>{try{let E,B=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((K,X)=>{let te=K.getChildren();console.log(`Layer ${X} children count:`,te.length);});let V=document.createElement("canvas");V.width=o.current.width(),V.height=o.current.height();let H=V.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:",V.width,"x",V.height),b.current=V;let oe=()=>{if(H.clearRect(0,0,V.width,V.height),U.forEach(K=>{let X=K.getCanvas()._canvas;X&&H.drawImage(X,0,0);}),a?.current){let K=a.current;H.drawImage(K,0,0);}};w.current=oe,o.current.draw(),oe(),await new Promise(K=>setTimeout(K,100)),console.log("Creating captureStream..."),E=V.captureStream(30),console.log("Canvas stream created, tracks:",E.getTracks().length);let W=E.getVideoTracks()[0];W&&console.log("Video track:",W.label,"state:",W.readyState);let q=0,_=()=>{oe(),o?.current&&(o.current.getLayers().forEach(X=>{X.batchDraw();}),q++,q%60===0&&console.log("Drawing frame:",q)),x.current=requestAnimationFrame(_);};_();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{B=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let T=[...E.getVideoTracks()];B&&T.push(...B.getAudioTracks());let G=new MediaStream(T);v.current=G;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 O=new MediaRecorder(G,{mimeType:F,videoBitsPerSecond:25e5});f.current=O,h.current=[],O.ondataavailable=U=>{console.log("Data available, size:",U.data.size),U.data.size>0&&h.current.push(U.data);},O.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&&w.current&&b.current&&(o.current.draw(),o.current.getLayers().forEach(H=>{H.batchDraw();}),w.current(),g.current=b.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",g.current.length)),G.getTracks().forEach(V=>V.stop()),m.current&&clearInterval(m.current),x.current&&(cancelAnimationFrame(x.current),x.current=null),i(U);},O.onerror=U=>{console.error("MediaRecorder error:",U);},console.log("Starting recording..."),O.start(1e3),n(!0),p(0),m.current=setInterval(()=>{p(U=>U+1);},1e3);}catch(E){console.error("Error starting screen recording:",E),alert("Failed to start recording. Please ensure you granted permission.");}},P=()=>{f.current&&r&&(console.log("Stopping recording, state:",f.current.state),f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),n(false));},k=()=>{if(u){let E=URL.createObjectURL(u),B=document.createElement("a");B.href=E,B.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(B),B.click(),document.body.removeChild(B),URL.revokeObjectURL(E);}},S=E=>{let B=Math.floor(E/60),T=E%60;return `${B.toString().padStart(2,"0")}:${T.toString().padStart(2,"0")}`};if(!s)return null;if(r){let E=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:S(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:P,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(E,s)}let y=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: ",S(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&g.current&&(t(u,g.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick: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),p(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(y,s)};var Nu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:s})=>{let r=qe(),[n,u]=useState(false),[i,c]=useState(null),[p,d]=useState(false),[l,f]=useState(0),h=useRef(null),m=useRef([]),v=useRef(null),x=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(E=>E.blob()).then(E=>c(E)).catch(E=>console.error("Error loading audio:",E));},[o,i]);let g=async()=>{try{let E=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),B=new MediaRecorder(E);h.current=B,m.current=[],B.ondataavailable=T=>{T.data.size>0&&m.current.push(T.data);},B.onstop=()=>{let T=new Blob(m.current,{type:"audio/webm"});c(T),E.getTracks().forEach(G=>G.stop()),v.current&&clearInterval(v.current);},B.start(),u(!0),f(0),v.current=setInterval(()=>{f(T=>T+1);},1e3);}catch(E){console.error("Error starting audio recording:",E),alert("Failed to start recording. Please allow microphone access.");}},b=()=>{h.current&&n&&(h.current.stop(),u(false));},w=()=>{if(i){let E=URL.createObjectURL(i),B=new Audio(E);x.current=B,B.onended=()=>{d(false),URL.revokeObjectURL(E);},B.play(),d(true);}},I=()=>{x.current&&(x.current.pause(),x.current.currentTime=0,d(false));},P=async()=>{if(i){let E=new FileReader;E.onloadend=()=>{let B=E.result;t(B),s();},E.readAsDataURL(i);}},k=()=>{c(null),a();},S=E=>{let B=Math.floor(E/60),T=E%60;return `${B.toString().padStart(2,"0")}:${T.toString().padStart(2,"0")}`};if(!r)return null;if(n){let E=jsx("div",{className:"pointer-events-none fixed inset-0 z-50",children:jsxs("div",{className:"pointer-events-auto fixed top-[100px] left-1/2 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:S(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: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(E,r)}let y=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:g,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:p?I:w,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),p?"Playing...":"Play Audio"]}),jsx("button",{onClick:k,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:P,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:s,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(y,r)};var Ft=({audioData:e,x:o,y:t,width:a,scale:s=1,offsetX:r=0,offsetY:n=0,containerTop:u=90,containerRight:i=320})=>{let[c,p]=useState(false),d=useRef(null),l=m=>{if(m.stopPropagation(),c&&d.current)d.current.pause(),d.current.currentTime=0,p(false);else {let v=new Audio(e);d.current=v,v.onended=()=>{p(false);},v.onerror=()=>{console.error("Error playing audio"),p(false);},v.play(),p(true);}},f=(o+a)*s+r-15,h=t*s+n+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:`${f}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var Hu=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=ve(),s=Q(ge),r=qe(),n=useMemo(()=>{if(!s)return [];let x=[];return s.images?.forEach(g=>{x.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),s.videos?.forEach(g=>{x.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),s.shapes?.forEach(g=>{x.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),s.texts?.forEach(g=>{x.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),s.flashcards?.forEach(g=>{x.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),s.photoFrames?.forEach(g=>{x.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),s.multipleChoices?.forEach(g=>{x.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),s.trueFalses?.forEach(g=>{x.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),s.shortAnswers?.forEach(g=>{x.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),s.LongAnswer?.forEach(g=>{x.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),s.fillInTheBlanks?.forEach(g=>{x.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),s.lines?.forEach(g=>{g.id&&x.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),x.sort((g,b)=>b.timestamp-g.timestamp)},[s]),[u,i]=useState(n),[c,p]=useState(false);useEffect(()=>{c||i(n);},[n]);let d=x=>{let g="h-5 w-5";switch(x){case "image":return jsx(Image$3,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes$1,{className:g});case "text":return jsx(TextT,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners,{className:g});case "line":return jsx(Pen,{className:g});default:return jsx(Question,{className:g})}},h=x=>{p(true),i(x);},m=()=>{p(false);let x=Date.now();u.forEach((g,b)=>{let w=x-b;a(rr({id:g.id,type:g.type,newTimestamp:w}));});};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(x=>{let g=x.id===e;return jsxs(Reorder.Item,{value:x,onDragEnd:m,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${g?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(x.id,x.type),className:`font-medium ${g?"text-[#096B76]":"text-[#00000099]"}`,children:x.name})}),jsx("div",{className:`${g?"text-[#096B76]":"text-[#00000099]"}`,children:d(x.type)})]},x.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 Uu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r,touchHandlers:n})=>{let u=useSelector(W=>W.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,p]=useState(new Set),[d,l]=useState(false),[f,h]=useState(null),m=useRef(null);useEffect(()=>{let W=m.current;if(W)return a.current.set(e.id,W),()=>{a.current.delete(e.id);}},[e.id]);let v=new Set(e.data.responseOptions.correctIndex),x=v.size>1,g=W=>{d||p(x?q=>{let _=new Set(q);return _.has(W)?_.delete(W):_.add(W),_}:new Set([W]));},b=()=>{c.size>0&&l(true);},w=()=>{l(false),p(new Set);},I=c.size===v.size&&Array.from(c).every(W=>v.has(W)),P=Array.from(c).filter(W=>v.has(W)),k=x&&P.length>0&&!I,S=()=>I?"\u2713 Correct! Great job! \u{1F389}":k?`\u26A0 Partially correct (${P.length}/${v.size})`:"\u2717 Try again!",y=()=>I?{bg:"#dcfce7",text:"#166534"}:k?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},E=55,B=8,T=24,G=60,F=60,O=x&&!d?25:0,U=e.data.feedbackMode==="practice"?48:0,V=12,H=G+O+(d?F:0),oe=e.data.responseOptions.options.length*(E+B),me=H+oe+V+U+T;return jsxs(Group,{ref:m,name:"mcq-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...n,...i?{}:{onDragEnd:s,onClick:W=>t&&t(e.id),onTap:W=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:me,width:e.width,onTransformEnd:W=>o(e.id,W),onContextMenu:W=>{W.cancelBubble=true,r(W.evt,e.id,"mcq");}}),jsx(Text,{x:T+8,y:T,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-T*2,listening:false}),x&&!d&&e.data.feedbackMode==="practice"?jsx(Text,{x:T,y:T+35,text:`Select ${v.size} answers (${c.size}/${v.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-T*2,listening:false}):null,d&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:T+24,y:G+O,width:e.width-T*2-40,height:F-20,fill:y().bg,cornerRadius:8}),jsx(Text,{x:T,y:G+O,width:e.width-T*2,height:F-20,text:S(),fontSize:16,fontStyle:"bold",fill:y().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((W,q)=>{let _=v.has(q),K=c.has(q),X=H+q*(E+B),te="#e5e7eb",$="#ffffff",re="#111827";return d&&_?(te="#22c55e",$="#dcfce7",re="#1B9D2C"):d&&K&&!_?(te="#ef4444",$="#fee2e2",re="#ef4444"):K&&(te="#096B76",$="#ECFFF8",re="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:T+12,y:X+(E-20)/2,width:20,height:20,fill:K?"#096B76":"white",stroke:K?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:x?4:10,onClick:ie=>{ie.cancelBubble=true,g(q);},onTap:ie=>{ie.cancelBubble=true,g(q);}}),K&&jsx(Text,{x:T+12,y:X+(E-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:T+44,y:X,width:e.width-T*2-60,height:E,fill:$,stroke:te,strokeWidth:2,cornerRadius:8,onClick:ie=>{ie.cancelBubble=true,g(q);},onTap:ie=>{ie.cancelBubble=true,g(q);}}),jsx(Text,{x:T+60,y:X,width:e.width-T*2-80,height:E,text:W,fontSize:16,fill:re,verticalAlign:"middle",listening:false})]},q)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:H+e.data.responseOptions.options.length*(E+B)+12,children:[jsxs(Group,{onMouseDown:W=>{W.cancelBubble=true,h("check");},onMouseUp:W=>{W.cancelBubble=true,h(null),b();},onMouseLeave:W=>{W.cancelBubble=true,h(null);},onTouchStart:W=>{W.cancelBubble=true,h("check");},onTouchEnd:W=>{W.cancelBubble=true,h(null),b();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:T+14,width:(e.width-T*2-24)/(d?2:1),height:48,fill:c.size===0||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.cancelBubble=true}),jsx(Text,{x:T+14,width:(e.width-T*2-24)/(d?2:1),height:48,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-T*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),w();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),w();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:T,width:(e.width-T*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.cancelBubble=true}),jsx(Text,{x:T,width:(e.width-T*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Uu.displayName="MultipleChoice";var Ku=Uu;var Qi=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:s,touchHandlers:r})=>{let n=useDispatch(),u=useSelector(K=>K.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,p]=useState(false),[d,l]=useState(new Set),[f,h]=useState(false),[m,v]=useState(false),[x,g]=useState(0),b=340,w=100,I=window.innerWidth*.4,P=window.innerHeight*.5,k=b+20,S=w+60,y=I-40,E=P-300,B=useRef(null);useEffect(()=>{let K=B.current;if(K)return s.current.set(e.id,K),()=>{s.current.delete(e.id);}},[e.id]);let T=K=>{n(pa({id:e.id,x:K.target.x(),y:K.target.y()}));},G=K=>{let X=K.target,te=X.x(),$=X.y(),re=window.innerWidth*.2,Ae=te+re>k&&te<k+y&&$+50>S&&$<S+E;p(Ae);},F=(K,X)=>{let te=X.target,$=te.x(),re=te.y(),ie=window.innerWidth*.2,Ce=$+ie>k&&$<k+y&&re+50>S&&re<S+E;l(Ce?Ee=>new Set(Ee).add(K):Ee=>{let lt=new Set(Ee);return lt.delete(K),lt}),p(false);},O=()=>{h(true);},U=()=>{h(false),l(new Set),g(K=>K+1);},V=new Set(e.data.responseOptions.correctIndex),H=d.size===V.size&&Array.from(d).every(K=>V.has(K)),oe=Array.from(d).filter(K=>V.has(K)),me=oe.length>0&&!H,W=()=>H?"\u2713 Correct! Great job!":me?`\u26A0 Partially correct (${oe.length}/${V.size})`:"\u2717 Try again!",q=()=>H?{bg:"#dcfce7",text:"#166534"}:me?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},_=()=>f?H?"#4CAF50":me?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:B,name:"mcq-element",width:I,height:P,draggable:!i,listening:!i,...r,...i?{}:{onClick:K=>a&&a(e.id),onTap:K=>a&&a(e.id),onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"mcq");}},children:[jsxs(Group,{x:b,y:w,rotation:e.rotation,onDragEnd:T,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?P-100:P-50,width:I,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:I-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:y,height:E,fill:"#EBF6F7",stroke:_(),strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:E+18,width:y-5,height:60,fill:q().bg,cornerRadius:8}),jsx(Text,{x:20,y:E+20,width:y,height:60,text:W(),fontSize:18,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle"})]}),d.size===0&&!f&&jsx(Text,{x:20,y:60,width:y,height:E-60,text:V.size>1?`Drop ${V.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:f?P-200:P-160,children:[jsxs(Group,{onMouseDown:()=>{v(true),O();},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),O();},onTouchEnd:()=>v(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:y}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:y,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:U,onTouchStart:U,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:y}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:y,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((K,X)=>{let te=X%2,$=Math.floor(X/2),re=window.innerWidth*.2,ie=50,Ae=10,Ce=d.has(X),Ee=V.has(X),lt=f&&Ce,bt="transparent";return lt?bt=Ee?"#4CAF50":"#ef4444":Ce&&(bt="#4CAF50"),jsxs(Group,{x:340+te*(re+Ae),y:w+P-80+$*(ie+Ae),draggable:!f,onDragMove:G,onDragEnd:lo=>F(X,lo),opacity:f&&!Ce?.5:1,children:[jsx(Rect,{width:re-20,height:ie,fill:"white",stroke:bt,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:re-20,height:ie,text:K,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${X}-${x}`)})]})};Qi.displayName="MultipleChoiceDragAndDrop";var Wu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r,onLongPress:n})=>{let{createHandlers:u}=Ne({onLongPress:n});return jsx(Fragment,{children:e.map(i=>i.data.responseType==="classic"?jsx(Ku,{multipleChoice:i,handleMcqTransform:o,mcqRefs:a,handleDragEnd:c=>s(c,i.id),onContextMenu:r,touchHandlers:u(i.id,"mcq")},i.id):jsx(Qi,{multipleChoice:i,handleMcqTransform:o,mcqRefs:a,onContextMenu:r,touchHandlers:u(i.id,"mcq")},i.id))})};var zu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r,touchHandlers:n})=>{let u=useSelector(V=>V.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,p]=useState(null),[d,l]=useState(false),[f,h]=useState(null),m=useRef(null);useEffect(()=>{let V=m.current;if(V)return a.current.set(e.id,V),()=>{a.current.delete(e.id);}},[e.id]);let v=()=>{c!==null&&l(true);},x=()=>{l(false),p(null);},g=e.data.responseOptions.correctAnswer,b=c===g,w=V=>{d||p(V);},I=()=>b?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",P=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},k=70,S=12,y=24,E=60,B=60,T=e.data.feedbackMode==="practice"?48:0,G=12,F=E+(d?B:0),O=2*(k+S),U=F+O+G+T+y;return jsxs(Group,{ref:m,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...n,...i?{}:{onDragEnd:V=>r(V,e.id),onClick:V=>t&&t(e.id),onTap:V=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:U-20,width:e.width,onTransformEnd:V=>o(e.id,V),onContextMenu:V=>{V.cancelBubble=true,s(V.evt,e.id,"trueFalse");}}),jsx(Text,{x:y,y,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),d&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:y,y:E,width:e.width-y*2,height:B-10,fill:P().bg,cornerRadius:8}),jsx(Text,{x:y,y:E,width:e.width-y*2,height:B-10,text:I(),fontSize:16,fontStyle:"bold",fill:P().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((V,H)=>{let oe=g===V.value,me=c===V.value,W=(e.width-y*3)/2,q=y+H*(W+y),_=F,K=V.value===true,X=K?"#10b981":"#ef4444",te="#ffffff",$="#ffffff",re="#e5e7eb";return d&&(oe?($=K?"#f0fdf4":"#fef2f2",re=K?"#86efac":"#fecaca"):me&&!oe&&($="#fee2e2",re="#ef4444")),me&&!d&&(re="#096B76",$="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:q,y:_,width:W,height:k+50,fill:$,stroke:re,strokeWidth:2,cornerRadius:12,onClick:ie=>{ie.cancelBubble=true,w(V.value);},onTap:ie=>{ie.cancelBubble=true,w(V.value);}}),jsx(Circle,{x:q+W/2,y:_+40,radius:28,fill:X,listening:false}),K?jsx(Text,{x:q+W/2-14,y:_+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:q+W/2-14,y:_+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:q,y:_+85,width:W,height:30,text:V.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},V.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:F+2*(k+S),children:[jsxs(Group,{onMouseDown:V=>{V.cancelBubble=true,h("check");},onMouseUp:V=>{V.cancelBubble=true,h(null),v();},onMouseLeave:V=>{V.cancelBubble=true,h(null);},onTouchStart:V=>{V.cancelBubble=true,h("check");},onTouchEnd:V=>{V.cancelBubble=true,h(null),v();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:y,width:(e.width-y*2-8)/(d?2:1),height:48,fill:c===null||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:V=>V.cancelBubble=true,onTap:V=>V.cancelBubble=true}),jsx(Text,{x:y,width:(e.width-y*2-8)/(d?2:1),height:48,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-y*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),x();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),x();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:y,width:(e.width-y*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:V=>V.cancelBubble=true,onTap:V=>V.cancelBubble=true}),jsx(Text,{x:y,width:(e.width-y*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});zu.displayName="TrueFalse";var Gu=zu;var Dx="#FFFFFF",al=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t,touchHandlers:a})=>{let s=useDispatch(),r=useSelector(X=>X.toolbar.selectedTool),n=r==="pen"||r==="eraser",[u,i]=useState(false),[c,p]=useState(null),[d,l]=useState(false),[f,h]=useState(false),[m,v]=useState(0),[x,g]=useState(false),b=340,w=100,I=window.innerWidth*.4,P=window.innerHeight*.5,k=I-40,S=P-300,y=20,E=60,B=k,T=S,G=I*.2-40,F=50,O=useRef(null),U=X=>{s(ha({id:e.id,x:X.target.x(),y:X.target.y()}));},V=X=>{let te=X.target,$=te.x(),re=te.y(),ie=Math.max(0,Math.min($+G,y+B)-Math.max($,y)),Ae=Math.max(0,Math.min(re+F,E+T)-Math.max(re,E)),Ce=ie*Ae,Ee=G*F;i(Ce/Ee>=.5);},H=(X,te)=>{let $=te.target,re=$.x(),ie=$.y(),Ae=Math.max(0,Math.min(re+G,y+B)-Math.max(re,y)),Ce=Math.max(0,Math.min(ie+F,E+T)-Math.max(ie,E)),Ee=Ae*Ce,lt=G*F;if(Ee/lt>=.5)p(X);else return;i(false);},oe=()=>{l(true);},me=()=>{l(false),p(null),v(X=>X+1);},W=e.data.responseOptions.correctAnswer,q=c===W,_=()=>q?"\u2713 Correct! Great job!":"\u2717 Try again!",K=()=>q?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:O,name:"trueFalse-element",width:I,height:P,draggable:!n,listening:!n,...a,...n?{}:{onContextMenu:X=>{X.evt.preventDefault(),o(X.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:w,rotation:e.rotation,onDragEnd:U,children:[jsx(Rect,{fill:"white",stroke:u?"#4CAF50":"#e5e7eb",strokeWidth:u?4:2,cornerRadius:12,height:d?P:e.data.feedbackMode==="practice"?P-50:P-100,width:I,shadowColor:u?"#4CAF50":"transparent",shadowBlur:u?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:I-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:k,height:S,fill:"transparent",stroke:u?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:k,height:60,fill:K().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:k,height:60,text:_(),fontSize:18,fontStyle:"bold",fill:K().text,align:"center",verticalAlign:"middle"})]}),c===null&&!d&&jsx(Text,{x:20,y:60,width:k,height:S-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:P-100,children:[jsxs(Group,{onMouseDown:()=>{c!==null&&(h(true),oe());},onMouseUp:()=>h(false),onMouseLeave:()=>h(false),onTouchStart:()=>{c!==null&&(h(true),oe());},onTouchEnd:()=>h(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:c===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{y:50,onMouseDown:me,onTouchStart:me,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((X,te)=>{let $=window.innerWidth*.2,re=50,ie=10,Ae=c===X.value,Ce=W===X.value,Ee=d&&Ae,lt="transparent";return Ee?lt=Ce?"#4CAF50":"#ef4444":Ae&&(lt="#4CAF50"),jsxs(Group,{x:16+te*($+ie),y:w+P-300,draggable:!d,onDragMove:V,onDragEnd:bt=>H(X.value,bt),opacity:d&&!Ae?.5:1,children:[jsx(Rect,{width:$-40,height:re,fill:"#075560",stroke:lt,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:$-40,height:re,text:X.label,fontSize:18,fontStyle:"bold",fill:Dx,align:"center",verticalAlign:"middle",listening:false})]},`${X.value}-${m}`)})]})})};al.displayName="TrueFalseDragAndDrop";var ju=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:s,onContextMenu:r,onLongPress:n})=>{let{createHandlers:u}=Ne({onLongPress:n});return jsx(Fragment,{children:e.map(i=>i.data.responseType==="classic"?jsx(Gu,{trueFalse:i,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s,touchHandlers:u(i.id,"trueFalse")},i.id):jsx(al,{trueFalse:i,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:r,touchHandlers:u(i.id,"trueFalse")},i.id))})};var ya=new WeakMap,Ao=new WeakMap,yr={current:[]},rl=false,vr=0,br=new Set,$s=new Map;function _u(e){let o=Array.from(e).sort((t,a)=>t instanceof Gt&&t.options.deps.includes(a)?1:a instanceof Gt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(yr.current.includes(t))continue;yr.current.push(t),t.recompute();let a=Ao.get(t);if(a)for(let s of a){let r=ya.get(s);r&&_u(r);}}}function Bx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Ox(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Ys(e){if(vr>0&&!$s.has(e)&&$s.set(e,e.prevState),br.add(e),!(vr>0)&&!rl)try{for(rl=!0;br.size>0;){let o=Array.from(br);br.clear();for(let t of o){let a=$s.get(t)??t.prevState;t.prevState=a,Bx(t);}for(let t of o){let a=ya.get(t);a&&(yr.current.push(t),_u(a));}for(let t of o){let a=ya.get(t);if(a)for(let s of a)Ox(s);}}}finally{rl=false,yr.current=[],$s.clear();}}function It(e){vr++;try{e();}finally{if(vr--,vr===0){let o=br.values().next().value;o&&Ys(o);}}}function Xu(e){return typeof e=="function"}var Qt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var s,r;this.listeners.add(a);let n=(r=(s=this.options)==null?void 0:s.onSubscribe)==null?void 0:r.call(s,a,this);return ()=>{this.listeners.delete(a),n?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,s;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):Xu(o)?this.state=o(this.prevState):this.state=o,(s=(a=this.options)==null?void 0:a.onUpdate)==null||s.call(a),Ys(this);}};var Gt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),s=new Array(t);for(let r=0;r<t;r++){let n=this.options.deps[r];a[r]=n.prevState,s[r]=n.state;}return this.lastSeenDepValues=s,{prevDepVals:a,currDepVals:s,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let s=this.getDepVals();this.state=this.options.fn(s),(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:s}=this.getDepVals();for(let r=0;r<s.length;r++)if(s[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,s;this.listeners.add(t);let r=(s=(a=this.options).onSubscribe)==null?void 0:s.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof Qt){let a=ya.get(t);a||(a=new Set,ya.set(t,a)),a.add(this);let s=Ao.get(this);s||(s=new Set,Ao.set(this,s)),s.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof Qt){let a=ya.get(t);a&&a.delete(this);let s=Ao.get(this);s&&s.delete(t);}}};function Nx(e){return typeof e=="function"}function sl(e,...o){return Nx(e)?e(...o):e}function $u(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var wa,pt,nt,wr,La,Ga,oa,Po,Lr,Js,Sr,Eo,ja=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:s=1e3}){Re(this,wa,true);Re(this,pt);Re(this,nt);Re(this,wr);Re(this,La);Re(this,Ga);Re(this,oa);Re(this,Po);Re(this,Lr,0);Re(this,Js,5);Re(this,Sr,()=>{this.debugLog("Connected to event bus"),Te(this,Ga,true),this.debugLog("Emitting queued events",j(this,La)),j(this,La).forEach(o=>this.emitEventToBus(o)),Te(this,La,[]),this.stopConnectLoop(),j(this,nt).call(this).removeEventListener("tanstack-connect-success",j(this,Sr));});Re(this,Eo,()=>{if(j(this,nt).call(this).addEventListener("tanstack-connect-success",j(this,Sr)),j(this,Lr)<j(this,Js)){Sd(this,Lr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}j(this,nt).call(this).removeEventListener("tanstack-connect",j(this,Eo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Te(this,pt,o),Te(this,wa,a),Te(this,nt,this.getGlobalTarget),Te(this,wr,t),this.debugLog(" Initializing event subscription for plugin",j(this,pt)),Te(this,La,[]),Te(this,Ga,false),Te(this,oa,null),Te(this,Po,s);}startConnectLoop(){j(this,oa)!==null||j(this,Ga)||(this.debugLog(`Starting connect loop (every ${j(this,Po)}ms)`),Te(this,oa,setInterval(j(this,Eo),j(this,Po))));}stopConnectLoop(){j(this,oa)!==null&&(clearInterval(j(this,oa)),Te(this,oa,null),this.debugLog("Stopped connect loop"));}debugLog(...o){j(this,wr)&&console.log(`\u{1F334} [tanstack-devtools:${j(this,pt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return j(this,pt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});j(this,nt).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{j(this,nt).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!j(this,wa)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!j(this,Ga)){this.debugLog("Bus not available, will be pushed as soon as connected"),j(this,La).push({type:`${j(this,pt)}:${o}`,payload:t,pluginId:j(this,pt)}),typeof CustomEvent<"u"&&(j(this,Eo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${j(this,pt)}:${o}`,payload:t,pluginId:j(this,pt)})}on(o,t){let a=`${j(this,pt)}:${o}`;if(!j(this,wa))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let s=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return j(this,nt).call(this).addEventListener(a,s),this.debugLog("Registered event to bus",a),()=>{j(this,nt).call(this).removeEventListener(a,s);}}onAll(o){if(!j(this,wa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;o(s);};return j(this,nt).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,nt).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!j(this,wa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;j(this,pt)&&s.pluginId!==j(this,pt)||o(s);};return j(this,nt).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,nt).call(this).removeEventListener("tanstack-devtools-global",t)}};wa=new WeakMap,pt=new WeakMap,nt=new WeakMap,wr=new WeakMap,La=new WeakMap,Ga=new WeakMap,oa=new WeakMap,Po=new WeakMap,Lr=new WeakMap,Js=new WeakMap,Sr=new WeakMap,Eo=new WeakMap;var nl=class extends ja{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Yu=(e,o)=>{il.emit(e,o);},il=new nl;function Ju(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Vx={enabled:true,leading:true,trailing:true,wait:0},Sa,Ct,_a,Xa,$a,Do,Zs=class{constructor(o,t){Re(this,Sa);Re(this,Ct);Re(this,_a);Re(this,Xa);Re(this,$a);Re(this,Do);this.fn=o,this.store=new Qt(Ju()),this.setOptions=a=>{this.options={...this.options,...a},j(this,_a).call(this)||this.cancel();},Te(this,Ct,a=>{this.store.setState(s=>{let r={...s,...a},{isPending:n}=r;return {...r,status:j(this,_a).call(this)?n?"pending":"idle":"disabled"}}),Yu("Throttler",this);}),Te(this,_a,()=>!!sl(this.options.enabled,this)),Te(this,Xa,()=>sl(this.options.wait,this)),this.maybeExecute=(...a)=>{j(this,Ct).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let s=Date.now(),r=s-this.store.state.lastExecutionTime,n=j(this,Xa).call(this);if(this.options.leading&&r>=n)j(this,$a).call(this,...a);else if(j(this,Ct).call(this,{lastArgs:a}),!j(this,Sa)&&this.options.trailing){let u=this.store.state.lastExecutionTime?s-this.store.state.lastExecutionTime:0,i=n-u;j(this,Ct).call(this,{isPending:true}),Te(this,Sa,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&j(this,$a).call(this,...c);},i));}},Te(this,$a,(...a)=>{if(!j(this,_a).call(this))return;this.fn(...a);let s=Date.now(),r=s+j(this,Xa).call(this);j(this,Do).call(this),j(this,Ct).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:s,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||j(this,Ct).call(this,{nextExecutionTime:void 0});},j(this,Xa).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&j(this,$a).call(this,...this.store.state.lastArgs);},Te(this,Do,()=>{j(this,Sa)&&(clearTimeout(j(this,Sa)),Te(this,Sa,void 0));}),this.cancel=()=>{j(this,Do).call(this),j(this,Ct).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{j(this,Ct).call(this,Ju());},this.key=$u(t.key),this.options={...Vx,...t},j(this,Ct).call(this,this.options.initialState??{}),il.on("d-Throttler",a=>{a.payload.key===this.key&&(j(this,Ct).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Sa=new WeakMap,Ct=new WeakMap,_a=new WeakMap,Xa=new WeakMap,$a=new WeakMap,Do=new WeakMap;function ll(e,o){return new Zs(e,o).maybeExecute}function Ia(e,o){return typeof e=="function"?e(o):e}function Ca(e,o){return an(o).reduce((a,s)=>{if(a===null)return null;if(typeof a<"u")return a[s]},e)}function Ro(e,o,t){let a=an(o);function s(r){if(!a.length)return Ia(t,r);let n=a.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[n]:s(r[n])}):{[n]:s()};if(Array.isArray(r)&&typeof n=="number"){let u=r.slice(0,n);return [...u.length?u:new Array(n),s(r[n]),...r.slice(n+1)]}return [...new Array(n),s()]}return s(e)}function ul(e,o){let t=an(o);function a(s){if(!s)return;if(t.length===1){let n=t[0];if(Array.isArray(s)&&typeof n=="number")return s.filter((c,p)=>p!==n);let{[n]:u,...i}=s;return i}let r=t.shift();if(typeof r=="string"&&typeof s=="object")return {...s,[r]:a(s[r])};if(typeof r=="number"&&Array.isArray(s)){if(r>=s.length)return s;let n=s.slice(0,r);return [...n.length?n:new Array(r),a(s[r]),...s.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var qx=/^(\d+)$/gm,Hx=/\.(\d+)(?=\.)/gm,Ux=/^(\d+)\./gm,Kx=/\.(\d+$)/gm,Wx=/\.{2,}/gm,dl="__int__",Qs=`${dl}$1`;function an(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(qx,Qs).replace(Hx,`.${Qs}.`).replace(Ux,`${Qs}.`).replace(Kx,`.${Qs}`).replace(Wx,".").split(".").map(o=>{if(o.startsWith(dl)){let t=o.substring(dl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function cl(e){return !(Array.isArray(e)&&e.length===0)}function Fo(e,o){let t=a=>a.validators.filter(Boolean).map(s=>({cause:s.cause,validate:s.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Bo(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:s,onDynamicAsyncDebounceMs:r}=o.validators||{},n=t??0,u=i=>i.validators.filter(Boolean).map(c=>{let p=c?.cause||e,d=n;switch(p){case "change":d=s??n;break;case "blur":d=a??n;break;case "dynamic":d=r??n;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:p,validate:c.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var Ir=e=>!!e&&typeof e=="object"&&"fields"in e;function ka(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[s,r]of e)if(!o.has(s)||!Object.is(r,o.get(s)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let s of e)if(!o.has(s))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let s of t)if(!a.includes(s)||!ka(e[s],o[s]))return false;return true}var on=({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},rn=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function $e(e,o){return e==null?o:{...e,...o}}var Ya=256,tn=[],en;for(;Ya--;)tn[Ya]=(Ya+256).toString(16).substring(1);function fl(){let e=0,o,t="";if(!en||Ya+16>256){for(en=new Array(256),e=256;e--;)en[e]=256*Math.random()|0;e=0,Ya=0;}for(;e<16;e++)o=en[Ya+e],e===6?t+=tn[o&15|64]:e===8?t+=tn[o&63|128]:t+=tn[o],e&1&&e>1&&e<11&&(t+="-");return Ya++,t}var Ta=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"},s={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,s,r,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[s,n],form:e.form});case "change":return e.runValidation({validators:[a,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function zx(e,o){let t=new Map;for(let a of e){let s=a.path??[],r=o,n="";for(let u=0;u<s.length;u++){let i=s[u];if(i===void 0)continue;let c=typeof i=="object"?i.key:i,p=Number(c);Array.isArray(r)&&!Number.isNaN(p)?n+=`[${p}]`:n+=(u>0?".":"")+String(c),typeof r=="object"&&r!==null?r=r[c]:r=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var Zu=(e,o)=>{let t=zx(e,o);return {form:t,fields:t}},Ma={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:Zu(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:Zu(a.issues,e)}},sn=e=>!!e&&"~standard"in e;var Oo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function Cr(e){function o(d,l,f,h){let m=a(d,l,f,h);({insert:()=>u(m,d,l),remove:()=>i(m),swap:()=>h!==void 0&&p(m,d,l,h),move:()=>h!==void 0&&c(m,d,l,h)})[f]();}function t(d,l){return `${d}[${l}]`}function a(d,l,f,h){let m=[t(d,l)];if(f==="swap")m.push(t(d,h));else if(f==="move"){let[v,x]=[Math.min(l,h),Math.max(l,h)];for(let g=v;g<=x;g++)m.push(t(d,g));}else {let v=e.getFieldValue(d),x=Array.isArray(v)?v.length:0;for(let g=l+1;g<x;g++)m.push(t(d,g));}return Object.keys(e.fieldInfo).filter(v=>m.some(x=>v.startsWith(x)))}function s(d,l){return d.replace(/\[(\d+)\]/,(f,h)=>{let m=parseInt(h,10);return `[${l==="up"?m+1:Math.max(0,m-1)}]`})}function r(d,l){(l==="up"?d:[...d].reverse()).forEach(h=>{let m=s(h.toString(),l),v=e.getFieldMeta(m);v?e.setFieldMeta(h,v):e.setFieldMeta(h,n());});}let n=()=>Oo,u=(d,l,f)=>{r(d,"down"),d.forEach(h=>{h.toString().startsWith(t(l,f))&&e.setFieldMeta(h,n());});},i=d=>{r(d,"up");},c=(d,l,f,h)=>{let m=new Map(Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,f))).map(v=>[v,e.getFieldMeta(v)]));r(d,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,h))).forEach(v=>{let x=v.replace(t(l,h),t(l,f)),g=m.get(x);g&&e.setFieldMeta(v,g);});},p=(d,l,f,h)=>{d.forEach(m=>{if(!m.toString().startsWith(t(l,f)))return;let v=m.toString().replace(t(l,f),t(l,h)),[x,g]=[e.getFieldMeta(m),e.getFieldMeta(v)];x&&e.setFieldMeta(v,x),g&&e.setFieldMeta(m,g);});};return {handleArrayFieldMetaShift:o}}var ml=class extends ja{constructor(){super({pluginId:"form-devtools"});}},kt=new ml;function pl(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 Tr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),s=this.store.mount(),r=()=>{a(),s(),kt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return kt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let s=this.options;this.options=a;let r=!!a.transform?.deps?.some((i,c)=>i!==this.prevTransformArray[c]),n=a.defaultValues&&!ka(a.defaultValues,s.defaultValues)&&!this.state.isTouched,u=!ka(a.defaultState,s.defaultState)&&!this.state.isTouched;!n&&!u&&!r||(It(()=>{this.baseStore.setState(()=>pl(Object.assign({},this.state,u?a.defaultState:{},n?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),kt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,s)=>{let{fieldMeta:r}=this.state,n=this.resetFieldMeta(r);a&&!s?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>pl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let s=[];return It(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let u=n.instance;s.push(Promise.resolve().then(()=>u.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(s)).flat()},this.validateArrayFieldsStartingFrom=async(a,s,r)=>{let n=this.getFieldValue(a),u=Array.isArray(n)?Math.max(n.length-1,0):null,i=[`${a}[${s}]`];for(let l=s+1;l<=(u??0);l++)i.push(`${a}[${l}]`);let c=Object.keys(this.fieldInfo).filter(l=>i.some(f=>l.startsWith(f))),p=[];return It(()=>{c.forEach(l=>{p.push(Promise.resolve().then(()=>this.validateField(l,r)));});}),(await Promise.all(p)).flat()},this.validateField=(a,s)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(n=>({...n,isTouched:true})),r.validate(s)):[]},this.validateSync=a=>{let s=Fo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ta}),r=false,n={};return It(()=>{for(let c of s){if(!c.validate)continue;let p=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:l}=nn(p),f=kr(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let m=this.getFieldMeta(h);if(!m)continue;let{errorMap:v,errorSourceMap:x}=m,g=l?.[h],{newErrorValue:b,newSource:w}=on({newFormValidatorError:g,isPreviousErrorFromFormValidator:x?.[f]==="form",previousErrorValue:v?.[f]});w==="form"&&(n[h]={...n[h],[f]:g}),v?.[f]!==b&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[f]:b},errorSourceMap:{...I.errorSourceMap,[f]:w}}));}this.state.errorMap?.[f]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:d}})),(d||l)&&(r=!0);}let u=kr("submit");this.state.errorMap?.[u]&&a!=="submit"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let i=kr("server");this.state.errorMap?.[i]&&a!=="server"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[i]:void 0}}));}),{hasErrored:r,fieldsErrorMap:n}},this.validateAsync=async a=>{let s=Bo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ta});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let r=[],n;for(let c of s){if(!c.validate)continue;let p=kr(c.cause);this.state.validationMetaMap[p]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[p]={lastAbortController:l},r.push(new Promise(async f=>{let h;try{h=await new Promise((g,b)=>{setTimeout(async()=>{if(l.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(w){b(w);}},c.debounceMs);});}catch(g){h=g;}let{formError:m,fieldErrors:v}=nn(h);v&&(n=n?{...n,...v}:v);let x=kr(c.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let b=this.getFieldMeta(g);if(!b)continue;let{errorMap:w,errorSourceMap:I}=b,P=n?.[g],{newErrorValue:k,newSource:S}=on({newFormValidatorError:P,isPreviousErrorFromFormValidator:I?.[x]==="form",previousErrorValue:w?.[x]});w?.[x]!==k&&this.setFieldMeta(g,y=>({...y,errorMap:{...y.errorMap,[x]:k},errorSourceMap:{...y.errorSourceMap,[x]:S}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[x]:m}})),f(n?{fieldErrors:n,errorMapKey:x}:void 0);}));}let u=[],i={};if(r.length){u=await Promise.all(r);for(let c of u)if(c?.fieldErrors){let{errorMapKey:p}=c;for(let[d,l]of Object.entries(c.fieldErrors)){let h={...i[d]||{},[p]:l};i[d]=h;}}}return this.baseStore.setState(c=>({...c,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:s,fieldsErrorMap:r}=this.validateSync(a);return s&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Ca(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var s;return (s=this.fieldInfo)[a]||(s[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,s)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Ia(s,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((s,r)=>{let n=r;return s[n]=Oo,s},{}),this.setFieldValue=(a,s,r)=>{let n=r?.dontUpdateMeta??false,u=r?.dontRunListeners??false,i=r?.dontValidate??false;It(()=>{n||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:Ro(c.values,a,s)}));}),u||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(n=>{let u=a.toString();return n!==u&&n.startsWith(u)}),a];this.baseStore.setState(n=>{let u={...n};return r.forEach(i=>{u.values=ul(u.values,i),delete this.fieldInfo[i],delete u.fieldMetaBase[i];}),u});},this.pushFieldValue=(a,s,r)=>{this.setFieldValue(a,n=>[...Array.isArray(n)?n:[],s],r);},this.insertFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,i=>[...i.slice(0,s),r,...i.slice(s)],$e(n,{dontValidate:true}));let u=n?.dontValidate??false;u||await this.validateField(a,"change"),Cr(this).handleArrayFieldMetaShift(a,s,"insert"),u||await this.validateArrayFieldsStartingFrom(a,s,"change");},this.replaceFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,i=>i.map((c,p)=>p===s?r:c),$e(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.removeFieldValue=async(a,s,r)=>{let n=this.getFieldValue(a),u=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,c=>c.filter((p,d)=>d!==s),$e(r,{dontValidate:true})),Cr(this).handleArrayFieldMetaShift(a,s,"remove"),u!==null){let c=`${a}[${u}]`;this.deleteField(c);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.swapFieldValues=(a,s,r,n)=>{this.setFieldValue(a,i=>{let c=i[s],p=i[r];return Ro(Ro(i,`${s}`,p),`${r}`,c)},$e(n,{dontValidate:true})),Cr(this).handleArrayFieldMetaShift(a,s,"swap",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,s,r,n)=>{this.setFieldValue(a,i=>{let c=[...i];return c.splice(r,0,c.splice(s,1)[0]),c},$e(n,{dontValidate:true})),Cr(this).handleArrayFieldMetaShift(a,s,"move",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,s)=>{let r=this.getFieldValue(a),n=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],$e(s,{dontValidate:true})),n!==null)for(let i=0;i<=n;i++){let c=`${a}[${i}]`;this.deleteField(c);}(s?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:Oo},values:this.options.defaultValues?Ro(s.values,a,Ca(this.options.defaultValues,a)):s.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[s,r])=>(Object.keys(r).length&&r.errors.length&&(a[s]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Ma.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ma.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??fl(),this._devtoolsSubmissionOverride=false,this.baseStore=new Qt(pl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Gt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,u=a?.[0],i=s[0],c=0,p={};for(let d of Object.keys(i.fieldMetaBase)){let l=i.fieldMetaBase[d],f=u?.fieldMetaBase[d],h=n?.[d],m=Ca(i.values,d),v=h?.errors;if(!f||l.errorMap!==f.errorMap){v=Object.values(l.errorMap??{}).filter(I=>I!==void 0);let w=this.getFieldInfo(d)?.instance;w&&!w.options.disableErrorFlat&&(v=v?.flat(1));}let x=!cl(v??[]),g=!l.isDirty,b=ka(m,Ca(this.options.defaultValues,d))||ka(m,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===x&&h.isDefaultValue===b&&h.errors===v&&l===f){p[d]=h,c++;continue}p[d]={...l,errors:v,isPristine:g,isValid:x,isDefaultValue:b};}return Object.keys(i.fieldMetaBase).length&&n&&c===Object.keys(i.fieldMetaBase).length?n:p}}),this.store=new Gt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,u=a?.[0],i=s[0],c=s[1],p=Object.values(c).filter(Boolean),d=p.some(F=>F.isValidating),l=p.every(F=>F.isValid),f=p.some(F=>F.isTouched),h=p.some(F=>F.isBlurred),m=p.every(F=>F.isDefaultValue),v=f&&i.errorMap?.onMount,x=p.some(F=>F.isDirty),g=!x,b=!!(i.errorMap?.onMount||p.some(F=>F?.errorMap?.onMount)),w=!!d,I=n?.errors??[];(!u||i.errorMap!==u.errorMap)&&(I=Object.values(i.errorMap).reduce((F,O)=>O===void 0?F:O&&Ir(O)?(F.push(O.form),F):(F.push(O),F),[]));let P=I.length===0,k=l&&P,S=this.options.canSubmitWhenInvalid??false,y=i.submissionAttempts===0&&!f&&!b||!w&&!i.isSubmitting&&k||S,E=i.errorMap;if(v&&(I=I.filter(F=>F!==i.errorMap.onMount),E=Object.assign(E,{onMount:void 0})),n&&u&&n.errorMap===E&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===I&&n.isFieldsValidating===d&&n.isFieldsValid===l&&n.isFormValid===P&&n.isValid===k&&n.canSubmit===y&&n.isTouched===f&&n.isBlurred===h&&n.isPristine===g&&n.isDefaultValue===m&&n.isDirty===x&&ka(u,i))return n;let B={...i,errorMap:E,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:l,isFormValid:P,isValid:k,canSubmit:y,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:m,isDirty:x},T=this.options.transform?.deps??[];if(T.length!==this.prevTransformArray.length||T.some((F,O)=>F!==this.prevTransformArray[O])){let F=Object.assign({},this,{state:B});this.options.transform?.fn(F),B=F.state,this.prevTransformArray=T;}return B}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=ll(a=>kt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),kt.on("request-form-state",a=>{a.payload.id===this._formId&&kt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),kt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),kt.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 sn(o.validate)?Ma[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(s=>({...s,isSubmitted:false,submissionAttempts:s.submissionAttempts+1,isSubmitSuccessful:false})),It(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance&&(s.instance.state.meta.isTouched||s.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(s=>({...s,isSubmitting:true}));let a=()=>{this.baseStore.setState(s=>({...s,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),kt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(s=>s.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),kt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}It(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance?.options.listeners?.onSubmit?.({value:s.instance.state.value,fieldApi:s.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),It(()=>{this.baseStore.setState(s=>({...s,isSubmitted:!0,isSubmitSuccessful:!0})),kt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(s){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),kt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:s}),a(),s}}setErrorMap(o){It(()=>{Object.entries(o).forEach(([t,a])=>{let s=t;if(Ir(a)){let{formError:r,fieldErrors:n}=nn(a);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,c=>({...c,errorMap:{...c.errorMap,[s]:n?.[u]},errorSourceMap:{...c.errorSourceMap,[s]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[s]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[s]:a}}));});});}};function nn(e){if(e){if(Ir(e)){let o=nn(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function kr(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 Mr=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:s}=this.options.validators||{};if(s){let r=this.runValidator({validate:s,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:r},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let s=Ca(t.form.options.defaultValues,t.name),r=t.defaultValue??s;a?this.setValue(n=>n||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,$e(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,$e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,s)=>{this.form.insertFieldValue(this.name,t,a,$e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,s)=>{this.form.replaceFieldValue(this.name,t,a,$e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,$e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,s)=>{this.form.swapFieldValues(this.name,t,a,$e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,s)=>{this.form.moveFieldValues(this.name,t,a,$e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,$e(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),s=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:n,onBlurListenTo:u}=r.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&s.push(r.instance),t==="blur"&&u?.includes(this.name)&&s.push(r.instance);}return s},this.validateSync=(t,a)=>{let s=Fo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ta}),n=this.getLinkedFields(t).reduce((c,p)=>{let d=Fo(t,{...p.options,form:p.form,validationLogic:p.form.options.validationLogic||Ta});return d.forEach(l=>{l.field=p;}),c.concat(d)},[]),u=false;It(()=>{let c=(p,d)=>{let l=ln(d.cause),f=d.validate?Qu(p.runValidator({validate:d.validate,value:{value:p.store.state.value,validationSource:"field",fieldApi:p},type:"validate"})):void 0,h=a[l],{newErrorValue:m,newSource:v}=rn({formLevelError:h,fieldLevelError:f});p.state.meta.errorMap?.[l]!==m&&p.setMeta(x=>({...x,errorMap:{...x.errorMap,[l]:m},errorSourceMap:{...x.errorSourceMap,[l]:v}})),m&&(u=!0);};for(let p of s)c(this,p);for(let p of n)p.validate&&c(p.field,p);});let i=ln("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 s=Bo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ta}),r=await a,n=this.getLinkedFields(t),u=n.reduce((l,f)=>{let h=Bo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Ta});return h.forEach(m=>{m.field=f;}),l.concat(h)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of n)l.setMeta(f=>({...f,isValidating:true}));let i=[],c=[],p=(l,f,h)=>{let m=ln(f.cause);l.getInfo().validationMetaMap[m]?.lastAbortController.abort();let x=new AbortController;this.getInfo().validationMetaMap[m]={lastAbortController:x},h.push(new Promise(async g=>{let b;try{b=await new Promise((S,y)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(x.signal.aborted)return S(void 0);try{S(await this.runValidator({validate:f.validate,value:{value:l.store.state.value,fieldApi:l,signal:x.signal,validationSource:"field"},type:"validateAsync"}));}catch(E){y(E);}},f.debounceMs);});}catch(S){b=S;}if(x.signal.aborted)return g(void 0);let w=Qu(b),I=r[this.name]?.[m],{newErrorValue:P,newSource:k}=rn({formLevelError:I,fieldLevelError:w});l.setMeta(S=>({...S,errorMap:{...S?.errorMap,[m]:P},errorSourceMap:{...S.errorSourceMap,[m]:k}})),g(P);}));};for(let l of s)l.validate&&p(this,l,i);for(let l of u)l.validate&&p(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 n)l.setMeta(f=>({...f,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:s}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,s[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[ln(t)]?.lastAbortController.abort(),this.state.meta.errors;let n=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,n)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Ma.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ma.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Gt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Oo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return sn(o.validate)?Ma[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function Qu(e){if(e)return e}function ln(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 dn(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,jx)}function jx(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,s]of e)if(!o.has(a)||!Object.is(s,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=ec(e);if(t.length!==ec(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 ec(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var No=typeof window<"u"?useLayoutEffect:useEffect;function Qx(e){let[o]=useState(()=>{let a=new Mr({...e,form:e.form,name:e.name});return a.Field=hl,a});return No(o.mount,[o]),No(()=>{o.update(e);}),dn(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var hl=(({children:e,...o})=>{let t=Qx(o),a=useMemo(()=>Ia(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function ab({form:e,selector:o,children:t}){let a=dn(e.store,o);return Ia(t,a)}function gl(e){let o=useId(),[t]=useState(()=>{let a=new Tr({...e,formId:o}),s=a;return s.Field=function(n){return jsx(hl,{...n,form:a})},s.Subscribe=function(n){return jsx(ab,{form:a,selector:n.selector,children:n.children})},s});return No(t.mount,[]),No(()=>{t.update(e);}),t}function xl({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(ge),a=useRef(null),s=qe(),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[u,i]=useState(n),c=gl({defaultValues:{questionType:n,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 f={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,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?ha(f):ci(f));}else if(l.questionType==="multiple-choice"){let f={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,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?pa(f):ui(f));}else if(l.questionType==="short-answer"){let f={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?er(f):fi(f));}else if(l.questionType==="fill-in-the-blank"){let f={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?ar(f):pi(f));}else if(l.questionType==="long-answer"){let f={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?tr(f):mi(f));}o(ga(false));}}),p=()=>{o(ga(false));};if(!s)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:()=>{p();},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:f=>{l.handleChange(f.target.value),i(f.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(xl,{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:f=>l.handleChange(f.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(xl,{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(xl,{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:f=>l.handleChange(f.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 f=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 ${f===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),f===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>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 ${f===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),f===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value: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 f=(x,g)=>{let b=[...l.state.value.options];b[x]=g,l.handleChange({...l.state.value,options:b});},h=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},m=x=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let g=l.state.value.options.filter((w,I)=>I!==x),b=l.state.value.correctIndex?.filter(w=>w!==x).map(w=>w>x?w-1:w);l.handleChange({...l.state.value,options:g,correctIndex:b});},v=x=>{let g=l.state.value.correctIndex||[];if(g.includes(x))l.handleChange({...l.state.value,correctIndex:g.filter(w=>w!==x)});else {if(g.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...g,x]});}};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((x,g)=>{let b=!x.trim(),w=l.state.value.correctIndex?.includes(g),I=l.state.meta.isTouched&&b;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>v(g),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${w?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:w&&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":w?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${g+1}`,value:x,onChange:P=>f(g,P.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:()=>m(g),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},g)})}),jsx("button",{type:"button",onClick:h,disabled:l.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),l.state.value.correctIndex.length===0||l.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:l.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.Field,{name:"responseOptions.correctShortAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:l.state.value,onChange:f=>{l.handleChange(f.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),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:f=>{l.handleChange(f.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),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,f])=>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:f?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(d,s)},oc=fb;var ic=({text:e,position:o})=>{let t=ve(),a=c=>{t(ue()),t(Dt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+c))}));},s=c=>{t(ue()),t(Dt({id:e.id,fill:c}));},r=()=>{t(ue()),t(Dt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ue()),t(Dt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},u=()=>{t(ue()),t(Dt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},i=c=>{t(ue()),t(Dt({id:e.id,fontFamily:c}));};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:`${o.x}px`,top:`${Math.max(60,o.y-60)}px`,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:c=>c.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:c=>i(c.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:r,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:[jsx(TextB,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextB,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:n,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:u,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:c=>s(c.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var dc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:s,scale:r,textareaRef:n})=>{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(p=>{p.style.height="auto",p.style.height=`${p.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(p).font,d.style.fontSize=p.style.fontSize,d.style.fontFamily=p.style.fontFamily,d.style.fontWeight=p.style.fontWeight,d.style.fontStyle=p.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let l=p.value.split(`
|
|
4
4
|
`),f=0;document.body.appendChild(d);for(let m of l){d.textContent=m||" ";let v=d.offsetWidth;v>f&&(f=v);}document.body.removeChild(d);let h=10;p.style.width=`${Math.max(200,f+h+20)}px`;},[]);return useEffect(()=>{let p=u.current;p&&(p.style.fontSize=`${e.fontSize*r}px`,p.style.fontFamily=e.fontFamily,p.style.fontStyle=e.fontStyle,p.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",p.style.textDecoration=e.textDecoration,p.style.color=e.fill,c(p));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,c]),jsx("div",{style:{position:"absolute",top:`${s.top}px`,left:`${s.left}px`,zIndex:1e3},children:jsx("textarea",{ref:p=>{if(u.current=p,n.current=p,p){p.focus();let d=p.value.length;p.setSelectionRange(d,d),c(p);}},value:o,onChange:p=>{t(p.target.value);},onKeyDown:p=>{p.key==="Escape"&&a();},style:i},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var uc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r,touchHandlers:n})=>{let u=useSelector(O=>O.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),[p,d]=useState(""),[l,f]=useState(false),[h,m]=useState(null);useEffect(()=>{let O=c.current;if(O)return a.current.set(e.id,O),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",x=l&&p.trim().toLowerCase()===v,g=()=>{f(false),d("");},b=()=>x?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",w=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},I=24,P=60,k=l?40:0,S=l?54:20,y=50,E=12,B=e.data.feedbackMode==="practice"?48:0,T=12,G=30,F=P+k+G+y+E+T+B+I;return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:F,name:"sa-element",...n,...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:F,onTransformEnd:O=>t(e.id,O),onContextMenu:O=>{O.cancelBubble=true,s(O.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:I,y:I,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-I*2,listening:false}),jsx(Rect,{x:I,y:P+k+G-S,width:e.width-I*2+4,height:y+6,fill:"#ffffff",stroke:x?"#22c55e":l?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:I,y:P+k+G-S},divProps:{style:{width:`${e.width-I*2-4}px`,height:`${y}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:p,onChange:O=>d(O.target.value),disabled:l,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:l?"none":"auto"}})}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:I,y:P+80,width:e.width/2+24,height:k,fill:w().bg,cornerRadius:8}),jsx(Text,{x:36,y:P+80,width:e.width-I*2,height:k,text:b(),fontSize:12,fontStyle:"bold",fill:w().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:P+k+G+y+E+T,children:[jsxs(Group,{onMouseDown:O=>{O.cancelBubble=true,m("check");},onMouseUp:O=>{O.cancelBubble=true,m(null),p.length>0&&f(true);},onMouseLeave:O=>{O.cancelBubble=true,m(null);},onTouchStart:O=>{O.cancelBubble=true,m("check");},onTouchEnd:O=>{O.cancelBubble=true,m(null),p.length>0&&f(true);},scaleX:h==="check"?.95:1,scaleY:h==="check"?.95:1,children:[jsx(Rect,{x:I,width:(e.width-I*2-8)/(l?2:1),height:48,fill:p.length===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:O=>O.cancelBubble=true,onTap:O=>O.cancelBubble=true}),jsx(Text,{x:I,width:(e.width-I*2-8)/(l?2:1),height:48,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-I*2)/2+8,onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),g();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:I,width:(e.width-I*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:O=>O.cancelBubble=true,onTap:O=>O.cancelBubble=true}),jsx(Text,{x:I,width:(e.width-I*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});uc.displayName="ShortAnswer";var cc=uc;var mc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r,onLongPress:n})=>{let{createHandlers:u}=Ne({onLongPress:n});return jsx(Fragment,{children:e.map(i=>jsx(cc,{shortAnswer:i,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"shortAnswer")},i.id))})};var pc=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],s=useRef(new Map),r=useCallback((n,u)=>{let i=n.target;o(ar({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:s,handleFillInTheBlanksDragEnd:r}};var Ot=24,yl=51,Fr=64,hc=15,fn=32,gc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:s,fibRefs:r,touchHandlers:n})=>{let u=useSelector(y=>y.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),[p,d]=useState(""),[l,f]=useState(false),[h,m]=useState(null);useEffect(()=>{let y=c.current;if(y)return r.current.set(e.id,y),()=>{r.current.delete(e.id);}},[e.id,r]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",x=l&&p.trim().toLowerCase()===v,g=()=>{f(false),d("");},b=()=>{p.length>0&&f(true);},w=e.width-Ot*2,I=(w-hc)/2,P=e.data.feedbackMode==="practice",k=useMemo(()=>{let y=Ot,E=y;y+=60;let B=y;y+=35;let T=y;y+=yl+16;let G=y;l&&(y+=fn+16);let F=y;return P&&(y+=Fr),y+=Ot,{questionY:E,helperTextY:B,inputY:T,feedbackY:G,buttonsY:F,totalHeight:y}},[l,P]),S=()=>l?x?"#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",...n,...i?{}:{onDragEnd:y=>a(y,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:k.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:y=>t(e.id,y),onContextMenu:y=>{y.cancelBubble=true,s?.(y.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Ot,y:k.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:w,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Ot,y:k.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:w,listening:false}),jsx(Rect,{x:Ot,y:k.inputY,width:w,height:yl,fill:"#ffffff",stroke:S(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Ot,y:k.inputY},divProps:{style:{width:`${w}px`,height:`${yl}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:p,onChange:y=>d(y.target.value),disabled:l,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"}})}),l&&jsxs(Group,{y:k.feedbackY,children:[jsx(Rect,{x:Ot,width:x?206:140,height:fn,fill:x?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:x?"\u2713":"\u2717",x:Ot+10,y:0,width:16,height:fn,fontSize:14,fill:x?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:x?"Right Answer, Great Job!":"Wrong Answer",x:Ot+30,y:0,height:fn,fontSize:14,fontStyle:"600",fill:x?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),P&&jsxs(Group,{y:k.buttonsY,children:[jsxs(Group,{x:Ot,onMouseDown:y=>{y.cancelBubble=true,m("reset");},onMouseUp:y=>{y.cancelBubble=true,m(null),g();},onMouseLeave:y=>{y.cancelBubble=true,m(null);},onTouchStart:y=>{y.cancelBubble=true,m("reset");},onTouchEnd:y=>{y.cancelBubble=true,m(null),g();},scaleX:h==="reset"?.98:1,scaleY:h==="reset"?.98:1,children:[jsx(Rect,{width:I,height:Fr,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:I,height:Fr,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Ot+I+hc,onMouseDown:y=>{y.cancelBubble=true,m("submit");},onMouseUp:y=>{y.cancelBubble=true,m(null),b();},onMouseLeave:y=>{y.cancelBubble=true,m(null);},onTouchStart:y=>{y.cancelBubble=true,m("submit");},onTouchEnd:y=>{y.cancelBubble=true,m(null),b();},scaleX:h==="submit"?.98:1,scaleY:h==="submit"?.98:1,children:[jsx(Rect,{width:I,height:Fr,fill:p.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:I,height:Fr,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});gc.displayName="FillInTheBlanks";var xc=gc;var vc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,onLongPress:r,fibRefs:n})=>{let{createHandlers:u}=Ne({onLongPress:r});return jsx(Fragment,{children:e.map(i=>jsx(xc,{fillInTheBlank:i,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:n,touchHandlers:u(i.id,"fillInTheBlanks")},i.id))})};var Il=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,touchHandlers:r,handleDragEnd:n})=>{let u=useSelector(F=>F.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),[p,d]=useState(""),[l,f]=useState(false),[h,m]=useState(null);useEffect(()=>{let F=c.current;if(F)return a.current.set(e.id,F),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",x=l&&p.trim().toLowerCase()===v,g=()=>{f(false),d("");},b=()=>x?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",w=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},I=24,P=60,k=l?60:0,S=120,y=12,E=48,B=12,T=30,G=P+k+T+S+y+B+E+I;return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...r,name:"la-element",...i?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:F=>{let O=c.current?.getStage()?.getPointerPosition();if(!O||!s)return;let U={x:e.x,y:e.y,width:e.width,height:e.height};O.x>=U.x&&O.x<=U.x+U.width&&O.y>=U.y&&O.y<=U.y+U.height&&s(F.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:G,onTransformEnd:F=>t(e.id,F)}),jsx(Text,{text:e.data.question,x:I,y:I,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-I*2,listening:false}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:I,y:P,width:e.width-I*2,height:k,fill:w().bg,cornerRadius:8}),jsx(Text,{x:I,y:P,width:e.width-I*2,height:k,text:b(),fontSize:14,fontStyle:"bold",fill:w().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:I,y:P+k+y,fontSize:14,fill:"#6b7280",width:e.width-I*2,listening:false}),jsx(Rect,{x:I,y:P+k+T,width:e.width-I*2,height:S,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:I,y:P+k+T},divProps:{style:{width:`${e.width-I*2}px`,height:`${S}px`,pointerEvents:l?"none":"auto"}},children:jsx("textarea",{value:p,onChange:F=>d(F.target.value),disabled:l,placeholder:`Type your extended answer here...\r
|
|
5
5
|
\r
|
|
6
|
-
This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:l?"none":"auto"}})}),jsx(Group,{y:P+k+T+S+y+B,children:l&&jsxs(Group,{onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),g();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:I,width:e.width-I*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:I,width:e.width-I*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Il.displayName="LongAnswer";var wc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r,onLongPress:n})=>{let{createHandlers:u}=Ne({onLongPress:n});return jsx(Fragment,{children:e.map(i=>jsx(Il,{longAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"longAnswer")},i.id))})};var Za=1600,Qa=900,Cc=3200,kc=1800,_b=e=>{let o=0,t=0,a=Za,s=Qa;if(!e)return {minX:o,minY:t,maxX:a,maxY:s,width:Za,height:Qa};let r=(i,c,p,d)=>{o=Math.min(o,i),t=Math.min(t,c),a=Math.max(a,i+p),s=Math.max(s,c+d);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let c=i.x||0,p=i.y||0,d=i.scaleX||1,l=i.scaleY||1;for(let f=0;f<i.points.length;f+=2){let h=c+i.points[f]*d,m=p+i.points[f+1]*l;o=Math.min(o,h),t=Math.min(t,m),a=Math.max(a,h),s=Math.max(s,m);}}}),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 n=Math.min(a-o,Cc),u=Math.min(s-t,kc);return o=Math.max(o,a-Cc),t=Math.max(t,s-kc),{minX:o,minY:t,maxX:a,maxY:s,width:n,height:u}},Xb=(e,o,t={minX:0,minY:0,maxX:Za,maxY:Qa,width:Za,height:Qa})=>{let a=Math.max(t.width,Za),s=Math.max(t.height,Qa),r=e/o,n=a/s,u,i,c,d=0;if(r>n){i=s,u=Math.round(i*r),c=o/i;}else {u=a,i=Math.round(u/r),c=e/u;let l=s*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}},Tc=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},$b=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:s={enabled:true}}={})=>{let r=ft(),n=qe(),u=Q(L=>L.toolbar.selectedTool),i=Q(ge),c=Q(ho),p=Q(Bs),l=(i?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),f=!!l,h=useCallback(()=>{l&&r(qa(l.id));},[r,l]),m=i?.editingActivity,v=i?.showMcqForm,x=i?.lines||[],g=useRef(null),b=useRef(null),[w,I]=useState(null),[P,k]=useState(""),S=useRef(null),[y,E]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Za,stageHeight:Qa,offsetX:0,offsetY:0,baseWidth:Za,baseHeight:Qa,contentOffsetX:0,contentOffsetY:0}),B=useMemo(()=>_b(i||null),[c]),[T,G]=useState(null),[F,O]=useState(null),[U,V]=useState(null),[H,oe]=useState(null),[me,W]=useState(null),[q,_]=useState(null),[K,X$1]=useState(null),[te,$]=useState(false),[re,ie]=useState(null),[Ae,Ce]=useState(false),Ee=useRef(null),lt=useRef(null),bt=useRef(null),{debouncedGenerateThumbnail:lo}=eu(c,g);useEffect(()=>{let L=()=>{if(b.current){let M=b.current.getBoundingClientRect(),R=Xb(M.width,M.height,B);E(R);}};L();let C=new ResizeObserver(L);return b.current&&C.observe(b.current),window.addEventListener("resize",L),()=>{C.disconnect(),window.removeEventListener("resize",L);}},[B]),useEffect(()=>{if(g.current){let L=g.current.container();L&&(L.style.cursor="");}},[u]);let se=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(C=>C.batchDraw()),!p)try{let M=g.current.toDataURL({pixelRatio:.16666666666666666});k(M),lo();}catch(C){console.warn("Preview generation failed (CORS):",C);}});},[lo,p]),Gr=useRef(c);useEffect(()=>{Gr.current!==c&&(Gr.current=c,se());},[c,se]);let Oa=useRef(null),jr=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),C=Oa.current?.count!==L;!jr.current&&C&&setTimeout(()=>{se();},100),Oa.current={slideId:c,count:L},jr.current=false;},[i,c,se]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{bt.current&&a&&a(bt);},[a]);let{startDrawing:_r,draw:Xr,stopDrawing:$o,setCanvasRef:Rn,tool:Fn,color:Bn,strokeWidth:On,isSketchMode:Nn}=Td(se),D=useRef(new Map),{images:ee,getLoadedImage:ke,imageRefs:xe,handleDragEnd:le,handleImageTransformEnd:fe}=Fd(se),{videos:Pe,videoRefs:_e,handleVideoClick:Yt,handleVideoDragEnd:vt,handleVideoTransformEnd:De}=Nd(se),{multipleChoice:at,handleMcqTransform:At,mcqRefs:Kt,handleDragEnd:Vn}=Bd(se),{trueFalse:qn,handleTrueFalseTransform:$r,trueFalseRefs:dt,handleTrueFalseDragEnd:fa}=Od(se),{shortAnswers:Na,saRefs:Yo,handleShortAnswerDragEnd:ym}=Wd(se),{longAnswers:wm,handleLongAnswerDragEnd:Lm}=zd(se),{fillInTheBlanks:Sm,handleFillInTheBlanksDragEnd:Im,fibRefs:Yr}=pc(se),{transformerRef:ce,boundBoxFunc:Pt}=Yd(),{shapes:Cm,shapeRefs:Jr,isDragging:cd,handleShapeDragEnd:km,handleShapeResizeEnd:Tm}=Hd(se),{texts:Jo,textRefs:ma,handleDragEnd:Mm,handleTransformEnd:Am,handleDoubleClick:Pm,startEditing:Zr,editingTextId:he,editingValue:fd,handleEditingChange:md,finishEditing:Hn}=Kd(se,Ee);useEffect(()=>{t&&t(Zr);},[t,Zr]);let Qr=Q(L=>L.canvas.editingTextId);useEffect(()=>{Qr&&Qr!==he&&Zr(Qr);},[Qr,he,Zr]);let{flashcards:Em,flashcardRefs:es,handleDragEnd:Dm,handleFlashcardTransformEnd:Rm,handleNext:Fm,handlePrevious:Bm}=jd(se),{photoFrames:pd,photoFrameRefs:ts,handleDragEnd:Om,handlePhotoFrameTransformEnd:Nm,startCamera:Vm,capturePhoto:qm,cameraStreams:Hm}=$d(se);useEffect(()=>{if(ce.current){if(he){ce.current.nodes([]),ce.current.getLayer()?.batchDraw();return}if(w&&!Pe.find(M=>M.id===w)?.isPlaying){let M=D.current.get(w)||xe.current.get(w)||_e.current.get(w)||Jr.current.get(w)||ma.current.get(w)||Kt.current.get(w)||es.current.get(w)||ts.current.get(w)||Yo.current.get(w)||dt.current.get(w)||Yr.current.get(w);if(M){let R=M.attrs?.locked;if(M.visible()&&R!==true){ce.current.nodes([M]),ce.current.getLayer()?.batchDraw();return}}}ce.current.nodes([]),ce.current.getLayer()?.batchDraw();}},[w,he,Pe,D,xe,_e,Jr,ma,es,ts,pd,Kt,dt,Yr,ce]);let He=useCallback(L=>{I(L),o?.(L);},[o]),uo=useCallback(()=>{I(null),o?.(null),ce.current&&(ce.current.nodes([]),ce.current.getLayer()?.batchDraw());},[ce,o]),hd=useCallback(L=>i?i.lines?.some(C=>C.id===L)?"line":i.images?.some(C=>C.id===L)?"image":i.videos?.some(C=>C.id===L)?"video":i.shapes?.some(C=>C.id===L)?"shape":i.texts?.some(C=>C.id===L)?"text":i.flashcards?.some(C=>C.id===L)?"flashcard":i.photoFrames?.some(C=>C.id===L)?"photoFrame":i.multipleChoices?.some(C=>C.id===L)?"mcq":i.trueFalses?.some(C=>C.id===L)?"trueFalse":i.shortAnswers?.some(C=>C.id===L)?"shortAnswer":i.LongAnswer?.some(C=>C.id===L)?"longAnswer":i.fillInTheBlanks?.some(C=>C.id===L)?"fillInTheBlanks":null:null,[i]),gd=useCallback((L,C)=>{switch(r(ue()),C){case "line":r(Es(L));break;case "image":r(os(L));break;case "video":r(is(L));break;case "shape":r(us(L));break;case "text":r(cs(L));break;case "flashcard":r(ms(L));break;case "photoFrame":r(hs(L));break;case "mcq":r(xs(L));break;case "trueFalse":r(vs(L));break;case "shortAnswer":r(ws(L));break;case "longAnswer":r(Ss(L));break;case "fillInTheBlanks":r(Cs(L));break}uo(),se();},[r,uo,se]);useEffect(()=>{let L=C=>{if(C.key!=="Delete"||!w||he)return;let M=document.activeElement;if(M instanceof HTMLInputElement||M instanceof HTMLTextAreaElement||M?.getAttribute("contenteditable")==="true")return;C.preventDefault();let we=hd(w);we&&gd(w,we);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[w,he,hd,gd]),useEffect(()=>{let L=ce.current;return ()=>{L&&L.nodes([]);}},[c]),useEffect(()=>{let L=C=>{he&&C.target.tagName!=="TEXTAREA"&&Hn();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[he,Hn]),useEffect(()=>{let L=he||w;if(!L||w&&he){O(null);return}let C=ma.current.get(L),M=g.current;if(!C||!M){O(null);return}let R=M.container().getBoundingClientRect(),we=C.absolutePosition(),be=M.scaleX();O({x:R.left+(we.x+C.width()*be/2)*be+y.offsetX,y:R.top+we.y*be+y.offsetY-70});},[w,he,Jo,ma,y.offsetX,y.offsetY]),useEffect(()=>{if(!he){V(null);return}let L=ma.current.get(he),C=g.current;if(!L||!C){V(null);return}let M=C.container().getBoundingClientRect(),R=L.absolutePosition(),we=C.scaleX();V({top:M.top+R.y*we+y.offsetY,left:M.left+R.x*we+y.offsetX,scale:we});},[he,Jo,ma,y.offsetY,y.offsetX]);let xd=useCallback(L=>{let C=L.target.getClassName(),M=L.target===L.target.getStage(),R=C==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",we=C==="Image",be=C==="Text",ae=C==="Group"||L.target.getParent()?.getClassName()==="Group",ut=C==="Circle"||C==="Star"||C==="RegularPolygon"||C==="Ellipse"||C==="Ring"||C==="Wedge"||C==="Arrow"||C==="Line"||C==="Arc"||C==="Rect"&&L.target.attrs.id,ct=C==="Group";if(M&&!R&&!we&&!be&&!ae&&!ut&&!ct&&uo(),!(u==="pen"||u==="eraser")&&(we||be||R||ae||ut||ct))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 N=Tc(Ue,y);_r(N);}},[u,_r,uo,y]),bd=useCallback(L=>{if(cd)return;let C=L.target.getStage()?.getPointerPosition();if(!C)return;let M=Tc(C,y);Xr(M);},[Xr,cd,y]),vd=useCallback(()=>{$o();},[$o]),Um=useCallback(L=>{le(L,se);},[le,se]),Km=useCallback(L=>{Yt(L),He(L);},[Yt,He]),Et=useCallback((L,C,M)=>{if(L.preventDefault(),!s.enabled)return;let R=L.clientX,we=L.clientY,be=S.current?.offsetHeight||450,ae=S.current?.offsetWidth||450,ut=window.innerHeight,ct=window.innerWidth,Je=R,Ue=we;we+be>ut&&(Ue=we-be),R+ae>ct&&(Je=R-ae),He(C),G({x:Je,y:Ue,elementId:C,elementType:M});},[He,s.enabled]),Va=useRef(null),Zo=useRef(null),yt=useCallback((L,C)=>M=>{if(!s.enabled)return;M.preventDefault();let R=M.changedTouches[0];if(!R)return;let we=R.clientX,be=R.clientY,ae=S.current?.offsetHeight||200,ut=S.current?.offsetWidth||200,ct=window.innerHeight,Je=window.innerWidth,Ue=we,Ze=be;be+ae>ct&&(Ze=be-ae),we+ut>Je&&(Ue=we-ut),He(L),G({x:Ue,y:Ze,elementId:L,elementType:C});},[He,s.enabled]),Wm=useCallback((L,C)=>({onTouchStart:M=>{let R=M.evt.touches[0];Zo.current={x:R.clientX,y:R.clientY},Va.current=setTimeout(()=>{yt(L,C)(M.evt);},500);},onTouchMove:M=>{if(!Zo.current)return;let R=M.evt.touches[0],we=Math.abs(R.clientX-Zo.current.x),be=Math.abs(R.clientY-Zo.current.y);(we>10||be>10)&&Va.current&&(clearTimeout(Va.current),Va.current=null);},onTouchEnd:()=>{Va.current&&(clearTimeout(Va.current),Va.current=null),Zo.current=null;}}),[yt]),yd=useCallback(L=>{r(or(L)),r(ga(true));},[r]),zm=useCallback(L=>{r(Qo(L)),r(Ua(true));},[r]),Gm=useCallback((L,C)=>{if(!T)return;let{elementId:M,elementType:R}=T;switch(L){case "order":if(C){let A=C.target.getBoundingClientRect();oe({x:A.right+5,y:A.top,type:"order"});}break;case "lock":if(C){let A=C.target.getBoundingClientRect();oe({x:A.right+5,y:A.top,type:"lock"});}break;case "link":if(G(null),R==="line")break;let we=i?R==="image"?i.images.find(A=>A.id===M):i.videos.find(A=>A.id===M):null;W({type:"link",defaultValue:we?.link||""});break;case "voice":if(G(null),R==="line")break;let be=i?R==="image"?i.images.find(A=>A.id===M):R==="video"?i.videos.find(A=>A.id===M):R==="text"?i.texts.find(A=>A.id===M):R==="flashcard"?i.flashcards.find(A=>A.id===M):R==="photoFrame"?i.photoFrames.find(A=>A.id===M):R==="mcq"?i.multipleChoices.find(A=>A.id===M):R==="fillInTheBlanks"?i.fillInTheBlanks.find(A=>A.id===M):R==="longAnswer"?i.LongAnswer.find(A=>A.id===M):R==="shortAnswer"?i.shortAnswers.find(A=>A.id===M):R==="trueFalse"?i.trueFalses.find(A=>A.id===M):R==="shape"?i.shapes.find(A=>A.id===M):null:null;ie({elementId:M,elementType:R,existingAudio:be?.audioData});break;case "edit":G(null);let ae=null;R==="mcq"?ae=i?.multipleChoices.find(A=>A.id===M):R==="trueFalse"?ae=i?.trueFalses.find(A=>A.id===M):R==="shortAnswer"?ae=i?.shortAnswers.find(A=>A.id===M):R==="longAnswer"?ae=i?.LongAnswer.find(A=>A.id===M):R==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(A=>A.id===M)),ae&&yd(ae);break;case "editFlashcard":G(null);let ut=i?.flashcards.find(A=>A.id===M);ut&&zm(ut);break;case "color":G(null);let ct=i?.shapes.find(A=>A.id===M);_({elementId:M,elementType:"shape",defaultColor:ct?.color||"#096B76"});break;case "crop":if(G(null),R==="image"){let A=i?.images.find(Zm=>Zm.id===M);A&&X$1({elementId:M,imageSrc:A.src});}break;case "draw":G(null),R==="image"?r(ni(M)):R==="photoFrame"&&r(li(M));break;case "duplicate":r(ue()),R==="line"?r(yi(M)):R==="image"?r(rs(M)):R==="video"?r(ls(M)):R==="shape"?r(ds(M)):R==="text"?r(fs(M)):R==="flashcard"?r(ps(M)):R==="photoFrame"?r(gs(M)):R==="mcq"?r(bs(M)):R==="trueFalse"?r(ys(M)):R==="shortAnswer"?r(Ls(M)):R==="fillInTheBlanks"?r(ks(M)):R==="longAnswer"&&r(Is(M)),se();break;case "infinite-clone":r(ue());let Je=5;for(let A=0;A<Je;A++)R==="image"?r(rs(M)):R==="video"?r(ls(M)):R==="shape"?r(ds(M)):R==="text"?r(fs(M)):R==="flashcard"?r(ps(M)):R==="photoFrame"?r(gs(M)):R==="mcq"?r(bs(M)):R==="trueFalse"?r(ys(M)):R==="shortAnswer"?r(Ls(M)):R==="fillInTheBlanks"?r(ks(M)):R==="longAnswer"&&r(Is(M));se();break;case "make-response":if(G(null),R==="line")break;let Ue=`#response-${M}`;r(ue()),r(Ts({id:M,type:R,link:Ue})),(i?R==="image"?i.images.find(A=>A.id===M):R==="video"?i.videos.find(A=>A.id===M):R==="shape"?i.shapes.find(A=>A.id===M):R==="flashcard"?i.flashcards.find(A=>A.id===M):R==="photoFrame"?i.photoFrames.find(A=>A.id===M):i.multipleChoices.find(A=>A.id===M):null)?.altText||r(Ms({id:M,type:R,altText:"Interactive response area"})),se(),console.log(`Element ${M} marked as interactive response area`);break;case "accessibility":if(G(null),R==="line")break;let N=i?R==="image"?i.images.find(A=>A.id===M):R==="video"?i.videos.find(A=>A.id===M):R==="shape"?i.shapes.find(A=>A.id===M):null:null;W({type:"altText",defaultValue:N?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),G(null),Ce(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ue()),R==="line"?r(Es(M)):R==="image"?r(os(M)):R==="video"?r(is(M)):R==="shape"?r(us(M)):R==="text"?r(cs(M)):R==="flashcard"?r(ms(M)):R==="photoFrame"?r(hs(M)):R==="mcq"?r(xs(M)):R==="trueFalse"?r(vs(M)):R==="shortAnswer"?r(ws(M)):R==="longAnswer"?r(Ss(M)):R==="fillInTheBlanks"&&r(Cs(M)),uo(),se();break}},[T,r,se,uo,i,yd]),jm=useCallback(()=>{G(null),oe(null);},[]),Un=useCallback(L=>{if(!T)return;let{elementId:C,elementType:M}=T;switch(r(ue()),L){case "bring-to-front":M!=="line"&&r(gi({id:C,type:M}));break;case "send-to-back":M!=="line"&&r(xi({id:C,type:M}));break;case "lock":case "unlock":M!=="line"&&r(bi({id:C,type:M}));break}se(),G(null),oe(null);},[T,r,se]),_m=useCallback(L=>{if(!T||!me)return;let{elementId:C,elementType:M}=T;r(ue()),me.type==="link"&&M!=="line"?r(Ts({id:C,type:M,link:L})):me.type==="altText"&&M!=="line"&&r(Ms({id:C,type:M,altText:L})),se(),W(null);},[T,me,r,se]),Xm=useCallback(L=>{if(!re)return;let{elementId:C,elementType:M}=re;r(ue()),r(As({id:C,type:M,audioData:L})),se(),ie(null);},[re,r,se]),$m=useCallback(()=>{if(!re)return;let{elementId:L,elementType:C}=re;r(ue()),r(As({id:L,type:C,audioData:""})),se();},[re,r,se]),Ym=useCallback(L=>{if(!q)return;let{elementId:C}=q;r(ue()),r(mo({id:C,color:L})),se(),_(null);},[q,r,se]),Jm=useCallback(L=>{if(!K)return;let{elementId:C}=K;r(ue()),r(fo({id:C,src:L})),se(),X$1(null);},[K,r,se]);return jsxs("div",{ref:b,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Dd,{ref:L=>{if(lt.current=L,Rn(L),L){let C=L.getCanvasElement();C&&(bt.current=C,a&&a(bt));}},width:y.baseWidth,height:y.baseHeight,tool:Fn,color:Bn,strokeWidth:On/y.scale,isSketchMode:Nn,xOffset:y.contentOffsetX,yOffset:y.contentOffsetY-y.offsetY/y.scale,style:{width:y.stageWidth,height:y.stageHeight}}),jsxs(Stage,{ref:g,width:y.stageWidth,height:y.stageHeight,scaleX:y.scaleX,scaleY:y.scaleY,x:y.offsetX,y:0,onMouseDown:xd,onMouseMove:bd,onMouseUp:vd,onTouchStart:xd,onTouchMove:bd,onTouchEnd:vd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:y.baseWidth,height:y.stageHeight/y.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-y.contentOffsetX,y:y.offsetY/y.scale-y.contentOffsetY,children:(()=>{let L=[];return x.forEach((C,M)=>{L.push({type:"line",timestamp:C.timestamp||M,element:{...C,id:C.id??`line-${M}`},index:M});}),Cm.forEach(C=>{L.push({type:"shape",timestamp:C.timestamp||0,element:C});}),ee.forEach(C=>{L.push({type:"image",timestamp:C.timestamp||0,element:C});}),Pe.forEach(C=>{L.push({type:"video",timestamp:C.timestamp||0,element:C});}),Jo.forEach(C=>{L.push({type:"text",timestamp:C.timestamp||0,element:C});}),Em.forEach(C=>{L.push({type:"flashcard",timestamp:C.timestamp||0,element:C});}),pd.forEach(C=>{L.push({type:"photoFrame",timestamp:C.timestamp||0,element:C});}),at.forEach(C=>{L.push({type:"mcq",timestamp:C.timestamp||0,element:C});}),qn.forEach(C=>{L.push({type:"trueFalse",timestamp:C.timestamp||0,element:C});}),Na.forEach(C=>{L.push({type:"shortAnswer",timestamp:C.timestamp||0,element:C});}),wm.forEach(C=>{L.push({type:"longAnswer",timestamp:C.timestamp||0,element:C});}),Sm.forEach(C=>{L.push({type:"fillInTheBlanks",timestamp:C.timestamp||0,element:C});}),L.sort((C,M)=>C.timestamp-M.timestamp),L.map((C,M)=>{let R=`${C.type}-${"id"in C.element&&C.element.id||C.index||M}`,we="id"in C.element?C.element.id:void 0,be=we&&w===we;switch(C.type){case "line":let ae=C.element,ut=C.index||0,ct=ae.tool==="eraser",Je=ae.isSketch&&ae.tool==="pen",Ue=ae.isSketch&&ct,Ze=ae.id||`line-${ut}`;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:Je||Ue?void 0:ae.color,strokeWidth:Je||Ue?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Je||Ue?ct?"black":ae.color:void 0,closed:Je||Ue,tension:0,globalCompositeOperation:ct?"destination-out":"source-over",listening:true,onClick:()=>{r(ue()),r(as(ut));},onTap:()=>{r(ue()),r(as(ut));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:N=>{let A=N.target.getStage();A&&(A.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:N=>{let A=N.target.getStage();A&&(A.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`);}})},R):jsxs(ye__default.Fragment,{children:[jsx(Group,{id:Ze,ref:N=>{N?D.current.set(Ze,N):D.current.delete(Ze);},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:",Ze),He(Ze));},onTap:()=>{u==="select"&&(console.log("Line tapped:",Ze),He(Ze));},onDragEnd:N=>{r(ue()),r(Ps({id:Ze,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),se();},onTransformEnd:N=>{r(ue()),r(Ps({id:Ze,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),se();},onMouseEnter:N=>{if(u==="select"){let A=N.target.getStage();A&&(A.container().style.cursor="move");}},onMouseLeave:N=>{if(u==="select"){let A=N.target.getStage();A&&(A.container().style.cursor="default");}},onContextMenu:N=>{let A=N.evt;A.preventDefault(),Et(A,Ze,"line");},...Wm(Ze,"line"),children:jsx(Line,{points:ae.points||[],stroke:Je||Ue?void 0:ae.color,strokeWidth:Je||Ue?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Je||Ue?ct?"black":ae.color:void 0,closed:Je||Ue,tension:0,globalCompositeOperation:ct?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=D.current.get(w);console.log("Line Transformer - selectedId:",w,"node found:",!!A),A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:Pt,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"]})]},R);case "shape":return jsxs(ye__default.Fragment,{children:[jsx(qi,{onSelect:He,shapes:[C.element],shapeRefs:Jr,handleShapeDragEnd:km,handleShapeResizeEnd:Tm,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Jr.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "image":return jsxs(ye__default.Fragment,{children:[jsx(Bi,{images:[C.element],getLoadedImage:ke,imageRefs:xe,onDragEnd:Um,onTransform:fe,onSelect:He,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=xe.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "video":return jsxs(ye__default.Fragment,{children:[jsx(Vi,{videos:[C.element],selectedId:w,videoRefs:_e,onVideoClick:Km,onDragEnd:vt,onTransformEnd:De,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=_e.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "text":return jsxs(ye__default.Fragment,{children:[jsx(fu,{texts:[C.element],textRefs:ma,onDragEnd:Mm,onTransformEnd:Am,onSelect:He,onContextMenu:Et,onLongPress:yt,onDoubleClick:Pm,editingTextId:he,editingValue:fd,onEditingChange:md}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=ma.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "flashcard":return jsxs(ye__default.Fragment,{children:[jsx(Ki,{flashcards:[C.element],flashcardRefs:es,selectedId:w,onDragEnd:Dm,onTransform:Rm,onSelect:He,onNext:Fm,onPrevious:Bm,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=es.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "photoFrame":return jsxs(ye__default.Fragment,{children:[jsx(Xi,{photoFrames:[C.element],photoFrameRefs:ts,selectedId:w,onDragEnd:Om,onTransform:Nm,onSelect:He,onStartCamera:Vm,onCapture:qm,cameraStreams:Hm,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=ts.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "mcq":return jsxs(ye__default.Fragment,{children:[jsx(Wu,{handleMcqTransform:At,multipleChoice:[C.element],handleSelect:He,mcqRefs:Kt,handleDragEnd:Vn,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Kt.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "trueFalse":return jsxs(ye__default.Fragment,{children:[jsx(ju,{trueFalses:[C.element],handleTrueFalseTransform:$r,handleSelect:He,trueFalseRefs:dt,onContextMenu:Et,onLongPress:yt,handleDragEnd:fa}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=dt.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "shortAnswer":return jsxs(ye__default.Fragment,{children:[jsx(mc,{shortAnswers:[C.element],handleSelect:He,handleTransform:At,saRefs:Yo,onContextMenu:Et,onLongPress:yt,handleDragEnd:ym}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Yo.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "longAnswer":return jsxs(ye__default.Fragment,{children:[jsx(wc,{longAnswer:[C.element],handleSelect:He,handleTransform:At,saRefs:Yo,onContextMenu:Et,onLongPress:yt,handleDragEnd:Lm}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Yo.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "fillInTheBlanks":return jsxs(ye__default.Fragment,{children:[jsx(vc,{fillInTheBlanks:[C.element],handleSelect:He,handleTransform:At,onContextMenu:Et,onLongPress:yt,handleDragEnd:Im,fibRefs:Yr}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Yr.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);default:return null}})})()})]}),T&&jsx(Cu,{menuRef:S,x:T.x,y:T.y,type:T.elementType,onAction:Gm,onClose:jm,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}),H&&T&&jsx(ku,{x:H.x,y:H.y,items:H.type==="order"?[{label:"Bring to Front",onClick:()=>Un("bring-to-front")},{label:"Send to Back",onClick:()=>Un("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:()=>Un(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:()=>oe(null)}),me&&jsx(Au,{title:me.type==="link"?"Add Link":"Add Alt Text",label:me.type==="link"?"URL":"Alternative Text",placeholder:me.type==="link"?"https://example.com":"Describe this image/video",defaultValue:me.defaultValue,onSave:_m,onClose:()=>W(null)}),q&&jsx(Ws,{defaultColor:q.defaultColor,onConfirm:Ym,onCancel:()=>_(null)}),K&&jsx(Ru,{imageSrc:K.imageSrc,onConfirm:Jm,onCancel:()=>X$1(null)}),te&&jsx(pr,{onClose:()=>$(false),stageRef:g}),re&&jsx(Nu,{elementId:re.elementId,elementType:re.elementType,existingAudio:re.existingAudio,onSave:Xm,onDelete:$m,onClose:()=>ie(null)}),Ae&&jsx(Hu,{selectedElementId:w||void 0,onClose:()=>Ce(false),onSelectElement:L=>{He(L),Ce(false);}}),i?.images.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.videos.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.shapes?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.texts?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),v&&jsx(oc,{editElement:m}),F&&(()=>{let L=he||w;if(!L)return null;let C=Jo.find(M=>M.id===L);return C?jsx(ic,{text:C,position:F}):null})(),U&&he&&(()=>{let L=Jo.find(C=>C.id===he);return L?jsx(dc,{text:L,editingValue:fd,onEditingChange:md,onFinish:Hn,position:{top:U.top,left:U.left},scale:U.scale,textareaRef:Ee},he):null})(),f&&n&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:l?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:h})}),jsx("button",{onClick:h,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"})})]}),n)]})},Yb=$b;function Cl(e,[o,t]){return Math.min(t,Math.max(o,e))}function et(e,o,{checkForDefaultPrevented:t=true}={}){return function(s){if(e?.(s),t===false||!s.defaultPrevented)return o?.(s)}}function Mc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Or(...e){return o=>{let t=false,a=e.map(s=>{let r=Mc(s,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let s=0;s<a.length;s++){let r=a[s];typeof r=="function"?r():Mc(e[s],null);}}}}function Ht(...e){return ye.useCallback(Or(...e),e)}function Aa(e,o=[]){let t=[];function a(r,n){let u=ye.createContext(n),i=t.length;t=[...t,n];let c=d=>{let{scope:l,children:f,...h}=d,m=l?.[e]?.[i]||u,v=ye.useMemo(()=>h,Object.values(h));return jsx(m.Provider,{value:v,children:f})};c.displayName=r+"Provider";function p(d,l){let f=l?.[e]?.[i]||u,h=ye.useContext(f);if(h)return h;if(n!==void 0)return n;throw new Error(`\`${d}\` must be used within \`${r}\``)}return [c,p]}let s=()=>{let r=t.map(n=>ye.createContext(n));return function(u){let i=u?.[e]||r;return ye.useMemo(()=>({[`__scope${e}`]:{...u,[e]:i}}),[u,i])}};return s.scopeName=e,[a,Qb(s,...o)]}function Qb(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(r){let n=a.reduce((u,{useScope:i,scopeName:c})=>{let d=i(r)[`__scope${c}`];return {...u,...d}},{});return ye.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var qo=globalThis?.document?ye.useLayoutEffect:()=>{};var ev=ye[" useInsertionEffect ".trim().toString()]||qo;function sa({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[s,r,n]=tv({defaultProp:o,onChange:t}),u=e!==void 0,i=u?e:s;{let p=ye.useRef(e!==void 0);ye.useEffect(()=>{let d=p.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.`),p.current=u;},[u,a]);}let c=ye.useCallback(p=>{if(u){let d=av(p)?p(e):p;d!==e&&n.current?.(d);}else r(p);},[u,e,r,n]);return [i,c]}function tv({defaultProp:e,onChange:o}){let[t,a]=ye.useState(e),s=ye.useRef(t),r=ye.useRef(o);return ev(()=>{r.current=o;},[o]),ye.useEffect(()=>{s.current!==t&&(r.current?.(t),s.current=t);},[t,s]),[t,a,r]}function av(e){return typeof e=="function"}var ov=ye.createContext(void 0);function Ho(e){let o=ye.useContext(ov);return e||o||"ltr"}function Ec(e){let o=ye.useRef({value:e,previous:e});return ye.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Rc(e){let[o,t]=ye.useState(void 0);return qo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;let r=s[0],n,u;if("borderBoxSize"in r){let i=r.borderBoxSize,c=Array.isArray(i)?i[0]:i;n=c.inlineSize,u=c.blockSize;}else n=e.offsetWidth,u=e.offsetHeight;t({width:n,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function Bc(e){let o=rv(e),t=ye.forwardRef((a,s)=>{let{children:r,...n}=a,u=ye.Children.toArray(r),i=u.find(nv);if(i){let c=i.props.children,p=u.map(d=>d===i?ye.Children.count(c)>1?ye.Children.only(null):ye.isValidElement(c)?c.props.children:null:d);return jsx(o,{...n,ref:s,children:ye.isValidElement(c)?ye.cloneElement(c,void 0,p):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function rv(e){let o=ye.forwardRef((t,a)=>{let{children:s,...r}=t;if(ye.isValidElement(s)){let n=lv(s),u=iv(r,s.props);return s.type!==ye.Fragment&&(u.ref=a?Or(a,n):n),ye.cloneElement(s,u)}return ye.Children.count(s)>1?ye.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var sv=Symbol("radix.slottable");function nv(e){return ye.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===sv}function iv(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...u)=>{let i=r(...u);return s(...u),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function lv(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 cv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gt=cv.reduce((e,o)=>{let t=Bc(`Primitive.${o}`),a=ye.forwardRef((s,r)=>{let{asChild:n,...u}=s,i=n?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 kl(e){let o=fv(e),t=ye.forwardRef((a,s)=>{let{children:r,...n}=a,u=ye.Children.toArray(r),i=u.find(pv);if(i){let c=i.props.children,p=u.map(d=>d===i?ye.Children.count(c)>1?ye.Children.only(null):ye.isValidElement(c)?c.props.children:null:d);return jsx(o,{...n,ref:s,children:ye.isValidElement(c)?ye.cloneElement(c,void 0,p):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function fv(e){let o=ye.forwardRef((t,a)=>{let{children:s,...r}=t;if(ye.isValidElement(s)){let n=gv(s),u=hv(r,s.props);return s.type!==ye.Fragment&&(u.ref=a?Or(a,n):n),ye.cloneElement(s,u)}return ye.Children.count(s)>1?ye.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var mv=Symbol("radix.slottable");function pv(e){return ye.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===mv}function hv(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...u)=>{let i=r(...u);return s(...u),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function gv(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 bn(e){let o=e+"CollectionProvider",[t,a]=Aa(o),[s,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=m=>{let{scope:v,children:x}=m,g=ye__default.useRef(null),b=ye__default.useRef(new Map).current;return jsx(s,{scope:v,itemMap:b,collectionRef:g,children:x})};n.displayName=o;let u=e+"CollectionSlot",i=kl(u),c=ye__default.forwardRef((m,v)=>{let{scope:x,children:g}=m,b=r(u,x),w=Ht(v,b.collectionRef);return jsx(i,{ref:w,children:g})});c.displayName=u;let p=e+"CollectionItemSlot",d="data-radix-collection-item",l=kl(p),f=ye__default.forwardRef((m,v)=>{let{scope:x,children:g,...b}=m,w=ye__default.useRef(null),I=Ht(v,w),P=r(p,x);return ye__default.useEffect(()=>(P.itemMap.set(w,{ref:w,...b}),()=>void P.itemMap.delete(w))),jsx(l,{[d]:"",ref:I,children:g})});f.displayName=p;function h(m){let v=r(e+"CollectionConsumer",m);return ye__default.useCallback(()=>{let g=v.collectionRef.current;if(!g)return [];let b=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(v.itemMap.values()).sort((P,k)=>b.indexOf(P.ref.current)-b.indexOf(k.ref.current))},[v.collectionRef,v.itemMap])}return [{Provider:n,Slot:c,ItemSlot:f},h,a]}var Vc=["PageUp","PageDown"],qc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Hc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Uo="Slider",[Ml,bv,vv]=bn(Uo),[Uc]=Aa(Uo,[vv]),[yv,vn]=Uc(Uo),Kc=ye.forwardRef((e,o)=>{let{name:t,min:a=0,max:s=100,step:r=1,orientation:n="horizontal",disabled:u=false,minStepsBetweenThumbs:i=0,defaultValue:c=[a],value:p,onValueChange:d=()=>{},onValueCommit:l=()=>{},inverted:f=false,form:h,...m}=e,v=ye.useRef(new Set),x=ye.useRef(0),b=n==="horizontal"?wv:Lv,[w=[],I]=sa({prop:p,defaultProp:c,onChange:B=>{[...v.current][x.current]?.focus(),d(B);}}),P=ye.useRef(w);function k(B){let T=Tv(w,B);E(B,T);}function S(B){E(B,x.current);}function y(){let B=P.current[x.current];w[x.current]!==B&&l(w);}function E(B,T,{commit:G}={commit:false}){let F=Ev(r),O=Dv(Math.round((B-a)/r)*r+a,F),U=Cl(O,[a,s]);I((V=[])=>{let H=Cv(V,U,T);if(Pv(H,i*r)){x.current=H.indexOf(U);let oe=String(H)!==String(V);return oe&&G&&l(H),oe?H:V}else return V});}return jsx(yv,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:s,valueIndexToChangeRef:x,thumbs:v.current,values:w,orientation:n,form:h,children:jsx(Ml.Provider,{scope:e.__scopeSlider,children:jsx(Ml.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":u,"data-disabled":u?"":void 0,...m,ref:o,onPointerDown:et(m.onPointerDown,()=>{u||(P.current=w);}),min:a,max:s,inverted:f,onSlideStart:u?void 0:k,onSlideMove:u?void 0:S,onSlideEnd:u?void 0:y,onHomeKeyDown:()=>!u&&E(a,0,{commit:true}),onEndKeyDown:()=>!u&&E(s,w.length-1,{commit:true}),onStepKeyDown:({event:B,direction:T})=>{if(!u){let O=Vc.includes(B.key)||B.shiftKey&&qc.includes(B.key)?10:1,U=x.current,V=w[U],H=r*O*T;E(V+H,U,{commit:true});}}})})})})});Kc.displayName=Uo;var[Wc,zc]=Uc(Uo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),wv=ye.forwardRef((e,o)=>{let{min:t,max:a,dir:s,inverted:r,onSlideStart:n,onSlideMove:u,onSlideEnd:i,onStepKeyDown:c,...p}=e,[d,l]=ye.useState(null),f=Ht(o,b=>l(b)),h=ye.useRef(void 0),m=Ho(s),v=m==="ltr",x=v&&!r||!v&&r;function g(b){let w=h.current||d.getBoundingClientRect(),I=[0,w.width],k=El(I,x?[t,a]:[a,t]);return h.current=w,k(b-w.left)}return jsx(Wc,{scope:e.__scopeSlider,startEdge:x?"left":"right",endEdge:x?"right":"left",direction:x?1:-1,size:"width",children:jsx(Gc,{dir:m,"data-orientation":"horizontal",...p,ref:f,style:{...p.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let w=g(b.clientX);n?.(w);},onSlideMove:b=>{let w=g(b.clientX);u?.(w);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:b=>{let I=Hc[x?"from-left":"from-right"].includes(b.key);c?.({event:b,direction:I?-1:1});}})})}),Lv=ye.forwardRef((e,o)=>{let{min:t,max:a,inverted:s,onSlideStart:r,onSlideMove:n,onSlideEnd:u,onStepKeyDown:i,...c}=e,p=ye.useRef(null),d=Ht(o,p),l=ye.useRef(void 0),f=!s;function h(m){let v=l.current||p.current.getBoundingClientRect(),x=[0,v.height],b=El(x,f?[a,t]:[t,a]);return l.current=v,b(m-v.top)}return jsx(Wc,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(Gc,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:m=>{let v=h(m.clientY);r?.(v);},onSlideMove:m=>{let v=h(m.clientY);n?.(v);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:m=>{let x=Hc[f?"from-bottom":"from-top"].includes(m.key);i?.({event:m,direction:x?-1:1});}})})}),Gc=ye.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:s,onSlideEnd:r,onHomeKeyDown:n,onEndKeyDown:u,onStepKeyDown:i,...c}=e,p=vn(Uo,t);return jsx(gt.span,{...c,ref:o,onKeyDown:et(e.onKeyDown,d=>{d.key==="Home"?(n(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):Vc.concat(qc).includes(d.key)&&(i(d),d.preventDefault());}),onPointerDown:et(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),p.thumbs.has(l)?l.focus():a(d);}),onPointerMove:et(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&s(d);}),onPointerUp:et(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),r(d));})})}),jc="SliderTrack",_c=ye.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=vn(jc,t);return jsx(gt.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...a,ref:o})});_c.displayName=jc;var Al="SliderRange",Xc=ye.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=vn(Al,t),r=zc(Al,t),n=ye.useRef(null),u=Ht(o,n),i=s.values.length,c=s.values.map(l=>Jc(l,s.min,s.max)),p=i>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(gt.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...a,ref:u,style:{...e.style,[r.startEdge]:p+"%",[r.endEdge]:d+"%"}})});Xc.displayName=Al;var Pl="SliderThumb",$c=ye.forwardRef((e,o)=>{let t=bv(e.__scopeSlider),[a,s]=ye.useState(null),r=Ht(o,u=>s(u)),n=ye.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(Sv,{...e,ref:r,index:n})}),Sv=ye.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:s,...r}=e,n=vn(Pl,t),u=zc(Pl,t),[i,c]=ye.useState(null),p=Ht(o,g=>c(g)),d=i?n.form||!!i.closest("form"):true,l=Rc(i),f=n.values[a],h=f===void 0?0:Jc(f,n.min,n.max),m=kv(a,n.values.length),v=l?.[u.size],x=v?Mv(v,h,u.direction):0;return ye.useEffect(()=>{if(i)return n.thumbs.add(i),()=>{n.thumbs.delete(i);}},[i,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${x}px)`},children:[jsx(Ml.ItemSlot,{scope:e.__scopeSlider,children:jsx(gt.span,{role:"slider","aria-label":e["aria-label"]||m,"aria-valuemin":n.min,"aria-valuenow":f,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...r,ref:p,style:f===void 0?{display:"none"}:e.style,onFocus:et(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),d&&jsx(Yc,{name:s??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:f},a)]})});$c.displayName=Pl;var Iv="RadioBubbleInput",Yc=ye.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let s=ye.useRef(null),r=Ht(s,a),n=Ec(o);return ye.useEffect(()=>{let u=s.current;if(!u)return;let i=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(i,"value").set;if(n!==o&&p){let d=new Event("input",{bubbles:true});p.call(u,o),u.dispatchEvent(d);}},[n,o]),jsx(gt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});Yc.displayName=Iv;function Cv(e=[],o,t){let a=[...e];return a[t]=o,a.sort((s,r)=>s-r)}function Jc(e,o,t){let r=100/(t-o)*(e-o);return Cl(r,[0,100])}function kv(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Tv(e,o){if(e.length===1)return 0;let t=e.map(s=>Math.abs(s-o)),a=Math.min(...t);return t.indexOf(a)}function Mv(e,o,t){let a=e/2,r=El([0,50],[0,a]);return (a-r(o)*t)*t}function Av(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Pv(e,o){if(o>0){let t=Av(e);return Math.min(...t)>=o}return true}function El(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 Ev(e){return (String(e).split(".")[1]||"").length}function Dv(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Zc=Kc,Qc=_c,ef=Xc,tf=$c;function af(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(o=0;o<s;o++)e[o]&&(t=af(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function yn(){for(var e,o,t=0,a="",s=arguments.length;t<s;t++)(e=arguments[t])&&(o=af(e))&&(a&&(a+=" "),a+=o);return a}var Fv=(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},Bv=(e,o)=>({classGroupId:e,validator:o}),lf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var of=[],Ov="arbitrary..",Nv=e=>{let o=qv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return Vv(n);let u=n.split("-"),i=u[0]===""&&u.length>1?1:0;return df(u,i,o)},getConflictingClassGroupIds:(n,u)=>{if(u){let i=a[n],c=t[n];return i?c?Fv(c,i):i:c||of}return t[n]||of}}},df=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let s=e[o],r=t.nextPart.get(s);if(r){let c=df(e,o+1,r);if(c)return c}let n=t.validators;if(n===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),i=n.length;for(let c=0;c<i;c++){let p=n[c];if(p.validator(u))return p.classGroupId}},Vv=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?Ov+a:void 0})(),qv=e=>{let{theme:o,classGroups:t}=e;return Hv(t,o)},Hv=(e,o)=>{let t=lf();for(let a in e){let s=e[a];Fl(s,t,a,o);}return t},Fl=(e,o,t,a)=>{let s=e.length;for(let r=0;r<s;r++){let n=e[r];Uv(n,o,t,a);}},Uv=(e,o,t,a)=>{if(typeof e=="string"){Kv(e,o,t);return}if(typeof e=="function"){Wv(e,o,t,a);return}zv(e,o,t,a);},Kv=(e,o,t)=>{let a=e===""?o:uf(o,e);a.classGroupId=t;},Wv=(e,o,t,a)=>{if(Gv(e)){Fl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Bv(t,e));},zv=(e,o,t,a)=>{let s=Object.entries(e),r=s.length;for(let n=0;n<r;n++){let[u,i]=s[n];Fl(i,uf(o,u),t,a);}},uf=(e,o)=>{let t=e,a=o.split("-"),s=a.length;for(let r=0;r<s;r++){let n=a[r],u=t.nextPart.get(n);u||(u=lf(),t.nextPart.set(n,u)),t=u;}return t},Gv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,jv=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),s=(r,n)=>{t[r]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let n=t[r];if(n!==void 0)return n;if((n=a[r])!==void 0)return s(r,n),n},set(r,n){r in t?t[r]=n:s(r,n);}}};var _v=[],rf=(e,o,t,a,s)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:s}),Xv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=s=>{let r=[],n=0,u=0,i=0,c,p=s.length;for(let m=0;m<p;m++){let v=s[m];if(n===0&&u===0){if(v===":"){r.push(s.slice(i,m)),i=m+1;continue}if(v==="/"){c=m;continue}}v==="["?n++:v==="]"?n--:v==="("?u++:v===")"&&u--;}let d=r.length===0?s:s.slice(i),l=d,f=false;d.endsWith("!")?(l=d.slice(0,-1),f=true):d.startsWith("!")&&(l=d.slice(1),f=true);let h=c&&c>i?c-i:void 0;return rf(r,f,l,h)};if(o){let s=o+":",r=a;a=n=>n.startsWith(s)?r(n.slice(s.length)):rf(_v,false,n,void 0,true);}if(t){let s=a;a=r=>t({className:r,parseClassName:s});}return a},$v=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],s=[];for(let r=0;r<t.length;r++){let n=t[r],u=n[0]==="[",i=o.has(n);u||i?(s.length>0&&(s.sort(),a.push(...s),s=[]),a.push(n)):s.push(n);}return s.length>0&&(s.sort(),a.push(...s)),a}},Yv=e=>({cache:jv(e.cacheSize),parseClassName:Xv(e),sortModifiers:$v(e),...Nv(e)}),Jv=/\s+/,Zv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:s,sortModifiers:r}=o,n=[],u=e.trim().split(Jv),i="";for(let c=u.length-1;c>=0;c-=1){let p=u[c],{isExternal:d,modifiers:l,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:m}=t(p);if(d){i=p+(i.length>0?" "+i:i);continue}let v=!!m,x=a(v?h.substring(0,m):h);if(!x){if(!v){i=p+(i.length>0?" "+i:i);continue}if(x=a(h),!x){i=p+(i.length>0?" "+i:i);continue}v=false;}let g=l.length===0?"":l.length===1?l[0]:r(l).join(":"),b=f?g+"!":g,w=b+x;if(n.indexOf(w)>-1)continue;n.push(w);let I=s(x,v);for(let P=0;P<I.length;++P){let k=I[P];n.push(b+k);}i=p+(i.length>0?" "+i:i);}return i},Qv=(...e)=>{let o=0,t,a,s="";for(;o<e.length;)(t=e[o++])&&(a=cf(t))&&(s&&(s+=" "),s+=a);return s},cf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=cf(e[a]))&&(t&&(t+=" "),t+=o);return t},ey=(e,...o)=>{let t,a,s,r,n=i=>{let c=o.reduce((p,d)=>d(p),e());return t=Yv(c),a=t.cache.get,s=t.cache.set,r=u,u(i)},u=i=>{let c=a(i);if(c)return c;let p=Zv(i,t);return s(i,p),p};return r=n,(...i)=>r(Qv(...i))},ty=[],ze=e=>{let o=t=>t[e]||ty;return o.isThemeGetter=true,o},ff=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,mf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,ay=/^\d+\/\d+$/,oy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ry=/\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$/,sy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ny=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,iy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ko=e=>ay.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Pa=e=>!!e&&Number.isInteger(Number(e)),Dl=e=>e.endsWith("%")&&de(e.slice(0,-1)),na=e=>oy.test(e),ly=()=>true,dy=e=>ry.test(e)&&!sy.test(e),pf=()=>false,uy=e=>ny.test(e),cy=e=>iy.test(e),fy=e=>!Y(e)&&!J(e),my=e=>Wo(e,xf,pf),Y=e=>ff.test(e),to=e=>Wo(e,bf,dy),Rl=e=>Wo(e,by,de),sf=e=>Wo(e,hf,pf),py=e=>Wo(e,gf,cy),wn=e=>Wo(e,vf,uy),J=e=>mf.test(e),Nr=e=>zo(e,bf),hy=e=>zo(e,vy),nf=e=>zo(e,hf),gy=e=>zo(e,xf),xy=e=>zo(e,gf),Ln=e=>zo(e,vf,true),Wo=(e,o,t)=>{let a=ff.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},zo=(e,o,t=false)=>{let a=mf.exec(e);return a?a[1]?o(a[1]):t:false},hf=e=>e==="position"||e==="percentage",gf=e=>e==="image"||e==="url",xf=e=>e==="length"||e==="size"||e==="bg-size",bf=e=>e==="length",by=e=>e==="number",vy=e=>e==="family-name",vf=e=>e==="shadow";var yy=()=>{let e=ze("color"),o=ze("font"),t=ze("text"),a=ze("font-weight"),s=ze("tracking"),r=ze("leading"),n=ze("breakpoint"),u=ze("container"),i=ze("spacing"),c=ze("radius"),p=ze("shadow"),d=ze("inset-shadow"),l=ze("text-shadow"),f=ze("drop-shadow"),h=ze("blur"),m=ze("perspective"),v=ze("aspect"),x=ze("ease"),g=ze("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],w=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...w(),J,Y],P=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],S=()=>[J,Y,i],y=()=>[Ko,"full","auto",...S()],E=()=>[Pa,"none","subgrid",J,Y],B=()=>["auto",{span:["full",Pa,J,Y]},Pa,J,Y],T=()=>[Pa,"auto",J,Y],G=()=>["auto","min","max","fr",J,Y],F=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],O=()=>["start","end","center","stretch","center-safe","end-safe"],U=()=>["auto",...S()],V=()=>[Ko,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...S()],H=()=>[e,J,Y],oe=()=>[...w(),nf,sf,{position:[J,Y]}],me=()=>["no-repeat",{repeat:["","x","y","space","round"]}],W=()=>["auto","cover","contain",gy,my,{size:[J,Y]}],q=()=>[Dl,Nr,to],_=()=>["","none","full",c,J,Y],K=()=>["",de,Nr,to],X=()=>["solid","dashed","dotted","double"],te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],$=()=>[de,Dl,nf,sf],re=()=>["","none",h,J,Y],ie=()=>["none",de,J,Y],Ae=()=>["none",de,J,Y],Ce=()=>[de,J,Y],Ee=()=>[Ko,"full",...S()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[na],breakpoint:[na],color:[ly],container:[na],"drop-shadow":[na],ease:["in","out","in-out"],font:[fy],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[na],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[na],shadow:[na],spacing:["px",de],text:[na],"text-shadow":[na],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ko,Y,J,v]}],container:["container"],columns:[{columns:[de,Y,J,u]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"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:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:y()}],"inset-x":[{"inset-x":y()}],"inset-y":[{"inset-y":y()}],start:[{start:y()}],end:[{end:y()}],top:[{top:y()}],right:[{right:y()}],bottom:[{bottom:y()}],left:[{left:y()}],visibility:["visible","invisible","collapse"],z:[{z:[Pa,"auto",J,Y]}],basis:[{basis:[Ko,"full","auto",u,...S()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Ko,"auto","initial","none",Y]}],grow:[{grow:["",de,J,Y]}],shrink:[{shrink:["",de,J,Y]}],order:[{order:[Pa,"first","last","none",J,Y]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:B()}],"col-start":[{"col-start":T()}],"col-end":[{"col-end":T()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:B()}],"row-start":[{"row-start":T()}],"row-end":[{"row-end":T()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:S()}],"gap-x":[{"gap-x":S()}],"gap-y":[{"gap-y":S()}],"justify-content":[{justify:[...F(),"normal"]}],"justify-items":[{"justify-items":[...O(),"normal"]}],"justify-self":[{"justify-self":["auto",...O()]}],"align-content":[{content:["normal",...F()]}],"align-items":[{items:[...O(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...O(),{baseline:["","last"]}]}],"place-content":[{"place-content":F()}],"place-items":[{"place-items":[...O(),"baseline"]}],"place-self":[{"place-self":["auto",...O()]}],p:[{p:S()}],px:[{px:S()}],py:[{py:S()}],ps:[{ps:S()}],pe:[{pe:S()}],pt:[{pt:S()}],pr:[{pr:S()}],pb:[{pb:S()}],pl:[{pl:S()}],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":S()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":S()}],"space-y-reverse":["space-y-reverse"],size:[{size:V()}],w:[{w:[u,"screen",...V()]}],"min-w":[{"min-w":[u,"screen","none",...V()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[n]},...V()]}],h:[{h:["screen","lh",...V()]}],"min-h":[{"min-h":["screen","lh","none",...V()]}],"max-h":[{"max-h":["screen","lh",...V()]}],"font-size":[{text:["base",t,Nr,to]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,J,Rl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Dl,Y]}],"font-family":[{font:[hy,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:[s,J,Y]}],"line-clamp":[{"line-clamp":[de,"none",J,Rl]}],leading:[{leading:[r,...S()]}],"list-image":[{"list-image":["none",J,Y]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",J,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:[...X(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",J,to]}],"text-decoration-color":[{decoration:H()}],"underline-offset":[{"underline-offset":[de,"auto",J,Y]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",J,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",J,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:oe()}],"bg-repeat":[{bg:me()}],"bg-size":[{bg:W()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Pa,J,Y],radial:["",J,Y],conic:[Pa,J,Y]},xy,py]}],"bg-color":[{bg:H()}],"gradient-from-pos":[{from:q()}],"gradient-via-pos":[{via:q()}],"gradient-to-pos":[{to:q()}],"gradient-from":[{from:H()}],"gradient-via":[{via:H()}],"gradient-to":[{to:H()}],rounded:[{rounded:_()}],"rounded-s":[{"rounded-s":_()}],"rounded-e":[{"rounded-e":_()}],"rounded-t":[{"rounded-t":_()}],"rounded-r":[{"rounded-r":_()}],"rounded-b":[{"rounded-b":_()}],"rounded-l":[{"rounded-l":_()}],"rounded-ss":[{"rounded-ss":_()}],"rounded-se":[{"rounded-se":_()}],"rounded-ee":[{"rounded-ee":_()}],"rounded-es":[{"rounded-es":_()}],"rounded-tl":[{"rounded-tl":_()}],"rounded-tr":[{"rounded-tr":_()}],"rounded-br":[{"rounded-br":_()}],"rounded-bl":[{"rounded-bl":_()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...X(),"hidden","none"]}],"divide-style":[{divide:[...X(),"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:[...X(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,J,Y]}],"outline-w":[{outline:["",de,Nr,to]}],"outline-color":[{outline:H()}],shadow:[{shadow:["","none",p,Ln,wn]}],"shadow-color":[{shadow:H()}],"inset-shadow":[{"inset-shadow":["none",d,Ln,wn]}],"inset-shadow-color":[{"inset-shadow":H()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:H()}],"ring-offset-w":[{"ring-offset":[de,to]}],"ring-offset-color":[{"ring-offset":H()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":H()}],"text-shadow":[{"text-shadow":["none",l,Ln,wn]}],"text-shadow-color":[{"text-shadow":H()}],opacity:[{opacity:[de,J,Y]}],"mix-blend":[{"mix-blend":[...te(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":te()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":$()}],"mask-image-linear-to-pos":[{"mask-linear-to":$()}],"mask-image-linear-from-color":[{"mask-linear-from":H()}],"mask-image-linear-to-color":[{"mask-linear-to":H()}],"mask-image-t-from-pos":[{"mask-t-from":$()}],"mask-image-t-to-pos":[{"mask-t-to":$()}],"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":$()}],"mask-image-r-to-pos":[{"mask-r-to":$()}],"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":$()}],"mask-image-b-to-pos":[{"mask-b-to":$()}],"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":$()}],"mask-image-l-to-pos":[{"mask-l-to":$()}],"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":$()}],"mask-image-x-to-pos":[{"mask-x-to":$()}],"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":$()}],"mask-image-y-to-pos":[{"mask-y-to":$()}],"mask-image-y-from-color":[{"mask-y-from":H()}],"mask-image-y-to-color":[{"mask-y-to":H()}],"mask-image-radial":[{"mask-radial":[J,Y]}],"mask-image-radial-from-pos":[{"mask-radial-from":$()}],"mask-image-radial-to-pos":[{"mask-radial-to":$()}],"mask-image-radial-from-color":[{"mask-radial-from":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":w()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":$()}],"mask-image-conic-to-pos":[{"mask-conic-to":$()}],"mask-image-conic-from-color":[{"mask-conic-from":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:oe()}],"mask-repeat":[{mask:me()}],"mask-size":[{mask:W()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",J,Y]}],filter:[{filter:["","none",J,Y]}],blur:[{blur:re()}],brightness:[{brightness:[de,J,Y]}],contrast:[{contrast:[de,J,Y]}],"drop-shadow":[{"drop-shadow":["","none",f,Ln,wn]}],"drop-shadow-color":[{"drop-shadow":H()}],grayscale:[{grayscale:["",de,J,Y]}],"hue-rotate":[{"hue-rotate":[de,J,Y]}],invert:[{invert:["",de,J,Y]}],saturate:[{saturate:[de,J,Y]}],sepia:[{sepia:["",de,J,Y]}],"backdrop-filter":[{"backdrop-filter":["","none",J,Y]}],"backdrop-blur":[{"backdrop-blur":re()}],"backdrop-brightness":[{"backdrop-brightness":[de,J,Y]}],"backdrop-contrast":[{"backdrop-contrast":[de,J,Y]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,J,Y]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,J,Y]}],"backdrop-invert":[{"backdrop-invert":["",de,J,Y]}],"backdrop-opacity":[{"backdrop-opacity":[de,J,Y]}],"backdrop-saturate":[{"backdrop-saturate":[de,J,Y]}],"backdrop-sepia":[{"backdrop-sepia":["",de,J,Y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":S()}],"border-spacing-x":[{"border-spacing-x":S()}],"border-spacing-y":[{"border-spacing-y":S()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",J,Y]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",J,Y]}],ease:[{ease:["linear","initial",x,J,Y]}],delay:[{delay:[de,J,Y]}],animate:[{animate:["none",g,J,Y]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[m,J,Y]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:ie()}],"rotate-x":[{"rotate-x":ie()}],"rotate-y":[{"rotate-y":ie()}],"rotate-z":[{"rotate-z":ie()}],scale:[{scale:Ae()}],"scale-x":[{"scale-x":Ae()}],"scale-y":[{"scale-y":Ae()}],"scale-z":[{"scale-z":Ae()}],"scale-3d":["scale-3d"],skew:[{skew:Ce()}],"skew-x":[{"skew-x":Ce()}],"skew-y":[{"skew-y":Ce()}],transform:[{transform:[J,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ee()}],"translate-x":[{"translate-x":Ee()}],"translate-y":[{"translate-y":Ee()}],"translate-z":[{"translate-z":Ee()}],"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",J,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":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"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",J,Y]}],fill:[{fill:["none",...H()]}],"stroke-w":[{stroke:[de,Nr,to,Rl]}],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 yf=ey(yy);function Ea(...e){return yf(yn(e))}function Sn({className:e,defaultValue:o,value:t,min:a=0,max:s=100,rangeClassName:r,trackClassName:n,thumbClassName:u,...i}){let c=ye.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,s],[t,o,a,s]);return jsxs(Zc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:s,className:Ea("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(Qc,{"data-slot":"slider-track",className:Ea("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(ef,{"data-slot":"slider-range",className:Ea("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(p,d)=>jsx(tf,{"data-slot":"slider-thumb",className:Ea("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 Ly="SchooplaVideoStorage";var ea="videos",In=()=>new Promise((e,o)=>{let t=indexedDB.open(Ly,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(ea)||s.createObjectStore(ea,{keyPath:"id"});};}),ao=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await In(),r=a.transaction([ea],"readwrite").objectStore(ea),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,i)=>{let c=r.put(n);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 Lf=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await In(),t=e.transaction([ea],"readonly").objectStore(ea);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result,u=new Map;n.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(),s(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Ol=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await In(),a=o.transaction([ea],"readwrite").objectStore(ea);await new Promise((s,r)=>{let n=a.delete(e);n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Sf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await In(),t=e.transaction([ea],"readwrite").objectStore(ea);await new Promise((a,s)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>s(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}},If=e=>URL.createObjectURL(e);var Sy=ye[" useId ".trim().toString()]||(()=>{}),Iy=0;function Cf(e){let[o,t]=ye.useState(Sy());return qo(()=>{t(a=>a??String(Iy++));},[e]),(o?`radix-${o}`:"")}function kf(e){let o=ye.useRef(e);return ye.useEffect(()=>{o.current=e;}),ye.useMemo(()=>(...t)=>o.current?.(...t),[])}var Vl="rovingFocusGroup.onEntryFocus",Cy={bubbles:false,cancelable:true},Vr="RovingFocusGroup",[ql,Tf,ky]=bn(Vr),[Ty,Hl]=Aa(Vr,[ky]),[My,Ay]=Ty(Vr),Mf=ye.forwardRef((e,o)=>jsx(ql.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(ql.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Py,{...e,ref:o})})}));Mf.displayName=Vr;var Py=ye.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:s=false,dir:r,currentTabStopId:n,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:i,onEntryFocus:c,preventScrollOnEntryFocus:p=false,...d}=e,l=ye.useRef(null),f=Ht(o,l),h=Ho(r),[m,v]=sa({prop:n,defaultProp:u??null,onChange:i,caller:Vr}),[x,g]=ye.useState(false),b=kf(c),w=Tf(t),I=ye.useRef(false),[P,k]=ye.useState(0);return ye.useEffect(()=>{let S=l.current;if(S)return S.addEventListener(Vl,b),()=>S.removeEventListener(Vl,b)},[b]),jsx(My,{scope:t,orientation:a,dir:h,loop:s,currentTabStopId:m,onItemFocus:ye.useCallback(S=>v(S),[v]),onItemShiftTab:ye.useCallback(()=>g(true),[]),onFocusableItemAdd:ye.useCallback(()=>k(S=>S+1),[]),onFocusableItemRemove:ye.useCallback(()=>k(S=>S-1),[]),children:jsx(gt.div,{tabIndex:x||P===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:et(e.onMouseDown,()=>{I.current=true;}),onFocus:et(e.onFocus,S=>{let y=!I.current;if(S.target===S.currentTarget&&y&&!x){let E=new CustomEvent(Vl,Cy);if(S.currentTarget.dispatchEvent(E),!E.defaultPrevented){let B=w().filter(U=>U.focusable),T=B.find(U=>U.active),G=B.find(U=>U.id===m),O=[T,G,...B].filter(Boolean).map(U=>U.ref.current);Ef(O,p);}}I.current=false;}),onBlur:et(e.onBlur,()=>g(false))})})}),Af="RovingFocusGroupItem",Pf=ye.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:s=false,tabStopId:r,children:n,...u}=e,i=Cf(),c=r||i,p=Ay(Af,t),d=p.currentTabStopId===c,l=Tf(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:m}=p;return ye.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(ql.ItemSlot,{scope:t,id:c,focusable:a,active:s,children:jsx(gt.span,{tabIndex:d?0:-1,"data-orientation":p.orientation,...u,ref:o,onMouseDown:et(e.onMouseDown,v=>{a?p.onItemFocus(c):v.preventDefault();}),onFocus:et(e.onFocus,()=>p.onItemFocus(c)),onKeyDown:et(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){p.onItemShiftTab();return}if(v.target!==v.currentTarget)return;let x=Ry(v,p.orientation,p.dir);if(x!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let b=l().filter(w=>w.focusable).map(w=>w.ref.current);if(x==="last")b.reverse();else if(x==="prev"||x==="next"){x==="prev"&&b.reverse();let w=b.indexOf(v.currentTarget);b=p.loop?Fy(b,w+1):b.slice(w+1);}setTimeout(()=>Ef(b));}}),children:typeof n=="function"?n({isCurrentTabStop:d,hasTabStop:m!=null}):n})})});Pf.displayName=Af;var Ey={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Dy(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Ry(e,o,t){let a=Dy(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Ey[a]}function Ef(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Fy(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Df=Mf,Rf=Pf;var Bf="Toggle",Ul=ye.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:s,...r}=e,[n,u]=sa({prop:t,onChange:s,defaultProp:a??false,caller:Bf});return jsx(gt.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:et(e.onClick,()=>{e.disabled||u(!n);})})});Ul.displayName=Bf;var Da="ToggleGroup",[Nf]=Aa(Da,[Hl]),Vf=Hl(),Kl=ye__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Ny,{...a,ref:o});if(t==="multiple")return jsx(Vy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Da}\``)});Kl.displayName=Da;var[qf,Hf]=Nf(Da),Ny=ye__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,u]=sa({prop:t,defaultProp:a??"",onChange:s,caller:Da});return jsx(qf,{scope:e.__scopeToggleGroup,type:"single",value:ye__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:u,onItemDeactivate:ye__default.useCallback(()=>u(""),[u]),children:jsx(Uf,{...r,ref:o})})}),Vy=ye__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,u]=sa({prop:t,defaultProp:a??[],onChange:s,caller:Da}),i=ye__default.useCallback(p=>u((d=[])=>[...d,p]),[u]),c=ye__default.useCallback(p=>u((d=[])=>d.filter(l=>l!==p)),[u]);return jsx(qf,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:i,onItemDeactivate:c,children:jsx(Uf,{...r,ref:o})})});Kl.displayName=Da;var[qy,Hy]=Nf(Da),Uf=ye__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:s=true,orientation:r,dir:n,loop:u=true,...i}=e,c=Vf(t),p=Ho(n),d={role:"group",dir:p,...i};return jsx(qy,{scope:t,rovingFocus:s,disabled:a,children:s?jsx(Df,{asChild:true,...c,orientation:r,dir:p,loop:u,children:jsx(gt.div,{...d,ref:o})}):jsx(gt.div,{...d,ref:o})})}),Cn="ToggleGroupItem",Uy=ye__default.forwardRef((e,o)=>{let t=Hf(Cn,e.__scopeToggleGroup),a=Hy(Cn,e.__scopeToggleGroup),s=Vf(e.__scopeToggleGroup),r=t.value.includes(e.value),n=a.disabled||e.disabled,u={...e,pressed:r,disabled:n},i=ye__default.useRef(null);return a.rovingFocus?jsx(Rf,{asChild:true,...s,focusable:!n,active:r,ref:i,children:jsx(Of,{...u,ref:o})}):jsx(Of,{...u,ref:o})});Uy.displayName=Cn;var Of=ye__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...s}=e,r=Hf(Cn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=r.type==="single"?n:void 0;return jsx(Ul,{...u,...s,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Kf=Kl;var zy=ye.createContext({size:"default",variant:"default",spacing:0});function Ra({className:e,variant:o,size:t,spacing:a=1,children:s,...r}){return jsx(Kf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Ea("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(zy.Provider,{value:{variant:o,size:t,spacing:a},children:s})})}var jy={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},_f=createSlice({name:"toolbar",initialState:jy,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:ta,setPenColor:jo,setStrokeWidth:qr,setFontSize:HE,setFontFamily:UE,setFontStyle:KE,setFontWeight:WE,setTextDecoration:zE,setTextColor:GE}=_f.actions,zl=_f.reducer;var Xf=({onClose:e,onRecordingComplete:o})=>{let t=qe(),[a,s]=useState(false),[r,n]=useState(null),[u,i]=useState(0),[c,p]=useState(null),[d,l]=useState(false),f=useRef(null),h=useRef([]),m=useRef(null),v=useRef(null),x=useRef(null);useEffect(()=>((async()=>{try{let y=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});p(y),l(!0),x.current&&(x.current.srcObject=y);}catch(y){console.error("Error accessing camera:",y),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{m.current&&clearInterval(m.current),c&&c.getTracks().forEach(y=>y.stop());}),[]);let g=()=>{c&&(c.getTracks().forEach(S=>S.stop()),p(null),l(false));},b=async()=>{try{let S=null,y=null;try{S=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{y=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(F){console.warn("Microphone access denied:",F);}let E=[...S.getVideoTracks()];y&&E.push(...y.getAudioTracks());let B=new MediaStream(E),T="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?T="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?T="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?T="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(T="video/webm;codecs=vp8");let G=new MediaRecorder(B,{mimeType:T,videoBitsPerSecond:25e5});f.current=G,h.current=[],G.ondataavailable=F=>{F.data.size>0&&h.current.push(F.data);},G.onstop=()=>{let F=new Blob(h.current,{type:T}),O=document.createElement("video");O.src=URL.createObjectURL(F),O.muted=!0,O.currentTime=.1,O.onseeked=()=>{let U=document.createElement("canvas");U.width=O.videoWidth,U.height=O.videoHeight;let V=U.getContext("2d");V&&(V.drawImage(O,0,0),v.current=U.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(O.src);},B.getTracks().forEach(U=>U.stop()),S&&S.getTracks().forEach(U=>U.stop()),y&&y.getTracks().forEach(U=>U.stop()),m.current&&clearInterval(m.current),n(F),g();},G.onerror=F=>{console.error("MediaRecorder error:",F);},G.start(1e3),s(!0),i(0),m.current=setInterval(()=>{i(F=>F+1);},1e3);}catch(S){console.error("Error starting camera recording:",S),alert("Failed to start recording. Please check permissions.");}},w=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),s(false));},I=()=>{if(r){let S=URL.createObjectURL(r),y=document.createElement("a");y.href=S,y.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(S);}},P=S=>{let y=Math.floor(S/60),E=S%60;return `${y.toString().padStart(2,"0")}:${E.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:S=>{S.target===S.currentTarget&&e(),S.stopPropagation();},onMouseUp:S=>S.stopPropagation(),onMouseMove:S=>S.stopPropagation(),onTouchStart:S=>S.stopPropagation(),onTouchMove:S=>S.stopPropagation(),onTouchEnd:S=>S.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:S=>S.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:x,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:b,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:w,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:P(u)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",P(u)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(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 ia=40,Yf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,s]=useState(t?.images||[]),[r,n]=useState(t?.order||"sequential"),[u,i]=useState(false),c=useRef(null),p=qe(),d=useRef(null);useEffect(()=>{let b=w=>{w.key==="Escape"&&o();};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[o]);let l=b=>{let w=b.target.files;if(!w||w.length===0)return;let I=ia-a.length;if(I<=0){alert(`You can only upload a maximum of ${ia} images`);return}let P=Array.from(w).slice(0,I);P.length<w.length&&alert(`Only ${I} more images can be added (max ${ia} total)`);let k=P.map(S=>new Promise((y,E)=>{let B=new FileReader;B.onload=T=>{T.target?.result?y(T.target.result):E(new Error("Failed to read file"));},B.onerror=E,B.readAsDataURL(S);}));Promise.all(k).then(S=>{s(y=>[...y,...S]),d.current&&(d.current.value="");});},f=b=>{b.preventDefault(),i(false);let w=Array.from(b.dataTransfer.files).filter(S=>S.type.startsWith("image/"));if(w.length===0)return;let I=ia-a.length;if(I<=0){alert(`You can only upload a maximum of ${ia} images`);return}let P=w.slice(0,I);P.length<w.length&&alert(`Only ${I} more images can be added (max ${ia} total)`);let k=P.map(S=>new Promise((y,E)=>{let B=new FileReader;B.onload=T=>{T.target?.result?y(T.target.result):E(new Error("Failed to read file"));},B.onerror=E,B.readAsDataURL(S);}));Promise.all(k).then(S=>{s(y=>[...y,...S]);});},h=b=>{b.preventDefault(),i(true);},m=()=>{i(false);},v=b=>{s(w=>w.filter((I,P)=>P!==b));},x=b=>{if(b.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!p)return null;let g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:b=>{b.target===b.currentTarget&&o(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{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:b=>b.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:x,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>=ia?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ia," images"]}):jsxs("span",{children:[a.length,"/",ia," 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:f,onDragOver:h,onDragLeave:m,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:()=>n("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:()=>n("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((b,w)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:b,alt:`Flashcard ${w+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(w),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:w+1})]},w))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(g,p)};var kn={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},lw={enabled:true};function _l(e){return e?{tools:{...kn.tools,...e.tools},actions:{...kn.actions,...e.actions}}:kn}var dw={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},uw={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var Fw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:s}={})=>{let r=ve(),n=Q(D=>D.canvas.slides.find(ee=>ee.id===D.canvas.currentSlideId)),u=n?.videos||[],i=n?.editingFlashcard,c=Q(D=>D.toolbar.selectedTool),p=Q(D=>D.toolbar.penColor),d=Q(D=>D.toolbar.strokeWidth),l=n?.showMcqForm,f=n?.showFlashcardForm,h=useRef(null);useEffect(()=>{let D=ee=>{(ee.ctrlKey||ee.metaKey)&&ee.key==="z"&&!ee.shiftKey&&(ee.preventDefault(),r(Ds())),(ee.ctrlKey&&ee.shiftKey&&ee.key==="Z"||ee.ctrlKey&&ee.key==="y")&&(ee.preventDefault(),r(Rs()));};return window.addEventListener("keydown",D),()=>{window.removeEventListener("keydown",D);}},[r]);let m=useMemo(()=>_l(s),[s]),{tools:v,actions:x}=m,g=u.some(D=>D.isRecorded&&D.isPlaying),b=Q(D=>D.toolbar.fontSize),w=Q(D=>D.toolbar.fontFamily),I=Q(D=>D.toolbar.fontStyle),P=Q(D=>D.toolbar.fontWeight),k=Q(D=>D.toolbar.textDecoration),S=Q(D=>D.toolbar.textColor),[y,E]=useState(false),[B,T]=useState(false),[G,F]=useState(false),[O,U]=useState(false),[V,H]=useState(false),[oe,me]=useState(false),[W,q]=useState(false),_=useRef(null),K=useRef(null),X=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),te=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),$=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),re=useMemo(()=>X.filter(D=>{let ee=v[D.configKey];return typeof ee=="boolean"?ee:Array.isArray(ee)?ee.length>0:true}),[v,X]),ie=useMemo(()=>{let D=v.shapes;return D===false?[]:D===true?te:Array.isArray(D)?te.filter(ee=>D.includes(ee.name)):te},[v.shapes,te]),Ae=useMemo(()=>{let D=v.activities;return D===false?[]:D===true?$:Array.isArray(D)?$.filter(ee=>D.includes(ee.name)):$},[v.activities,$]),Ce=useMemo(()=>{let D=v.media;return D===false?{photoFrame:false,image:false,video:false}:D===true?{photoFrame:true,image:true,video:true}:Array.isArray(D)?{photoFrame:D.includes("photo-frame"),image:D.includes("image"),video:D.includes("video")}:{photoFrame:true,image:true,video:true}},[v.media]),Ee=useMemo(()=>{let D=v.activities;return D===false?false:D===true?true:Array.isArray(D)?D.includes("flashcard"):true},[v.activities]),lt=D=>{let ee=D.target.files;!ee||ee.length===0||(r(ta("select")),r(wt(false)),U(false),Array.from(ee).forEach(ke=>{let xe=new FileReader;xe.onload=le=>{let fe=new window.Image;fe.src=le.target?.result,fe.onload=()=>{let Pe=fe.width/fe.height,_e=300,Yt=300,vt=fe.width,De=fe.height;vt>_e&&(vt=_e,De=vt/Pe),De>Yt&&(De=Yt,vt=De*Pe),r(ue());let at=800-vt/2,At=450-De/2;r(Qn({id:v4(),src:fe.src,x:at,y:At,width:vt,height:De,draggable:true,rotation:0}));};},xe.readAsDataURL(ke);}),D.target.value="");},bt=async D=>{let ee=D.target.files;if(!(!ee||ee.length===0)){console.log("files",D),r(ta("select")),r(wt(false)),U(false);for(let ke of Array.from(ee))try{let xe=URL.createObjectURL(ke),le=document.createElement("video");console.log("video",le),le.src=xe,le.muted=!0,le.playsInline=!0,le.preload="auto",le.load(),await new Promise((dt,fa)=>{let Na=setTimeout(()=>fa(new Error("Metadata load timeout")),1e4);le.onloadedmetadata=()=>{clearTimeout(Na),dt();},le.onerror=()=>{clearTimeout(Na),fa(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:le.duration,width:le.videoWidth,height:le.videoHeight}),await new Promise((dt,fa)=>{let Na=setTimeout(()=>fa(new Error("Video load timeout")),1e4);le.readyState>=2?(clearTimeout(Na),dt()):le.onloadeddata=()=>{clearTimeout(Na),dt();};});let fe=Math.min(.8,le.duration/2);console.log("Seeking to:",fe),le.currentTime=fe,await new Promise(dt=>{let fa=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),dt();},5e3);le.onseeked=()=>{clearTimeout(fa),console.log("Seek completed"),dt();};});let Pe=document.createElement("canvas"),_e=le.videoWidth/le.videoHeight,Yt=400,vt=400,De=le.videoWidth,at=le.videoHeight;De>Yt&&(De=Yt,at=De/_e),at>vt&&(at=vt,De=at*_e),Pe.width=De,Pe.height=at;let At=Pe.getContext("2d",{willReadFrequently:!1});if(!At)throw new Error("Failed to get canvas context");if(await new Promise(dt=>setTimeout(dt,100)),le.videoWidth===0||le.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:De,height:at}),At.drawImage(le,0,0,De,at);let Kt=Pe.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Kt.length),r(ue());let Vn=800-De/2,qn=450-at/2,$r=v4();await ao($r,ke,Kt),r(ss({id:$r,objectUrl:xe,thumbnailDataUrl:Kt,videoBlob:ke,x:Vn,y:qn,width:De,height:at,draggable:!0,isPlaying:!1,rotation:0})),le.src="",le.load(),console.log(`Video uploaded: ${ke.name}`);}catch(xe){console.error("Error processing video:",xe),alert(`Failed to process video: ${ke.name}`);}D.target.value="";}},lo=(D,ee,ke)=>{r(ue()),r(ta("select")),r(wt(false));let xe=300,le=300,fe=800-xe/2,Pe=450-le/2;r(ke?po({id:ke,images:D,order:ee,x:fe,y:Pe,width:xe,height:le,rotation:0,draggable:true}):ai({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:D,currentIndex:0,order:ee,x:fe,y:Pe,width:xe,height:le,rotation:0,draggable:true})),r(Ua(false));},se=()=>{r(ue()),r(ta("select")),r(wt(false));let D=400,ee=300,ke=800-D/2,xe=450-ee/2;r(si({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ke,y:xe,width:D,height:ee,rotation:0,draggable:true,isCapturing:false})),H(false);},Gr=D=>{let fe={};switch(D.name){case "circle":case "ring":case "wedge":case "arc":fe.radius=50,(D.name==="ring"||D.name==="arc")&&(fe.innerRadius=25,fe.outerRadius=50),(D.name==="wedge"||D.name==="arc")&&(fe.angle=D.name==="wedge"?60:90);break;case "ellipse":fe.radiusX=60,fe.radiusY=40;break;case "triangle":fe.radius=50,fe.sides=3;break;case "polygon":fe.radius=50,fe.sides=6;break;case "star":fe.innerRadius=25,fe.outerRadius=50,fe.numPoints=5;break;case "arrow":case "line":fe.points=[0,0,100,0],D.name==="arrow"&&(fe.pointerLength=10,fe.pointerWidth=10);break}let Pe={id:`shape-${Date.now()}`,type:D.name,x:750,y:400,width:100,height:100,rotation:0,color:p,...fe};r(ue()),r(wt(false)),r(ta(D.name)),r(ei(Pe));},Oa=D=>{if(r(ta(D)),D==="select")r(wt(false));else if(D==="text"){r(wt(false)),r(ue());let ee=200,ke=50,xe=800-ee/2,le=450-ke/2,Pe=window.innerWidth<768?Math.max(b,32):b,_e=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(ti({id:_e,text:"",x:xe,y:le,width:ee,height:ke,rotation:0,draggable:true,fontSize:Pe,fontFamily:w,fontStyle:I,fontWeight:P,textDecoration:k,fill:S,align:"left"})),setTimeout(()=>{r(sr(_e));},100),a&&a(_e);}else r(wt(true));},jr=()=>{r(wi()),r(wt(false));},_r=()=>{o?o():t?E(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Xr=()=>{T(true);},$o=async(D,ee)=>{try{r(ta("select")),r(wt(!1));let ke=URL.createObjectURL(D),xe=document.createElement("video");xe.src=ke,xe.muted=!0,xe.playsInline=!0,xe.preload="auto",await new Promise((at,At)=>{let Kt=setTimeout(()=>At(new Error("Metadata load timeout")),1e4);xe.onloadedmetadata=()=>{clearTimeout(Kt),at();},xe.onerror=()=>{clearTimeout(Kt),At(new Error("Failed to load video"));};});let le=640,fe=xe.videoWidth/xe.videoHeight,Pe=le,_e=Pe/fe;r(ue());let Yt=800-Pe/2,vt=450-_e/2,De=v4();await ao(De,D,ee),r(ss({id:De,objectUrl:ke,thumbnailDataUrl:ee,videoBlob:D,x:Yt,y:vt,width:Pe,height:_e,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),E(!1),T(!1);}catch(ke){console.error("Error adding recorded video to canvas:",ke),alert("Failed to add video to canvas. Please try again.");}},Rn=D=>{r(ta("select")),r(wt(false)),r(or(null)),D&&r(hi(D)),r(ga(!l));},Fn=()=>{r(Qo(null)),r(Ua(true)),H(false);},Bn=()=>{F(!G);},On=()=>{U(!O);},Nn=()=>{H(!V);};return useEffect(()=>{if(!W)return;let D=ee=>{h.current&&!h.current.contains(ee.target)&&q(false);};return document.addEventListener("mousedown",D),()=>{document.removeEventListener("mousedown",D);}},[W]),g?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Ra,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:re.map((D,ee)=>jsx("div",{title:D.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 ${D.name===c?"bg-primary/10":""}`,onClick:()=>{if(D.name==="image"){On(),F(false),H(false),Oa(D.name);return}else if(D.name==="shapes"){Bn(),U(false),H(false),Oa(D.name);return}else if(D.name==="activities"){Oa(D.name),Nn(),F(false),U(false);return}Oa(D.name),F(false),U(false),H(false);},children:jsx(D.icon,{weight:"fill",className:"text-primary text-xl"})},ee))}),G&&jsx(Ra,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:ie.map((D,ee)=>jsx("div",{title:D.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Gr(D),children:jsx(D.icon,{weight:"fill",className:"text-primary text-xl"})},ee))}),O&&jsxs(Ra,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:[Ce.photoFrame&&jsx("div",{title:"Photo frame",onClick:se,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Ce.image&&jsx("div",{title:"Image",onClick:()=>_.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Ce.video&&jsx("div",{title:"Video",onClick:()=>K.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),V&&jsxs(Ra,{type:"single",className:"mx-1 mt-auto mb-11 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl",children:[Ee&&jsx("div",{title:"Flashcard",onClick:()=>Fn(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),Ae.map((D,ee)=>jsx("div",{title:D.label,onClick:()=>Rn(D.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(D.icon,{weight:"fill",className:"text-primary text-xl"})},ee))]})]}),(x.undo||x.redo||x.screenRecord||x.cameraRecord||x.clear)&&jsxs(Ra,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[x.undo&&jsx("button",{value:"undo",onClick:()=>r(Ds()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.redo&&jsx("button",{value:"redo",onClick:()=>r(Rs()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.screenRecord&&jsx("button",{value:"screen-record",onClick:_r,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6279F8] md:block",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl"})}),jsx("button",{title:"Pen Color",onClick:()=>me(true),className:"relative mx-4 my-2 flex cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-white text-xl md:hidden",style:{borderColor:p},children:jsx("div",{className:"h-5 w-5 rounded-full border-2 border-white shadow-sm",style:{backgroundColor:p}})}),jsxs("div",{ref:h,className:"relative md:hidden",children:[jsx("button",{title:"Pen Size",onClick:()=>q(!W),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${W?"bg-primary/10":""}`,children:jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border-2 border-[#FFFFFF80] bg-[#000000CC]",children:jsx("span",{className:"text-xs font-semibold text-white",children:d})})}),W&&jsxs("div",{className:"absolute top-1/2 left-full z-50 ml-2 w-48 -translate-y-1/2 rounded-lg border bg-white p-4 shadow-xl",children:[jsx("p",{className:"mb-3 text-xs font-semibold text-black/40",children:"PEN SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 shrink-0 rounded-full bg-black"}),jsx(Sn,{defaultValue:[12],max:28,min:6,step:1,className:"w-full",value:[d],rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:D=>r(qr(D[0]))}),jsx("div",{className:"h-5 w-5 shrink-0 rounded-full bg-black"})]})]})]}),x.cameraRecord&&jsx("button",{value:"camera-record",onClick:Xr,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6BBB93] md:block",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl"})}),x.clear&&jsx("button",{value:"clear",onClick:()=>jr(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl"})})]})]}),jsx("input",{ref:_,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:lt}),jsx("input",{ref:K,type:"file",accept:"video/*",className:"hidden",onChange:bt}),!o&&y&&t&&jsx(pr,{onClose:()=>E(false),stageRef:t,onRecordingComplete:$o}),B&&jsx(Xf,{onClose:()=>T(false),onRecordingComplete:$o}),f&&jsx(Yf,{editingFlashcard:i,onConfirm:lo,onCancel:()=>r(Ua(false))}),oe&&jsx(Ws,{defaultColor:p,onConfirm:D=>{r(jo(D)),me(false);},onCancel:()=>me(false)})]})},Bw=Fw;var Zl=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let s=ot(go),r=ot(Ci),n=a?r:s,u=ot(nr),p=(ot(g=>g.canvas.slides.find(b=>b.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[d,l]=useState(false),[f,h]=useState(null),[m,v]=useState(null),x=async()=>{if(s.length===0){v({type:"error",message:"No slides to publish"});return}if(!e){v({type:"error",message:"No publish handler provided"});return}l(true),v(null);try{let g=await e(n,u,b=>{h(b);});g.success?v({type:"success",message:g.message}):v({type:"error",message:g.message});}catch(g){v({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),v(null);},3e3);}};return p?null:jsxs("button",{onClick:x,disabled:d||s.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var Hw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:s,onDescriptionChange:r,showPublishButton:n=true,showBackButton:u=true,editableTitle:i=true,editableDescription:c=true,className:p="",rightContent:d,leftContent:l,includeInactiveSlides:f=false})=>{let h=ft(),m=ot(nr),v=ot(Ti),x=e??(v?m.title:"")??"Untitled",g=o??(v?m.description:"")??"Add a description...",[b,w]=useState(false),[I,P]=useState(false),[k,S]=useState(x),[y,E]=useState(g),B=useRef(null),T=useRef(null);useEffect(()=>{S(x);},[x]),useEffect(()=>{E(g);},[g]),useEffect(()=>{b&&B.current&&(B.current.focus(),B.current.select());},[b]),useEffect(()=>{I&&T.current&&(T.current.focus(),T.current.select());},[I]);let G=()=>{i&&w(true);},F=()=>{c&&P(true);},O=()=>{w(false),k.trim()&&k!==x?s?s(k.trim()):h(Li(k.trim())):k.trim()||S(x);},U=()=>{P(false),y.trim()&&y!==g?r?r(y.trim()):h(Si(y.trim())):y.trim()||E(g);},V=oe=>{oe.key==="Enter"?O():oe.key==="Escape"&&(S(x),w(false));},H=oe=>{oe.key==="Enter"?U():oe.key==="Escape"&&(E(g),P(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${p}`,children:[l||jsxs("div",{className:"flex items-center gap-6",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:[b?jsx("input",{ref:B,type:"text",value:k,onChange:oe=>S(oe.target.value),onBlur:O,onKeyDown:V,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:G,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:T,type:"text",value:y,onChange:oe=>E(oe.target.value),onBlur:U,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:F,title:y,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:y})]})]}),d||n&&a&&jsx(Zl,{onPublish:a,includeInactiveSlides:f})]})};var jw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],_w=({colors:e=jw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:s=""})=>{let[r,n]=useState(true),u=Q(ge),i=Q(l=>l.toolbar.penColor),c=Q(l=>l.toolbar.strokeWidth),p=u?.backgroundColor,d=ve();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-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:px-8 2xl:py-6 ${s}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(Sn,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:l=>d(qr(l[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"COLOR"}),jsxs(Ra,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${i===l.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:l.value},onClick:()=>d(jo(l.value))},l.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(jo(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-4 text-xs font-semibold whitespace-nowrap text-[#00000066] 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] lg:h-12 lg:w-12",style:{backgroundColor:p},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(Jn(l.target.value))})})]})}),jsx("div",{className:"absolute -top-4 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2",children:jsx("button",{onClick:()=>n(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{size:20,weight:"bold",className:"text-gray-600"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>n(true),className:"fixed bottom-3 left-1/2 z-50 flex -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var tm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Xw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),ed=e=>{let o=Xw(e);return o.charAt(0).toUpperCase()+o.slice(1)},Pn=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),am=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var om={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var sm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:n,...u},i)=>createElement("svg",{ref:i,...om,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Pn("lucide",s),...!r&&!am(u)&&{"aria-hidden":"true"},...u},[...n.map(([c,p])=>createElement(c,p)),...Array.isArray(r)?r:[r]]));var En=(e,o)=>{let t=forwardRef(({className:a,...s},r)=>createElement(sm,{ref:r,iconNode:o,className:Pn(`lucide-${tm(ed(e))}`,`lucide-${e}`,a),...s}));return t.displayName=ed(e),t};var Zw=[["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"}]],Kr=En("copy",Zw);var Qw=[["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"}]],Wr=En("trash-2",Qw);var im=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:s,onDuplicate:r,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:s,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(Kr,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Wr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var oL=({softDelete:e=false})=>{let o=ft(),t=ot(go),a=ot(ho),s=ot(ki),[r,n]=useState(true),c=(ot(h=>h.canvas.slides.find(m=>m.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),p=()=>{s&&o(jn());},d=h=>{o($n(h));},l=h=>{o(Xn(h));},f=h=>{t.length>1&&o(_n({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:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((h,m)=>jsx(im,{slide:h,index:m,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>l(h.id),onDelete:()=>f(h.id)},h.id))}),jsxs("button",{onClick:p,disabled:!s,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${s?"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:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var rL="SchooplaEditorDB",sL=1,Fa="slides",Ba="metadata",td="schoopla_current_slide_id",um="presentation_metadata",zr=()=>new Promise((e,o)=>{let t=indexedDB.open(rL,sL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Fa)||s.createObjectStore(Fa,{keyPath:"id"}),s.objectStoreNames.contains(Ba)||s.createObjectStore(Ba,{keyPath:"id"});};}),ad=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await zr(),a=o.transaction([Fa],"readwrite").objectStore(Fa);await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);});for(let s of e)await new Promise((r,n)=>{let u=a.add(s);u.onsuccess=()=>r(!0),u.onerror=()=>n(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);}}},od=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await zr(),t=e.transaction([Fa],"readonly").objectStore(Fa);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(n.length>0?n:null);},r.onerror=()=>{e.close(),s(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}}},Dn=async()=>{try{let e=await zr(),o=e.transaction([Fa,Ba],"readwrite"),t=o.objectStore(Fa),a=o.objectStore(Ba);await new Promise((s,r)=>{let n=t.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(td),localStorage.removeItem("schoopla_presentation_metadata"),await Sf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},rd=e=>{try{localStorage.setItem(td,e);}catch(o){console.error("Error saving current slide ID:",o);}},sd=()=>{try{return localStorage.getItem(td)}catch(e){return console.error("Error loading current slide ID:",e),null}},nd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},id=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await zr(),a=o.transaction([Ba],"readwrite").objectStore(Ba);await new Promise((s,r)=>{let n=a.put({id:um,...e});n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},ld=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await zr(),t=e.transaction([Ba],"readonly").objectStore(Ba);return new Promise((a,s)=>{let r=t.get(um);r.onsuccess=()=>{e.close();let n=r.result;if(n){let{id:u,...i}=n;console.log("\u2705 Loaded presentation metadata:",i),a(i);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var nL=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides","canvas/updateSlideThumbnail"],iL=["canvas/clearCanvas"],lL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],dL=nd((e,o)=>{ad(e),rd(o);},500),uL=nd(e=>{id(e);},500),cL=(e,o)=>{ad(e),rd(o);},dd=false,cm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Ol(r).catch(n=>{console.error("Error deleting video blob:",n);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,u=e.getState().canvas.slides.find(i=>i.id===r);u&&u.videos&&u.videos.length>0&&u.videos.forEach(i=>{Ol(i.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,n=e.getState(),i=n.canvas.slides.find(c=>c.id===n.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&&ao(d.id,i.videoBlob,d.thumbnailDataUrl).catch(l=>{console.error("Error saving duplicated video blob:",l);});},0);}let a=o(t),s=e.getState();if(s.canvas.viewerMode)return a;if(t.type&&iL.includes(t.type)){if(!dd){dd=true;try{let{slides:r,currentSlideId:n}=s.canvas;cL(r,n);}finally{setTimeout(()=>{dd=false;},0);}}}else if(t.type&&nL.includes(t.type)){let{slides:r,currentSlideId:n}=s.canvas;dL(r,n);}else if(t.type&&lL.includes(t.type)){let{presentationMetadata:r}=s.canvas;uL(r);}return a});new QueryClient;var mL=configureStore({reducer:{toolbar:zl,canvas:Mi},middleware:e=>e({serializableCheck:false}).concat(cm)}),pL=()=>configureStore({reducer:{toolbar:zl,canvas:Mi},middleware:e=>e({serializableCheck:false})});var hL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2,fileName:r=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:n,quality:a,pixelRatio:s}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=u,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},gL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o;return new Promise((r,n)=>{try{let u=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:u,quality:a,pixelRatio:s});fetch(i).then(c=>c.blob()).then(c=>r(c)).catch(c=>n(c));}catch(u){n(u);}})},xL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:s})};var bL=(e,o,t)=>{let a=t.x-o.x,s=t.y-o.y;if(a===0&&s===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+s*s,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*s)/r)),u=o.x+n*a,i=o.y+n*s;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-i,2))},ud=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,s=e[0],r=e[e.length-1];for(let n=1;n<e.length-1;n++){let u=bL(e[n],s,r);u>t&&(t=u,a=n);}if(t>o){let n=ud(e.slice(0,a+1),o),u=ud(e.slice(a),o);return [...n.slice(0,-1),...u]}return [s,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},mm=(e,o=1.5)=>{if(e.length<=4)return e;let t=vL(e),a=ud(t,o);return yL(a)},pm=(e,o=1.5)=>({...e,points:mm(e.points,o)}),wL=(e,o=1.5)=>e.map(t=>pm(t,o)),LL=(e,o)=>{let t=e.length/2,a=o.length/2,s=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${s}%`}};var SL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var hm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:s=.85}=o;return new Promise((r,n)=>{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 p=document.createElement("canvas");p.width=i,p.height=c;let d=p.getContext("2d");if(!d){n(new Error("Failed to get canvas context"));return}d.drawImage(u,0,0,i,c);let l=SL(e),f=p.toDataURL(l,s);r(f);},u.onerror=n,u.src=e;})};var io=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return a.buffer},_o=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Xo=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:s=1080,imageQuality:r=.85}=o,n=[],u=0;for(let i of e){let c=[],p=[],d=[];for(let l of i.images){let f=l.src;if(t&&f.startsWith("data:"))try{f=await hm(f,{maxWidth:a,maxHeight:s,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=io(f),m=_o(f);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:m};if(l.audioData&&l.audioData.startsWith("data:")){let x=io(l.audioData),g=_o(l.audioData);u+=x.byteLength,v.audioBuffer=x,v.audioMimeType=g;}c.push(v);}}for(let l of i.videos){let f,h;if(l.videoBlob)f=await l.videoBlob.arrayBuffer(),h=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))f=io(l.videoData),h=_o(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}u+=f.byteLength;let m={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:f,mimeType:h};if(l.audioData&&l.audioData.startsWith("data:")){let v=io(l.audioData),x=_o(l.audioData);u+=v.byteLength,m.audioBuffer=v,m.audioMimeType=x;}p.push(m);}for(let l of i.photoFrames){let f={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=io(l.capturedImageUrl),m=_o(l.capturedImageUrl);u+=h.byteLength,f.buffer=h,f.mimeType=m;}if(l.audioData&&l.audioData.startsWith("data:")){let h=io(l.audioData),m=_o(l.audioData);u+=h.byteLength,f.audioBuffer=h,f.audioMimeType=m;}d.push(f);}n.push({...i,images:c,videos:p,photoFrames:d});}return {slides:n,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,s)=>({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,n)=>({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_${s}_image_${n}`,audioFileKey:r.audioBuffer?`slide_${s}_image_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,n)=>({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_${s}_video_${n}`,thumbnailFileKey:`slide_${s}_video_${n}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${s}_video_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,n)=>({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_${s}_photoframe_${n}`:void 0,audioFileKey:r.audioBuffer?`slide_${s}_photoframe_${n}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,s)=>{a.images.forEach((r,n)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Xo(r.mimeType)}`;if(o.append(`slide_${s}_image_${n}`,u,i),r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),p=`${r.id}_audio.${Xo(r.audioMimeType)}`;o.append(`slide_${s}_image_${n}_audio`,c,p);}}),a.videos.forEach((r,n)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Xo(r.mimeType)}`;if(o.append(`slide_${s}_video_${n}`,u,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let c=io(r.thumbnailDataUrl),p=new Blob([c],{type:"image/jpeg"}),d=`${r.id}_thumbnail.jpg`;o.append(`slide_${s}_video_${n}_thumbnail`,p,d);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),p=`${r.id}_audio.${Xo(r.audioMimeType)}`;o.append(`slide_${s}_video_${n}_audio`,c,p);}}),a.photoFrames.forEach((r,n)=>{if(r.buffer&&r.mimeType){let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Xo(r.mimeType)}`;o.append(`slide_${s}_photoframe_${n}`,u,i);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${Xo(r.audioMimeType)}`;o.append(`slide_${s}_photoframe_${n}_audio`,u,i);}});}),o};var AL=()=>{let e=ft(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let s=await od(),r=sd(),n=await ld();if(s&&s.length>0){let u=await Lf(),i=s.map(p=>{if(p.videos&&p.videos.length>0){let d=p.videos.map(l=>{let f=u.get(l.id);if(f){let h=If(f.blob);return {...l,objectUrl:h,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return l});return {...p,videos:d}}return p}),c=r&&i.find(p=>p.id===r)?r:i[0].id;e(co({slides:i,currentSlideId:c}));}e(n?Ii({title:n.title,description:n.description}):Fs(!0));}catch(s){console.error("Error loading persisted slides:",s),e(Fs(true));}finally{t(false);}})();},[e]),{isLoading:o}};var xm=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||""})),bm=new WeakSet,vm=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 ao(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},PL=()=>{let e=ft(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||bm.has(a))return;bm.add(a);let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Dn(),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&&s.find(c=>c.id===r)?r:s[0].id,i=xm(s);e(co({slides:i,currentSlideId:u})),await vm(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Dn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&s.find(c=>c.id===r)?r:s[0].id,i=xm(s);e(co({slides:i,currentSlideId:u})),await vm(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
|
|
6
|
+
This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:l?"none":"auto"}})}),jsx(Group,{y:P+k+T+S+y+B,children:l&&jsxs(Group,{onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),g();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:I,width:e.width-I*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:I,width:e.width-I*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Il.displayName="LongAnswer";var wc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r,onLongPress:n})=>{let{createHandlers:u}=Ne({onLongPress:n});return jsx(Fragment,{children:e.map(i=>jsx(Il,{longAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"longAnswer")},i.id))})};var Za=1600,Qa=900,Cc=3200,kc=1800,Xb=e=>{let o=0,t=0,a=Za,s=Qa;if(!e)return {minX:o,minY:t,maxX:a,maxY:s,width:Za,height:Qa};let r=(i,c,p,d)=>{o=Math.min(o,i),t=Math.min(t,c),a=Math.max(a,i+p),s=Math.max(s,c+d);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let c=i.x||0,p=i.y||0,d=i.scaleX||1,l=i.scaleY||1;for(let f=0;f<i.points.length;f+=2){let h=c+i.points[f]*d,m=p+i.points[f+1]*l;o=Math.min(o,h),t=Math.min(t,m),a=Math.max(a,h),s=Math.max(s,m);}}}),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 n=Math.min(a-o,Cc),u=Math.min(s-t,kc);return o=Math.max(o,a-Cc),t=Math.max(t,s-kc),{minX:o,minY:t,maxX:a,maxY:s,width:n,height:u}},$b=(e,o,t={minX:0,minY:0,maxX:Za,maxY:Qa,width:Za,height:Qa})=>{let a=Math.max(t.width,Za),s=Math.max(t.height,Qa),r=e/o,n=a/s,u,i,c,d=0;if(r>n){i=s,u=Math.round(i*r),c=o/i;}else {u=a,i=Math.round(u/r),c=e/u;let l=s*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}},Tc=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},Yb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:s={enabled:true}}={})=>{let r=ft(),n=qe(),u=Q(L=>L.toolbar.selectedTool),i=Q(ge),c=Q(ho),p=Q(Bs),l=(i?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),f=!!l,h=useCallback(()=>{l&&r(qa(l.id));},[r,l]),m=i?.editingActivity,v=i?.showMcqForm,x=i?.lines||[],g=useRef(null),b=useRef(null),[w,I]=useState(null),[P,k]=useState(""),S=useRef(null),[y,E]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Za,stageHeight:Qa,offsetX:0,offsetY:0,baseWidth:Za,baseHeight:Qa,contentOffsetX:0,contentOffsetY:0}),B=useMemo(()=>Xb(i||null),[c]),[T,G]=useState(null),[F,O]=useState(null),[U,V]=useState(null),[H,oe]=useState(null),[me,W]=useState(null),[q,_]=useState(null),[K,X$1]=useState(null),[te,$]=useState(false),[re,ie]=useState(null),[Ae,Ce]=useState(false),Ee=useRef(null),lt=useRef(null),bt=useRef(null),{debouncedGenerateThumbnail:lo}=eu(c,g);useEffect(()=>{let L=()=>{if(b.current){let M=b.current.getBoundingClientRect(),R=$b(M.width,M.height,B);E(R);}};L();let C=new ResizeObserver(L);return b.current&&C.observe(b.current),window.addEventListener("resize",L),()=>{C.disconnect(),window.removeEventListener("resize",L);}},[B]),useEffect(()=>{if(g.current){let L=g.current.container();L&&(L.style.cursor="");}},[u]);let se=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(C=>C.batchDraw()),!p)try{let M=g.current.toDataURL({pixelRatio:.16666666666666666});k(M),lo();}catch(C){console.warn("Preview generation failed (CORS):",C);}});},[lo,p]),Gr=useRef(c);useEffect(()=>{Gr.current!==c&&(Gr.current=c,se());},[c,se]);let Oa=useRef(null),jr=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),C=Oa.current?.count!==L;!jr.current&&C&&setTimeout(()=>{se();},100),Oa.current={slideId:c,count:L},jr.current=false;},[i,c,se]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{bt.current&&a&&a(bt);},[a]);let{startDrawing:_r,draw:Xr,stopDrawing:$o,setCanvasRef:Rn,tool:Fn,color:Bn,strokeWidth:On,isSketchMode:Nn}=Td(se),D=useRef(new Map),{images:ee,getLoadedImage:ke,imageRefs:xe,handleDragEnd:le,handleImageTransformEnd:fe}=Fd(se),{videos:Pe,videoRefs:_e,handleVideoClick:Yt,handleVideoDragEnd:vt,handleVideoTransformEnd:De}=Nd(se),{multipleChoice:at,handleMcqTransform:At,mcqRefs:Kt,handleDragEnd:Vn}=Bd(se),{trueFalse:qn,handleTrueFalseTransform:$r,trueFalseRefs:dt,handleTrueFalseDragEnd:fa}=Od(se),{shortAnswers:Na,saRefs:Yo,handleShortAnswerDragEnd:ym}=Wd(se),{longAnswers:wm,handleLongAnswerDragEnd:Lm}=zd(se),{fillInTheBlanks:Sm,handleFillInTheBlanksDragEnd:Im,fibRefs:Yr}=pc(se),{transformerRef:ce,boundBoxFunc:Pt}=Yd(),{shapes:Cm,shapeRefs:Jr,isDragging:cd,handleShapeDragEnd:km,handleShapeResizeEnd:Tm}=Hd(se),{texts:Jo,textRefs:ma,handleDragEnd:Mm,handleTransformEnd:Am,handleDoubleClick:Pm,startEditing:Zr,editingTextId:he,editingValue:fd,handleEditingChange:md,finishEditing:Hn}=Kd(se,Ee);useEffect(()=>{t&&t(Zr);},[t,Zr]);let Qr=Q(L=>L.canvas.editingTextId);useEffect(()=>{Qr&&Qr!==he&&Zr(Qr);},[Qr,he,Zr]);let{flashcards:Em,flashcardRefs:es,handleDragEnd:Dm,handleFlashcardTransformEnd:Rm,handleNext:Fm,handlePrevious:Bm}=jd(se),{photoFrames:pd,photoFrameRefs:ts,handleDragEnd:Om,handlePhotoFrameTransformEnd:Nm,startCamera:Vm,capturePhoto:qm,cameraStreams:Hm}=$d(se);useEffect(()=>{if(ce.current){if(he){ce.current.nodes([]),ce.current.getLayer()?.batchDraw();return}if(w&&!Pe.find(M=>M.id===w)?.isPlaying){let M=D.current.get(w)||xe.current.get(w)||_e.current.get(w)||Jr.current.get(w)||ma.current.get(w)||Kt.current.get(w)||es.current.get(w)||ts.current.get(w)||Yo.current.get(w)||dt.current.get(w)||Yr.current.get(w);if(M){let R=M.attrs?.locked;if(M.visible()&&R!==true){ce.current.nodes([M]),ce.current.getLayer()?.batchDraw();return}}}ce.current.nodes([]),ce.current.getLayer()?.batchDraw();}},[w,he,Pe,D,xe,_e,Jr,ma,es,ts,pd,Kt,dt,Yr,ce]);let He=useCallback(L=>{I(L),o?.(L);},[o]),uo=useCallback(()=>{I(null),o?.(null),ce.current&&(ce.current.nodes([]),ce.current.getLayer()?.batchDraw());},[ce,o]),hd=useCallback(L=>i?i.lines?.some(C=>C.id===L)?"line":i.images?.some(C=>C.id===L)?"image":i.videos?.some(C=>C.id===L)?"video":i.shapes?.some(C=>C.id===L)?"shape":i.texts?.some(C=>C.id===L)?"text":i.flashcards?.some(C=>C.id===L)?"flashcard":i.photoFrames?.some(C=>C.id===L)?"photoFrame":i.multipleChoices?.some(C=>C.id===L)?"mcq":i.trueFalses?.some(C=>C.id===L)?"trueFalse":i.shortAnswers?.some(C=>C.id===L)?"shortAnswer":i.LongAnswer?.some(C=>C.id===L)?"longAnswer":i.fillInTheBlanks?.some(C=>C.id===L)?"fillInTheBlanks":null:null,[i]),gd=useCallback((L,C)=>{switch(r(ue()),C){case "line":r(Es(L));break;case "image":r(os(L));break;case "video":r(is(L));break;case "shape":r(us(L));break;case "text":r(cs(L));break;case "flashcard":r(ms(L));break;case "photoFrame":r(hs(L));break;case "mcq":r(xs(L));break;case "trueFalse":r(vs(L));break;case "shortAnswer":r(ws(L));break;case "longAnswer":r(Ss(L));break;case "fillInTheBlanks":r(Cs(L));break}uo(),se();},[r,uo,se]);useEffect(()=>{let L=C=>{if(C.key!=="Delete"||!w||he)return;let M=document.activeElement;if(M instanceof HTMLInputElement||M instanceof HTMLTextAreaElement||M?.getAttribute("contenteditable")==="true")return;C.preventDefault();let we=hd(w);we&&gd(w,we);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[w,he,hd,gd]),useEffect(()=>{let L=ce.current;return ()=>{L&&L.nodes([]);}},[c]),useEffect(()=>{let L=C=>{he&&C.target.tagName!=="TEXTAREA"&&Hn();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[he,Hn]),useEffect(()=>{let L=he||w;if(!L||w&&he){O(null);return}let C=ma.current.get(L),M=g.current;if(!C||!M){O(null);return}let R=M.container().getBoundingClientRect(),we=C.absolutePosition(),be=M.scaleX();O({x:R.left+(we.x+C.width()*be/2)*be+y.offsetX,y:R.top+we.y*be+y.offsetY-70});},[w,he,Jo,ma,y.offsetX,y.offsetY]),useEffect(()=>{if(!he){V(null);return}let L=ma.current.get(he),C=g.current;if(!L||!C){V(null);return}let M=C.container().getBoundingClientRect(),R=L.absolutePosition(),we=C.scaleX();V({top:M.top+R.y*we+y.offsetY,left:M.left+R.x*we+y.offsetX,scale:we});},[he,Jo,ma,y.offsetY,y.offsetX]);let xd=useCallback(L=>{let C=L.target.getClassName(),M=L.target===L.target.getStage(),R=C==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",we=C==="Image",be=C==="Text",ae=C==="Group"||L.target.getParent()?.getClassName()==="Group",ut=C==="Circle"||C==="Star"||C==="RegularPolygon"||C==="Ellipse"||C==="Ring"||C==="Wedge"||C==="Arrow"||C==="Line"||C==="Arc"||C==="Rect"&&L.target.attrs.id,ct=C==="Group";if(M&&!R&&!we&&!be&&!ae&&!ut&&!ct&&uo(),!(u==="pen"||u==="eraser")&&(we||be||R||ae||ut||ct))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 N=Tc(Ue,y);_r(N);}},[u,_r,uo,y]),bd=useCallback(L=>{if(cd)return;let C=L.target.getStage()?.getPointerPosition();if(!C)return;let M=Tc(C,y);Xr(M);},[Xr,cd,y]),vd=useCallback(()=>{$o();},[$o]),Um=useCallback(L=>{le(L,se);},[le,se]),Km=useCallback(L=>{Yt(L),He(L);},[Yt,He]),Et=useCallback((L,C,M)=>{if(L.preventDefault(),!s.enabled)return;let R=L.clientX,we=L.clientY,be=S.current?.offsetHeight||450,ae=S.current?.offsetWidth||450,ut=window.innerHeight,ct=window.innerWidth,Je=R,Ue=we;we+be>ut&&(Ue=we-be),R+ae>ct&&(Je=R-ae),He(C),G({x:Je,y:Ue,elementId:C,elementType:M});},[He,s.enabled]),Va=useRef(null),Zo=useRef(null),yt=useCallback((L,C)=>M=>{if(!s.enabled)return;M.preventDefault();let R=M.changedTouches[0];if(!R)return;let we=R.clientX,be=R.clientY,ae=S.current?.offsetHeight||200,ut=S.current?.offsetWidth||200,ct=window.innerHeight,Je=window.innerWidth,Ue=we,Ze=be;be+ae>ct&&(Ze=be-ae),we+ut>Je&&(Ue=we-ut),He(L),G({x:Ue,y:Ze,elementId:L,elementType:C});},[He,s.enabled]),Wm=useCallback((L,C)=>({onTouchStart:M=>{let R=M.evt.touches[0];Zo.current={x:R.clientX,y:R.clientY},Va.current=setTimeout(()=>{yt(L,C)(M.evt);},500);},onTouchMove:M=>{if(!Zo.current)return;let R=M.evt.touches[0],we=Math.abs(R.clientX-Zo.current.x),be=Math.abs(R.clientY-Zo.current.y);(we>10||be>10)&&Va.current&&(clearTimeout(Va.current),Va.current=null);},onTouchEnd:()=>{Va.current&&(clearTimeout(Va.current),Va.current=null),Zo.current=null;}}),[yt]),yd=useCallback(L=>{r(or(L)),r(ga(true));},[r]),zm=useCallback(L=>{r(Qo(L)),r(Ua(true));},[r]),Gm=useCallback((L,C)=>{if(!T)return;let{elementId:M,elementType:R}=T;switch(L){case "order":if(C){let A=C.target.getBoundingClientRect();oe({x:A.right+5,y:A.top,type:"order"});}break;case "lock":if(C){let A=C.target.getBoundingClientRect();oe({x:A.right+5,y:A.top,type:"lock"});}break;case "link":if(G(null),R==="line")break;let we=i?R==="image"?i.images.find(A=>A.id===M):i.videos.find(A=>A.id===M):null;W({type:"link",defaultValue:we?.link||""});break;case "voice":if(G(null),R==="line")break;let be=i?R==="image"?i.images.find(A=>A.id===M):R==="video"?i.videos.find(A=>A.id===M):R==="text"?i.texts.find(A=>A.id===M):R==="flashcard"?i.flashcards.find(A=>A.id===M):R==="photoFrame"?i.photoFrames.find(A=>A.id===M):R==="mcq"?i.multipleChoices.find(A=>A.id===M):R==="fillInTheBlanks"?i.fillInTheBlanks.find(A=>A.id===M):R==="longAnswer"?i.LongAnswer.find(A=>A.id===M):R==="shortAnswer"?i.shortAnswers.find(A=>A.id===M):R==="trueFalse"?i.trueFalses.find(A=>A.id===M):R==="shape"?i.shapes.find(A=>A.id===M):null:null;ie({elementId:M,elementType:R,existingAudio:be?.audioData});break;case "edit":G(null);let ae=null;R==="mcq"?ae=i?.multipleChoices.find(A=>A.id===M):R==="trueFalse"?ae=i?.trueFalses.find(A=>A.id===M):R==="shortAnswer"?ae=i?.shortAnswers.find(A=>A.id===M):R==="longAnswer"?ae=i?.LongAnswer.find(A=>A.id===M):R==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(A=>A.id===M)),ae&&yd(ae);break;case "editFlashcard":G(null);let ut=i?.flashcards.find(A=>A.id===M);ut&&zm(ut);break;case "color":G(null);let ct=i?.shapes.find(A=>A.id===M);_({elementId:M,elementType:"shape",defaultColor:ct?.color||"#096B76"});break;case "crop":if(G(null),R==="image"){let A=i?.images.find(Zm=>Zm.id===M);A&&X$1({elementId:M,imageSrc:A.src});}break;case "draw":G(null),R==="image"?r(ni(M)):R==="photoFrame"&&r(li(M));break;case "duplicate":r(ue()),R==="line"?r(yi(M)):R==="image"?r(rs(M)):R==="video"?r(ls(M)):R==="shape"?r(ds(M)):R==="text"?r(fs(M)):R==="flashcard"?r(ps(M)):R==="photoFrame"?r(gs(M)):R==="mcq"?r(bs(M)):R==="trueFalse"?r(ys(M)):R==="shortAnswer"?r(Ls(M)):R==="fillInTheBlanks"?r(ks(M)):R==="longAnswer"&&r(Is(M)),se();break;case "infinite-clone":r(ue());let Je=5;for(let A=0;A<Je;A++)R==="image"?r(rs(M)):R==="video"?r(ls(M)):R==="shape"?r(ds(M)):R==="text"?r(fs(M)):R==="flashcard"?r(ps(M)):R==="photoFrame"?r(gs(M)):R==="mcq"?r(bs(M)):R==="trueFalse"?r(ys(M)):R==="shortAnswer"?r(Ls(M)):R==="fillInTheBlanks"?r(ks(M)):R==="longAnswer"&&r(Is(M));se();break;case "make-response":if(G(null),R==="line")break;let Ue=`#response-${M}`;r(ue()),r(Ts({id:M,type:R,link:Ue})),(i?R==="image"?i.images.find(A=>A.id===M):R==="video"?i.videos.find(A=>A.id===M):R==="shape"?i.shapes.find(A=>A.id===M):R==="flashcard"?i.flashcards.find(A=>A.id===M):R==="photoFrame"?i.photoFrames.find(A=>A.id===M):i.multipleChoices.find(A=>A.id===M):null)?.altText||r(Ms({id:M,type:R,altText:"Interactive response area"})),se(),console.log(`Element ${M} marked as interactive response area`);break;case "accessibility":if(G(null),R==="line")break;let N=i?R==="image"?i.images.find(A=>A.id===M):R==="video"?i.videos.find(A=>A.id===M):R==="shape"?i.shapes.find(A=>A.id===M):null:null;W({type:"altText",defaultValue:N?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),G(null),Ce(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ue()),R==="line"?r(Es(M)):R==="image"?r(os(M)):R==="video"?r(is(M)):R==="shape"?r(us(M)):R==="text"?r(cs(M)):R==="flashcard"?r(ms(M)):R==="photoFrame"?r(hs(M)):R==="mcq"?r(xs(M)):R==="trueFalse"?r(vs(M)):R==="shortAnswer"?r(ws(M)):R==="longAnswer"?r(Ss(M)):R==="fillInTheBlanks"&&r(Cs(M)),uo(),se();break}},[T,r,se,uo,i,yd]),jm=useCallback(()=>{G(null),oe(null);},[]),Un=useCallback(L=>{if(!T)return;let{elementId:C,elementType:M}=T;switch(r(ue()),L){case "bring-to-front":M!=="line"&&r(gi({id:C,type:M}));break;case "send-to-back":M!=="line"&&r(xi({id:C,type:M}));break;case "lock":case "unlock":M!=="line"&&r(bi({id:C,type:M}));break}se(),G(null),oe(null);},[T,r,se]),_m=useCallback(L=>{if(!T||!me)return;let{elementId:C,elementType:M}=T;r(ue()),me.type==="link"&&M!=="line"?r(Ts({id:C,type:M,link:L})):me.type==="altText"&&M!=="line"&&r(Ms({id:C,type:M,altText:L})),se(),W(null);},[T,me,r,se]),Xm=useCallback(L=>{if(!re)return;let{elementId:C,elementType:M}=re;r(ue()),r(As({id:C,type:M,audioData:L})),se(),ie(null);},[re,r,se]),$m=useCallback(()=>{if(!re)return;let{elementId:L,elementType:C}=re;r(ue()),r(As({id:L,type:C,audioData:""})),se();},[re,r,se]),Ym=useCallback(L=>{if(!q)return;let{elementId:C}=q;r(ue()),r(mo({id:C,color:L})),se(),_(null);},[q,r,se]),Jm=useCallback(L=>{if(!K)return;let{elementId:C}=K;r(ue()),r(fo({id:C,src:L})),se(),X$1(null);},[K,r,se]);return jsxs("div",{ref:b,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Dd,{ref:L=>{if(lt.current=L,Rn(L),L){let C=L.getCanvasElement();C&&(bt.current=C,a&&a(bt));}},width:y.baseWidth,height:y.baseHeight,tool:Fn,color:Bn,strokeWidth:On/y.scale,isSketchMode:Nn,xOffset:y.contentOffsetX,yOffset:y.contentOffsetY-y.offsetY/y.scale,style:{width:y.stageWidth,height:y.stageHeight}}),jsxs(Stage,{ref:g,width:y.stageWidth,height:y.stageHeight,scaleX:y.scaleX,scaleY:y.scaleY,x:y.offsetX,y:0,onMouseDown:xd,onMouseMove:bd,onMouseUp:vd,onTouchStart:xd,onTouchMove:bd,onTouchEnd:vd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:y.baseWidth,height:y.stageHeight/y.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-y.contentOffsetX,y:y.offsetY/y.scale-y.contentOffsetY,children:(()=>{let L=[];return x.forEach((C,M)=>{L.push({type:"line",timestamp:C.timestamp||M,element:{...C,id:C.id??`line-${M}`},index:M});}),Cm.forEach(C=>{L.push({type:"shape",timestamp:C.timestamp||0,element:C});}),ee.forEach(C=>{L.push({type:"image",timestamp:C.timestamp||0,element:C});}),Pe.forEach(C=>{L.push({type:"video",timestamp:C.timestamp||0,element:C});}),Jo.forEach(C=>{L.push({type:"text",timestamp:C.timestamp||0,element:C});}),Em.forEach(C=>{L.push({type:"flashcard",timestamp:C.timestamp||0,element:C});}),pd.forEach(C=>{L.push({type:"photoFrame",timestamp:C.timestamp||0,element:C});}),at.forEach(C=>{L.push({type:"mcq",timestamp:C.timestamp||0,element:C});}),qn.forEach(C=>{L.push({type:"trueFalse",timestamp:C.timestamp||0,element:C});}),Na.forEach(C=>{L.push({type:"shortAnswer",timestamp:C.timestamp||0,element:C});}),wm.forEach(C=>{L.push({type:"longAnswer",timestamp:C.timestamp||0,element:C});}),Sm.forEach(C=>{L.push({type:"fillInTheBlanks",timestamp:C.timestamp||0,element:C});}),L.sort((C,M)=>C.timestamp-M.timestamp),L.map((C,M)=>{let R=`${C.type}-${"id"in C.element&&C.element.id||C.index||M}`,we="id"in C.element?C.element.id:void 0,be=we&&w===we;switch(C.type){case "line":let ae=C.element,ut=C.index||0,ct=ae.tool==="eraser",Je=ae.isSketch&&ae.tool==="pen",Ue=ae.isSketch&&ct,Ze=ae.id||`line-${ut}`;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:Je||Ue?void 0:ae.color,strokeWidth:Je||Ue?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Je||Ue?ct?"black":ae.color:void 0,closed:Je||Ue,tension:0,globalCompositeOperation:ct?"destination-out":"source-over",listening:true,onClick:()=>{r(ue()),r(as(ut));},onTap:()=>{r(ue()),r(as(ut));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:N=>{let A=N.target.getStage();A&&(A.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:N=>{let A=N.target.getStage();A&&(A.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`);}})},R):jsxs(ye__default.Fragment,{children:[jsx(Group,{id:Ze,ref:N=>{N?D.current.set(Ze,N):D.current.delete(Ze);},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:",Ze),He(Ze));},onTap:()=>{u==="select"&&(console.log("Line tapped:",Ze),He(Ze));},onDragEnd:N=>{r(ue()),r(Ps({id:Ze,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),se();},onTransformEnd:N=>{r(ue()),r(Ps({id:Ze,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),se();},onMouseEnter:N=>{if(u==="select"){let A=N.target.getStage();A&&(A.container().style.cursor="move");}},onMouseLeave:N=>{if(u==="select"){let A=N.target.getStage();A&&(A.container().style.cursor="default");}},onContextMenu:N=>{let A=N.evt;A.preventDefault(),Et(A,Ze,"line");},...Wm(Ze,"line"),children:jsx(Line,{points:ae.points||[],stroke:Je||Ue?void 0:ae.color,strokeWidth:Je||Ue?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Je||Ue?ct?"black":ae.color:void 0,closed:Je||Ue,tension:0,globalCompositeOperation:ct?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=D.current.get(w);console.log("Line Transformer - selectedId:",w,"node found:",!!A),A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:Pt,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"]})]},R);case "shape":return jsxs(ye__default.Fragment,{children:[jsx(qi,{onSelect:He,shapes:[C.element],shapeRefs:Jr,handleShapeDragEnd:km,handleShapeResizeEnd:Tm,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Jr.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "image":return jsxs(ye__default.Fragment,{children:[jsx(Bi,{images:[C.element],getLoadedImage:ke,imageRefs:xe,onDragEnd:Um,onTransform:fe,onSelect:He,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=xe.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "video":return jsxs(ye__default.Fragment,{children:[jsx(Vi,{videos:[C.element],selectedId:w,videoRefs:_e,onVideoClick:Km,onDragEnd:vt,onTransformEnd:De,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=_e.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "text":return jsxs(ye__default.Fragment,{children:[jsx(fu,{texts:[C.element],textRefs:ma,onDragEnd:Mm,onTransformEnd:Am,onSelect:He,onContextMenu:Et,onLongPress:yt,onDoubleClick:Pm,editingTextId:he,editingValue:fd,onEditingChange:md}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=ma.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "flashcard":return jsxs(ye__default.Fragment,{children:[jsx(Ki,{flashcards:[C.element],flashcardRefs:es,selectedId:w,onDragEnd:Dm,onTransform:Rm,onSelect:He,onNext:Fm,onPrevious:Bm,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=es.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "photoFrame":return jsxs(ye__default.Fragment,{children:[jsx(Xi,{photoFrames:[C.element],photoFrameRefs:ts,selectedId:w,onDragEnd:Om,onTransform:Nm,onSelect:He,onStartCamera:Vm,onCapture:qm,cameraStreams:Hm,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=ts.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "mcq":return jsxs(ye__default.Fragment,{children:[jsx(Wu,{handleMcqTransform:At,multipleChoice:[C.element],handleSelect:He,mcqRefs:Kt,handleDragEnd:Vn,onContextMenu:Et,onLongPress:yt}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Kt.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "trueFalse":return jsxs(ye__default.Fragment,{children:[jsx(ju,{trueFalses:[C.element],handleTrueFalseTransform:$r,handleSelect:He,trueFalseRefs:dt,onContextMenu:Et,onLongPress:yt,handleDragEnd:fa}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=dt.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "shortAnswer":return jsxs(ye__default.Fragment,{children:[jsx(mc,{shortAnswers:[C.element],handleSelect:He,handleTransform:At,saRefs:Yo,onContextMenu:Et,onLongPress:yt,handleDragEnd:ym}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Yo.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "longAnswer":return jsxs(ye__default.Fragment,{children:[jsx(wc,{longAnswer:[C.element],handleSelect:He,handleTransform:At,saRefs:Yo,onContextMenu:Et,onLongPress:yt,handleDragEnd:Lm}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Yo.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);case "fillInTheBlanks":return jsxs(ye__default.Fragment,{children:[jsx(vc,{fillInTheBlanks:[C.element],handleSelect:He,handleTransform:At,onContextMenu:Et,onLongPress:yt,handleDragEnd:Im,fibRefs:Yr}),be&&!he&&w&&jsx(Transformer,{ref:N=>{if(N&&ce.current!==N){ce.current=N;let A=Yr.current.get(w);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:Pt,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"]})]},R);default:return null}})})()})]}),T&&jsx(Cu,{menuRef:S,x:T.x,y:T.y,type:T.elementType,onAction:Gm,onClose:jm,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}),H&&T&&jsx(ku,{x:H.x,y:H.y,items:H.type==="order"?[{label:"Bring to Front",onClick:()=>Un("bring-to-front")},{label:"Send to Back",onClick:()=>Un("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:()=>Un(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:()=>oe(null)}),me&&jsx(Au,{title:me.type==="link"?"Add Link":"Add Alt Text",label:me.type==="link"?"URL":"Alternative Text",placeholder:me.type==="link"?"https://example.com":"Describe this image/video",defaultValue:me.defaultValue,onSave:_m,onClose:()=>W(null)}),q&&jsx(Ws,{defaultColor:q.defaultColor,onConfirm:Ym,onCancel:()=>_(null)}),K&&jsx(Ru,{imageSrc:K.imageSrc,onConfirm:Jm,onCancel:()=>X$1(null)}),te&&jsx(pr,{onClose:()=>$(false),stageRef:g}),re&&jsx(Nu,{elementId:re.elementId,elementType:re.elementType,existingAudio:re.existingAudio,onSave:Xm,onDelete:$m,onClose:()=>ie(null)}),Ae&&jsx(Hu,{selectedElementId:w||void 0,onClose:()=>Ce(false),onSelectElement:L=>{He(L),Ce(false);}}),i?.images.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.videos.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.shapes?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.texts?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),i?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:y.scale,offsetX:y.offsetX,offsetY:y.offsetY},`audio-${L.id}`)),v&&jsx(oc,{editElement:m}),F&&(()=>{let L=he||w;if(!L)return null;let C=Jo.find(M=>M.id===L);return C?jsx(ic,{text:C,position:F}):null})(),U&&he&&(()=>{let L=Jo.find(C=>C.id===he);return L?jsx(dc,{text:L,editingValue:fd,onEditingChange:md,onFinish:Hn,position:{top:U.top,left:U.left},scale:U.scale,textareaRef:Ee},he):null})(),f&&n&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:l?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:h})}),jsx("button",{onClick:h,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"})})]}),n)]})},Jb=Yb;function Cl(e,[o,t]){return Math.min(t,Math.max(o,e))}function et(e,o,{checkForDefaultPrevented:t=true}={}){return function(s){if(e?.(s),t===false||!s.defaultPrevented)return o?.(s)}}function Mc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Or(...e){return o=>{let t=false,a=e.map(s=>{let r=Mc(s,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let s=0;s<a.length;s++){let r=a[s];typeof r=="function"?r():Mc(e[s],null);}}}}function Ht(...e){return ye.useCallback(Or(...e),e)}function Aa(e,o=[]){let t=[];function a(r,n){let u=ye.createContext(n),i=t.length;t=[...t,n];let c=d=>{let{scope:l,children:f,...h}=d,m=l?.[e]?.[i]||u,v=ye.useMemo(()=>h,Object.values(h));return jsx(m.Provider,{value:v,children:f})};c.displayName=r+"Provider";function p(d,l){let f=l?.[e]?.[i]||u,h=ye.useContext(f);if(h)return h;if(n!==void 0)return n;throw new Error(`\`${d}\` must be used within \`${r}\``)}return [c,p]}let s=()=>{let r=t.map(n=>ye.createContext(n));return function(u){let i=u?.[e]||r;return ye.useMemo(()=>({[`__scope${e}`]:{...u,[e]:i}}),[u,i])}};return s.scopeName=e,[a,ev(s,...o)]}function ev(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(r){let n=a.reduce((u,{useScope:i,scopeName:c})=>{let d=i(r)[`__scope${c}`];return {...u,...d}},{});return ye.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var qo=globalThis?.document?ye.useLayoutEffect:()=>{};var tv=ye[" useInsertionEffect ".trim().toString()]||qo;function sa({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[s,r,n]=av({defaultProp:o,onChange:t}),u=e!==void 0,i=u?e:s;{let p=ye.useRef(e!==void 0);ye.useEffect(()=>{let d=p.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.`),p.current=u;},[u,a]);}let c=ye.useCallback(p=>{if(u){let d=ov(p)?p(e):p;d!==e&&n.current?.(d);}else r(p);},[u,e,r,n]);return [i,c]}function av({defaultProp:e,onChange:o}){let[t,a]=ye.useState(e),s=ye.useRef(t),r=ye.useRef(o);return tv(()=>{r.current=o;},[o]),ye.useEffect(()=>{s.current!==t&&(r.current?.(t),s.current=t);},[t,s]),[t,a,r]}function ov(e){return typeof e=="function"}var rv=ye.createContext(void 0);function Ho(e){let o=ye.useContext(rv);return e||o||"ltr"}function Ec(e){let o=ye.useRef({value:e,previous:e});return ye.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Rc(e){let[o,t]=ye.useState(void 0);return qo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;let r=s[0],n,u;if("borderBoxSize"in r){let i=r.borderBoxSize,c=Array.isArray(i)?i[0]:i;n=c.inlineSize,u=c.blockSize;}else n=e.offsetWidth,u=e.offsetHeight;t({width:n,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function Bc(e){let o=sv(e),t=ye.forwardRef((a,s)=>{let{children:r,...n}=a,u=ye.Children.toArray(r),i=u.find(iv);if(i){let c=i.props.children,p=u.map(d=>d===i?ye.Children.count(c)>1?ye.Children.only(null):ye.isValidElement(c)?c.props.children:null:d);return jsx(o,{...n,ref:s,children:ye.isValidElement(c)?ye.cloneElement(c,void 0,p):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function sv(e){let o=ye.forwardRef((t,a)=>{let{children:s,...r}=t;if(ye.isValidElement(s)){let n=dv(s),u=lv(r,s.props);return s.type!==ye.Fragment&&(u.ref=a?Or(a,n):n),ye.cloneElement(s,u)}return ye.Children.count(s)>1?ye.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var nv=Symbol("radix.slottable");function iv(e){return ye.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===nv}function lv(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...u)=>{let i=r(...u);return s(...u),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function dv(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var fv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gt=fv.reduce((e,o)=>{let t=Bc(`Primitive.${o}`),a=ye.forwardRef((s,r)=>{let{asChild:n,...u}=s,i=n?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 kl(e){let o=mv(e),t=ye.forwardRef((a,s)=>{let{children:r,...n}=a,u=ye.Children.toArray(r),i=u.find(hv);if(i){let c=i.props.children,p=u.map(d=>d===i?ye.Children.count(c)>1?ye.Children.only(null):ye.isValidElement(c)?c.props.children:null:d);return jsx(o,{...n,ref:s,children:ye.isValidElement(c)?ye.cloneElement(c,void 0,p):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function mv(e){let o=ye.forwardRef((t,a)=>{let{children:s,...r}=t;if(ye.isValidElement(s)){let n=xv(s),u=gv(r,s.props);return s.type!==ye.Fragment&&(u.ref=a?Or(a,n):n),ye.cloneElement(s,u)}return ye.Children.count(s)>1?ye.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var pv=Symbol("radix.slottable");function hv(e){return ye.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===pv}function gv(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...u)=>{let i=r(...u);return s(...u),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function xv(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 bn(e){let o=e+"CollectionProvider",[t,a]=Aa(o),[s,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=m=>{let{scope:v,children:x}=m,g=ye__default.useRef(null),b=ye__default.useRef(new Map).current;return jsx(s,{scope:v,itemMap:b,collectionRef:g,children:x})};n.displayName=o;let u=e+"CollectionSlot",i=kl(u),c=ye__default.forwardRef((m,v)=>{let{scope:x,children:g}=m,b=r(u,x),w=Ht(v,b.collectionRef);return jsx(i,{ref:w,children:g})});c.displayName=u;let p=e+"CollectionItemSlot",d="data-radix-collection-item",l=kl(p),f=ye__default.forwardRef((m,v)=>{let{scope:x,children:g,...b}=m,w=ye__default.useRef(null),I=Ht(v,w),P=r(p,x);return ye__default.useEffect(()=>(P.itemMap.set(w,{ref:w,...b}),()=>void P.itemMap.delete(w))),jsx(l,{[d]:"",ref:I,children:g})});f.displayName=p;function h(m){let v=r(e+"CollectionConsumer",m);return ye__default.useCallback(()=>{let g=v.collectionRef.current;if(!g)return [];let b=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(v.itemMap.values()).sort((P,k)=>b.indexOf(P.ref.current)-b.indexOf(k.ref.current))},[v.collectionRef,v.itemMap])}return [{Provider:n,Slot:c,ItemSlot:f},h,a]}var Vc=["PageUp","PageDown"],qc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Hc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Uo="Slider",[Ml,vv,yv]=bn(Uo),[Uc]=Aa(Uo,[yv]),[wv,vn]=Uc(Uo),Kc=ye.forwardRef((e,o)=>{let{name:t,min:a=0,max:s=100,step:r=1,orientation:n="horizontal",disabled:u=false,minStepsBetweenThumbs:i=0,defaultValue:c=[a],value:p,onValueChange:d=()=>{},onValueCommit:l=()=>{},inverted:f=false,form:h,...m}=e,v=ye.useRef(new Set),x=ye.useRef(0),b=n==="horizontal"?Lv:Sv,[w=[],I]=sa({prop:p,defaultProp:c,onChange:B=>{[...v.current][x.current]?.focus(),d(B);}}),P=ye.useRef(w);function k(B){let T=Mv(w,B);E(B,T);}function S(B){E(B,x.current);}function y(){let B=P.current[x.current];w[x.current]!==B&&l(w);}function E(B,T,{commit:G}={commit:false}){let F=Dv(r),O=Rv(Math.round((B-a)/r)*r+a,F),U=Cl(O,[a,s]);I((V=[])=>{let H=kv(V,U,T);if(Ev(H,i*r)){x.current=H.indexOf(U);let oe=String(H)!==String(V);return oe&&G&&l(H),oe?H:V}else return V});}return jsx(wv,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:s,valueIndexToChangeRef:x,thumbs:v.current,values:w,orientation:n,form:h,children:jsx(Ml.Provider,{scope:e.__scopeSlider,children:jsx(Ml.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":u,"data-disabled":u?"":void 0,...m,ref:o,onPointerDown:et(m.onPointerDown,()=>{u||(P.current=w);}),min:a,max:s,inverted:f,onSlideStart:u?void 0:k,onSlideMove:u?void 0:S,onSlideEnd:u?void 0:y,onHomeKeyDown:()=>!u&&E(a,0,{commit:true}),onEndKeyDown:()=>!u&&E(s,w.length-1,{commit:true}),onStepKeyDown:({event:B,direction:T})=>{if(!u){let O=Vc.includes(B.key)||B.shiftKey&&qc.includes(B.key)?10:1,U=x.current,V=w[U],H=r*O*T;E(V+H,U,{commit:true});}}})})})})});Kc.displayName=Uo;var[Wc,zc]=Uc(Uo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Lv=ye.forwardRef((e,o)=>{let{min:t,max:a,dir:s,inverted:r,onSlideStart:n,onSlideMove:u,onSlideEnd:i,onStepKeyDown:c,...p}=e,[d,l]=ye.useState(null),f=Ht(o,b=>l(b)),h=ye.useRef(void 0),m=Ho(s),v=m==="ltr",x=v&&!r||!v&&r;function g(b){let w=h.current||d.getBoundingClientRect(),I=[0,w.width],k=El(I,x?[t,a]:[a,t]);return h.current=w,k(b-w.left)}return jsx(Wc,{scope:e.__scopeSlider,startEdge:x?"left":"right",endEdge:x?"right":"left",direction:x?1:-1,size:"width",children:jsx(Gc,{dir:m,"data-orientation":"horizontal",...p,ref:f,style:{...p.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let w=g(b.clientX);n?.(w);},onSlideMove:b=>{let w=g(b.clientX);u?.(w);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:b=>{let I=Hc[x?"from-left":"from-right"].includes(b.key);c?.({event:b,direction:I?-1:1});}})})}),Sv=ye.forwardRef((e,o)=>{let{min:t,max:a,inverted:s,onSlideStart:r,onSlideMove:n,onSlideEnd:u,onStepKeyDown:i,...c}=e,p=ye.useRef(null),d=Ht(o,p),l=ye.useRef(void 0),f=!s;function h(m){let v=l.current||p.current.getBoundingClientRect(),x=[0,v.height],b=El(x,f?[a,t]:[t,a]);return l.current=v,b(m-v.top)}return jsx(Wc,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(Gc,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:m=>{let v=h(m.clientY);r?.(v);},onSlideMove:m=>{let v=h(m.clientY);n?.(v);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:m=>{let x=Hc[f?"from-bottom":"from-top"].includes(m.key);i?.({event:m,direction:x?-1:1});}})})}),Gc=ye.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:s,onSlideEnd:r,onHomeKeyDown:n,onEndKeyDown:u,onStepKeyDown:i,...c}=e,p=vn(Uo,t);return jsx(gt.span,{...c,ref:o,onKeyDown:et(e.onKeyDown,d=>{d.key==="Home"?(n(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):Vc.concat(qc).includes(d.key)&&(i(d),d.preventDefault());}),onPointerDown:et(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),p.thumbs.has(l)?l.focus():a(d);}),onPointerMove:et(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&s(d);}),onPointerUp:et(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),r(d));})})}),jc="SliderTrack",_c=ye.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=vn(jc,t);return jsx(gt.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...a,ref:o})});_c.displayName=jc;var Al="SliderRange",Xc=ye.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=vn(Al,t),r=zc(Al,t),n=ye.useRef(null),u=Ht(o,n),i=s.values.length,c=s.values.map(l=>Jc(l,s.min,s.max)),p=i>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(gt.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...a,ref:u,style:{...e.style,[r.startEdge]:p+"%",[r.endEdge]:d+"%"}})});Xc.displayName=Al;var Pl="SliderThumb",$c=ye.forwardRef((e,o)=>{let t=vv(e.__scopeSlider),[a,s]=ye.useState(null),r=Ht(o,u=>s(u)),n=ye.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(Iv,{...e,ref:r,index:n})}),Iv=ye.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:s,...r}=e,n=vn(Pl,t),u=zc(Pl,t),[i,c]=ye.useState(null),p=Ht(o,g=>c(g)),d=i?n.form||!!i.closest("form"):true,l=Rc(i),f=n.values[a],h=f===void 0?0:Jc(f,n.min,n.max),m=Tv(a,n.values.length),v=l?.[u.size],x=v?Av(v,h,u.direction):0;return ye.useEffect(()=>{if(i)return n.thumbs.add(i),()=>{n.thumbs.delete(i);}},[i,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${x}px)`},children:[jsx(Ml.ItemSlot,{scope:e.__scopeSlider,children:jsx(gt.span,{role:"slider","aria-label":e["aria-label"]||m,"aria-valuemin":n.min,"aria-valuenow":f,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...r,ref:p,style:f===void 0?{display:"none"}:e.style,onFocus:et(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),d&&jsx(Yc,{name:s??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:f},a)]})});$c.displayName=Pl;var Cv="RadioBubbleInput",Yc=ye.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let s=ye.useRef(null),r=Ht(s,a),n=Ec(o);return ye.useEffect(()=>{let u=s.current;if(!u)return;let i=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(i,"value").set;if(n!==o&&p){let d=new Event("input",{bubbles:true});p.call(u,o),u.dispatchEvent(d);}},[n,o]),jsx(gt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});Yc.displayName=Cv;function kv(e=[],o,t){let a=[...e];return a[t]=o,a.sort((s,r)=>s-r)}function Jc(e,o,t){let r=100/(t-o)*(e-o);return Cl(r,[0,100])}function Tv(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Mv(e,o){if(e.length===1)return 0;let t=e.map(s=>Math.abs(s-o)),a=Math.min(...t);return t.indexOf(a)}function Av(e,o,t){let a=e/2,r=El([0,50],[0,a]);return (a-r(o)*t)*t}function Pv(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Ev(e,o){if(o>0){let t=Pv(e);return Math.min(...t)>=o}return true}function El(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 Dv(e){return (String(e).split(".")[1]||"").length}function Rv(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Zc=Kc,Qc=_c,ef=Xc,tf=$c;function af(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(o=0;o<s;o++)e[o]&&(t=af(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function yn(){for(var e,o,t=0,a="",s=arguments.length;t<s;t++)(e=arguments[t])&&(o=af(e))&&(a&&(a+=" "),a+=o);return a}var Bv=(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},Ov=(e,o)=>({classGroupId:e,validator:o}),lf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var of=[],Nv="arbitrary..",Vv=e=>{let o=Hv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return qv(n);let u=n.split("-"),i=u[0]===""&&u.length>1?1:0;return df(u,i,o)},getConflictingClassGroupIds:(n,u)=>{if(u){let i=a[n],c=t[n];return i?c?Bv(c,i):i:c||of}return t[n]||of}}},df=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let s=e[o],r=t.nextPart.get(s);if(r){let c=df(e,o+1,r);if(c)return c}let n=t.validators;if(n===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),i=n.length;for(let c=0;c<i;c++){let p=n[c];if(p.validator(u))return p.classGroupId}},qv=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?Nv+a:void 0})(),Hv=e=>{let{theme:o,classGroups:t}=e;return Uv(t,o)},Uv=(e,o)=>{let t=lf();for(let a in e){let s=e[a];Fl(s,t,a,o);}return t},Fl=(e,o,t,a)=>{let s=e.length;for(let r=0;r<s;r++){let n=e[r];Kv(n,o,t,a);}},Kv=(e,o,t,a)=>{if(typeof e=="string"){Wv(e,o,t);return}if(typeof e=="function"){zv(e,o,t,a);return}Gv(e,o,t,a);},Wv=(e,o,t)=>{let a=e===""?o:uf(o,e);a.classGroupId=t;},zv=(e,o,t,a)=>{if(jv(e)){Fl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Ov(t,e));},Gv=(e,o,t,a)=>{let s=Object.entries(e),r=s.length;for(let n=0;n<r;n++){let[u,i]=s[n];Fl(i,uf(o,u),t,a);}},uf=(e,o)=>{let t=e,a=o.split("-"),s=a.length;for(let r=0;r<s;r++){let n=a[r],u=t.nextPart.get(n);u||(u=lf(),t.nextPart.set(n,u)),t=u;}return t},jv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,_v=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),s=(r,n)=>{t[r]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let n=t[r];if(n!==void 0)return n;if((n=a[r])!==void 0)return s(r,n),n},set(r,n){r in t?t[r]=n:s(r,n);}}};var Xv=[],rf=(e,o,t,a,s)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:s}),$v=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=s=>{let r=[],n=0,u=0,i=0,c,p=s.length;for(let m=0;m<p;m++){let v=s[m];if(n===0&&u===0){if(v===":"){r.push(s.slice(i,m)),i=m+1;continue}if(v==="/"){c=m;continue}}v==="["?n++:v==="]"?n--:v==="("?u++:v===")"&&u--;}let d=r.length===0?s:s.slice(i),l=d,f=false;d.endsWith("!")?(l=d.slice(0,-1),f=true):d.startsWith("!")&&(l=d.slice(1),f=true);let h=c&&c>i?c-i:void 0;return rf(r,f,l,h)};if(o){let s=o+":",r=a;a=n=>n.startsWith(s)?r(n.slice(s.length)):rf(Xv,false,n,void 0,true);}if(t){let s=a;a=r=>t({className:r,parseClassName:s});}return a},Yv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],s=[];for(let r=0;r<t.length;r++){let n=t[r],u=n[0]==="[",i=o.has(n);u||i?(s.length>0&&(s.sort(),a.push(...s),s=[]),a.push(n)):s.push(n);}return s.length>0&&(s.sort(),a.push(...s)),a}},Jv=e=>({cache:_v(e.cacheSize),parseClassName:$v(e),sortModifiers:Yv(e),...Vv(e)}),Zv=/\s+/,Qv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:s,sortModifiers:r}=o,n=[],u=e.trim().split(Zv),i="";for(let c=u.length-1;c>=0;c-=1){let p=u[c],{isExternal:d,modifiers:l,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:m}=t(p);if(d){i=p+(i.length>0?" "+i:i);continue}let v=!!m,x=a(v?h.substring(0,m):h);if(!x){if(!v){i=p+(i.length>0?" "+i:i);continue}if(x=a(h),!x){i=p+(i.length>0?" "+i:i);continue}v=false;}let g=l.length===0?"":l.length===1?l[0]:r(l).join(":"),b=f?g+"!":g,w=b+x;if(n.indexOf(w)>-1)continue;n.push(w);let I=s(x,v);for(let P=0;P<I.length;++P){let k=I[P];n.push(b+k);}i=p+(i.length>0?" "+i:i);}return i},ey=(...e)=>{let o=0,t,a,s="";for(;o<e.length;)(t=e[o++])&&(a=cf(t))&&(s&&(s+=" "),s+=a);return s},cf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=cf(e[a]))&&(t&&(t+=" "),t+=o);return t},ty=(e,...o)=>{let t,a,s,r,n=i=>{let c=o.reduce((p,d)=>d(p),e());return t=Jv(c),a=t.cache.get,s=t.cache.set,r=u,u(i)},u=i=>{let c=a(i);if(c)return c;let p=Qv(i,t);return s(i,p),p};return r=n,(...i)=>r(ey(...i))},ay=[],ze=e=>{let o=t=>t[e]||ay;return o.isThemeGetter=true,o},ff=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,mf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,oy=/^\d+\/\d+$/,ry=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,sy=/\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$/,ny=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,iy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ly=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ko=e=>oy.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Pa=e=>!!e&&Number.isInteger(Number(e)),Dl=e=>e.endsWith("%")&&de(e.slice(0,-1)),na=e=>ry.test(e),dy=()=>true,uy=e=>sy.test(e)&&!ny.test(e),pf=()=>false,cy=e=>iy.test(e),fy=e=>ly.test(e),my=e=>!Y(e)&&!J(e),py=e=>Wo(e,xf,pf),Y=e=>ff.test(e),to=e=>Wo(e,bf,uy),Rl=e=>Wo(e,vy,de),sf=e=>Wo(e,hf,pf),hy=e=>Wo(e,gf,fy),wn=e=>Wo(e,vf,cy),J=e=>mf.test(e),Nr=e=>zo(e,bf),gy=e=>zo(e,yy),nf=e=>zo(e,hf),xy=e=>zo(e,xf),by=e=>zo(e,gf),Ln=e=>zo(e,vf,true),Wo=(e,o,t)=>{let a=ff.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},zo=(e,o,t=false)=>{let a=mf.exec(e);return a?a[1]?o(a[1]):t:false},hf=e=>e==="position"||e==="percentage",gf=e=>e==="image"||e==="url",xf=e=>e==="length"||e==="size"||e==="bg-size",bf=e=>e==="length",vy=e=>e==="number",yy=e=>e==="family-name",vf=e=>e==="shadow";var wy=()=>{let e=ze("color"),o=ze("font"),t=ze("text"),a=ze("font-weight"),s=ze("tracking"),r=ze("leading"),n=ze("breakpoint"),u=ze("container"),i=ze("spacing"),c=ze("radius"),p=ze("shadow"),d=ze("inset-shadow"),l=ze("text-shadow"),f=ze("drop-shadow"),h=ze("blur"),m=ze("perspective"),v=ze("aspect"),x=ze("ease"),g=ze("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],w=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...w(),J,Y],P=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],S=()=>[J,Y,i],y=()=>[Ko,"full","auto",...S()],E=()=>[Pa,"none","subgrid",J,Y],B=()=>["auto",{span:["full",Pa,J,Y]},Pa,J,Y],T=()=>[Pa,"auto",J,Y],G=()=>["auto","min","max","fr",J,Y],F=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],O=()=>["start","end","center","stretch","center-safe","end-safe"],U=()=>["auto",...S()],V=()=>[Ko,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...S()],H=()=>[e,J,Y],oe=()=>[...w(),nf,sf,{position:[J,Y]}],me=()=>["no-repeat",{repeat:["","x","y","space","round"]}],W=()=>["auto","cover","contain",xy,py,{size:[J,Y]}],q=()=>[Dl,Nr,to],_=()=>["","none","full",c,J,Y],K=()=>["",de,Nr,to],X=()=>["solid","dashed","dotted","double"],te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],$=()=>[de,Dl,nf,sf],re=()=>["","none",h,J,Y],ie=()=>["none",de,J,Y],Ae=()=>["none",de,J,Y],Ce=()=>[de,J,Y],Ee=()=>[Ko,"full",...S()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[na],breakpoint:[na],color:[dy],container:[na],"drop-shadow":[na],ease:["in","out","in-out"],font:[my],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[na],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[na],shadow:[na],spacing:["px",de],text:[na],"text-shadow":[na],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ko,Y,J,v]}],container:["container"],columns:[{columns:[de,Y,J,u]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"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:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:y()}],"inset-x":[{"inset-x":y()}],"inset-y":[{"inset-y":y()}],start:[{start:y()}],end:[{end:y()}],top:[{top:y()}],right:[{right:y()}],bottom:[{bottom:y()}],left:[{left:y()}],visibility:["visible","invisible","collapse"],z:[{z:[Pa,"auto",J,Y]}],basis:[{basis:[Ko,"full","auto",u,...S()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Ko,"auto","initial","none",Y]}],grow:[{grow:["",de,J,Y]}],shrink:[{shrink:["",de,J,Y]}],order:[{order:[Pa,"first","last","none",J,Y]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:B()}],"col-start":[{"col-start":T()}],"col-end":[{"col-end":T()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:B()}],"row-start":[{"row-start":T()}],"row-end":[{"row-end":T()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:S()}],"gap-x":[{"gap-x":S()}],"gap-y":[{"gap-y":S()}],"justify-content":[{justify:[...F(),"normal"]}],"justify-items":[{"justify-items":[...O(),"normal"]}],"justify-self":[{"justify-self":["auto",...O()]}],"align-content":[{content:["normal",...F()]}],"align-items":[{items:[...O(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...O(),{baseline:["","last"]}]}],"place-content":[{"place-content":F()}],"place-items":[{"place-items":[...O(),"baseline"]}],"place-self":[{"place-self":["auto",...O()]}],p:[{p:S()}],px:[{px:S()}],py:[{py:S()}],ps:[{ps:S()}],pe:[{pe:S()}],pt:[{pt:S()}],pr:[{pr:S()}],pb:[{pb:S()}],pl:[{pl:S()}],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":S()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":S()}],"space-y-reverse":["space-y-reverse"],size:[{size:V()}],w:[{w:[u,"screen",...V()]}],"min-w":[{"min-w":[u,"screen","none",...V()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[n]},...V()]}],h:[{h:["screen","lh",...V()]}],"min-h":[{"min-h":["screen","lh","none",...V()]}],"max-h":[{"max-h":["screen","lh",...V()]}],"font-size":[{text:["base",t,Nr,to]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,J,Rl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Dl,Y]}],"font-family":[{font:[gy,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:[s,J,Y]}],"line-clamp":[{"line-clamp":[de,"none",J,Rl]}],leading:[{leading:[r,...S()]}],"list-image":[{"list-image":["none",J,Y]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",J,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:[...X(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",J,to]}],"text-decoration-color":[{decoration:H()}],"underline-offset":[{"underline-offset":[de,"auto",J,Y]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",J,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",J,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:oe()}],"bg-repeat":[{bg:me()}],"bg-size":[{bg:W()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Pa,J,Y],radial:["",J,Y],conic:[Pa,J,Y]},by,hy]}],"bg-color":[{bg:H()}],"gradient-from-pos":[{from:q()}],"gradient-via-pos":[{via:q()}],"gradient-to-pos":[{to:q()}],"gradient-from":[{from:H()}],"gradient-via":[{via:H()}],"gradient-to":[{to:H()}],rounded:[{rounded:_()}],"rounded-s":[{"rounded-s":_()}],"rounded-e":[{"rounded-e":_()}],"rounded-t":[{"rounded-t":_()}],"rounded-r":[{"rounded-r":_()}],"rounded-b":[{"rounded-b":_()}],"rounded-l":[{"rounded-l":_()}],"rounded-ss":[{"rounded-ss":_()}],"rounded-se":[{"rounded-se":_()}],"rounded-ee":[{"rounded-ee":_()}],"rounded-es":[{"rounded-es":_()}],"rounded-tl":[{"rounded-tl":_()}],"rounded-tr":[{"rounded-tr":_()}],"rounded-br":[{"rounded-br":_()}],"rounded-bl":[{"rounded-bl":_()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...X(),"hidden","none"]}],"divide-style":[{divide:[...X(),"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:[...X(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,J,Y]}],"outline-w":[{outline:["",de,Nr,to]}],"outline-color":[{outline:H()}],shadow:[{shadow:["","none",p,Ln,wn]}],"shadow-color":[{shadow:H()}],"inset-shadow":[{"inset-shadow":["none",d,Ln,wn]}],"inset-shadow-color":[{"inset-shadow":H()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:H()}],"ring-offset-w":[{"ring-offset":[de,to]}],"ring-offset-color":[{"ring-offset":H()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":H()}],"text-shadow":[{"text-shadow":["none",l,Ln,wn]}],"text-shadow-color":[{"text-shadow":H()}],opacity:[{opacity:[de,J,Y]}],"mix-blend":[{"mix-blend":[...te(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":te()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":$()}],"mask-image-linear-to-pos":[{"mask-linear-to":$()}],"mask-image-linear-from-color":[{"mask-linear-from":H()}],"mask-image-linear-to-color":[{"mask-linear-to":H()}],"mask-image-t-from-pos":[{"mask-t-from":$()}],"mask-image-t-to-pos":[{"mask-t-to":$()}],"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":$()}],"mask-image-r-to-pos":[{"mask-r-to":$()}],"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":$()}],"mask-image-b-to-pos":[{"mask-b-to":$()}],"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":$()}],"mask-image-l-to-pos":[{"mask-l-to":$()}],"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":$()}],"mask-image-x-to-pos":[{"mask-x-to":$()}],"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":$()}],"mask-image-y-to-pos":[{"mask-y-to":$()}],"mask-image-y-from-color":[{"mask-y-from":H()}],"mask-image-y-to-color":[{"mask-y-to":H()}],"mask-image-radial":[{"mask-radial":[J,Y]}],"mask-image-radial-from-pos":[{"mask-radial-from":$()}],"mask-image-radial-to-pos":[{"mask-radial-to":$()}],"mask-image-radial-from-color":[{"mask-radial-from":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":w()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":$()}],"mask-image-conic-to-pos":[{"mask-conic-to":$()}],"mask-image-conic-from-color":[{"mask-conic-from":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:oe()}],"mask-repeat":[{mask:me()}],"mask-size":[{mask:W()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",J,Y]}],filter:[{filter:["","none",J,Y]}],blur:[{blur:re()}],brightness:[{brightness:[de,J,Y]}],contrast:[{contrast:[de,J,Y]}],"drop-shadow":[{"drop-shadow":["","none",f,Ln,wn]}],"drop-shadow-color":[{"drop-shadow":H()}],grayscale:[{grayscale:["",de,J,Y]}],"hue-rotate":[{"hue-rotate":[de,J,Y]}],invert:[{invert:["",de,J,Y]}],saturate:[{saturate:[de,J,Y]}],sepia:[{sepia:["",de,J,Y]}],"backdrop-filter":[{"backdrop-filter":["","none",J,Y]}],"backdrop-blur":[{"backdrop-blur":re()}],"backdrop-brightness":[{"backdrop-brightness":[de,J,Y]}],"backdrop-contrast":[{"backdrop-contrast":[de,J,Y]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,J,Y]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,J,Y]}],"backdrop-invert":[{"backdrop-invert":["",de,J,Y]}],"backdrop-opacity":[{"backdrop-opacity":[de,J,Y]}],"backdrop-saturate":[{"backdrop-saturate":[de,J,Y]}],"backdrop-sepia":[{"backdrop-sepia":["",de,J,Y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":S()}],"border-spacing-x":[{"border-spacing-x":S()}],"border-spacing-y":[{"border-spacing-y":S()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",J,Y]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",J,Y]}],ease:[{ease:["linear","initial",x,J,Y]}],delay:[{delay:[de,J,Y]}],animate:[{animate:["none",g,J,Y]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[m,J,Y]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:ie()}],"rotate-x":[{"rotate-x":ie()}],"rotate-y":[{"rotate-y":ie()}],"rotate-z":[{"rotate-z":ie()}],scale:[{scale:Ae()}],"scale-x":[{"scale-x":Ae()}],"scale-y":[{"scale-y":Ae()}],"scale-z":[{"scale-z":Ae()}],"scale-3d":["scale-3d"],skew:[{skew:Ce()}],"skew-x":[{"skew-x":Ce()}],"skew-y":[{"skew-y":Ce()}],transform:[{transform:[J,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ee()}],"translate-x":[{"translate-x":Ee()}],"translate-y":[{"translate-y":Ee()}],"translate-z":[{"translate-z":Ee()}],"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",J,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":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"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",J,Y]}],fill:[{fill:["none",...H()]}],"stroke-w":[{stroke:[de,Nr,to,Rl]}],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 yf=ty(wy);function Ea(...e){return yf(yn(e))}function Sn({className:e,defaultValue:o,value:t,min:a=0,max:s=100,rangeClassName:r,trackClassName:n,thumbClassName:u,...i}){let c=ye.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,s],[t,o,a,s]);return jsxs(Zc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:s,className:Ea("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(Qc,{"data-slot":"slider-track",className:Ea("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(ef,{"data-slot":"slider-range",className:Ea("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(p,d)=>jsx(tf,{"data-slot":"slider-thumb",className:Ea("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 Sy="SchooplaVideoStorage";var ea="videos",In=()=>new Promise((e,o)=>{let t=indexedDB.open(Sy,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(ea)||s.createObjectStore(ea,{keyPath:"id"});};}),ao=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await In(),r=a.transaction([ea],"readwrite").objectStore(ea),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,i)=>{let c=r.put(n);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 Lf=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await In(),t=e.transaction([ea],"readonly").objectStore(ea);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result,u=new Map;n.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(),s(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Ol=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await In(),a=o.transaction([ea],"readwrite").objectStore(ea);await new Promise((s,r)=>{let n=a.delete(e);n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Sf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await In(),t=e.transaction([ea],"readwrite").objectStore(ea);await new Promise((a,s)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>s(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}},If=e=>URL.createObjectURL(e);var Iy=ye[" useId ".trim().toString()]||(()=>{}),Cy=0;function Cf(e){let[o,t]=ye.useState(Iy());return qo(()=>{t(a=>a??String(Cy++));},[e]),(o?`radix-${o}`:"")}function kf(e){let o=ye.useRef(e);return ye.useEffect(()=>{o.current=e;}),ye.useMemo(()=>(...t)=>o.current?.(...t),[])}var Vl="rovingFocusGroup.onEntryFocus",ky={bubbles:false,cancelable:true},Vr="RovingFocusGroup",[ql,Tf,Ty]=bn(Vr),[My,Hl]=Aa(Vr,[Ty]),[Ay,Py]=My(Vr),Mf=ye.forwardRef((e,o)=>jsx(ql.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(ql.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Ey,{...e,ref:o})})}));Mf.displayName=Vr;var Ey=ye.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:s=false,dir:r,currentTabStopId:n,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:i,onEntryFocus:c,preventScrollOnEntryFocus:p=false,...d}=e,l=ye.useRef(null),f=Ht(o,l),h=Ho(r),[m,v]=sa({prop:n,defaultProp:u??null,onChange:i,caller:Vr}),[x,g]=ye.useState(false),b=kf(c),w=Tf(t),I=ye.useRef(false),[P,k]=ye.useState(0);return ye.useEffect(()=>{let S=l.current;if(S)return S.addEventListener(Vl,b),()=>S.removeEventListener(Vl,b)},[b]),jsx(Ay,{scope:t,orientation:a,dir:h,loop:s,currentTabStopId:m,onItemFocus:ye.useCallback(S=>v(S),[v]),onItemShiftTab:ye.useCallback(()=>g(true),[]),onFocusableItemAdd:ye.useCallback(()=>k(S=>S+1),[]),onFocusableItemRemove:ye.useCallback(()=>k(S=>S-1),[]),children:jsx(gt.div,{tabIndex:x||P===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:et(e.onMouseDown,()=>{I.current=true;}),onFocus:et(e.onFocus,S=>{let y=!I.current;if(S.target===S.currentTarget&&y&&!x){let E=new CustomEvent(Vl,ky);if(S.currentTarget.dispatchEvent(E),!E.defaultPrevented){let B=w().filter(U=>U.focusable),T=B.find(U=>U.active),G=B.find(U=>U.id===m),O=[T,G,...B].filter(Boolean).map(U=>U.ref.current);Ef(O,p);}}I.current=false;}),onBlur:et(e.onBlur,()=>g(false))})})}),Af="RovingFocusGroupItem",Pf=ye.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:s=false,tabStopId:r,children:n,...u}=e,i=Cf(),c=r||i,p=Py(Af,t),d=p.currentTabStopId===c,l=Tf(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:m}=p;return ye.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(ql.ItemSlot,{scope:t,id:c,focusable:a,active:s,children:jsx(gt.span,{tabIndex:d?0:-1,"data-orientation":p.orientation,...u,ref:o,onMouseDown:et(e.onMouseDown,v=>{a?p.onItemFocus(c):v.preventDefault();}),onFocus:et(e.onFocus,()=>p.onItemFocus(c)),onKeyDown:et(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){p.onItemShiftTab();return}if(v.target!==v.currentTarget)return;let x=Fy(v,p.orientation,p.dir);if(x!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let b=l().filter(w=>w.focusable).map(w=>w.ref.current);if(x==="last")b.reverse();else if(x==="prev"||x==="next"){x==="prev"&&b.reverse();let w=b.indexOf(v.currentTarget);b=p.loop?By(b,w+1):b.slice(w+1);}setTimeout(()=>Ef(b));}}),children:typeof n=="function"?n({isCurrentTabStop:d,hasTabStop:m!=null}):n})})});Pf.displayName=Af;var Dy={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 Fy(e,o,t){let a=Ry(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Dy[a]}function Ef(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function By(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Df=Mf,Rf=Pf;var Bf="Toggle",Ul=ye.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:s,...r}=e,[n,u]=sa({prop:t,onChange:s,defaultProp:a??false,caller:Bf});return jsx(gt.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:et(e.onClick,()=>{e.disabled||u(!n);})})});Ul.displayName=Bf;var Da="ToggleGroup",[Nf]=Aa(Da,[Hl]),Vf=Hl(),Kl=ye__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Vy,{...a,ref:o});if(t==="multiple")return jsx(qy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Da}\``)});Kl.displayName=Da;var[qf,Hf]=Nf(Da),Vy=ye__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,u]=sa({prop:t,defaultProp:a??"",onChange:s,caller:Da});return jsx(qf,{scope:e.__scopeToggleGroup,type:"single",value:ye__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:u,onItemDeactivate:ye__default.useCallback(()=>u(""),[u]),children:jsx(Uf,{...r,ref:o})})}),qy=ye__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,u]=sa({prop:t,defaultProp:a??[],onChange:s,caller:Da}),i=ye__default.useCallback(p=>u((d=[])=>[...d,p]),[u]),c=ye__default.useCallback(p=>u((d=[])=>d.filter(l=>l!==p)),[u]);return jsx(qf,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:i,onItemDeactivate:c,children:jsx(Uf,{...r,ref:o})})});Kl.displayName=Da;var[Hy,Uy]=Nf(Da),Uf=ye__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:s=true,orientation:r,dir:n,loop:u=true,...i}=e,c=Vf(t),p=Ho(n),d={role:"group",dir:p,...i};return jsx(Hy,{scope:t,rovingFocus:s,disabled:a,children:s?jsx(Df,{asChild:true,...c,orientation:r,dir:p,loop:u,children:jsx(gt.div,{...d,ref:o})}):jsx(gt.div,{...d,ref:o})})}),Cn="ToggleGroupItem",Ky=ye__default.forwardRef((e,o)=>{let t=Hf(Cn,e.__scopeToggleGroup),a=Uy(Cn,e.__scopeToggleGroup),s=Vf(e.__scopeToggleGroup),r=t.value.includes(e.value),n=a.disabled||e.disabled,u={...e,pressed:r,disabled:n},i=ye__default.useRef(null);return a.rovingFocus?jsx(Rf,{asChild:true,...s,focusable:!n,active:r,ref:i,children:jsx(Of,{...u,ref:o})}):jsx(Of,{...u,ref:o})});Ky.displayName=Cn;var Of=ye__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...s}=e,r=Hf(Cn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=r.type==="single"?n:void 0;return jsx(Ul,{...u,...s,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Kf=Kl;var Gy=ye.createContext({size:"default",variant:"default",spacing:0});function Ra({className:e,variant:o,size:t,spacing:a=1,children:s,...r}){return jsx(Kf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Ea("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Gy.Provider,{value:{variant:o,size:t,spacing:a},children:s})})}var _y={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},_f=createSlice({name:"toolbar",initialState:_y,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:ta,setPenColor:jo,setStrokeWidth:qr,setFontSize:UE,setFontFamily:KE,setFontStyle:WE,setFontWeight:zE,setTextDecoration:GE,setTextColor:jE}=_f.actions,zl=_f.reducer;var Xf=({onClose:e,onRecordingComplete:o})=>{let t=qe(),[a,s]=useState(false),[r,n]=useState(null),[u,i]=useState(0),[c,p]=useState(null),[d,l]=useState(false),f=useRef(null),h=useRef([]),m=useRef(null),v=useRef(null),x=useRef(null);useEffect(()=>((async()=>{try{let y=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});p(y),l(!0),x.current&&(x.current.srcObject=y);}catch(y){console.error("Error accessing camera:",y),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{m.current&&clearInterval(m.current),c&&c.getTracks().forEach(y=>y.stop());}),[]);let g=()=>{c&&(c.getTracks().forEach(S=>S.stop()),p(null),l(false));},b=async()=>{try{let S=null,y=null;try{S=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{y=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(F){console.warn("Microphone access denied:",F);}let E=[...S.getVideoTracks()];y&&E.push(...y.getAudioTracks());let B=new MediaStream(E),T="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?T="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?T="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?T="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(T="video/webm;codecs=vp8");let G=new MediaRecorder(B,{mimeType:T,videoBitsPerSecond:25e5});f.current=G,h.current=[],G.ondataavailable=F=>{F.data.size>0&&h.current.push(F.data);},G.onstop=()=>{let F=new Blob(h.current,{type:T}),O=document.createElement("video");O.src=URL.createObjectURL(F),O.muted=!0,O.currentTime=.1,O.onseeked=()=>{let U=document.createElement("canvas");U.width=O.videoWidth,U.height=O.videoHeight;let V=U.getContext("2d");V&&(V.drawImage(O,0,0),v.current=U.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(O.src);},B.getTracks().forEach(U=>U.stop()),S&&S.getTracks().forEach(U=>U.stop()),y&&y.getTracks().forEach(U=>U.stop()),m.current&&clearInterval(m.current),n(F),g();},G.onerror=F=>{console.error("MediaRecorder error:",F);},G.start(1e3),s(!0),i(0),m.current=setInterval(()=>{i(F=>F+1);},1e3);}catch(S){console.error("Error starting camera recording:",S),alert("Failed to start recording. Please check permissions.");}},w=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),s(false));},I=()=>{if(r){let S=URL.createObjectURL(r),y=document.createElement("a");y.href=S,y.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(S);}},P=S=>{let y=Math.floor(S/60),E=S%60;return `${y.toString().padStart(2,"0")}:${E.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:S=>{S.target===S.currentTarget&&e(),S.stopPropagation();},onMouseUp:S=>S.stopPropagation(),onMouseMove:S=>S.stopPropagation(),onTouchStart:S=>S.stopPropagation(),onTouchMove:S=>S.stopPropagation(),onTouchEnd:S=>S.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:S=>S.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:x,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:b,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:w,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:P(u)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",P(u)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(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 ia=40,Yf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,s]=useState(t?.images||[]),[r,n]=useState(t?.order||"sequential"),[u,i]=useState(false),c=useRef(null),p=qe(),d=useRef(null);useEffect(()=>{let b=w=>{w.key==="Escape"&&o();};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[o]);let l=b=>{let w=b.target.files;if(!w||w.length===0)return;let I=ia-a.length;if(I<=0){alert(`You can only upload a maximum of ${ia} images`);return}let P=Array.from(w).slice(0,I);P.length<w.length&&alert(`Only ${I} more images can be added (max ${ia} total)`);let k=P.map(S=>new Promise((y,E)=>{let B=new FileReader;B.onload=T=>{T.target?.result?y(T.target.result):E(new Error("Failed to read file"));},B.onerror=E,B.readAsDataURL(S);}));Promise.all(k).then(S=>{s(y=>[...y,...S]),d.current&&(d.current.value="");});},f=b=>{b.preventDefault(),i(false);let w=Array.from(b.dataTransfer.files).filter(S=>S.type.startsWith("image/"));if(w.length===0)return;let I=ia-a.length;if(I<=0){alert(`You can only upload a maximum of ${ia} images`);return}let P=w.slice(0,I);P.length<w.length&&alert(`Only ${I} more images can be added (max ${ia} total)`);let k=P.map(S=>new Promise((y,E)=>{let B=new FileReader;B.onload=T=>{T.target?.result?y(T.target.result):E(new Error("Failed to read file"));},B.onerror=E,B.readAsDataURL(S);}));Promise.all(k).then(S=>{s(y=>[...y,...S]);});},h=b=>{b.preventDefault(),i(true);},m=()=>{i(false);},v=b=>{s(w=>w.filter((I,P)=>P!==b));},x=b=>{if(b.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!p)return null;let g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:b=>{b.target===b.currentTarget&&o(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{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:b=>b.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:x,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>=ia?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ia," images"]}):jsxs("span",{children:[a.length,"/",ia," 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:f,onDragOver:h,onDragLeave:m,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:()=>n("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:()=>n("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((b,w)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:b,alt:`Flashcard ${w+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(w),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:w+1})]},w))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(g,p)};var kn={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},dw={enabled:true};function _l(e){return e?{tools:{...kn.tools,...e.tools},actions:{...kn.actions,...e.actions}}:kn}var uw={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},cw={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var Bw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:s}={})=>{let r=ve(),n=Q(D=>D.canvas.slides.find(ee=>ee.id===D.canvas.currentSlideId)),u=n?.videos||[],i=n?.editingFlashcard,c=Q(D=>D.toolbar.selectedTool),p=Q(D=>D.toolbar.penColor),d=Q(D=>D.toolbar.strokeWidth),l=n?.showMcqForm,f=n?.showFlashcardForm,h=useRef(null);useEffect(()=>{let D=ee=>{(ee.ctrlKey||ee.metaKey)&&ee.key==="z"&&!ee.shiftKey&&(ee.preventDefault(),r(Ds())),(ee.ctrlKey&&ee.shiftKey&&ee.key==="Z"||ee.ctrlKey&&ee.key==="y")&&(ee.preventDefault(),r(Rs()));};return window.addEventListener("keydown",D),()=>{window.removeEventListener("keydown",D);}},[r]);let m=useMemo(()=>_l(s),[s]),{tools:v,actions:x}=m,g=u.some(D=>D.isRecorded&&D.isPlaying),b=Q(D=>D.toolbar.fontSize),w=Q(D=>D.toolbar.fontFamily),I=Q(D=>D.toolbar.fontStyle),P=Q(D=>D.toolbar.fontWeight),k=Q(D=>D.toolbar.textDecoration),S=Q(D=>D.toolbar.textColor),[y,E]=useState(false),[B,T]=useState(false),[G,F]=useState(false),[O,U]=useState(false),[V,H]=useState(false),[oe,me]=useState(false),[W,q]=useState(false),_=useRef(null),K=useRef(null),X=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),te=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),$=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),re=useMemo(()=>X.filter(D=>{let ee=v[D.configKey];return typeof ee=="boolean"?ee:Array.isArray(ee)?ee.length>0:true}),[v,X]),ie=useMemo(()=>{let D=v.shapes;return D===false?[]:D===true?te:Array.isArray(D)?te.filter(ee=>D.includes(ee.name)):te},[v.shapes,te]),Ae=useMemo(()=>{let D=v.activities;return D===false?[]:D===true?$:Array.isArray(D)?$.filter(ee=>D.includes(ee.name)):$},[v.activities,$]),Ce=useMemo(()=>{let D=v.media;return D===false?{photoFrame:false,image:false,video:false}:D===true?{photoFrame:true,image:true,video:true}:Array.isArray(D)?{photoFrame:D.includes("photo-frame"),image:D.includes("image"),video:D.includes("video")}:{photoFrame:true,image:true,video:true}},[v.media]),Ee=useMemo(()=>{let D=v.activities;return D===false?false:D===true?true:Array.isArray(D)?D.includes("flashcard"):true},[v.activities]),lt=D=>{let ee=D.target.files;!ee||ee.length===0||(r(ta("select")),r(wt(false)),U(false),Array.from(ee).forEach(ke=>{let xe=new FileReader;xe.onload=le=>{let fe=new window.Image;fe.src=le.target?.result,fe.onload=()=>{let Pe=fe.width/fe.height,_e=300,Yt=300,vt=fe.width,De=fe.height;vt>_e&&(vt=_e,De=vt/Pe),De>Yt&&(De=Yt,vt=De*Pe),r(ue());let at=800-vt/2,At=450-De/2;r(Qn({id:v4(),src:fe.src,x:at,y:At,width:vt,height:De,draggable:true,rotation:0}));};},xe.readAsDataURL(ke);}),D.target.value="");},bt=async D=>{let ee=D.target.files;if(!(!ee||ee.length===0)){console.log("files",D),r(ta("select")),r(wt(false)),U(false);for(let ke of Array.from(ee))try{let xe=URL.createObjectURL(ke),le=document.createElement("video");console.log("video",le),le.src=xe,le.muted=!0,le.playsInline=!0,le.preload="auto",le.load(),await new Promise((dt,fa)=>{let Na=setTimeout(()=>fa(new Error("Metadata load timeout")),1e4);le.onloadedmetadata=()=>{clearTimeout(Na),dt();},le.onerror=()=>{clearTimeout(Na),fa(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:le.duration,width:le.videoWidth,height:le.videoHeight}),await new Promise((dt,fa)=>{let Na=setTimeout(()=>fa(new Error("Video load timeout")),1e4);le.readyState>=2?(clearTimeout(Na),dt()):le.onloadeddata=()=>{clearTimeout(Na),dt();};});let fe=Math.min(.8,le.duration/2);console.log("Seeking to:",fe),le.currentTime=fe,await new Promise(dt=>{let fa=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),dt();},5e3);le.onseeked=()=>{clearTimeout(fa),console.log("Seek completed"),dt();};});let Pe=document.createElement("canvas"),_e=le.videoWidth/le.videoHeight,Yt=400,vt=400,De=le.videoWidth,at=le.videoHeight;De>Yt&&(De=Yt,at=De/_e),at>vt&&(at=vt,De=at*_e),Pe.width=De,Pe.height=at;let At=Pe.getContext("2d",{willReadFrequently:!1});if(!At)throw new Error("Failed to get canvas context");if(await new Promise(dt=>setTimeout(dt,100)),le.videoWidth===0||le.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:De,height:at}),At.drawImage(le,0,0,De,at);let Kt=Pe.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Kt.length),r(ue());let Vn=800-De/2,qn=450-at/2,$r=v4();await ao($r,ke,Kt),r(ss({id:$r,objectUrl:xe,thumbnailDataUrl:Kt,videoBlob:ke,x:Vn,y:qn,width:De,height:at,draggable:!0,isPlaying:!1,rotation:0})),le.src="",le.load(),console.log(`Video uploaded: ${ke.name}`);}catch(xe){console.error("Error processing video:",xe),alert(`Failed to process video: ${ke.name}`);}D.target.value="";}},lo=(D,ee,ke)=>{r(ue()),r(ta("select")),r(wt(false));let xe=300,le=300,fe=800-xe/2,Pe=450-le/2;r(ke?po({id:ke,images:D,order:ee,x:fe,y:Pe,width:xe,height:le,rotation:0,draggable:true}):ai({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:D,currentIndex:0,order:ee,x:fe,y:Pe,width:xe,height:le,rotation:0,draggable:true})),r(Ua(false));},se=()=>{r(ue()),r(ta("select")),r(wt(false));let D=400,ee=300,ke=800-D/2,xe=450-ee/2;r(si({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ke,y:xe,width:D,height:ee,rotation:0,draggable:true,isCapturing:false})),H(false);},Gr=D=>{let fe={};switch(D.name){case "circle":case "ring":case "wedge":case "arc":fe.radius=50,(D.name==="ring"||D.name==="arc")&&(fe.innerRadius=25,fe.outerRadius=50),(D.name==="wedge"||D.name==="arc")&&(fe.angle=D.name==="wedge"?60:90);break;case "ellipse":fe.radiusX=60,fe.radiusY=40;break;case "triangle":fe.radius=50,fe.sides=3;break;case "polygon":fe.radius=50,fe.sides=6;break;case "star":fe.innerRadius=25,fe.outerRadius=50,fe.numPoints=5;break;case "arrow":case "line":fe.points=[0,0,100,0],D.name==="arrow"&&(fe.pointerLength=10,fe.pointerWidth=10);break}let Pe={id:`shape-${Date.now()}`,type:D.name,x:750,y:400,width:100,height:100,rotation:0,color:p,...fe};r(ue()),r(wt(false)),r(ta(D.name)),r(ei(Pe));},Oa=D=>{if(r(ta(D)),D==="select")r(wt(false));else if(D==="text"){r(wt(false)),r(ue());let ee=200,ke=50,xe=800-ee/2,le=450-ke/2,Pe=window.innerWidth<768?Math.max(b,32):b,_e=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(ti({id:_e,text:"",x:xe,y:le,width:ee,height:ke,rotation:0,draggable:true,fontSize:Pe,fontFamily:w,fontStyle:I,fontWeight:P,textDecoration:k,fill:S,align:"left"})),setTimeout(()=>{r(sr(_e));},100),a&&a(_e);}else r(wt(true));},jr=()=>{r(wi()),r(wt(false));},_r=()=>{o?o():t?E(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Xr=()=>{T(true);},$o=async(D,ee)=>{try{r(ta("select")),r(wt(!1));let ke=URL.createObjectURL(D),xe=document.createElement("video");xe.src=ke,xe.muted=!0,xe.playsInline=!0,xe.preload="auto",await new Promise((at,At)=>{let Kt=setTimeout(()=>At(new Error("Metadata load timeout")),1e4);xe.onloadedmetadata=()=>{clearTimeout(Kt),at();},xe.onerror=()=>{clearTimeout(Kt),At(new Error("Failed to load video"));};});let le=640,fe=xe.videoWidth/xe.videoHeight,Pe=le,_e=Pe/fe;r(ue());let Yt=800-Pe/2,vt=450-_e/2,De=v4();await ao(De,D,ee),r(ss({id:De,objectUrl:ke,thumbnailDataUrl:ee,videoBlob:D,x:Yt,y:vt,width:Pe,height:_e,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),E(!1),T(!1);}catch(ke){console.error("Error adding recorded video to canvas:",ke),alert("Failed to add video to canvas. Please try again.");}},Rn=D=>{r(ta("select")),r(wt(false)),r(or(null)),D&&r(hi(D)),r(ga(!l));},Fn=()=>{r(Qo(null)),r(Ua(true)),H(false);},Bn=()=>{F(!G);},On=()=>{U(!O);},Nn=()=>{H(!V);};return useEffect(()=>{if(!W)return;let D=ee=>{h.current&&!h.current.contains(ee.target)&&q(false);};return document.addEventListener("mousedown",D),()=>{document.removeEventListener("mousedown",D);}},[W]),g?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Ra,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:re.map((D,ee)=>jsx("div",{title:D.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 ${D.name===c?"bg-primary/10":""}`,onClick:()=>{if(D.name==="image"){On(),F(false),H(false),Oa(D.name);return}else if(D.name==="shapes"){Bn(),U(false),H(false),Oa(D.name);return}else if(D.name==="activities"){Oa(D.name),Nn(),F(false),U(false);return}Oa(D.name),F(false),U(false),H(false);},children:jsx(D.icon,{weight:"fill",className:"text-primary text-xl"})},ee))}),G&&jsx(Ra,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:ie.map((D,ee)=>jsx("div",{title:D.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Gr(D),children:jsx(D.icon,{weight:"fill",className:"text-primary text-xl"})},ee))}),O&&jsxs(Ra,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:[Ce.photoFrame&&jsx("div",{title:"Photo frame",onClick:se,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Ce.image&&jsx("div",{title:"Image",onClick:()=>_.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Ce.video&&jsx("div",{title:"Video",onClick:()=>K.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),V&&jsxs(Ra,{type:"single",className:"mx-1 mt-auto mb-11 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl",children:[Ee&&jsx("div",{title:"Flashcard",onClick:()=>Fn(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),Ae.map((D,ee)=>jsx("div",{title:D.label,onClick:()=>Rn(D.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(D.icon,{weight:"fill",className:"text-primary text-xl"})},ee))]})]}),(x.undo||x.redo||x.screenRecord||x.cameraRecord||x.clear)&&jsxs(Ra,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[x.undo&&jsx("button",{value:"undo",onClick:()=>r(Ds()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.redo&&jsx("button",{value:"redo",onClick:()=>r(Rs()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.screenRecord&&jsx("button",{value:"screen-record",onClick:_r,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6279F8] md:block",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl"})}),jsx("button",{title:"Pen Color",onClick:()=>me(true),className:"relative mx-4 my-2 flex cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-white text-xl md:hidden",style:{borderColor:p},children:jsx("div",{className:"h-5 w-5 rounded-full border-2 border-white shadow-sm",style:{backgroundColor:p}})}),jsxs("div",{ref:h,className:"relative md:hidden",children:[jsx("button",{title:"Pen Size",onClick:()=>q(!W),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${W?"bg-primary/10":""}`,children:jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border-2 border-[#FFFFFF80] bg-[#000000CC]",children:jsx("span",{className:"text-xs font-semibold text-white",children:d})})}),W&&jsxs("div",{className:"absolute top-1/2 left-full z-50 ml-2 w-48 -translate-y-1/2 rounded-lg border bg-white p-4 shadow-xl",children:[jsx("p",{className:"mb-3 text-xs font-semibold text-black/40",children:"PEN SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 shrink-0 rounded-full bg-black"}),jsx(Sn,{defaultValue:[12],max:28,min:6,step:1,className:"w-full",value:[d],rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:D=>r(qr(D[0]))}),jsx("div",{className:"h-5 w-5 shrink-0 rounded-full bg-black"})]})]})]}),x.cameraRecord&&jsx("button",{value:"camera-record",onClick:Xr,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6BBB93] md:block",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl"})}),x.clear&&jsx("button",{value:"clear",onClick:()=>jr(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl"})})]})]}),jsx("input",{ref:_,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:lt}),jsx("input",{ref:K,type:"file",accept:"video/*",className:"hidden",onChange:bt}),!o&&y&&t&&jsx(pr,{onClose:()=>E(false),stageRef:t,onRecordingComplete:$o}),B&&jsx(Xf,{onClose:()=>T(false),onRecordingComplete:$o}),f&&jsx(Yf,{editingFlashcard:i,onConfirm:lo,onCancel:()=>r(Ua(false))}),oe&&jsx(Ws,{defaultColor:p,onConfirm:D=>{r(jo(D)),me(false);},onCancel:()=>me(false)})]})},Ow=Bw;var Zl=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let s=ot(go),r=ot(Ci),n=a?r:s,u=ot(nr),p=(ot(g=>g.canvas.slides.find(b=>b.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[d,l]=useState(false),[f,h]=useState(null),[m,v]=useState(null),x=async()=>{if(s.length===0){v({type:"error",message:"No slides to publish"});return}if(!e){v({type:"error",message:"No publish handler provided"});return}l(true),v(null);try{let g=await e(n,u,b=>{h(b);});g.success?v({type:"success",message:g.message}):v({type:"error",message:g.message});}catch(g){v({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),v(null);},3e3);}};return p?null:jsxs("button",{onClick:x,disabled:d||s.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 Uw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:s,onDescriptionChange:r,showPublishButton:n=true,showBackButton:u=true,editableTitle:i=true,editableDescription:c=true,className:p="",rightContent:d,leftContent:l,includeInactiveSlides:f=false})=>{let h=ft(),m=ot(nr),v=ot(Ti),x=e??(v?m.title:"")??"Untitled",g=o??(v?m.description:"")??"Add a description...",[b,w]=useState(false),[I,P]=useState(false),[k,S]=useState(x),[y,E]=useState(g),B=useRef(null),T=useRef(null);useEffect(()=>{S(x);},[x]),useEffect(()=>{E(g);},[g]),useEffect(()=>{b&&B.current&&(B.current.focus(),B.current.select());},[b]),useEffect(()=>{I&&T.current&&(T.current.focus(),T.current.select());},[I]);let G=()=>{i&&w(true);},F=()=>{c&&P(true);},O=()=>{w(false),k.trim()&&k!==x?s?s(k.trim()):h(Li(k.trim())):k.trim()||S(x);},U=()=>{P(false),y.trim()&&y!==g?r?r(y.trim()):h(Si(y.trim())):y.trim()||E(g);},V=oe=>{oe.key==="Enter"?O():oe.key==="Escape"&&(S(x),w(false));},H=oe=>{oe.key==="Enter"?U():oe.key==="Escape"&&(E(g),P(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${p}`,children:[l||jsxs("div",{className:"flex items-center gap-6",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:[b?jsx("input",{ref:B,type:"text",value:k,onChange:oe=>S(oe.target.value),onBlur:O,onKeyDown:V,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:G,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:T,type:"text",value:y,onChange:oe=>E(oe.target.value),onBlur:U,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:F,title:y,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:y})]})]}),d||n&&a&&jsx(Zl,{onPublish:a,includeInactiveSlides:f})]})};var _w=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Xw=({colors:e=_w,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:s=""})=>{let[r,n]=useState(true),u=Q(ge),i=Q(l=>l.toolbar.penColor),c=Q(l=>l.toolbar.strokeWidth),p=u?.backgroundColor,d=ve();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-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:px-8 2xl:py-6 ${s}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(Sn,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:l=>d(qr(l[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"COLOR"}),jsxs(Ra,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${i===l.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:l.value},onClick:()=>d(jo(l.value))},l.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(jo(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-4 text-xs font-semibold whitespace-nowrap text-[#00000066] 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] lg:h-12 lg:w-12",style:{backgroundColor:p},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(Jn(l.target.value))})})]})}),jsx("div",{className:"absolute -top-4 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2",children:jsx("button",{onClick:()=>n(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{size:20,weight:"bold",className:"text-gray-600"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>n(true),className:"fixed bottom-3 left-1/2 z-50 flex -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var tm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),$w=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),ed=e=>{let o=$w(e);return o.charAt(0).toUpperCase()+o.slice(1)},Pn=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),am=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var om={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var sm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:n,...u},i)=>createElement("svg",{ref:i,...om,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Pn("lucide",s),...!r&&!am(u)&&{"aria-hidden":"true"},...u},[...n.map(([c,p])=>createElement(c,p)),...Array.isArray(r)?r:[r]]));var En=(e,o)=>{let t=forwardRef(({className:a,...s},r)=>createElement(sm,{ref:r,iconNode:o,className:Pn(`lucide-${tm(ed(e))}`,`lucide-${e}`,a),...s}));return t.displayName=ed(e),t};var Qw=[["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"}]],Kr=En("copy",Qw);var eL=[["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"}]],Wr=En("trash-2",eL);var im=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:s,onDuplicate:r,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:s,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(Kr,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Wr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var rL=({softDelete:e=false})=>{let o=ft(),t=ot(go),a=ot(ho),s=ot(ki),[r,n]=useState(true),c=(ot(h=>h.canvas.slides.find(m=>m.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),p=()=>{s&&o(jn());},d=h=>{o($n(h));},l=h=>{o(Xn(h));},f=h=>{t.length>1&&o(_n({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:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((h,m)=>jsx(im,{slide:h,index:m,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>l(h.id),onDelete:()=>f(h.id)},h.id))}),jsxs("button",{onClick:p,disabled:!s,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${s?"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:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var sL="SchooplaEditorDB",nL=1,Fa="slides",Ba="metadata",td="schoopla_current_slide_id",um="presentation_metadata",zr=()=>new Promise((e,o)=>{let t=indexedDB.open(sL,nL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Fa)||s.createObjectStore(Fa,{keyPath:"id"}),s.objectStoreNames.contains(Ba)||s.createObjectStore(Ba,{keyPath:"id"});};}),ad=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await zr(),a=o.transaction([Fa],"readwrite").objectStore(Fa);await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);});for(let s of e)await new Promise((r,n)=>{let u=a.add(s);u.onsuccess=()=>r(!0),u.onerror=()=>n(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);}}},od=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await zr(),t=e.transaction([Fa],"readonly").objectStore(Fa);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(n.length>0?n:null);},r.onerror=()=>{e.close(),s(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}}},Dn=async()=>{try{let e=await zr(),o=e.transaction([Fa,Ba],"readwrite"),t=o.objectStore(Fa),a=o.objectStore(Ba);await new Promise((s,r)=>{let n=t.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(td),localStorage.removeItem("schoopla_presentation_metadata"),await Sf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},rd=e=>{try{localStorage.setItem(td,e);}catch(o){console.error("Error saving current slide ID:",o);}},sd=()=>{try{return localStorage.getItem(td)}catch(e){return console.error("Error loading current slide ID:",e),null}},nd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},id=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await zr(),a=o.transaction([Ba],"readwrite").objectStore(Ba);await new Promise((s,r)=>{let n=a.put({id:um,...e});n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},ld=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await zr(),t=e.transaction([Ba],"readonly").objectStore(Ba);return new Promise((a,s)=>{let r=t.get(um);r.onsuccess=()=>{e.close();let n=r.result;if(n){let{id:u,...i}=n;console.log("\u2705 Loaded presentation metadata:",i),a(i);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),s(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 iL=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides","canvas/updateSlideThumbnail"],lL=["canvas/clearCanvas"],dL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],uL=nd((e,o)=>{ad(e),rd(o);},500),cL=nd(e=>{id(e);},500),fL=(e,o)=>{ad(e),rd(o);},dd=false,cm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Ol(r).catch(n=>{console.error("Error deleting video blob:",n);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,u=e.getState().canvas.slides.find(i=>i.id===r);u&&u.videos&&u.videos.length>0&&u.videos.forEach(i=>{Ol(i.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,n=e.getState(),i=n.canvas.slides.find(c=>c.id===n.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&&ao(d.id,i.videoBlob,d.thumbnailDataUrl).catch(l=>{console.error("Error saving duplicated video blob:",l);});},0);}let a=o(t),s=e.getState();if(s.canvas.viewerMode)return a;if(t.type&&lL.includes(t.type)){if(!dd){dd=true;try{let{slides:r,currentSlideId:n}=s.canvas;fL(r,n);}finally{setTimeout(()=>{dd=false;},0);}}}else if(t.type&&iL.includes(t.type)){let{slides:r,currentSlideId:n}=s.canvas;uL(r,n);}else if(t.type&&dL.includes(t.type)){let{presentationMetadata:r}=s.canvas;cL(r);}return a});new QueryClient;var pL=configureStore({reducer:{toolbar:zl,canvas:Mi},middleware:e=>e({serializableCheck:false}).concat(cm)}),hL=()=>configureStore({reducer:{toolbar:zl,canvas:Mi},middleware:e=>e({serializableCheck:false})});var gL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2,fileName:r=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:n,quality:a,pixelRatio:s}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=u,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},xL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o;return new Promise((r,n)=>{try{let u=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:u,quality:a,pixelRatio:s});fetch(i).then(c=>c.blob()).then(c=>r(c)).catch(c=>n(c));}catch(u){n(u);}})},bL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:s})};var vL=(e,o,t)=>{let a=t.x-o.x,s=t.y-o.y;if(a===0&&s===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+s*s,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*s)/r)),u=o.x+n*a,i=o.y+n*s;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-i,2))},ud=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,s=e[0],r=e[e.length-1];for(let n=1;n<e.length-1;n++){let u=vL(e[n],s,r);u>t&&(t=u,a=n);}if(t>o){let n=ud(e.slice(0,a+1),o),u=ud(e.slice(a),o);return [...n.slice(0,-1),...u]}return [s,r]},yL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},wL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},mm=(e,o=1.5)=>{if(e.length<=4)return e;let t=yL(e),a=ud(t,o);return wL(a)},pm=(e,o=1.5)=>({...e,points:mm(e.points,o)}),LL=(e,o=1.5)=>e.map(t=>pm(t,o)),SL=(e,o)=>{let t=e.length/2,a=o.length/2,s=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${s}%`}};var IL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var hm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:s=.85}=o;return new Promise((r,n)=>{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 p=document.createElement("canvas");p.width=i,p.height=c;let d=p.getContext("2d");if(!d){n(new Error("Failed to get canvas context"));return}d.drawImage(u,0,0,i,c);let l=IL(e),f=p.toDataURL(l,s);r(f);},u.onerror=n,u.src=e;})};var io=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return a.buffer},_o=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Xo=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",CL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:s=1080,imageQuality:r=.85}=o,n=[],u=0;for(let i of e){let c=[],p=[],d=[];for(let l of i.images){let f=l.src;if(t&&f.startsWith("data:"))try{f=await hm(f,{maxWidth:a,maxHeight:s,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=io(f),m=_o(f);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:m};if(l.audioData&&l.audioData.startsWith("data:")){let x=io(l.audioData),g=_o(l.audioData);u+=x.byteLength,v.audioBuffer=x,v.audioMimeType=g;}c.push(v);}}for(let l of i.videos){let f,h;if(l.videoBlob)f=await l.videoBlob.arrayBuffer(),h=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))f=io(l.videoData),h=_o(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}u+=f.byteLength;let m={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:f,mimeType:h};if(l.audioData&&l.audioData.startsWith("data:")){let v=io(l.audioData),x=_o(l.audioData);u+=v.byteLength,m.audioBuffer=v,m.audioMimeType=x;}p.push(m);}for(let l of i.photoFrames){let f={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=io(l.capturedImageUrl),m=_o(l.capturedImageUrl);u+=h.byteLength,f.buffer=h,f.mimeType=m;}if(l.audioData&&l.audioData.startsWith("data:")){let h=io(l.audioData),m=_o(l.audioData);u+=h.byteLength,f.audioBuffer=h,f.audioMimeType=m;}d.push(f);}n.push({...i,images:c,videos:p,photoFrames:d});}return {slides:n,totalSize:u}},kL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},TL=e=>{let o=new FormData,t=e.slides.map((a,s)=>({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,n)=>({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_${s}_image_${n}`,audioFileKey:r.audioBuffer?`slide_${s}_image_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,n)=>({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_${s}_video_${n}`,thumbnailFileKey:`slide_${s}_video_${n}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${s}_video_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,n)=>({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_${s}_photoframe_${n}`:void 0,audioFileKey:r.audioBuffer?`slide_${s}_photoframe_${n}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,s)=>{a.images.forEach((r,n)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Xo(r.mimeType)}`;if(o.append(`slide_${s}_image_${n}`,u,i),r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),p=`${r.id}_audio.${Xo(r.audioMimeType)}`;o.append(`slide_${s}_image_${n}_audio`,c,p);}}),a.videos.forEach((r,n)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Xo(r.mimeType)}`;if(o.append(`slide_${s}_video_${n}`,u,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let c=io(r.thumbnailDataUrl),p=new Blob([c],{type:"image/jpeg"}),d=`${r.id}_thumbnail.jpg`;o.append(`slide_${s}_video_${n}_thumbnail`,p,d);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),p=`${r.id}_audio.${Xo(r.audioMimeType)}`;o.append(`slide_${s}_video_${n}_audio`,c,p);}}),a.photoFrames.forEach((r,n)=>{if(r.buffer&&r.mimeType){let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Xo(r.mimeType)}`;o.append(`slide_${s}_photoframe_${n}`,u,i);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${Xo(r.audioMimeType)}`;o.append(`slide_${s}_photoframe_${n}_audio`,u,i);}});}),o};var PL=()=>{let e=ft(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let s=await od(),r=sd(),n=await ld();if(s&&s.length>0){let u=await Lf(),i=s.map(p=>{if(p.videos&&p.videos.length>0){let d=p.videos.map(l=>{let f=u.get(l.id);if(f){let h=If(f.blob);return {...l,objectUrl:h,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return l});return {...p,videos:d}}return p}),c=r&&i.find(p=>p.id===r)?r:i[0].id;e(co({slides:i,currentSlideId:c}));}e(n?Ii({title:n.title,description:n.description}):Fs(!0));}catch(s){console.error("Error loading persisted slides:",s),e(Fs(true));}finally{t(false);}})();},[e]),{isLoading:o}};var xm=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||""})),bm=new WeakSet,vm=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 ao(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},EL=()=>{let e=ft(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||bm.has(a))return;bm.add(a);let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Dn(),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&&s.find(c=>c.id===r)?r:s[0].id,i=xm(s);e(co({slides:i,currentSlideId:u})),await vm(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Dn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&s.find(c=>c.id===r)?r:s[0].id,i=xm(s);e(co({slides:i,currentSlideId:u})),await vm(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
|
|
7
7
|
|
|
8
8
|
lucide-react/dist/esm/shared/src/utils.js:
|
|
9
9
|
lucide-react/dist/esm/defaultAttributes.js:
|
|
@@ -18,5 +18,5 @@ lucide-react/dist/esm/lucide-react.js:
|
|
|
18
18
|
* This source code is licensed under the ISC license.
|
|
19
19
|
* See the LICENSE file in the root directory of this source tree.
|
|
20
20
|
*)
|
|
21
|
-
*/export{
|
|
21
|
+
*/export{cw as BASIC_EDITOR_TOOLBAR_CONFIG,Xw as BottomToolbar,Jb as Canvas,dw as DEFAULT_CONTEXT_MENU_CONFIG,kn as DEFAULT_TOOLBAR_CONFIG,pg as EditorRoot,Zl as PublishButton,pr as ScreenRecorder,rL as SlideNavigation,Ow as Toolbar,Uw as TopNavBar,uw as VIEWER_TOOLBAR_CONFIG,pi as addFillInTheBlanks,ai as addFlashcard,Qn as addImage,ii as addImageAnnotation,Zn as addLine,mi as addLongAnswer,ui as addMultipleChoice,si as addPhotoFrame,di as addPhotoFrameAnnotation,ei as addShape,fi as addShortAnswer,jn as addSlide,ti as addText,ci as addTrueFalse,ss as addVideo,kL as arrayBufferToBase64,gi as bringToFront,wi as clearCanvas,np as clearImageAnnotations,Dn as clearLocalData,lp as clearPhotoFrameAnnotations,Gn as createEmptySlide,hL as createViewerStore,Cs as deleteFillInTheBlanks,ms as deleteFlashcard,os as deleteImage,Es as deleteLineById,Ss as deleteLongAnswer,xs as deleteMultipleChoice,hs as deletePhotoFrame,us as deleteShape,ws as deleteShortAnswer,_n as deleteSlide,cs as deleteText,vs as deleteTrueFalse,is as deleteVideo,ks as duplicateFillInTheBlanks,ps as duplicateFlashcard,rs as duplicateImage,yi as duplicateLine,Is as duplicateLongAnswer,bs as duplicateMultipleChoice,gs as duplicatePhotoFrame,ds as duplicateShape,Ls as duplicateShortAnswer,Xn as duplicateSlide,fs as duplicateText,ys as duplicateTrueFalse,ls as duplicateVideo,Qo as editFlashcard,dp as editMultipleChoice,xL as exportSlideAsBlob,gL as exportSlideAsImage,vi as finalizeDrawing,SL as getCompressionStats,bL as getSlideDataURL,sd as loadCurrentSlideId,od as loadFromIndexedDB,Ii as loadPresentationMetadata,ld as loadPresentationMetadataFromDB,co as loadSlides,_l as mergeToolbarConfig,oi as nextFlashcard,TL as prepareFormData,CL as prepareSlidesForPublishing,ri as previousFlashcard,Rs as redo,as as removeLine,rp as reorderSlides,id as savePresentationMetadata,ue as saveToHistory,go as selectAllSlides,Ci as selectAllSlidesIncludingInactive,ki as selectCanAddSlide,ge as selectCurrentSlide,ho as selectCurrentSlideId,Ti as selectMetadataLoaded,nr as selectPresentationMetadata,pp as selectSlideById,xi as sendToBack,hi as setActivityType,Ms as setAltText,As as setAudioData,Jn as setBackgroundColor,$n as setCurrentSlide,or as setEditingActivity,sr as setEditingTextId,cp as setLines,Ts as setLink,Fs as setMetadataLoaded,jo as setPenColor,Si as setPresentationDescription,Li as setPresentationTitle,Ua as setShowFlashcardForm,ga as setShowMcqForm,wt as setSketchMode,qr as setStrokeWidth,ta as setTool,op as setViewerMode,mm as simplifyFlatPoints,pm as simplifyLine,LL as simplifyLines,pL as store,ni as toggleImageDrawingMode,bi as toggleLock,li as togglePhotoFrameDrawingMode,mp as toggleSketchMode,qa as toggleVideoPlaying,Ds as undo,rr as updateElementOrder,ar as updateFillInTheBlanks,po as updateFlashcard,fo as updateImage,sp as updateImageAnnotation,up as updateLastLine,fp as updateLinePosition,Ps as updateLineTransform,tr as updateLongAnswer,pa as updateMultipleChoice,Ha as updatePhotoFrame,ip as updatePhotoFrameAnnotation,mo as updateShape,er as updateShortAnswer,Yn as updateSlideThumbnail,Dt as updateText,ha as updateTrueFalse,ns as updateVideo,ve as useDispatch,EL as useInitialSlides,$i as useModalPortal,Q as useSelector,PL as useSlidesPersistence};//# sourceMappingURL=index.js.map
|
|
22
22
|
//# sourceMappingURL=index.js.map
|