@turnix-co/konva-editor 3.0.55 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +21 -2
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
export{default as Konva}from'konva';import*as Le from'react';import Le__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,createContext,useState,useMemo,createElement,useContext,useId,useLayoutEffect}from'react';import {createPortal}from'react-dom';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {CameraPlus,Camera,Stop,X as X$1,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Palette,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,List,Plus,Export,CaretLeft,CaretDown,CaretUp,SidebarSimple,CaretRight,ArrowsOut,SpeakerHifiIcon,NotePencilIcon,PencilSimple,CopySimple,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,TextUnderline,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Copy,Pen}from'@phosphor-icons/react/dist/ssr';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import jd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import $u from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {Stack as Stack$1,X as X$2,DotsSixVertical,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Bd=e=>{throw TypeError(e)};var Od=(e,o,t)=>o.has(e)||Bd("Cannot "+t);var $=(e,o,t)=>(Od(e,o,"read from private field"),t?t.call(e):o.get(e)),Be=(e,o,t)=>o.has(e)?Bd("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Pe=(e,o,t,a)=>(Od(e,o,"write to private field"),o.set(e,t),t);var Nd=(e,o,t,a)=>({set _(n){Pe(e,o,n);},get _(){return $(e,o,a)}});var Se=()=>useDispatch(),J=e=>useSelector(e),$e=Se,Ee=J;var ri=20,si=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now(),isActive:true}),oi=si("Slide 1"),vp={slides:[oi],currentSlideId:oi.id,history:{[oi.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false,editingOverlayPosition:null,zoomLevel:1},Hd=createSlice({name:"canvas",initialState:vp,reducers:{addSlide:e=>{if(e.slides.length>=ri)return;let o=si(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(u=>u.isActive).length<=1)return;let r=e.slides.findIndex(u=>u.id===t);if(r===-1)return;let s=e.slides[r];if(a?(s.isActive=false,s.updatedAt=Date.now()):(e.slides.splice(r,1),delete e.history[t]),e.currentSlideId===t){let u=e.slides.filter(i=>i.isActive);u.length>0&&(e.currentSlideId=u[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=ri)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],n={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),isActive:true,lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,n),e.currentSlideId=n.id,e.history[n.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},setViewerMode:(e,o)=>{e.viewerMode=o.payload;},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[n]=e.slides.splice(t,1);e.slides.splice(a,0,n);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(n=>n.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload);if(a){let n={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(n),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,newTimestamp:r}=o.payload;switch(n){case "image":let s=t.images.find(g=>g.id===a);s&&(s.timestamp=r);break;case "video":let u=t.videos.find(g=>g.id===a);u&&(u.timestamp=r);break;case "shape":let i=t.shapes.find(g=>g.id===a);i&&(i.timestamp=r);break;case "text":let c=t.texts.find(g=>g.id===a);c&&(c.timestamp=r);break;case "flashcard":let m=t.flashcards.find(g=>g.id===a);m&&(m.timestamp=r);break;case "photoFrame":let l=t.photoFrames.find(g=>g.id===a);l&&(l.timestamp=r);break;case "mcq":let d=t.multipleChoices.find(g=>g.id===a);d&&(d.timestamp=r);break;case "trueFalse":let f=t.trueFalses.find(g=>g.id===a);f&&(f.timestamp=r);break;case "shortAnswer":let h=t.shortAnswers.find(g=>g.id===a);h&&(h.timestamp=r);break;case "longAnswer":let p=t.LongAnswer.find(g=>g.id===a);p&&(p.timestamp=r);break;case "fillInTheBlanks":let y=t.fillInTheBlanks.find(g=>g.id===a);y&&(y.timestamp=r);break;case "line":let w=t.lines.find(g=>g.id===a);w&&(w.timestamp=r);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);if(a){let n={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(n),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(n=>n.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(n=>n.id===o.payload);if(a){let n={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(n),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(n=>n.id===o.payload);if(a){let n={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(n),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let n=t.multipleChoices[t.multipleChoices.length-1];a.x=n.x+20,a.y=n.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},updateMultipleChoiceDragAndDrop(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a].dragDropPos=o.payload.dragDropPos,t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(n=>n.id===o.payload);if(a){let n={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(n),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let n=t.trueFalses[t.trueFalses.length-1];a.x=n.x+20,a.y=n.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(n=>n.id===o.payload);if(a){let n={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(n),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let n=t.shortAnswers[t.shortAnswers.length-1];a.x=n.x+20,a.y=n.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(n=>n.id===o.payload);if(a){let n={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(n),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let n=t.LongAnswer[t.LongAnswer.length-1];a.x=n.x+20,a.y=n.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload);if(a){let n={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(n),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let n=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=n.x+20,a.y=n.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(n=>n.id===o.payload);if(a){let n={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(n),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.images.splice(r,1);t.images.push(s);}}else if(n==="video"){let r=t.videos.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.videos.splice(r,1);t.videos.push(s);}}else if(n==="shape"){let r=t.shapes.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shapes.splice(r,1);t.shapes.push(s);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.flashcards.splice(r,1);t.flashcards.push(s);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.photoFrames.splice(r,1);t.photoFrames.push(s);}}else if(n==="text"){let r=t.texts.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.texts.splice(r,1);t.texts.push(s);}}else if(n==="trueFalse"){let r=t.trueFalses.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.trueFalses.splice(r,1);t.trueFalses.push(s);}}else if(n==="shortAnswer"){let r=t.shortAnswers.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shortAnswers.splice(r,1);t.shortAnswers.push(s);}}else if(n==="fillInTheBlanks"){let r=t.fillInTheBlanks.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.fillInTheBlanks.splice(r,1);t.fillInTheBlanks.push(s);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.images.splice(r,1);t.images.unshift(s);}}else if(n==="video"){let r=t.videos.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.videos.splice(r,1);t.videos.unshift(s);}}else if(n==="shape"){let r=t.shapes.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shapes.splice(r,1);t.shapes.unshift(s);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.flashcards.splice(r,1);t.flashcards.unshift(s);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.photoFrames.splice(r,1);t.photoFrames.unshift(s);}}else if(n==="text"){let r=t.texts.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.texts.splice(r,1);t.texts.unshift(s);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload,s=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);s&&(s.locked=!s.locked,"draggable"in s&&(s.draggable=!s.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,link:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="mcq"?t.multipleChoices:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.link=r,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,altText:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.altText=r,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,audioData:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.audioData=r,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},editingOverlayPosition:(e,o)=>{e.editingOverlayPosition=o.payload;},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(n=>n.id===o.payload);if(a){let n={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(n),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);if(a){let n={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(n),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let n=a.images.map((r,s)=>s).filter(r=>r!==a.currentIndex);if(n.length>0){let r=n[Math.floor(Math.random()*n.length)];a.navigationHistory.push(r),a.currentIndex=r;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);if(a){let n={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(n),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let n=o.past.pop();e.slides[t]=n;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let n=o.future.shift();e.slides[t]=n;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let n=JSON.parse(JSON.stringify(t));a.past.push(n),a.future=[],a.past.length>20&&a.past.shift();}catch(n){console.warn("Failed to save to history - data too large:",n),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;},setZoomLevel:(e,o)=>{e.zoomLevel=Math.max(.5,Math.min(2,o.payload));},zoomIn:e=>{e.zoomLevel=Math.min(2,e.zoomLevel+.25);},zoomOut:e=>{e.zoomLevel=Math.max(.5,e.zoomLevel-.25);},resetZoom:e=>{e.zoomLevel=1;}}}),{addSlide:ir,deleteSlide:lr,duplicateSlide:dr,setCurrentSlide:ur,setViewerMode:yp,updateSlideThumbnail:ii,setBackgroundColor:cr,reorderSlides:wp,loadSlides:vo,addLine:li,removeLine:yn,addImage:di,updateImage:yo,deleteImage:wn,duplicateImage:Sn,addVideo:wo,updateVideo:Ln,deleteVideo:In,duplicateVideo:Cn,toggleVideoPlaying:Ga,addShape:ui,updateShape:So,duplicateShape:kn,deleteShape:Tn,addText:ci,editingOverlayPosition:qd,updateText:Rt,deleteText:Mn,duplicateText:An,addFlashcard:fi,updateFlashcard:Lo,deleteFlashcard:Pn,duplicateFlashcard:En,editFlashcard:fr,nextFlashcard:mi,previousFlashcard:pi,addPhotoFrame:hi,updatePhotoFrame:ja,deletePhotoFrame:Dn,duplicatePhotoFrame:Rn,toggleImageDrawingMode:gi,addImageAnnotation:xi,updateImageAnnotation:Sp,clearImageAnnotations:Lp,togglePhotoFrameDrawingMode:bi,addPhotoFrameAnnotation:vi,updatePhotoFrameAnnotation:Ip,clearPhotoFrameAnnotations:Cp,addMultipleChoice:yi,updateMultipleChoice:Zt,updateMultipleChoiceDragAndDrop:wi,editMultipleChoice:kp,deleteMultipleChoice:Fn,duplicateMultipleChoice:Bn,addTrueFalse:Si,updateTrueFalse:Ft,deleteTrueFalse:On,duplicateTrueFalse:Nn,addShortAnswer:Li,updateShortAnswer:ya,deleteShortAnswer:Hn,duplicateShortAnswer:qn,addLongAnswer:Ii,updateLongAnswer:_a,deleteLongAnswer:Vn,duplicateLongAnswer:zn,addFillInTheBlanks:Ci,updateFillInTheBlanks:$a,deleteFillInTheBlanks:Un,duplicateFillInTheBlanks:Wn,setShowMcqForm:wa,setShowFlashcardForm:Xa,setActivityType:ki,setEditingActivity:mr,bringToFront:Ti,sendToBack:Mi,toggleLock:Ai,setLink:Kn,setAltText:Gn,setAudioData:jn,updateLastLine:Tp,finalizeDrawing:Pi,setLines:Mp,updateLinePosition:Ap,updateLineTransform:_n,deleteLineById:$n,duplicateLine:Ei,updateElementOrder:pr,clearCanvas:hr,undo:Io,redo:Co,saveToHistory:fe,toggleSketchMode:Pp,setSketchMode:wt,setEditingTextId:gr,setPresentationTitle:Di,setPresentationDescription:Ri,loadPresentationMetadata:Fi,setMetadataLoaded:Xn,setZoomLevel:BL,zoomIn:OL,zoomOut:NL,resetZoom:Vd}=Hd.actions;var zd=e=>e.canvas.slides,Sa=e=>e.canvas.currentSlideId,ye=createSelector([zd,Sa],(e,o)=>e.find(t=>t.id===o)),La=createSelector([zd],e=>e.filter(o=>o.isActive!==false)),Bi=e=>e.canvas.slides,xr=createSelector([La],e=>e.length<ri),Ep=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},br=e=>e.canvas.presentationMetadata,Oi=e=>e.canvas.metadataLoaded,Yn=e=>e.canvas.viewerMode,Ni=Hd.reducer;var Wd=e=>{let o=Se(),t=useRef(null),a=useRef(false),n=J(f=>f.toolbar.selectedTool),r=J(f=>f.toolbar.penColor),s=J(f=>f.toolbar.strokeWidth),u=J(f=>f.canvas.isSketchMode),i=J(f=>f.canvas.slides.find(p=>p.id===f.canvas.currentSlideId)?.lines||[]),c=useCallback(f=>{t.current=f;},[]),m=useCallback(f=>{n==="pen"&&t.current&&(o(fe()),t.current.startDrawing(f),a.current=true);},[n,o]),l=useCallback(f=>{!t.current||!a.current||t.current.draw(f);},[]),d=useCallback(()=>{if(!t.current||!a.current)return;let f=t.current.stopDrawing();a.current=false,f&&f.points.length>=4&&o(li(f)),o(Pi()),e?.();},[o,e]);return {lines:i,tool:n,color:r,strokeWidth:s,isSketchMode:u,setCanvasRef:c,startDrawing:m,draw:l,stopDrawing:d}};var _d=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:n,isSketchMode:r,style:s,xOffset:u=0,yOffset:i=0},c)=>{let m=useRef(null),l=useRef(false),d=useRef([]),f=useRef([]),h=useRef(null),p=useRef(t),y=useRef(a),w=useRef(n),g=useRef(r),x=useRef(u),I=useRef(i);useEffect(()=>{p.current=t,y.current=a,w.current=n,g.current=r,x.current=u,I.current=i;},[t,a,n,r,u,i]);let L=useCallback(()=>{let C=m.current;if(!C)return;let b=C.getContext("2d");b&&b.clearRect(0,0,C.width,C.height);},[]),P=useCallback(()=>{let C=m.current,b=f.current;if(!C||b.length<1)return;let v=C.getContext("2d");if(!v)return;if(v.clearRect(0,0,C.width,C.height),p.current==="eraser"?(v.globalCompositeOperation="destination-out",v.fillStyle="rgba(0,0,0,1)"):(v.globalCompositeOperation="source-over",v.fillStyle=y.current),b.length===1){v.beginPath(),v.arc(b[0].x,b[0].y,w.current/2,0,Math.PI*2),v.fill();return}let T=jd(b,{size:w.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:F=>F,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(T.length<2)){v.beginPath(),v.moveTo(T[0][0],T[0][1]);for(let F=1;F<T.length;F++)v.lineTo(T[F][0],T[F][1]);v.closePath(),v.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:C=>{l.current=true;let b={x:C.x-x.current,y:C.y-I.current};d.current=[{x:C.x,y:C.y}],f.current=[b],h.current=C,P();},draw:C=>{if(!l.current||!h.current)return;let b=C.x-h.current.x,v=C.y-h.current.y;if(Math.sqrt(b*b+v*v)<2)return;let T={x:C.x-x.current,y:C.y-I.current};d.current.push({x:C.x,y:C.y}),f.current.push(T),h.current=C,P();},stopDrawing:()=>{if(!l.current)return null;if(l.current=false,d.current.length<2)return d.current=[],f.current=[],h.current=null,L(),null;let b=jd(d.current,{size:w.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:k=>k,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(k=>[k[0],k[1]]),v={tool:p.current,points:b,color:y.current,strokeWidth:w.current,isSketch:true};return d.current=[],f.current=[],h.current=null,L(),v},clear:()=>{L(),d.current=[],f.current=[],h.current=null,l.current=false;},isDrawing:()=>l.current,getCanvasElement:()=>m.current}),[L,P]),useEffect(()=>{let C=m.current;C&&(C.width=e,C.height=o);},[e,o]),jsx("canvas",{ref:m,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});_d.displayName="DirectDrawingCanvas";var $d=_d;var Yd=e=>{let o=Se(),a=J(ye)?.images||[],n=useRef(new Map),r=useRef(new Map),s=useRef(new Set);useEffect(()=>{let m=new Set(a.map(l=>l.id));s.current.forEach(l=>{if(!m.has(l)){let d=r.current.get(l);d&&(d.src="",r.current.delete(l)),n.current.delete(l);}}),s.current=m;},[a]),useEffect(()=>()=>{r.current.forEach(m=>{m.src="";}),r.current.clear(),n.current.clear();},[]);let u=useCallback(m=>{if(r.current.has(m.id))return r.current.get(m.id);let l=new window.Image;return (m.src.startsWith("http://")||m.src.startsWith("https://"))&&(l.crossOrigin="anonymous"),l.src=m.src,r.current.set(m.id,l),l},[]),i=useCallback((m,l)=>{let d=m.target,f=d.id();a.find(p=>p.id===f)&&(o(yo({id:f,x:d.x(),y:d.y(),width:d.width(),height:d.height(),rotation:d.rotation()})),l?.());},[a,o]),c=useCallback((m,l)=>{let d=l.target,f=n.current.get(m);if(!f){console.error("\u274C Image node not found for id:",m);return}let h=d.scaleX(),p=d.scaleY(),y=d.rotation(),w=f.width(),g=f.height(),x=Math.max(5,w*h),I=Math.max(5,g*p);d.scaleX(1),d.scaleY(1),f.width(x),f.height(I),o(yo({id:m,width:x,height:I,x:d.x(),y:d.y(),rotation:y})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:u,imageRefs:n,handleDragEnd:i,handleImageTransformEnd:c}};var Zd=e=>{let o=useDispatch(),t=useSelector(ye),a=useRef(new Map),n=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((u,i)=>{let c=i.target,m=c.scaleX(),l=c.scaleY(),d=c.rotation();o(Zt({id:u,scaleX:m,scaleY:l,x:c.x(),y:c.y(),rotation:d})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:n,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(u,i)=>{o(Zt({id:i,x:u.target.x(),y:u.target.y()})),e?.();}}};var Jd=e=>{let o=useDispatch(),t=useSelector(ye),a=useRef(new Map),n=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((u,i)=>{let c=i.target,m=c.scaleX(),l=c.scaleY(),d=c.rotation(),f=Math.max(5,c.width()*m),h=Math.max(5,c.height()*l);c.scaleX(1),c.scaleY(1),c.width(f),c.height(h),o(Ft({id:u,width:f,height:h,x:c.x(),y:c.y(),rotation:d})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:n,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(u,i)=>{o(Ft({id:i,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var Qd=e=>{let o=Se(),a=J(ye)?.videos||[],n=useRef(new Map),r=useCallback(i=>{o(Ga(i));},[o]),s=useCallback((i,c)=>{let m=c.target;o(Ln({id:i,x:m.x(),y:m.y()})),e?.();},[o,e]),u=useCallback((i,c)=>{let m=c.target,l=m.scaleX(),d=m.scaleY(),f=m.rotation(),h=Math.max(5,m.width()*l),p=Math.max(5,m.height()*d);m.scaleX(1),m.scaleY(1),m.width(h),m.height(p),o(Ln({id:i,width:h,height:p,x:m.x(),y:m.y(),rotation:f})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:n,handleVideoClick:r,handleVideoDragEnd:s,handleVideoTransformEnd:u}};var au=e=>{let o=Se(),a=J(ye)?.shapes||[],n=useRef(new Map),r=useRef(new Map),[s,u]=useState(false),i=useCallback((m,l)=>{let d=l.target;o(So({id:m,x:d.x(),y:d.y()})),e?.();},[o,e]),c=useCallback((m,l)=>{let d=l.target,f=a.find(x=>x.id===m);if(!f)return;let h=d.scaleX(),p=d.scaleY(),y=f.type?.toLowerCase();y==="arrow"||y==="line"||(d.scaleX(1),d.scaleY(1));let g={id:m,x:d.x(),y:d.y(),width:Math.max(5,d.width()*h),height:Math.max(5,d.height()*p),rotation:d.rotation()};switch(y){case "circle":g.radius=d.width()*h/2;break;case "star":g.innerRadius=d.width()*h/4,g.outerRadius=d.width()*h/2;break;case "triangle":g.radius=d.width()*h/2;break;case "ellipse":g.radiusX=d.width()*h/2,g.radiusY=d.height()*p/2;break;case "polygon":g.radius=d.width()*h/2;break;case "ring":let x=h;g.innerRadius=f.innerRadius&&f.innerRadius*x,g.outerRadius=f.outerRadius&&f.outerRadius*x;break;case "wedge":g.radius=f.radius&&f.radius*h;break;case "arc":g.innerRadius=f.innerRadius&&f.innerRadius*h,g.outerRadius=f.outerRadius&&f.outerRadius*h;break;case "arrow":case "line":{g.scaleX=h,g.scaleY=p,delete g.width,delete g.height;break}}o(So(g)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:n,isDragging:s,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:c}};var ru=(e,o)=>{let t=$e(),n=J(ye)?.texts||[],r=useRef(new Map),[s,u]=useState(null),[i,c]=useState("");return {texts:n,textRefs:r,handleDragEnd:(y,w)=>{let g=y.target;t(fe()),t(Rt({id:w,x:g.x(),y:g.y()})),e();},handleTransformEnd:y=>{let w=r.current.get(y);if(!w)return;let g=w.scaleX(),x=w.scaleY(),I=n.find(P=>P.id===y);if(!I)return;let L=(g+x)/2;w.scaleX(1),w.scaleY(1),t(fe()),t(Rt({id:y,x:w.x(),y:w.y(),width:Math.max(5,(I.width||100)*g),height:Math.max(5,(I.height||50)*x),fontSize:Math.round(Math.max(8,I.fontSize*L)),rotation:w.rotation()})),e();},handleDoubleClick:y=>{let w=n.find(g=>g.id===y);w&&!w.locked&&(u(y),c(w.text));},startEditing:y=>{let w=n.find(g=>g.id===y);w&&!w.locked&&(u(y),c(w.text));},editingTextId:s,editingValue:i,handleEditingChange:y=>{c(y);},finishEditing:()=>{if(s){let y=r.current.get(s),w=n.find(x=>x.id===s);t(fe());let g={id:s,text:i};if(w&&(w.fontWeight!==void 0&&(g.fontWeight=w.fontWeight),w.fontStyle!==void 0&&(g.fontStyle=w.fontStyle),w.textDecoration!==void 0&&(g.textDecoration=w.textDecoration)),o?.current&&i.trim()){let x=o.current,I=x.offsetWidth,L=x.offsetHeight,P=1;if(y){let U=y.getStage();U&&(P=U.scaleX());}let C=14,b=(I-C)/P,v=(L-C)/P,k=i.split(`
|
|
3
|
-
`).length,F=n.find(U=>U.id===s)?.fontSize||24,O=k*F*1.2+10;g.width=Math.max(200,b),g.height=Math.max(50,v,O);}else if(y&&i.trim()){let x=y.text(),I=y.width();y.text(i),y.width(void 0);let L=y.width(),P=y.height();y.text(x),y.width(I),g.width=Math.max(200,L+20),g.height=Math.max(50,P+20);}t(Rt(g)),u(null),c(""),t(gr(null)),e();}}}};var nu=e=>{let o=useDispatch(),a=useSelector(ye)?.shortAnswers||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(ya({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:n,handleShortAnswerDragEnd:r}};var su=e=>{let o=useDispatch(),t=useSelector(ye),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),n=useCallback((r,s)=>{let u=r.target;o(_a({id:s,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:n}};var lu=e=>{let o=Se(),a=J(ye)?.flashcards||[],n=useRef(new Map),r=useRef(new Map),s=useCallback((l,d)=>{if(r.current.has(d))return r.current.get(d);let f=new window.Image;return (l.startsWith("http://")||l.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=l,r.current.set(d,f),f},[]),u=useCallback(l=>{let d=l.target,f=d.id();a.find(p=>p.id===f)&&(o(Lo({id:f,x:d.x(),y:d.y()})),e?.());},[a,o,e]),i=useCallback((l,d)=>{let f=d.target,h=f.scaleX(),p=f.scaleY(),y=f.rotation(),w=Math.max(50,f.width()*h),g=Math.max(50,f.height()*p);f.scaleX(1),f.scaleY(1),f.width(w),f.height(g),o(Lo({id:l,width:w,height:g,x:f.x(),y:f.y(),rotation:y})),f.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(l=>{o(mi(l)),e?.();},[o,e]),m=useCallback(l=>{o(pi(l)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:n,handleDragEnd:u,handleFlashcardTransformEnd:i,handleNext:c,handlePrevious:m}};var cu=e=>{let o=Se(),a=J(ye)?.photoFrames||[],n=useRef(new Map),[r,s]=useState(new Map),u=useCallback((f,h)=>{console.log("handleDragEnd"),o(ja({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),i=useCallback((f,h)=>{let p=h.target,y=p.scaleX(),w=p.scaleY(),g=p.rotation(),x=a.find(P=>P.id===f);if(!x)return;let I=Math.max(100,x.width*y),L=Math.max(100,x.height*w);p.scaleX(1),p.scaleY(1),o(ja({id:f,width:I,height:L,x:p.x(),y:p.y(),rotation:g})),p.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(p=>{let y=new Map(p);return y.set(f,h),y}),o(ja({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),m=useCallback(f=>{let h=r.get(f);h&&(h.getTracks().forEach(p=>p.stop()),s(p=>{let y=new Map(p);return y.delete(f),y}),o(ja({id:f,isCapturing:false})),e?.());},[r,o,e]),l=useCallback((f,h)=>{let p=document.createElement("canvas");p.width=h.videoWidth,p.height=h.videoHeight;let y=p.getContext("2d");if(y){y.drawImage(h,0,0,p.width,p.height);let w=p.toDataURL("image/jpeg",.8);return o(ja({id:f,capturedImageUrl:w,isCapturing:false})),m(f),e?.(),w}return null},[o,m,e]),d=useRef(r);return useEffect(()=>{d.current=r;},[r]),useEffect(()=>()=>{d.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:n,handleDragEnd:u,handlePhotoFrameTransformEnd:i,startCamera:c,stopCamera:m,capturePhoto:l,cameraStreams:r}};var fu=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,s)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...s,width:Math.max(o.minWidth,Math.min(s.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(s.height,o.maxHeight))}:s,[o]),a=useCallback((r,s,u,i,c,m,l,d=[])=>{if(e.current){if(r&&!d.find(p=>p.id===r)?.isPlaying){let p=s.get(r)||u.get(r)||i.get(r)||c.get(r)||m.get(r)||(l?l.get(r):null);if(p){e.current.boundBoxFunc(t),e.current.nodes([p]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),n=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:n,boundBoxFunc:t}};var nh=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},gu=(e,o)=>{let t=$e(),a=Ee(Yn),n=useRef(e);useEffect(()=>{n.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(ii({id:n.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),s=nh(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var ih=e=>e.flatMap(o=>[o[0],o[1]]),Jn=(e,o)=>{let t=jd(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:a=>a,start:{taper:0,cap:true},end:{taper:0,cap:true}});return ih(t)};var xu=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null),u=J(x=>x.toolbar.selectedTool),i=J(x=>x.toolbar.penColor),c=J(x=>x.toolbar.strokeWidth),m=J(x=>x.canvas.isSketchMode),l=J(x=>x.canvas.slides.find(L=>L.id===x.canvas.currentSlideId)?.images.find(L=>L.id===e)),d=l?.annotations||[],f=l?.isDrawingMode||false,h=l?.width||1,p=l?.height||1,y=useCallback(x=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,n.current=[{x:x.x,y:x.y}];let I=x.x/h,L=x.y/p;s({tool:u,points:[I,L],color:i,strokeWidth:c/h,isSketch:m});},[u,i,c,m,h,p]),w=useCallback(x=>{if(!t.current||!r)return;a.current=true;let I=n.current[n.current.length-1];if(Math.sqrt(Math.pow(x.x-I.x,2)+Math.pow(x.y-I.y,2))<2)return;n.current.push({x:x.x,y:x.y});let P;if(m)P=Jn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,v)=>v%2===0?b/h:b/p);else {let C=x.x/h,b=x.y/p;P=[...r.points,C,b];}s(C=>C?{...C,points:P}:null);},[m,c,r,h,p]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(xi({imageId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:d,activeLine:r,isDrawingMode:f,startDrawing:y,draw:w,stopDrawing:g,tool:u}};function qe({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),n=useRef(null);return {createHandlers:useCallback((s,u)=>({onTouchStart:i=>{let c=i.evt.touches[0];n.current={x:c.clientX,y:c.clientY},a.current=setTimeout(()=>{e(s,u)(i.evt);},o);},onTouchMove:i=>{if(!n.current)return;let c=i.evt.touches[0],m=Math.abs(c.clientX-n.current.x),l=Math.abs(c.clientY-n.current.y);(m>t||l>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),n.current=null;}}),[e,o,t])}}var Su=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u})=>{let{annotations:i,activeLine:c,stopDrawing:d,tool:f}=xu(e.id),{createHandlers:h}=qe({onLongPress:u});useEffect(()=>{let x=t.current.get(e.id);x&&(x.width()!==e.width||x.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:x.width(),konvaHeight:x.height()}),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[d,p]);let y=x=>{{r(e.id);return}},w=x=>{return;},g=x=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="eraser",children:[jsx(Image$1,{id:e.id,ref:x=>{if(x)t.current.set(e.id,x),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw();else {let I=t.current.get(e.id);I?._contextMenuCleanup&&I._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:x=>n(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:x=>{x.evt.preventDefault();let I=x.evt;s(I,e.id,"image");},...f!=="pen"&&f!=="eraser"?{onClick:y,onTap:y,onMouseDown:y,onMouseMove:w,onMouseUp:g,...h(e.id,"image")}:{}}),i?.map((x,I)=>{let L=x.points.map((C,b)=>b%2===0?C*e.width+e.x:C*e.height+e.y),P=x.strokeWidth*e.width;return jsx(Line,{points:L,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:P,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},I)}),c&&jsx(Line,{points:c.points.map((x,I)=>I%2===0?x*e.width+e.x:x*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});Su.displayName="ImageWithDrawing";var Ki=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u})=>jsx(Fragment,{children:e.map(i=>{let c=o(i);return c?jsx(Su,{img:i,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u},i.id):null})}));Ki.displayName="ImageLayer";var bh=({src:e,x:o,id:t,y:a,width:n,height:r,isSelected:s,rotation:u=0,onTransformEnd:i,onDragEnd:c})=>{let m=Se(),l=useRef(null),d=f=>{m(Ga(f));};return jsxs(Group,{draggable:true,x:o,y:a,width:n,height:r,rotation:u,onDragEnd:c,onTransformEnd:i,children:[jsx(Rect,{width:n,height:r,fill:"black",stroke:s?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${n}px`,height:`${r}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:l,src:e,controls:true,autoPlay:true,onClick:()=>d(t),onSeeking:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Lu=bh;var kh=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,nodeRef:s})=>{let[u,i]=useState(null),c=useSelector(p=>p.toolbar.selectedTool),m=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let p=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(p.crossOrigin="anonymous"),p.src=e.thumbnailDataUrl,p.onload=()=>{i(p);};}},[e.thumbnailDataUrl]),!u)return null;let l=e.width/2,d=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,80));return jsxs(Group,{draggable:!m,listening:!m,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...m?{}:{onDragEnd:a,onTransformEnd:n},ref:p=>{if(s(p),p){let y=p.getStage()?.container();if(y){let w=g=>{let x=p.getStage()?.getPointerPosition();if(x){let I={x:e.x,y:e.y,width:e.width,height:e.height};x.x>=I.x&&x.x<=I.x+I.width&&x.y>=I.y&&x.y<=I.y+I.height&&r(g);}};y.addEventListener("contextmenu",w),p._contextMenuCleanup=()=>{y.removeEventListener("contextmenu",w);};}}},children:[jsx(Image$1,{image:u,width:e.width,height:e.height,listening:!m,...m?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:l,y:d,radius:h,fill:"white",listening:!m,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...m?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:l,y:d,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!m,...m?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:l+h*.1,y:d,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!m,...m?{}:{onClick:t,onTap:t}})]})},Cu=kh;var _i=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:n,onTransformEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(u=>jsxs(Le__default.Fragment,{children:[jsx(Cu,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>a(u.id),onDragEnd:i=>n(u.id,i),onTransformEnd:i=>r(u.id,i),onContextMenu:i=>s(i,u.id,"video"),nodeRef:i=>{i?t.current.set(u.id,i):t.current.delete(u.id);}}),u.isPlaying&&!u.isRecorded&&jsx(Lu,{id:u.id,src:u.objectUrl,x:u.x,y:u.y,width:u.width,height:u.height,isSelected:false,rotation:u.rotation,onTransformEnd:i=>r(u.id,i),onDragEnd:i=>n(u.id,i)})]},u.id))}));_i.displayName="VideoLayer";var $i=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:n,handleShapeDragStart:r,onContextMenu:s,onLongPress:u})=>{let i=useSelector(l=>l.toolbar.selectedTool),c=i==="pen"||i==="eraser",{createHandlers:m}=qe({onLongPress:u});return jsx(Fragment,{children:e.map((l,d)=>{let f=l.id||d,h={id:l.id,x:l.x,y:l.y,rotation:l.rotation,draggable:!l.locked&&!c,listening:!c,fill:l.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(l.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},radius:l.radius||l.width/2,width:l.width,height:l.width},f);case "star":return jsx(Star,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},numPoints:5,innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},sides:3,radius:l.radius||l.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},sides:l.sides||6,radius:l.radius||l.width/2},f);case "ellipse":return jsx(Ellipse,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},radiusX:l.radiusX||l.width/2,radiusY:l.radiusY||l.height/2},f);case "ring":return jsx(Ring,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},f);case "wedge":return jsx(Wedge,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},radius:l.radius||l.width/2,angle:l.angle||60},f);case "arrow":return jsx(Arrow,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},points:l.points||[0,0,l.width,0],pointerLength:l.pointerLength||10,pointerWidth:l.pointerWidth||10,stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},f);case "line":return jsx(Line,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},points:l.points||[0,0,l.width,0],stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2,angle:l.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);},...h,draggable:!l.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(l.id,p),onTransformEnd:p=>a(l.id,p),onClick:()=>n(l.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,l.id,"shape");},...m(l.id,"shape")},width:l.width,height:l.height,cornerRadius:l.type==="rounded-rectangle"?10:0},f)}})})});$i.displayName="ShapeLayer";var Mu=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:n,onContextMenu:r,onDoubleClick:s,editingTextId:u,onLongPress:i})=>{useEffect(()=>{e.forEach(d=>{let f=o.current.get(d.id);f&&(f.cache(),f.getLayer()?.batchDraw());});},[e,o]);let c=useSelector(d=>d.toolbar.selectedTool),m=c==="pen"||c==="eraser",{createHandlers:l}=qe({onLongPress:i});return jsx(Fragment,{children:e.map(d=>{let f=d.id===u,h=d.fontWeight==="bold",p=h?Math.max(1,d.fontSize/25):0;return jsx(Text,{id:d.id,ref:y=>{y?o.current.set(d.id,y):o.current.delete(d.id);},text:d.text,x:d.x,y:d.y,width:d.width,height:d.height,rotation:d.rotation,draggable:!d.locked&&!f&&!m,listening:!m,fontSize:d.fontSize,fontFamily:d.fontFamily,fontStyle:d.fontStyle,fontWeight:d.fontWeight,textDecoration:d.textDecoration,fill:d.fill,stroke:h?d.fill:void 0,strokeWidth:p,align:d.align,wrap:"word",lineHeight:1.2,opacity:f?0:1,visible:!f,...m?{}:{onClick:()=>n(d.id),onTap:()=>n(d.id),onDblClick:()=>s(d.id),onDblTap:()=>s(d.id),onDragEnd:y=>t(y,d.id),onTransformEnd:()=>a(d.id),onContextMenu:y=>{y.evt.preventDefault();let w=y.evt;r(w,d.id,"text");},...l(d.id,"text")}},d.id)})})};var Jh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onNext:s,onPrevious:u,nodeRef:i,touchHandlers:c,currentTool:m})=>{let[l,d]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let g=new window.Image,x=e.images[e.currentIndex];(x.startsWith("http://")||x.startsWith("https://"))&&(g.crossOrigin="anonymous"),g.src=x,g.onload=()=>{d(g);};}},[e.images,e.currentIndex]),!l||e.images.length===0)return null;let f=8,h=2,p=Math.min(e.width,e.height)*.08,y=Math.max(16,Math.min(p,32)),w=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked&&m==="select",x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:n,...c,ref:g=>{if(i(g),g){let x=g.getStage()?.container();if(x){let I=L=>{let P=g.getStage()?.getPointerPosition();if(P){let C={x:e.x,y:e.y,width:e.width,height:e.height};P.x>=C.x&&P.x<=C.x+C.width&&P.y>=C.y&&P.y<=C.y+C.height&&r(L);}};x.addEventListener("contextmenu",I),g._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",I);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,stroke:"#E5E7EB",strokeWidth:h,listening:false}),jsx(Image$1,{x:h+4,y:h+4,image:l,width:e.width-(h+4)*2,height:e.height-(h+4)*2,cornerRadius:f-h,onClick:t,onTap:t}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:w+y,y:e.height/2,onClick:g=>{g.cancelBubble=true,u();},onTap:g=>{g.cancelBubble=true,u();},children:[jsx(Circle,{radius:y,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-w-y,y:e.height/2,onClick:g=>{g.cancelBubble=true,s();},onTap:g=>{g.cancelBubble=true,s();},children:[jsx(Circle,{radius:y,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Eu=Jh;var Ji=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onNext:s,onPrevious:u,onContextMenu:i,onLongPress:c})=>{let{createHandlers:m}=qe({onLongPress:c}),l=J(d=>d.toolbar.selectedTool);return jsx(Fragment,{children:e.map(d=>jsx(Eu,{flashcard:d,isSelected:t===d.id,onClick:()=>r(d.id),currentTool:l,onDragEnd:a,onTransformEnd:f=>n(d.id,f),onContextMenu:f=>i(f,d.id,"flashcard"),onNext:()=>s(d.id),onPrevious:()=>u(d.id),touchHandlers:m(d.id,"flashcard"),nodeRef:f=>{f?o.current.set(d.id,f):o.current.delete(d.id);}},d.id))})});Ji.displayName="FlashcardLayer";var Ru=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null);J(x=>x.toolbar.selectedTool);let i=J(x=>x.toolbar.penColor),c=J(x=>x.toolbar.strokeWidth),m=J(x=>x.canvas.isSketchMode),l=J(x=>x.canvas.slides.find(L=>L.id===x.canvas.currentSlideId)?.photoFrames.find(L=>L.id===e)),d=l?.annotations||[],f=l?.isDrawingMode||false,h=l?.width||1,p=l?.height||1,y=useCallback(x=>{if(!f)return;t.current=true,a.current=false,n.current=[{x:x.x,y:x.y}];let I=x.x/h,L=x.y/p;s({tool:"pen",points:[I,L],color:i,strokeWidth:c/h,isSketch:m});},[f,i,c,m,h,p]),w=useCallback(x=>{if(!t.current||!r)return;a.current=true;let I=n.current[n.current.length-1];if(Math.sqrt(Math.pow(x.x-I.x,2)+Math.pow(x.y-I.y,2))<2)return;n.current.push({x:x.x,y:x.y});let P;if(m)P=Jn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,v)=>v%2===0?b/h:b/p);else {let C=x.x/h,b=x.y/p;P=[...r.points,C,b];}s(C=>C?{...C,points:P}:null);},[m,c,r,h,p]),g=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(vi({frameId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:d,activeLine:r,isDrawingMode:f,startDrawing:y,draw:w,stopDrawing:g}};var sg=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onStartCamera:s,onCapture:u,cameraStream:i,nodeRef:c,touchHandlers:m})=>{let[l,d]=useState(null),[f,h]=useState(null),p=useRef(null),y=useRef(null),w=useRef(null),g=useRef(null),x=useRef(0),I=33,L=useSelector(z=>z.toolbar.selectedTool),P=L==="pen"||L==="eraser",{annotations:C,activeLine:b,isDrawingMode:v,startDrawing:k,draw:T,stopDrawing:F}=Ru(e.id);useEffect(()=>{if(!v)return;let z=()=>{F();},N=()=>{F();};return window.addEventListener("mouseup",z),window.addEventListener("touchend",N),()=>{window.removeEventListener("mouseup",z),window.removeEventListener("touchend",N);}},[F,v]),useEffect(()=>{if(e.capturedImageUrl){let z=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(z.crossOrigin="anonymous"),z.src=e.capturedImageUrl,z.onload=()=>{d(z);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),y.current||(y.current=document.createElement("canvas"));let z=p.current,N=y.current;z.srcObject=i;let _=()=>{N.width=z.videoWidth||640,N.height=z.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",N.width,N.height);let Z=ae=>{if(ae-x.current<I){w.current=requestAnimationFrame(Z);return}x.current=ae;let Q=N.getContext("2d");if(Q&&z.readyState===z.HAVE_ENOUGH_DATA){Q.drawImage(z,0,0,N.width,N.height);let pe=N.toDataURL("image/jpeg",.6),ue=new window.Image;ue.onload=()=>{h(ue);},ue.src=pe;}w.current=requestAnimationFrame(Z);};w.current=requestAnimationFrame(Z);};return z.onloadedmetadata=_,z.readyState>=z.HAVE_METADATA&&_(),z.play().catch(Z=>console.error("Error playing video:",Z)),()=>{w.current&&(cancelAnimationFrame(w.current),w.current=null);}}return ()=>{h(null),g.current&&(g.current.src="");}},[e.isCapturing,i]);let V=()=>{p.current&&e.isCapturing&&u(p.current);},O=z=>{if(e.capturedImageUrl){if(!v){t();return}let N=z.currentTarget,_=N.getAbsoluteTransform().copy(),ae=N.getStage()?.getPointerPosition();if(ae){_.invert();let Q=_.point(ae);k(Q);}z.cancelBubble=true;}else t();},U=z=>{if(!v||!e.capturedImageUrl)return;let N=z.currentTarget,_=N.getAbsoluteTransform().copy(),ae=N.getStage()?.getPointerPosition();if(ae){_.invert();let Q=_.point(ae);T(Q);}},H=()=>{!v||!e.capturedImageUrl||F();},K=e.isCapturing?f:l,E=Math.min(e.width,e.height)*.12,W=Math.max(25,Math.min(E,50)),te=e.width/2,G=e.height/2;return jsxs(Group,{id:e.id,draggable:!v&&!P,listening:true,onClick:t,onTap:t,x:e.x,y:e.y,...m,...P?{}:{onDragEnd:a,onTransformEnd:n},rotation:e.rotation,width:e.width,height:e.height,ref:z=>{if(c(z),z){let N=z.getStage()?.container();if(N){let _=Z=>{let ae=z.getStage()?.getPointerPosition();if(ae){let Q={x:e.x,y:e.y,width:e.width,height:e.height};ae.x>=Q.x&&ae.x<=Q.x+Q.width&&ae.y>=Q.y&&ae.y<=Q.y+Q.height&&r(Z);}};N.addEventListener("contextmenu",_),z._contextMenuCleanup=()=>{N.removeEventListener("contextmenu",_);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:K?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),K&&jsx(Image$1,{image:K,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:O,onTap:O,onMouseDown:O,onTouchStart:O,onMouseMove:U,onTouchMove:U,onMouseUp:H,onTouchEnd:H,...P?{}:{onDragEnd:a,onTransformEnd:n}}),C?.map((z,N)=>{let _=z.points.map((ae,Q)=>Q%2===0?ae*e.width:ae*e.height),Z=z.strokeWidth*e.width;return jsx(Line,{points:_,stroke:z.tool==="eraser"?"white":z.color,strokeWidth:Z,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:z.tool==="eraser"?"destination-out":"source-over",fill:z.isSketch?z.color:void 0,closed:z.isSketch,listening:false},N)}),b&&jsx(Line,{points:b.points.map((z,N)=>N%2===0?z*e.width:z*e.height),stroke:b.tool==="eraser"?"white":b.color,strokeWidth:b.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},"active"),!K&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:G-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:te-W+6,y:G-60,width:W*1.6,height:W*1.6,radius:W,fill:"white",cornerRadius:8,listening:true,onClick:z=>{z.cancelBubble=true,e.isCapturing?V():s();},onTap:z=>{z.cancelBubble=true,e.isCapturing?V():s();}}),jsx(Html,{groupProps:{x:te-12,y:G-40,width:W*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:z=>{z.stopPropagation(),e.isCapturing?V():s();}})})]}),jsx(Text,{x:0,y:G,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:G+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:te-24,y:G+104,width:W*1.6,height:W*1.6,radius:W,fill:"#096B76",cornerRadius:W,listening:true,onClick:z=>{z.cancelBubble=true,e.isCapturing?V():s();},onTap:z=>{z.cancelBubble=true,e.isCapturing?V():s();}}),jsx(Html,{groupProps:{x:te-8,y:G+120,width:W*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:z=>{z.stopPropagation(),e.isCapturing?V():s();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:te-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:z=>{z.stopPropagation(),V();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},Nu=sg;var rl=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onStartCamera:s,onCapture:u,cameraStreams:i,onContextMenu:c,onLongPress:m})=>{let{createHandlers:l}=qe({onLongPress:m});return jsx(Fragment,{children:e.map(d=>jsx(Nu,{photoFrame:d,isSelected:t===d.id,onClick:()=>r(d.id),onDragEnd:f=>a(f,d.id),onContextMenu:f=>c(f,d.id,"photoFrame"),onStartCamera:()=>s(d.id),onCapture:f=>u(d.id,f),cameraStream:i.get(d.id),touchHandlers:l(d.id,"photoFrame"),nodeRef:f=>{f?o.current.set(d.id,f):o.current.delete(d.id);}},d.id))})});rl.displayName="PhotoFrameLayer";var zu=({x:e,y:o,onAction:t,onClose:a,type:n,isDrawingMode:r,menuRef:s})=>{useEffect(()=>{let m=d=>{s?.current&&!s.current.contains(d.target)&&a();},l=d=>{d.key==="Escape"&&a();};return document.addEventListener("mousedown",m),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("keydown",l);}},[a]);let u=useMemo(()=>[{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"draw",label:r?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line","video"]},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(l=>!(l.showForTypes&&!l.showForTypes.includes(n)||l.hideForTypes&&l.hideForTypes.includes(n))),[n,r]),i=(m,l)=>{m==="order"||m==="lock"?t(m,l):(t(m),a());},c=jsx("div",{ref:s,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:u.map((m,l)=>jsxs("button",{onClick:d=>i(m.action,d),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${m.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[m.icon,jsx("span",{className:`font-medium ${m.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:m.label})]}),m.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},l))})});return createPortal(c,document.body)};var Uu=({x:e,y:o,items:t,onClose:a})=>{let n=useRef(null);return useEffect(()=>{let r=s=>{n.current&&!n.current.contains(s.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:n,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((r,s)=>jsx("button",{onClick:()=>{r.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:r.label})},s))})})};var Ku=createContext(null),nl=()=>useContext(Ku);function kg({children:e,className:o="",style:t}){let a=useRef(null),[n,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Ku.Provider,{value:n,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function Ve(){let e=nl();return typeof document>"u"?null:e||document.body}var Gu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:n,onClose:r})=>{let[s,u]=useState(a),i=useRef(null),c=Ve();useEffect(()=>{i.current?.focus();},[]);let m=()=>{n(s),r();},l=f=>{f.key==="Enter"?m():f.key==="Escape"&&r();};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:i,type:"text",value:s,onChange:f=>u(f.target.value),onKeyDown:l,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:r,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:m,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),c):null};var os=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,n]=useState(e),r=useRef(null),s=Ve();useEffect(()=>{let l=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[t]);let u=l=>{l.preventDefault(),o(a);},i=(l,d,f)=>{f/=100;let h=d*Math.min(f,1-f)/100,p=y=>{let w=(y+l/30)%12,g=f-h*Math.max(Math.min(w-3,9-w,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!s)return null;let m=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:l=>l.stopPropagation(),onMouseUp:l=>l.stopPropagation(),onMouseMove:l=>l.stopPropagation(),onTouchStart:l=>l.stopPropagation(),onTouchMove:l=>l.stopPropagation(),onTouchEnd:l=>l.stopPropagation(),children:jsxs("div",{ref:r,className:"max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:l=>l.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:u,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:l=>n(l.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:l=>n(l.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:l=>{let d=parseInt(l.target.value),f=i(d,100,50);n(f);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(l=>jsx("button",{type:"button",onClick:()=>n(l),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===l.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:l},title:l},l))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(m,s)};var Gg=({imageSrc:e,onCrop:o})=>{let[t]=$u(e),a=useRef(null),n=useRef(null),r=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),u=useMemo(()=>{let d=s.width*.5,f=s.height*.5,h=(s.width-d)/2,p=(s.height-f)/2;return {x:h,y:p,width:d,height:f}},[s]),[i,c]=useState(u);useEffect(()=>{c(u);},[u]),useEffect(()=>{r.current&&n.current&&(r.current.nodes([n.current]),r.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let m=()=>{let d=n.current;if(!d)return;let f=d.scaleX(),h=d.scaleY();d.scaleX(1),d.scaleY(1),c({x:d.x(),y:d.y(),width:Math.max(20,d.width()*f),height:Math.max(20,d.height()*h)});},l=()=>{let d=n.current;d&&c({x:d.x(),y:d.y(),width:d.width(),height:d.height()});};return jsx(Stage,{width:s.width,height:s.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:s.width,height:s.height}),jsx(Rect,{x:0,y:0,width:s.width,height:s.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:n,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:l,onTransformEnd:m,dragBoundFunc:d=>{let f=Math.max(0,Math.min(d.x,s.width-i.width)),h=Math.max(0,Math.min(d.y,s.height-i.height));return {x:f,y:h}}}),jsx(Transformer,{ref:r,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(d,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>s.width||f.y+f.height>s.height?d:f})]})})},Xu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[n,r]=useState({x:0,y:0,width:0,height:0}),[s]=$u(e),u=Ve();useEffect(()=>{let l=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[t]);let i=(l,d,f,h)=>{r({x:l,y:d,width:f,height:h});},c=()=>{if(!s)return;let f=Math.min(600/s.width,400/s.height),h=n.x/f,p=n.y/f,y=n.width/f,w=n.height/f,g=document.createElement("canvas");g.width=y,g.height=w;let x=g.getContext("2d");if(!x)return;x.drawImage(s,h,p,y,w,0,0,y,w);let I=g.toDataURL("image/png");o(I);};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:l=>l.stopPropagation(),onMouseUp:l=>l.stopPropagation(),onMouseMove:l=>l.stopPropagation(),onTouchStart:l=>l.stopPropagation(),onTouchMove:l=>l.stopPropagation(),onTouchEnd:l=>l.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:l=>l.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(Gg,{imageSrc:e,onCrop:i})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:c,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),u):null};var Ya=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let n=Ve(),[r,s]=useState(false),[u,i]=useState(null),[c,m]=useState(0),[l,d]=useState(true),f=useRef(null),h=useRef([]),p=useRef(null),y=useRef(null),w=useRef(null),g=useRef(null),x=useRef(null),I=useRef(null);useEffect(()=>()=>{w.current&&cancelAnimationFrame(w.current),p.current&&clearInterval(p.current),y.current&&y.current.getTracks().forEach(k=>k.stop());},[]);let L=async()=>{try{let k,T=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let H=o.current.getLayers();console.log("Konva layers:",H.length),H.forEach((_,Z)=>{let ae=_.getChildren();console.log(`Layer ${Z} children count:`,ae.length);});let K=document.createElement("canvas");K.width=o.current.width(),K.height=o.current.height();let E=K.getContext("2d",{willReadFrequently:!1});if(!E){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",K.width,"x",K.height),x.current=K;let W=()=>{if(E.clearRect(0,0,K.width,K.height),H.forEach(_=>{let Z=_.getCanvas()._canvas;Z&&E.drawImage(Z,0,0);}),a?.current){let _=a.current;E.drawImage(_,0,0);}};I.current=W,o.current.draw(),W(),await new Promise(_=>setTimeout(_,100)),console.log("Creating captureStream..."),k=K.captureStream(30),console.log("Canvas stream created, tracks:",k.getTracks().length);let G=k.getVideoTracks()[0];G&&console.log("Video track:",G.label,"state:",G.readyState);let z=0,N=()=>{W(),o?.current&&(o.current.getLayers().forEach(Z=>{Z.batchDraw();}),z++,z%60===0&&console.log("Drawing frame:",z)),w.current=requestAnimationFrame(N);};N();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(l)try{T=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(H){console.warn("Microphone access denied:",H);}let F=[...k.getVideoTracks()];T&&F.push(...T.getAudioTracks());let V=new MediaStream(F);y.current=V;let O="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?O="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?O="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?O="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(O="video/webm;codecs=vp8"),console.log("Using mimeType:",O);let U=new MediaRecorder(V,{mimeType:O,videoBitsPerSecond:25e5});f.current=U,h.current=[],U.ondataavailable=H=>{console.log("Data available, size:",H.data.size),H.data.size>0&&h.current.push(H.data);},U.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let H=new Blob(h.current,{type:O});console.log("Final blob size:",H.size),o?.current&&I.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(E=>{E.batchDraw();}),I.current(),g.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",g.current.length)),V.getTracks().forEach(K=>K.stop()),p.current&&clearInterval(p.current),w.current&&(cancelAnimationFrame(w.current),w.current=null),i(H);},U.onerror=H=>{console.error("MediaRecorder error:",H);},console.log("Starting recording..."),U.start(1e3),s(!0),m(0),p.current=setInterval(()=>{m(H=>H+1);},1e3);}catch(k){console.error("Error starting screen recording:",k),alert("Failed to start recording. Please ensure you granted permission.");}},P=()=>{f.current&&r&&(console.log("Stopping recording, state:",f.current.state),f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),s(false));},C=()=>{if(u){let k=URL.createObjectURL(u),T=document.createElement("a");T.href=k,T.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(k);}},b=k=>{let T=Math.floor(k/60),F=k%60;return `${T.toString().padStart(2,"0")}:${F.toString().padStart(2,"0")}`};if(!n)return null;if(r){let k=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:b(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:P,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(k,n)}let v=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!u&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>d(!l),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${l?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:l?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:L,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),u&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(u),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",b(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&g.current&&(t(u,g.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:C,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),m(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})});return createPortal(v,n)};var Qu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:n})=>{let r=Ve(),[s,u]=useState(false),[i,c]=useState(null),[m,l]=useState(false),[d,f]=useState(0),h=useRef(null),p=useRef([]),y=useRef(null),w=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(k=>k.blob()).then(k=>c(k)).catch(k=>console.error("Error loading audio:",k));},[o,i]);let g=async()=>{try{let k=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),T=new MediaRecorder(k);h.current=T,p.current=[],T.ondataavailable=F=>{F.data.size>0&&p.current.push(F.data);},T.onstop=()=>{let F=new Blob(p.current,{type:"audio/webm"});c(F),k.getTracks().forEach(V=>V.stop()),y.current&&clearInterval(y.current);},T.start(),u(!0),f(0),y.current=setInterval(()=>{f(F=>F+1);},1e3);}catch(k){console.error("Error starting audio recording:",k),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{h.current&&s&&(h.current.stop(),u(false));},I=()=>{if(i){let k=URL.createObjectURL(i),T=new Audio(k);w.current=T,T.onended=()=>{l(false),URL.revokeObjectURL(k);},T.play(),l(true);}},L=()=>{w.current&&(w.current.pause(),w.current.currentTime=0,l(false));},P=async()=>{if(i){let k=new FileReader;k.onloadend=()=>{let T=k.result;t(T),n();},k.readAsDataURL(i);}},C=()=>{c(null),a();},b=k=>{let T=Math.floor(k/60),F=k%60;return `${T.toString().padStart(2,"0")}:${F.toString().padStart(2,"0")}`};if(!r)return null;if(s){let k=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:b(d)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:x,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(k,r)}let v=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:g,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:m?L:I,className:"flex w-full cursor-pointer items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),m?"Playing...":"Play Audio"]}),jsxs("button",{onClick:C,className:"flex w-full cursor-pointer items-center gap-2 rounded-lg border border-red-300 bg-red-600 px-4 py-3 text-white transition-colors hover:bg-red-700",children:[jsx(Trash,{className:"h-5 w-5",weight:"fill"}),"Delete Audio"]})]}),jsx("button",{onClick:P,className:"w-full cursor-pointer rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:n,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})});return createPortal(v,r)};var Nt=({audioData:e,x:o,y:t,width:a,scale:n=1,offsetX:r=0,offsetY:s=0,containerTop:u=90,containerRight:i=320})=>{let[c,m]=useState(false),l=useRef(null),d=p=>{if(p.stopPropagation(),c&&l.current)l.current.pause(),l.current.currentTime=0,m(false);else {let y=new Audio(e);l.current=y,y.onended=()=>{m(false);},y.onerror=()=>{console.error("Error playing audio"),m(false);},y.play(),m(true);}},f=(o+a)*n+r-15,h=t*n+s+u-15;return jsx("button",{onClick:d,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${c?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${f}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var ac=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=Se(),n=J(ye),r=Ve(),s=useMemo(()=>{if(!n)return [];let w=[];return n.images?.forEach(g=>{w.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),n.videos?.forEach(g=>{w.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),n.shapes?.forEach(g=>{w.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),n.texts?.forEach(g=>{w.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),n.flashcards?.forEach(g=>{w.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),n.photoFrames?.forEach(g=>{w.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),n.multipleChoices?.forEach(g=>{w.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),n.trueFalses?.forEach(g=>{w.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),n.shortAnswers?.forEach(g=>{w.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),n.LongAnswer?.forEach(g=>{w.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),n.fillInTheBlanks?.forEach(g=>{w.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),n.lines?.forEach(g=>{g.id&&w.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),w.sort((g,x)=>x.timestamp-g.timestamp)},[n]),[u,i]=useState(s),[c,m]=useState(false);useEffect(()=>{c||i(s);},[s]);let l=w=>{let g="h-5 w-5";switch(w){case "image":return jsx(Image$3,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes$1,{className:g});case "text":return jsx(TextT,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners,{className:g});case "line":return jsx(Pen,{className:g});default:return jsx(Question,{className:g})}},h=w=>{m(true),i(w);},p=()=>{m(false);let w=Date.now();u.forEach((g,x)=>{let I=w-x;a(pr({id:g.id,type:g.type,newTimestamp:I}));});};if(!r)return null;let y=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-50 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-50 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$2,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:u.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:u,onReorder:h,className:"space-y-1",children:u.map(w=>{let g=w.id===e;return jsxs(Reorder.Item,{value:w,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${g?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(w.id,w.type),className:`font-medium ${g?"text-[#096B76]":"text-[#00000099]"}`,children:w.name})}),jsx("div",{className:`${g?"text-[#096B76]":"text-[#00000099]"}`,children:l(w.type)})]},w.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[u.length," Layers"]})]})]})]});return createPortal(y,r)};var ds=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},oc=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,touchHandlers:s})=>{let u=useSelector(F=>F.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,m]=useState(new Set),[l,d]=useState(false),[f,h]=useState(null),p=useRef(null),y=useDispatch();useEffect(()=>{let F=p.current;if(F)return a.current.set(e.id,F),()=>{a.current.delete(e.id);}},[e.id]);let w=new Set(e.data.responseOptions.correctIndex),g=w.size>1,x=F=>{if(l)return;let V;g?(V=new Set(c),V.has(F)?V.delete(F):V.add(F)):V=new Set([F]),m(V);let O=Array.from(V),U=O.length===e.data.responseOptions.correctIndex.length&&O.every(H=>e.data.responseOptions.correctIndex.includes(H));y(Zt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:O,isCorrect:U}}}));},I=()=>{c.size>0&&d(true);},L=()=>{d(false),m(new Set);},P=c.size===w.size&&Array.from(c).every(F=>w.has(F)),C=Array.from(c).filter(F=>w.has(F)),b=g&&C.length>0&&!P,v=()=>P?"\u2713 Correct! Great job! \u{1F389}":b?`\u26A0 Partially correct (${C.length}/${w.size})`:"\u2717 Try again!",k=()=>P?{bg:"#dcfce7",text:"#166534"}:b?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},T=useMemo(()=>{let W=e.data.feedbackMode==="practice"?48:0,te=12,G=e.width-48,z=G-80,N=Math.max(60,ds(e.data.question,20,G,"bold")+20),_=`Select ${w.size} answers (${c.size}/${w.size} selected)`,Z=g&&!l&&e.data.feedbackMode==="practice"?ds(_,14,G)+10:0,ae=l&&e.data.feedbackMode==="practice"?Math.max(60,ds(v(),16,G-40)+30):0,Q=e.data.responseOptions.options.map(he=>{let ce=ds(he,16,z);return Math.max(55,ce+20)}),pe=N+Z+ae,ue=Q.reduce((he,ce)=>he+ce+8,-8),le=pe+ue+te+W+24;return {padding:24,questionHeight:N,instructionHeight:Z,feedbackHeight:ae,optionsStartY:pe,optionHeights:Q,totalHeight:le,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:W,buttonTopMargin:te,availableWidth:G,optionTextWidth:z}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,l,c.size,w.size,g,v]);return jsxs(Group,{ref:p,name:"mcq-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:T.totalHeight,onTransformEnd:F=>o(e.id,F),...s,...i?{}:{onDragEnd:n,onClick:F=>t&&t(e.id),onTap:F=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:T.totalHeight,width:e.width,onContextMenu:F=>{F.cancelBubble=true,r(F.evt,e.id,"mcq");}}),jsx(Text,{x:T.padding+8,y:T.padding,text:e.data.question,fontSize:T.questionFontSize,fontStyle:"bold",fill:"#111827",width:T.availableWidth,height:T.questionHeight-T.padding,wrap:"word",ellipsis:true,listening:false}),T.instructionHeight>0&&jsx(Text,{x:T.padding,y:T.questionHeight,text:`Select ${w.size} answers (${c.size}/${w.size} selected)`,fontSize:T.instructionFontSize,fill:"#6b7280",width:T.availableWidth,wrap:"word",listening:false}),l&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:T.padding+24,y:T.questionHeight+T.instructionHeight+10,width:T.availableWidth-40,height:T.feedbackHeight-20,fill:k().bg,cornerRadius:8}),jsx(Text,{x:T.padding+24,y:T.questionHeight+T.instructionHeight+10,width:T.availableWidth-40,height:T.feedbackHeight-20,text:v(),fontSize:T.feedbackFontSize,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((F,V)=>{let O=w.has(V),U=c.has(V),H=T.optionsStartY;for(let G=0;G<V;G++)H+=T.optionHeights[G]+T.optionGap;let K=T.optionHeights[V],E="#e5e7eb",W="#ffffff",te="#111827";return l&&O?(E="#22c55e",W="#dcfce7",te="#1B9D2C"):l&&U&&!O?(E="#ef4444",W="#fee2e2",te="#ef4444"):U&&(E="#096B76",W="#ECFFF8",te="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:T.padding+12,y:H+(K-20)/2,width:20,height:20,fill:U?"#096B76":"white",stroke:U?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:g?4:10,onClick:G=>{G.cancelBubble=true,x(V);},onTap:G=>{G.cancelBubble=true,x(V);}}),U&&jsx(Text,{x:T.padding+12,y:H+(K-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:T.padding+44,y:H,width:T.availableWidth-60,height:K,fill:W,stroke:E,strokeWidth:2,cornerRadius:8,onClick:G=>{G.cancelBubble=true,x(V);},onTap:G=>{G.cancelBubble=true,x(V);}}),jsx(Text,{x:T.padding+60,y:H+10,width:T.optionTextWidth,height:K-20,text:F,fontSize:T.optionFontSize,fill:te,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},V)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:T.optionsStartY+T.optionHeights.reduce((F,V)=>F+V+T.optionGap,-T.optionGap)+T.buttonTopMargin,children:[jsxs(Group,{onMouseDown:F=>{F.cancelBubble=true,h("check");},onMouseUp:F=>{F.cancelBubble=true,h(null),I();},onMouseLeave:F=>{F.cancelBubble=true,h(null);},onTouchStart:F=>{F.cancelBubble=true,h("check");},onTouchEnd:F=>{F.cancelBubble=true,h(null),I();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:T.padding+14,width:(T.availableWidth-24)/(l?2:1),height:T.buttonHeight,fill:c.size===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:T.padding+14,width:(T.availableWidth-24)/(l?2:1),height:T.buttonHeight,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-T.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),L();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),L();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:T.padding,width:(T.availableWidth-8)/2,height:T.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:T.padding,width:(T.availableWidth-8)/2,height:T.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});oc.displayName="MultipleChoice";var rc=oc;var Nx=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},dl=({multipleChoice:e,onContextMenu:o,handleSelect:t,mcqRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(E=>E.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,m]=useState(false),[l,d]=useState(new Set),[f,h]=useState(false),[p,y]=useState(false),[w,g]=useState(0),x=new Set(e.data.responseOptions.correctIndex),I=Array.from(l).filter(E=>x.has(E)),L=l.size===x.size&&Array.from(l).every(E=>x.has(E)),P=I.length>0&&!L,C=()=>L?"\u2713 Correct! Great job!":P?`\u26A0 Partially correct (${I.length}/${x.size})`:"\u2717 Try again!",b=useCallback(E=>{let W=E.target;s(wi({id:e.id,dragDropPos:{x:W.x(),y:W.y()}})),r?.();},[s,e.id,r]),v=useMemo(()=>{let W=Math.max(window.innerWidth*.4,500),te=20,G=18,z=28,N=40,_=50,Z=20,ae=60,Q=Math.max(W-40,400),pe=Math.max(60,Nx(e.data.question,te,Q,"bold")),ue=Math.max(W-Z*2,400),le=Math.max(150,window.innerHeight*.3),he=e.data.feedbackMode==="practice",ce=pe+20+le+(f?ae+18:0)+(he?N+(f?_:0)+20:0),_e=ce+100;return {screenWidth:W,screenHeight:_e,dropZoneWidth:ue,dropZoneHeight:le,questionFontSize:te,questionHeight:pe,feedbackFontSize:G,feedbackHeight:ae,dropHereFontSize:z,buttonHeight:N,buttonGap:_,padding:Z,contentWidth:Q,totalContentHeight:ce,isPracticeMode:he}},[e.data.question,e.data.feedbackMode,f,l.size]),k=useRef(null);useEffect(()=>{let E=k.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id]);let T=E=>{s(wi({id:e.id,dragDropPos:{x:E.target.x(),y:E.target.y()}})),r?.();},F=E=>{let W=E.target,te=W.x(),G=W.y(),z=window.innerWidth*.2,N=50,_=v.padding,Z=v.padding+v.dropZoneWidth,ae=v.questionHeight+20,Q=v.questionHeight+20+v.dropZoneHeight,pe=te+z>_&&te<Z&&G+N>ae&&G<Q;m(pe);},V=(E,W)=>{let te=W.target,G=te.x(),z=te.y(),N=window.innerWidth*.2,_=50,Z=v.padding,ae=v.padding+v.dropZoneWidth,Q=v.questionHeight+20,pe=v.questionHeight+20+v.dropZoneHeight,ue=G+N>Z&&G<ae&&z+_>Q&&z<pe,le;ue?le=new Set(l).add(E):(le=new Set(l),le.delete(E)),d(le),m(false);let he=Array.from(le),ce=he.length===x.size&&he.every(_e=>x.has(_e));s(Zt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:he,isCorrect:ce}}}));},O=()=>{h(true);},U=()=>{h(false),d(new Set),g(E=>E+1);},H=()=>L?{bg:"#dcfce7",text:"#166534"}:P?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},K=()=>f?L?"#4CAF50":P?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:k,x:e.dragDropPos?.x,y:e.dragDropPos?.y,name:"mcq-element",width:v.screenWidth,height:v.screenHeight,draggable:!i,listening:!i,onDragMove:b,...n,...i?{}:{onClick:E=>t&&t(e.id),onTap:E=>t&&t(e.id),onContextMenu:E=>{E.evt.preventDefault(),o(E.evt,e.id,"mcq");}},children:[jsxs(Group,{rotation:e.rotation,onDragEnd:T,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:v.totalContentHeight+20,width:v.screenWidth,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:v.padding,y:v.padding,width:v.contentWidth,height:v.questionHeight-v.padding,text:e.data.question,fontSize:v.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:v.padding,y:v.questionHeight+20,width:v.dropZoneWidth,height:v.dropZoneHeight,fill:"#EBF6F7",stroke:K(),strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:v.padding+3,y:v.questionHeight+20+v.dropZoneHeight+18,width:v.dropZoneWidth-5,height:v.feedbackHeight,fill:H().bg,cornerRadius:8}),jsx(Text,{x:v.padding,y:v.questionHeight+20+v.dropZoneHeight+20,width:v.dropZoneWidth,height:v.feedbackHeight,text:C(),fontSize:v.feedbackFontSize,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),l.size===0&&!f&&jsx(Text,{x:v.padding,y:v.questionHeight+20,width:v.dropZoneWidth,height:v.dropZoneHeight,text:x.size>1?`Drop ${x.size} Correct Answers Here`:"Drop Here",fontSize:v.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),v.isPracticeMode?jsxs(Group,{x:v.padding,y:v.questionHeight+20+v.dropZoneHeight+(f?v.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:()=>{y(true),O();},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{y(true),O();},onTouchEnd:()=>y(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:v.buttonHeight,width:v.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:v.dropZoneWidth,height:v.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:v.buttonGap,onMouseDown:U,onTouchStart:U,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:v.buttonHeight,width:v.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:v.dropZoneWidth,height:v.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((E,W)=>{let te=W%2,G=Math.floor(W/2),z=Math.max(window.innerWidth*.2,250),N=50,_=10,Z=l.has(W),ae=x.has(W),Q=f&&Z,pe="transparent";Q?pe=ae?"#4CAF50":"#ef4444":Z&&(pe="#4CAF50");let ue=f?0:1;return jsxs(Group,{x:te*(z+_),y:v.totalContentHeight+30+G*(N+_),draggable:!f,onDragStart:le=>{le.cancelBubble=true;},onDragMove:le=>{le.cancelBubble=true,F(le);},onDragEnd:le=>{le.cancelBubble=true,V(W,le);},opacity:ue,children:[jsx(Rect,{width:z-20,height:N,fill:"white",stroke:pe,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:z-20,height:N,text:E,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${W}-${w}`)})]})};dl.displayName="MultipleChoiceDragAndDrop";var nc=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(rc,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:m=>n(m,c.id),onContextMenu:r,touchHandlers:i(c.id,"mcq")},c.id):jsx(dl,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id))})};var sc=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},ic=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s})=>{let u=useSelector(v=>v.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,m]=useState(null),[l,d]=useState(false),[f,h]=useState(null),p=useDispatch(),y=useRef(null);useEffect(()=>{let v=y.current;if(v)return a.current.set(e.id,v),()=>{a.current.delete(e.id);}},[e.id]);let w=()=>{c!==null&&d(true);},g=()=>{d(false),m(null);},x=e.data.responseOptions.correctAnswer,I=c===x,L=v=>{if(l)return;m(v);let k=v===e.data.responseOptions.correctAnswer;p(Ft({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:v,isCorrect:k}}}));},P=()=>I?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>I?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},b=useMemo(()=>{let U=e.data.feedbackMode==="practice"?48:0,H=12,K=e.width-48,E=Math.max(60,sc(e.data.question,20,K,"bold")+20),W=l&&e.data.feedbackMode==="practice"?Math.max(60,sc(P(),16,K-40)+30):0,te=E+W,G=164,z=te+G+H+U+24;return {padding:24,questionHeight:E,feedbackHeight:W,optionsStartY:te,optionsHeight:G,totalHeight:z,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:U,buttonTopMargin:H,availableWidth:K}},[e.width,e.data.question,e.data.feedbackMode,l,P]);return jsxs(Group,{ref:y,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:b.totalHeight,...s,...i?{}:{onDragEnd:v=>r(v,e.id),onClick:v=>t&&t(e.id),onTap:v=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:b.totalHeight,width:e.width,onTransformEnd:v=>o(e.id,v),onContextMenu:v=>{v.cancelBubble=true,n(v.evt,e.id,"trueFalse");}}),jsx(Text,{x:b.padding+8,y:b.padding,text:e.data.question,fontSize:b.questionFontSize,fontStyle:"bold",fill:"#111827",width:b.availableWidth,height:b.questionHeight-b.padding,wrap:"word",ellipsis:true,listening:false}),l&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:b.padding+24,y:b.questionHeight+10,width:b.availableWidth-40,height:b.feedbackHeight-20,fill:C().bg,cornerRadius:8}),jsx(Text,{x:b.padding+24,y:b.questionHeight+10,width:b.availableWidth-40,height:b.feedbackHeight-20,text:P(),fontSize:b.feedbackFontSize,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((v,k)=>{let T=x===v.value,F=c===v.value,V=(e.width-b.padding*3)/2,O=b.padding+k*(V+b.padding),U=b.optionsStartY,H=v.value===true,K=H?"#10b981":"#ef4444",E="#ffffff",W="#ffffff",te="#e5e7eb";return l&&(T?(W=H?"#f0fdf4":"#fef2f2",te=H?"#86efac":"#fecaca"):F&&!T&&(W="#fee2e2",te="#ef4444")),F&&!l&&(te="#096B76",W="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:O,y:U,width:V,height:b.optionHeight+50,fill:W,stroke:te,strokeWidth:2,cornerRadius:12,onClick:G=>{G.cancelBubble=true,L(v.value);},onTap:G=>{G.cancelBubble=true,L(v.value);}}),jsx(Circle,{x:O+V/2,y:U+40,radius:28,fill:K,listening:false}),H?jsx(Text,{x:O+V/2-14,y:U+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:E,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:O+V/2-14,y:U+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:E,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:O,y:U+85,width:V,height:30,text:v.label,fontSize:b.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},v.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:b.optionsStartY+2*(b.optionHeight+b.optionGap)+b.buttonTopMargin,children:[jsxs(Group,{onMouseDown:v=>{v.cancelBubble=true,h("check");},onMouseUp:v=>{v.cancelBubble=true,h(null),w();},onMouseLeave:v=>{v.cancelBubble=true,h(null);},onTouchStart:v=>{v.cancelBubble=true,h("check");},onTouchEnd:v=>{v.cancelBubble=true,h(null),w();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:b.padding+14,width:(b.availableWidth-24)/(l?2:1),height:b.buttonHeight,fill:c===null||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true}),jsx(Text,{x:b.padding+14,width:(b.availableWidth-24)/(l?2:1),height:b.buttonHeight,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-b.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),g();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),g();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:b.padding,width:(b.availableWidth-8)/2,height:b.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true}),jsx(Text,{x:b.padding,width:(b.availableWidth-8)/2,height:b.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});ic.displayName="TrueFalse";var lc=ic;var Qx="#FFFFFF",fl=({trueFalse:e,onContextMenu:o,handleSelect:t,trueFalseRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(N=>N.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,m]=useState(false),[l,d]=useState(null),[f,h]=useState(false),[p,y]=useState(false),[w,g]=useState(0),x=340,I=100,L=Math.max(window.innerWidth*.4,400),P=window.innerHeight*.5,C=useRef(null);useEffect(()=>{let N=C.current;if(N)return a.current.set(e.id,N),()=>{a.current.delete(e.id);}},[e.id]);let v=Math.max(60,((N,_,Z,ae)=>{let pe=document.createElement("canvas").getContext("2d");if(!pe)return _;pe.font=`${ae} ${_}px Arial, sans-serif`;let ue=N.split(" "),le=[],he="";return ue.forEach(ce=>{let _e=he?`${he} ${ce}`:ce;pe.measureText(_e).width>Z&&he!==""?(le.push(he),he=ce):he=_e;}),he&&le.push(he),le.length*_*1.2})(e.data.question,20,L-40,"bold")+20),k=v+10,T=L-40,F=P-v-250,V=useCallback(N=>{let _=N.target;s(Ft({id:e.id,dragDropPos:{x:_.x(),y:_.y()}})),r?.();},[s,e.id,r]),O=N=>{s(Ft({id:e.id,dragDropPos:{x:N.target.x(),y:N.target.y()}})),r?.();},U=N=>{let _=N.target,Z=_.x(),ae=_.y(),Q=window.innerWidth*.2-40,pe=50,ue=20,le=20+T,he=k,ce=k+F,_e=Z+Q>ue&&Z<le&&ae+pe>he&&ae<ce;m(_e);},H=(N,_)=>{let Z=_.target,ae=Z.x(),Q=Z.y(),pe=window.innerWidth*.2-40,ue=50,le=20,he=20+T,ce=k,_e=k+F;if(!(ae+pe>le&&ae<he&&Q+ue>ce&&Q<_e)){m(false);return}d(N),m(false);let ga=N===e.data.responseOptions.correctAnswer;s(Ft({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:N,isCorrect:ga}}}));},K=()=>{h(true);},E=()=>{h(false),d(null),g(N=>N+1);},W=e.data.responseOptions.correctAnswer,te=l===W,G=()=>te?"\u2713 Correct! Great job!":"\u2717 Try again!",z=()=>te?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:C,name:"trueFalse-element",width:L,height:P,x:e.dragDropPos?.x,y:e.dragDropPos?.y,draggable:!i,listening:!i,onDragMove:V,...n,...i?{}:{onClick:N=>t&&t(e.id),onTap:N=>t&&t(e.id),onContextMenu:N=>{N.evt.preventDefault(),o(N.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:I,rotation:e.rotation,onDragEnd:O,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:f?P:e.data.feedbackMode==="practice"?P-50:P-100,width:L,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:k,width:T,height:F,fill:"transparent",stroke:c?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:k,width:T,height:60,fill:z().bg,cornerRadius:8}),jsx(Text,{x:20,y:k,width:T,height:60,text:G(),fontSize:18,fontStyle:"bold",fill:z().text,align:"center",verticalAlign:"middle"})]}),l===null&&!f&&jsx(Text,{x:20,y:k,width:T,height:F,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:P-100,children:[jsxs(Group,{onMouseDown:()=>{l!==null&&(y(true),K());},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{l!==null&&(y(true),K());},onTouchEnd:()=>y(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:l===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:T}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:T,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:E,onTouchStart:E,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:T}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:T,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((N,_)=>{let Z=Math.max(window.innerWidth*.2,200),ae=50,Q=10,pe=l===N.value,ue=W===N.value,le=f&&pe,he="transparent";return le?he=ue?"#4CAF50":"#ef4444":pe&&(he="#4CAF50"),jsxs(Group,{x:16+_*(Z+Q),y:I+P-300,draggable:!f,onDragStart:ce=>{ce.cancelBubble=true;},onDragMove:ce=>{ce.cancelBubble=true,U(ce);},onDragEnd:ce=>{ce.cancelBubble=true,H(N.value,ce);},opacity:f&&!pe?.5:1,children:[jsx(Rect,{width:Z-40,height:ae,fill:"#075560",stroke:he,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z-40,height:ae,text:N.label,fontSize:18,fontStyle:"bold",fill:Qx,align:"center",verticalAlign:"middle",listening:false})]},`${N.value}-${w}`)})]})})};fl.displayName="TrueFalseDragAndDrop";var dc=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(lc,{trueFalse:c,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i(c.id,"trueFalse")},c.id):jsx(fl,{trueFalse:c,handleSelect:t,trueFalseRefs:a,onContextMenu:r,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id))})};var Ta=new WeakMap,No=new WeakMap,Dr={current:[]},pl=false,Er=0,Pr=new Set,us=new Map;function uc(e){let o=Array.from(e).sort((t,a)=>t instanceof Gt&&t.options.deps.includes(a)?1:a instanceof Gt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(Dr.current.includes(t))continue;Dr.current.push(t),t.recompute();let a=No.get(t);if(a)for(let n of a){let r=Ta.get(n);r&&uc(r);}}}function ab(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function ob(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function cs(e){if(Er>0&&!us.has(e)&&us.set(e,e.prevState),Pr.add(e),!(Er>0)&&!pl)try{for(pl=!0;Pr.size>0;){let o=Array.from(Pr);Pr.clear();for(let t of o){let a=us.get(t)??t.prevState;t.prevState=a,ab(t);}for(let t of o){let a=Ta.get(t);a&&(Dr.current.push(t),uc(a));}for(let t of o){let a=Ta.get(t);if(a)for(let n of a)ob(n);}}}finally{pl=false,Dr.current=[],us.clear();}}function Ct(e){Er++;try{e();}finally{if(Er--,Er===0){let o=Pr.values().next().value;o&&cs(o);}}}function cc(e){return typeof e=="function"}var Qt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var n,r;this.listeners.add(a);let s=(r=(n=this.options)==null?void 0:n.onSubscribe)==null?void 0:r.call(n,a,this);return ()=>{this.listeners.delete(a),s?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,n;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):cc(o)?this.state=o(this.prevState):this.state=o,(n=(a=this.options)==null?void 0:a.onUpdate)==null||n.call(a),cs(this);}};var Gt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),n=new Array(t);for(let r=0;r<t;r++){let s=this.options.deps[r];a[r]=s.prevState,n[r]=s.state;}return this.lastSeenDepValues=n,{prevDepVals:a,currDepVals:n,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let n=this.getDepVals();this.state=this.options.fn(n),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let r of this.options.deps)r instanceof e&&r.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:n}=this.getDepVals();for(let r=0;r<n.length;r++)if(n[r]!==a[r]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,n;this.listeners.add(t);let r=(n=(a=this.options).onSubscribe)==null?void 0:n.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof Qt){let a=Ta.get(t);a||(a=new Set,Ta.set(t,a)),a.add(this);let n=No.get(this);n||(n=new Set,No.set(this,n)),n.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof Qt){let a=Ta.get(t);a&&a.delete(this);let n=No.get(this);n&&n.delete(t);}}};function rb(e){return typeof e=="function"}function hl(e,...o){return rb(e)?e(...o):e}function fc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Ma,pt,st,Rr,Aa,eo,na,Ho,Fr,fs,Br,qo,to=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:n=1e3}){Be(this,Ma,true);Be(this,pt);Be(this,st);Be(this,Rr);Be(this,Aa);Be(this,eo);Be(this,na);Be(this,Ho);Be(this,Fr,0);Be(this,fs,5);Be(this,Br,()=>{this.debugLog("Connected to event bus"),Pe(this,eo,true),this.debugLog("Emitting queued events",$(this,Aa)),$(this,Aa).forEach(o=>this.emitEventToBus(o)),Pe(this,Aa,[]),this.stopConnectLoop(),$(this,st).call(this).removeEventListener("tanstack-connect-success",$(this,Br));});Be(this,qo,()=>{if($(this,st).call(this).addEventListener("tanstack-connect-success",$(this,Br)),$(this,Fr)<$(this,fs)){Nd(this,Fr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}$(this,st).call(this).removeEventListener("tanstack-connect",$(this,qo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Pe(this,pt,o),Pe(this,Ma,a),Pe(this,st,this.getGlobalTarget),Pe(this,Rr,t),this.debugLog(" Initializing event subscription for plugin",$(this,pt)),Pe(this,Aa,[]),Pe(this,eo,false),Pe(this,na,null),Pe(this,Ho,n);}startConnectLoop(){$(this,na)!==null||$(this,eo)||(this.debugLog(`Starting connect loop (every ${$(this,Ho)}ms)`),Pe(this,na,setInterval($(this,qo),$(this,Ho))));}stopConnectLoop(){$(this,na)!==null&&(clearInterval($(this,na)),Pe(this,na,null),this.debugLog("Stopped connect loop"));}debugLog(...o){$(this,Rr)&&console.log(`\u{1F334} [tanstack-devtools:${$(this,pt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return $(this,pt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});$(this,st).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{$(this,st).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!$(this,Ma)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!$(this,eo)){this.debugLog("Bus not available, will be pushed as soon as connected"),$(this,Aa).push({type:`${$(this,pt)}:${o}`,payload:t,pluginId:$(this,pt)}),typeof CustomEvent<"u"&&($(this,qo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${$(this,pt)}:${o}`,payload:t,pluginId:$(this,pt)})}on(o,t){let a=`${$(this,pt)}:${o}`;if(!$(this,Ma))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let n=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return $(this,st).call(this).addEventListener(a,n),this.debugLog("Registered event to bus",a),()=>{$(this,st).call(this).removeEventListener(a,n);}}onAll(o){if(!$(this,Ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;o(n);};return $(this,st).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,st).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!$(this,Ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;$(this,pt)&&n.pluginId!==$(this,pt)||o(n);};return $(this,st).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,st).call(this).removeEventListener("tanstack-devtools-global",t)}};Ma=new WeakMap,pt=new WeakMap,st=new WeakMap,Rr=new WeakMap,Aa=new WeakMap,eo=new WeakMap,na=new WeakMap,Ho=new WeakMap,Fr=new WeakMap,fs=new WeakMap,Br=new WeakMap,qo=new WeakMap;var gl=class extends to{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},mc=(e,o)=>{xl.emit(e,o);},xl=new gl;function pc(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var nb={enabled:true,leading:true,trailing:true,wait:0},Pa,kt,ao,oo,ro,Vo,ms=class{constructor(o,t){Be(this,Pa);Be(this,kt);Be(this,ao);Be(this,oo);Be(this,ro);Be(this,Vo);this.fn=o,this.store=new Qt(pc()),this.setOptions=a=>{this.options={...this.options,...a},$(this,ao).call(this)||this.cancel();},Pe(this,kt,a=>{this.store.setState(n=>{let r={...n,...a},{isPending:s}=r;return {...r,status:$(this,ao).call(this)?s?"pending":"idle":"disabled"}}),mc("Throttler",this);}),Pe(this,ao,()=>!!hl(this.options.enabled,this)),Pe(this,oo,()=>hl(this.options.wait,this)),this.maybeExecute=(...a)=>{$(this,kt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let n=Date.now(),r=n-this.store.state.lastExecutionTime,s=$(this,oo).call(this);if(this.options.leading&&r>=s)$(this,ro).call(this,...a);else if($(this,kt).call(this,{lastArgs:a}),!$(this,Pa)&&this.options.trailing){let u=this.store.state.lastExecutionTime?n-this.store.state.lastExecutionTime:0,i=s-u;$(this,kt).call(this,{isPending:true}),Pe(this,Pa,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&$(this,ro).call(this,...c);},i));}},Pe(this,ro,(...a)=>{if(!$(this,ao).call(this))return;this.fn(...a);let n=Date.now(),r=n+$(this,oo).call(this);$(this,Vo).call(this),$(this,kt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:n,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||$(this,kt).call(this,{nextExecutionTime:void 0});},$(this,oo).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&$(this,ro).call(this,...this.store.state.lastArgs);},Pe(this,Vo,()=>{$(this,Pa)&&(clearTimeout($(this,Pa)),Pe(this,Pa,void 0));}),this.cancel=()=>{$(this,Vo).call(this),$(this,kt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{$(this,kt).call(this,pc());},this.key=fc(t.key),this.options={...nb,...t},$(this,kt).call(this,this.options.initialState??{}),xl.on("d-Throttler",a=>{a.payload.key===this.key&&($(this,kt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Pa=new WeakMap,kt=new WeakMap,ao=new WeakMap,oo=new WeakMap,ro=new WeakMap,Vo=new WeakMap;function bl(e,o){return new ms(e,o).maybeExecute}function Ea(e,o){return typeof e=="function"?e(o):e}function Da(e,o){return xs(o).reduce((a,n)=>{if(a===null)return null;if(typeof a<"u")return a[n]},e)}function zo(e,o,t){let a=xs(o);function n(r){if(!a.length)return Ea(t,r);let s=a.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[s]:n(r[s])}):{[s]:n()};if(Array.isArray(r)&&typeof s=="number"){let u=r.slice(0,s);return [...u.length?u:new Array(s),n(r[s]),...r.slice(s+1)]}return [...new Array(s),n()]}return n(e)}function yl(e,o){let t=xs(o);function a(n){if(!n)return;if(t.length===1){let s=t[0];if(Array.isArray(n)&&typeof s=="number")return n.filter((c,m)=>m!==s);let{[s]:u,...i}=n;return i}let r=t.shift();if(typeof r=="string"&&typeof n=="object")return {...n,[r]:a(n[r])};if(typeof r=="number"&&Array.isArray(n)){if(r>=n.length)return n;let s=n.slice(0,r);return [...s.length?s:new Array(r),a(n[r]),...n.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var sb=/^(\d+)$/gm,ib=/\.(\d+)(?=\.)/gm,lb=/^(\d+)\./gm,db=/\.(\d+$)/gm,ub=/\.{2,}/gm,vl="__int__",ps=`${vl}$1`;function xs(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(sb,ps).replace(ib,`.${ps}.`).replace(lb,`${ps}.`).replace(db,`.${ps}`).replace(ub,".").split(".").map(o=>{if(o.startsWith(vl)){let t=o.substring(vl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function wl(e){return !(Array.isArray(e)&&e.length===0)}function Uo(e,o){let t=a=>a.validators.filter(Boolean).map(n=>({cause:n.cause,validate:n.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Wo(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:n,onDynamicAsyncDebounceMs:r}=o.validators||{},s=t??0,u=i=>i.validators.filter(Boolean).map(c=>{let m=c?.cause||e,l=s;switch(m){case "change":l=n??s;break;case "blur":l=a??s;break;case "dynamic":l=r??s;break;case "submit":l=0;break}return e==="submit"&&(l=0),{cause:m,validate:c.fn,debounceMs:l}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var Or=e=>!!e&&typeof e=="object"&&"fields"in e;function Ra(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[n,r]of e)if(!o.has(n)||!Object.is(r,o.get(n)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let n of e)if(!o.has(n))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let n of t)if(!a.includes(n)||!Ra(e[n],o[n]))return false;return true}var bs=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},vs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Je(e,o){return e==null?o:{...e,...o}}var no=256,gs=[],hs;for(;no--;)gs[no]=(no+256).toString(16).substring(1);function Sl(){let e=0,o,t="";if(!hs||no+16>256){for(hs=new Array(256),e=256;e--;)hs[e]=256*Math.random()|0;e=0,no=0;}for(;e<16;e++)o=hs[no+e],e===6?t+=gs[o&15|64]:e===8?t+=gs[o&63|128]:t+=gs[o],e&1&&e>1&&e<11&&(t+="-");return no++,t}var Fa=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},n={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},s=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,n,r,s],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[n,s],form:e.form});case "change":return e.runValidation({validators:[a,s],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function cb(e,o){let t=new Map;for(let a of e){let n=a.path??[],r=o,s="";for(let u=0;u<n.length;u++){let i=n[u];if(i===void 0)continue;let c=typeof i=="object"?i.key:i,m=Number(c);Array.isArray(r)&&!Number.isNaN(m)?s+=`[${m}]`:s+=(u>0?".":"")+String(c),typeof r=="object"&&r!==null?r=r[c]:r=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var hc=(e,o)=>{let t=cb(e,o);return {form:t,fields:t}},Ba={validate({value:e,validationSource:o},t){let a=t["~standard"].validate(e);if(a instanceof Promise)throw new Error("async function passed to sync validator");if(a.issues)return o==="field"?a.issues:hc(a.issues,e)},async validateAsync({value:e,validationSource:o},t){let a=await t["~standard"].validate(e);if(a.issues)return o==="field"?a.issues:hc(a.issues,e)}},ys=e=>!!e&&"~standard"in e;var Ko={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function Nr(e){function o(l,d,f,h){let p=a(l,d,f,h);({insert:()=>u(p,l,d),remove:()=>i(p),swap:()=>h!==void 0&&m(p,l,d,h),move:()=>h!==void 0&&c(p,l,d,h)})[f]();}function t(l,d){return `${l}[${d}]`}function a(l,d,f,h){let p=[t(l,d)];if(f==="swap")p.push(t(l,h));else if(f==="move"){let[y,w]=[Math.min(d,h),Math.max(d,h)];for(let g=y;g<=w;g++)p.push(t(l,g));}else {let y=e.getFieldValue(l),w=Array.isArray(y)?y.length:0;for(let g=d+1;g<w;g++)p.push(t(l,g));}return Object.keys(e.fieldInfo).filter(y=>p.some(w=>y.startsWith(w)))}function n(l,d){return l.replace(/\[(\d+)\]/,(f,h)=>{let p=parseInt(h,10);return `[${d==="up"?p+1:Math.max(0,p-1)}]`})}function r(l,d){(d==="up"?l:[...l].reverse()).forEach(h=>{let p=n(h.toString(),d),y=e.getFieldMeta(p);y?e.setFieldMeta(h,y):e.setFieldMeta(h,s());});}let s=()=>Ko,u=(l,d,f)=>{r(l,"down"),l.forEach(h=>{h.toString().startsWith(t(d,f))&&e.setFieldMeta(h,s());});},i=l=>{r(l,"up");},c=(l,d,f,h)=>{let p=new Map(Object.keys(e.fieldInfo).filter(y=>y.startsWith(t(d,f))).map(y=>[y,e.getFieldMeta(y)]));r(l,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(y=>y.startsWith(t(d,h))).forEach(y=>{let w=y.replace(t(d,h),t(d,f)),g=p.get(w);g&&e.setFieldMeta(y,g);});},m=(l,d,f,h)=>{l.forEach(p=>{if(!p.toString().startsWith(t(d,f)))return;let y=p.toString().replace(t(d,f),t(d,h)),[w,g]=[e.getFieldMeta(p),e.getFieldMeta(y)];w&&e.setFieldMeta(y,w),g&&e.setFieldMeta(p,g);});};return {handleArrayFieldMetaShift:o}}var Ll=class extends to{constructor(){super({pluginId:"form-devtools"});}},Tt=new Ll;function Il(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var qr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),n=this.store.mount(),r=()=>{a(),n(),Tt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return Tt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),s&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let n=this.options;this.options=a;let r=!!a.transform?.deps?.some((i,c)=>i!==this.prevTransformArray[c]),s=a.defaultValues&&!Ra(a.defaultValues,n.defaultValues)&&!this.state.isTouched,u=!Ra(a.defaultState,n.defaultState)&&!this.state.isTouched;!s&&!u&&!r||(Ct(()=>{this.baseStore.setState(()=>Il(Object.assign({},this.state,u?a.defaultState:{},s?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),Tt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,n)=>{let{fieldMeta:r}=this.state,s=this.resetFieldMeta(r);a&&!n?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Il({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let n=[];return Ct(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;let u=s.instance;n.push(Promise.resolve().then(()=>u.validate(a,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(n)).flat()},this.validateArrayFieldsStartingFrom=async(a,n,r)=>{let s=this.getFieldValue(a),u=Array.isArray(s)?Math.max(s.length-1,0):null,i=[`${a}[${n}]`];for(let d=n+1;d<=(u??0);d++)i.push(`${a}[${d}]`);let c=Object.keys(this.fieldInfo).filter(d=>i.some(f=>d.startsWith(f))),m=[];return Ct(()=>{c.forEach(d=>{m.push(Promise.resolve().then(()=>this.validateField(d,r)));});}),(await Promise.all(m)).flat()},this.validateField=(a,n)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(s=>({...s,isTouched:true})),r.validate(n)):[]},this.validateSync=a=>{let n=Uo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Fa}),r=false,s={};return Ct(()=>{for(let c of n){if(!c.validate)continue;let m=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:l,fieldErrors:d}=ws(m),f=Hr(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let p=this.getFieldMeta(h);if(!p)continue;let{errorMap:y,errorSourceMap:w}=p,g=d?.[h],{newErrorValue:x,newSource:I}=bs({newFormValidatorError:g,isPreviousErrorFromFormValidator:w?.[f]==="form",previousErrorValue:y?.[f]});I==="form"&&(s[h]={...s[h],[f]:g}),y?.[f]!==x&&this.setFieldMeta(h,L=>({...L,errorMap:{...L.errorMap,[f]:x},errorSourceMap:{...L.errorSourceMap,[f]:I}}));}this.state.errorMap?.[f]!==l&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:l}})),(l||d)&&(r=!0);}let u=Hr("submit");this.state.errorMap?.[u]&&a!=="submit"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let i=Hr("server");this.state.errorMap?.[i]&&a!=="server"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[i]:void 0}}));}),{hasErrored:r,fieldsErrorMap:s}},this.validateAsync=async a=>{let n=Wo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Fa});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let r=[],s;for(let c of n){if(!c.validate)continue;let m=Hr(c.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let d=new AbortController;this.state.validationMetaMap[m]={lastAbortController:d},r.push(new Promise(async f=>{let h;try{h=await new Promise((g,x)=>{setTimeout(async()=>{if(d.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:d.signal},type:"validateAsync"}));}catch(I){x(I);}},c.debounceMs);});}catch(g){h=g;}let{formError:p,fieldErrors:y}=ws(h);y&&(s=s?{...s,...y}:y);let w=Hr(c.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let x=this.getFieldMeta(g);if(!x)continue;let{errorMap:I,errorSourceMap:L}=x,P=s?.[g],{newErrorValue:C,newSource:b}=bs({newFormValidatorError:P,isPreviousErrorFromFormValidator:L?.[w]==="form",previousErrorValue:I?.[w]});I?.[w]!==C&&this.setFieldMeta(g,v=>({...v,errorMap:{...v.errorMap,[w]:C},errorSourceMap:{...v.errorSourceMap,[w]:b}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[w]:p}})),f(s?{fieldErrors:s,errorMapKey:w}:void 0);}));}let u=[],i={};if(r.length){u=await Promise.all(r);for(let c of u)if(c?.fieldErrors){let{errorMapKey:m}=c;for(let[l,d]of Object.entries(c.fieldErrors)){let h={...i[l]||{},[m]:d};i[l]=h;}}}return this.baseStore.setState(c=>({...c,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(a);return n&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Da(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var n;return (n=this.fieldInfo)[a]||(n[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,n)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Ea(n,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((n,r)=>{let s=r;return n[s]=Ko,n},{}),this.setFieldValue=(a,n,r)=>{let s=r?.dontUpdateMeta??false,u=r?.dontRunListeners??false,i=r?.dontValidate??false;Ct(()=>{s||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:zo(c.values,a,n)}));}),u||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(s=>{let u=a.toString();return s!==u&&s.startsWith(u)}),a];this.baseStore.setState(s=>{let u={...s};return r.forEach(i=>{u.values=yl(u.values,i),delete this.fieldInfo[i],delete u.fieldMetaBase[i];}),u});},this.pushFieldValue=(a,n,r)=>{this.setFieldValue(a,s=>[...Array.isArray(s)?s:[],n],r);},this.insertFieldValue=async(a,n,r,s)=>{this.setFieldValue(a,i=>[...i.slice(0,n),r,...i.slice(n)],Je(s,{dontValidate:true}));let u=s?.dontValidate??false;u||await this.validateField(a,"change"),Nr(this).handleArrayFieldMetaShift(a,n,"insert"),u||await this.validateArrayFieldsStartingFrom(a,n,"change");},this.replaceFieldValue=async(a,n,r,s)=>{this.setFieldValue(a,i=>i.map((c,m)=>m===n?r:c),Je(s,{dontValidate:true})),(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.removeFieldValue=async(a,n,r)=>{let s=this.getFieldValue(a),u=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,c=>c.filter((m,l)=>l!==n),Je(r,{dontValidate:true})),Nr(this).handleArrayFieldMetaShift(a,n,"remove"),u!==null){let c=`${a}[${u}]`;this.deleteField(c);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.swapFieldValues=(a,n,r,s)=>{this.setFieldValue(a,i=>{let c=i[n],m=i[r];return zo(zo(i,`${n}`,m),`${r}`,c)},Je(s,{dontValidate:true})),Nr(this).handleArrayFieldMetaShift(a,n,"swap",r),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,n,r,s)=>{this.setFieldValue(a,i=>{let c=[...i];return c.splice(r,0,c.splice(n,1)[0]),c},Je(s,{dontValidate:true})),Nr(this).handleArrayFieldMetaShift(a,n,"move",r),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,n)=>{let r=this.getFieldValue(a),s=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],Je(n,{dontValidate:true})),s!==null)for(let i=0;i<=s;i++){let c=`${a}[${i}]`;this.deleteField(c);}(n?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:Ko},values:this.options.defaultValues?zo(n.values,a,Da(this.options.defaultValues,a)):n.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[n,r])=>(Object.keys(r).length&&r.errors.length&&(a[n]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Ba.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ba.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Sl(),this._devtoolsSubmissionOverride=false,this.baseStore=new Qt(Il({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Gt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=0,m={};for(let l of Object.keys(i.fieldMetaBase)){let d=i.fieldMetaBase[l],f=u?.fieldMetaBase[l],h=s?.[l],p=Da(i.values,l),y=h?.errors;if(!f||d.errorMap!==f.errorMap){y=Object.values(d.errorMap??{}).filter(L=>L!==void 0);let I=this.getFieldInfo(l)?.instance;I&&!I.options.disableErrorFlat&&(y=y?.flat(1));}let w=!wl(y??[]),g=!d.isDirty,x=Ra(p,Da(this.options.defaultValues,l))||Ra(p,this.getFieldInfo(l)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===w&&h.isDefaultValue===x&&h.errors===y&&d===f){m[l]=h,c++;continue}m[l]={...d,errors:y,isPristine:g,isValid:w,isDefaultValue:x};}return Object.keys(i.fieldMetaBase).length&&s&&c===Object.keys(i.fieldMetaBase).length?s:m}}),this.store=new Gt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=n[1],m=Object.values(c).filter(Boolean),l=m.some(O=>O.isValidating),d=m.every(O=>O.isValid),f=m.some(O=>O.isTouched),h=m.some(O=>O.isBlurred),p=m.every(O=>O.isDefaultValue),y=f&&i.errorMap?.onMount,w=m.some(O=>O.isDirty),g=!w,x=!!(i.errorMap?.onMount||m.some(O=>O?.errorMap?.onMount)),I=!!l,L=s?.errors??[];(!u||i.errorMap!==u.errorMap)&&(L=Object.values(i.errorMap).reduce((O,U)=>U===void 0?O:U&&Or(U)?(O.push(U.form),O):(O.push(U),O),[]));let P=L.length===0,C=d&&P,b=this.options.canSubmitWhenInvalid??false,v=i.submissionAttempts===0&&!f&&!x||!I&&!i.isSubmitting&&C||b,k=i.errorMap;if(y&&(L=L.filter(O=>O!==i.errorMap.onMount),k=Object.assign(k,{onMount:void 0})),s&&u&&s.errorMap===k&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===L&&s.isFieldsValidating===l&&s.isFieldsValid===d&&s.isFormValid===P&&s.isValid===C&&s.canSubmit===v&&s.isTouched===f&&s.isBlurred===h&&s.isPristine===g&&s.isDefaultValue===p&&s.isDirty===w&&Ra(u,i))return s;let T={...i,errorMap:k,fieldMeta:this.fieldMetaDerived.state,errors:L,isFieldsValidating:l,isFieldsValid:d,isFormValid:P,isValid:C,canSubmit:v,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:p,isDirty:w},F=this.options.transform?.deps??[];if(F.length!==this.prevTransformArray.length||F.some((O,U)=>O!==this.prevTransformArray[U])){let O=Object.assign({},this,{state:T});this.options.transform?.fn(O),T=O.state,this.prevTransformArray=F;}return T}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=bl(a=>Tt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),Tt.on("request-form-state",a=>{a.payload.id===this._formId&&Tt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Tt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),Tt.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return ys(o.validate)?Ba[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(n=>({...n,isSubmitted:false,submissionAttempts:n.submissionAttempts+1,isSubmitSuccessful:false})),Ct(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance&&(n.instance.state.meta.isTouched||n.instance.setMeta(r=>({...r,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(n=>({...n,isSubmitting:true}));let a=()=>{this.baseStore.setState(n=>({...n,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Tt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(n=>n.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Tt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}Ct(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance?.options.listeners?.onSubmit?.({value:n.instance.state.value,fieldApi:n.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),Ct(()=>{this.baseStore.setState(n=>({...n,isSubmitted:!0,isSubmitSuccessful:!0})),Tt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(n){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),Tt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:n}),a(),n}}setErrorMap(o){Ct(()=>{Object.entries(o).forEach(([t,a])=>{let n=t;if(Or(a)){let{formError:r,fieldErrors:s}=ws(a);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,c=>({...c,errorMap:{...c.errorMap,[n]:s?.[u]},errorSourceMap:{...c.errorSourceMap,[n]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[n]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[n]:a}}));});});}};function ws(e){if(e){if(Or(e)){let o=ws(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function Hr(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}var Vr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:n}=this.options.validators||{};if(n){let r=this.runValidator({validate:n,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:r},errorSourceMap:{...s?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let n=Da(t.form.options.defaultValues,t.name),r=t.defaultValue??n;a?this.setValue(s=>s||r,{dontUpdateMeta:true}):r!==void 0&&this.setValue(r,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Je(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,n)=>{this.form.insertFieldValue(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,n)=>{this.form.replaceFieldValue(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,n)=>{this.form.swapFieldValues(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,n)=>{this.form.moveFieldValues(this.name,t,a,Je(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Je(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),n=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:s,onBlurListenTo:u}=r.instance.options.validators||{};t==="change"&&s?.includes(this.name)&&n.push(r.instance),t==="blur"&&u?.includes(this.name)&&n.push(r.instance);}return n},this.validateSync=(t,a)=>{let n=Uo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Fa}),s=this.getLinkedFields(t).reduce((c,m)=>{let l=Uo(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Fa});return l.forEach(d=>{d.field=m;}),c.concat(l)},[]),u=false;Ct(()=>{let c=(m,l)=>{let d=Ss(l.cause),f=l.validate?gc(m.runValidator({validate:l.validate,value:{value:m.store.state.value,validationSource:"field",fieldApi:m},type:"validate"})):void 0,h=a[d],{newErrorValue:p,newSource:y}=vs({formLevelError:h,fieldLevelError:f});m.state.meta.errorMap?.[d]!==p&&m.setMeta(w=>({...w,errorMap:{...w.errorMap,[d]:p},errorSourceMap:{...w.errorSourceMap,[d]:y}})),p&&(u=!0);};for(let m of n)c(this,m);for(let m of s)m.validate&&c(m.field,m);});let i=Ss("submit");return this.state.meta.errorMap?.[i]&&t!=="submit"&&!u&&this.setMeta(c=>({...c,errorMap:{...c.errorMap,[i]:void 0},errorSourceMap:{...c.errorSourceMap,[i]:void 0}})),{hasErrored:u}},this.validateAsync=async(t,a)=>{let n=Wo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Fa}),r=await a,s=this.getLinkedFields(t),u=s.reduce((d,f)=>{let h=Wo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Fa});return h.forEach(p=>{p.field=f;}),d.concat(h)},[]);this.state.meta.isValidating||this.setMeta(d=>({...d,isValidating:true}));for(let d of s)d.setMeta(f=>({...f,isValidating:true}));let i=[],c=[],m=(d,f,h)=>{let p=Ss(f.cause);d.getInfo().validationMetaMap[p]?.lastAbortController.abort();let w=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:w},h.push(new Promise(async g=>{let x;try{x=await new Promise((b,v)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(w.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:f.validate,value:{value:d.store.state.value,fieldApi:d,signal:w.signal,validationSource:"field"},type:"validateAsync"}));}catch(k){v(k);}},f.debounceMs);});}catch(b){x=b;}if(w.signal.aborted)return g(void 0);let I=gc(x),L=r[this.name]?.[p],{newErrorValue:P,newSource:C}=vs({formLevelError:L,fieldLevelError:I});d.setMeta(b=>({...b,errorMap:{...b?.errorMap,[p]:P},errorSourceMap:{...b.errorSourceMap,[p]:C}})),g(P);}));};for(let d of n)d.validate&&m(this,d,i);for(let d of u)d.validate&&m(d.field,d,c);let l=[];(i.length||c.length)&&(l=await Promise.all(i),await Promise.all(c)),this.setMeta(d=>({...d,isValidating:false}));for(let d of s)d.setMeta(f=>({...f,isValidating:false}));return l.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:n}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,n[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Ss(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Ba.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ba.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Gt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Ko,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return ys(o.validate)?Ba[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function gc(e){if(e)return e}function Ss(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function Ls(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,mb)}function mb(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,n]of e)if(!o.has(a)||!Object.is(n,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=xc(e);if(t.length!==xc(o).length)return false;for(let a=0;a<t.length;a++)if(!Object.prototype.hasOwnProperty.call(o,t[a])||!Object.is(e[t[a]],o[t[a]]))return false;return true}function xc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Go=typeof window<"u"?useLayoutEffect:useEffect;function yb(e){let[o]=useState(()=>{let a=new Vr({...e,form:e.form,name:e.name});return a.Field=Cl,a});return Go(o.mount,[o]),Go(()=>{o.update(e);}),Ls(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Cl=(({children:e,...o})=>{let t=yb(o),a=useMemo(()=>Ea(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Lb({form:e,selector:o,children:t}){let a=Ls(e.store,o);return Ea(t,a)}function kl(e){let o=useId(),[t]=useState(()=>{let a=new qr({...e,formId:o}),n=a;return n.Field=function(s){return jsx(Cl,{...s,form:a})},n.Subscribe=function(s){return jsx(Lb,{form:a,selector:s.selector,children:s.children})},n});return Go(t.mount,[]),Go(()=>{t.update(e);}),t}function Tl({field:e}){return jsxs(Fragment,{children:[e.state.meta.isTouched&&!e.state.meta.isValid?jsx("em",{children:e.state.meta.errors.join(", ")}):null,e.state.meta.isValidating?"Validating...":null]})}var Rb=({editElement:e})=>{let o=useDispatch(),t=useSelector(ye),a=useRef(null),n=Ve(),r=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[u,i]=useState(s),c=kl({defaultValues:{questionType:s,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:d})=>{if(d.questionType==="true-false"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctAnswer:d.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,dragDropPos:{x:r&&"dragDropPos"in e?e.dragDropPos?.x??400:200,y:r&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?Ft(f):Si(f));}else if(d.questionType==="multiple-choice"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctIndex:d.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,dragDropPos:{x:r&&"dragDropPos"in e?e.dragDropPos?.x??400:400,y:r&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Zt(f):yi(f));}else if(d.questionType==="short-answer"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?ya(f):Li(f));}else if(d.questionType==="fill-in-the-blank"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?$a(f):Ci(f));}else if(d.questionType==="long-answer"){let f={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctLongAnswer:d.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?_a(f):Ii(f));}o(wa(false));}}),m=()=>{o(wa(false));};if(!n)return null;let l=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:d=>{d.preventDefault(),d.stopPropagation(),c.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{m();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(c.Field,{name:"questionType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:f=>{d.handleChange(f.target.value),i(f.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(Tl,{field:d})]})}),u&&!["short-answer","fill-in-the-blank","long-answer"].includes(u)&&jsx(c.Field,{name:"responseType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:f=>d.handleChange(f.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(Tl,{field:d})]})})]}),jsx(c.Field,{name:"feedbackMode",children:d=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${u==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>d.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${d.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>d.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${d.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),u==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(Tl,{field:d})]})}),jsx(c.Field,{name:"question",validators:{onChange:({value:d})=>d?void 0:"A question is required"},children:d=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:d.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:d.state.value,onChange:f=>d.handleChange(f.target.value),onBlur:d.handleBlur,placeholder:"Enter Your Question"})}),d.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:d.state.meta.errors.join(", ")})]})}),u==="true-false"&&jsx(c.Field,{name:"responseOptions.correctAnswer",children:d=>{let f=d.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>d.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${f===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),f===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>d.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${f===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),f===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value:d})=>{if(d.options.filter(h=>!h.trim()).length>0)return "All options must have text";if(!d.correctIndex||d.correctIndex.length===0)return "Please select at least one correct answer"}},children:d=>{let f=(w,g)=>{let x=[...d.state.value.options];x[w]=g,d.handleChange({...d.state.value,options:x});},h=()=>{if(d.state.value.options.length>=6){alert("Maximum 6 options allowed");return}d.handleChange({...d.state.value,options:[...d.state.value.options,""]});},p=w=>{if(d.state.value.options.length<=2){alert("Minimum 2 options required");return}let g=d.state.value.options.filter((I,L)=>L!==w),x=d.state.value.correctIndex?.filter(I=>I!==w).map(I=>I>w?I-1:I);d.handleChange({...d.state.value,options:g,correctIndex:x});},y=w=>{let g=d.state.value.correctIndex||[];if(g.includes(w))d.handleChange({...d.state.value,correctIndex:g.filter(I=>I!==w)});else {if(g.length>=6){alert("Maximum 6 correct answers allowed");return}d.handleChange({...d.state.value,correctIndex:[...g,w]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:d.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:d.state.value.options.map((w,g)=>{let x=!w.trim(),I=d.state.value.correctIndex?.includes(g),L=d.state.meta.isTouched&&x;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>y(g),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${I?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:I&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${L?"border-red-500 bg-red-50":I?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${g+1}`,value:w,onChange:P=>f(g,P.target.value),onBlur:d.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),d.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>p(g),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},g)})}),jsx("button",{type:"button",onClick:h,disabled:d.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),d.state.value.correctIndex.length===0||d.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:d.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.Field,{name:"responseOptions.correctShortAnswer",children:d=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:d.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:d.state.value,onChange:f=>{d.handleChange(f.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:d.state.meta.errors.join(", ")})]})}),u==="long-answer"&&jsx(c.Field,{name:"responseOptions.correctLongAnswer",children:d=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:d.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:d.state.value,onChange:f=>{d.handleChange(f.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:d.state.meta.errors.join(", ")})]})}),jsx(c.Subscribe,{selector:d=>[d.canSubmit,d.isSubmitting],children:([d,f])=>jsx("button",{type:"submit",disabled:!d,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:f?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(l,n)},yc=Rb;var Ic=({text:e,position:o})=>{let t=Se(),a=(m,l,d,f,h)=>{let y=document.createElement("canvas").getContext("2d");if(!y)return {width:e.width,height:e.height};y.font=`${h} ${f} ${l}px ${d}`;let w=m.split(`
|
|
4
|
-
`),
|
|
5
|
-
`),f=0;document.body.appendChild(l);for(let p of d){l.textContent=p||" ";let y=l.offsetWidth;y>f&&(f=y);}document.body.removeChild(l);let h=10;m.style.width=`${Math.max(200,f+h+20)}px`;},[]);return useEffect(()=>{let m=u.current;m&&(m.style.fontSize=`${e.fontSize*r}px`,m.style.fontFamily=e.fontFamily,m.style.fontStyle=e.fontStyle,m.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",m.style.textDecoration=e.textDecoration,m.style.color=e.fill,c(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,c]),jsx("div",{style:{position:"absolute",top:`${n.top}px`,left:`${n.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(u.current=m,s.current=m,m){m.focus();let l=m.value.length;m.setSelectionRange(l,l),c(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:i},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Tc=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},Mc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s})=>{let u=useSelector(v=>v.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useDispatch(),m=useRef(null),[l,d]=useState(""),[f,h]=useState(false),[p,y]=useState(null);useEffect(()=>{let v=m.current;if(v)return a.current.set(e.id,v),()=>{a.current.delete(e.id);}},[e.id,a]);let w=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=f&&l.trim().toLowerCase()===w,x=v=>{d(v);let k=v.trim(),T=k.toLowerCase()===w;c(ya({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:k,isCorrect:T}}}));},I=()=>{h(false),d(""),c(ya({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:"",isCorrect:false}}}));},L=()=>g?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",P=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},C=e.data.feedbackMode==="practice",b=useMemo(()=>{let O=C?48:0,U=12,H=30,K=e.width-48,E=Math.max(60,Tc(e.data.question,18,K,"bold")+20),W=f?Math.max(40,Tc(L(),12,K/2)+20):0,te=f?54:20,G=E+W+H+50+12+U+O+24;return {padding:24,questionHeight:E,questionFontSize:18,feedbackHeight:W,feedbackFontSize:12,inputY:te,inputHeight:50,inputMargin:12,buttonHeight:O,buttonTopMargin:U,placeholderHeight:H,contentWidth:K,totalHeight:G}},[e.width,e.data.question,f,g,C,L]);return jsxs(Group,{ref:m,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:b.totalHeight,name:"sa-element",...s,...i?{}:{onDragEnd:r,onClick:()=>o&&o(e.id),onTap:()=>o&&o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:b.totalHeight,onTransformEnd:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,n(v.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:b.padding+8,y:b.padding,fontSize:b.questionFontSize,fontStyle:"bold",fill:"#111827",width:b.contentWidth,height:b.questionHeight-b.padding,wrap:"word",listening:false}),jsx(Rect,{x:b.padding,y:b.questionHeight+b.feedbackHeight+b.placeholderHeight-b.inputY,width:b.contentWidth+4,height:b.inputHeight+6,fill:"#ffffff",stroke:g?"#22c55e":f?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:b.padding,y:b.questionHeight+b.feedbackHeight+b.placeholderHeight-b.inputY},divProps:{style:{width:`${b.contentWidth-4}px`,height:`${b.inputHeight}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:l,onChange:v=>x(v.target.value),disabled:f,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:f?"none":"auto"}})}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:b.padding,y:b.questionHeight+80,width:e.width/2+24,height:b.feedbackHeight,fill:P().bg,cornerRadius:8}),jsx(Text,{x:36,y:b.questionHeight+80,width:b.contentWidth,height:b.feedbackHeight,text:L(),fontSize:b.feedbackFontSize,fontStyle:"bold",fill:P().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:b.questionHeight+b.feedbackHeight+b.placeholderHeight+b.inputHeight+b.inputMargin+b.buttonTopMargin,children:[jsxs(Group,{onMouseDown:v=>{v.cancelBubble=true,y("check");},onMouseUp:v=>{v.cancelBubble=true,y(null),l.length>0&&h(true);},onMouseLeave:v=>{v.cancelBubble=true,y(null);},onTouchStart:v=>{v.cancelBubble=true,y("check");},onTouchEnd:v=>{v.cancelBubble=true,y(null),l.length>0&&h(true);},scaleX:p==="check"?.95:1,scaleY:p==="check"?.95:1,children:[jsx(Rect,{x:b.padding+14,width:(b.contentWidth-24)/(f?2:1),height:b.buttonHeight,fill:l.length===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true}),jsx(Text,{x:b.padding+14,width:(b.contentWidth-24)/(f?2:1),height:b.buttonHeight,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-b.padding*2)/2+8,onMouseDown:()=>y("reset"),onMouseUp:()=>{y(null),I();},onMouseLeave:()=>y(null),onTouchStart:()=>y("reset"),onTouchEnd:()=>{y(null),I();},scaleX:p==="reset"?.95:1,scaleY:p==="reset"?.95:1,children:[jsx(Rect,{x:b.padding,width:(b.contentWidth-8)/2,height:b.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:v=>v.cancelBubble=true,onTap:v=>v.cancelBubble=true}),jsx(Text,{x:b.padding,width:(b.contentWidth-8)/2,height:b.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Mc.displayName="ShortAnswer";var Ac=Mc;var Ec=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Ac,{shortAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"shortAnswer")},i.id))})};var Dc=e=>{let o=useDispatch(),a=useSelector(ye)?.fillInTheBlanks||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o($a({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:n,handleFillInTheBlanksDragEnd:r}};var Pl=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},Rc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:n,fibRefs:r,touchHandlers:s})=>{let u=useSelector(v=>v.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),m=useDispatch(),[l,d]=useState(""),[f,h]=useState(false),[p,y]=useState(null);useEffect(()=>{let v=c.current;if(v)return r.current.set(e.id,v),()=>{r.current.delete(e.id);}},[e.id,r]);let w=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=f&&l.trim().toLowerCase()===w,x=v=>{d(v);let k=v.trim(),T=k.toLowerCase()===w;m($a({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:k,isCorrect:T}}}));},I=()=>{h(false),d("");},L=()=>{l.length>0&&h(true);},P=e.data.feedbackMode==="practice",C=useMemo(()=>{let H=e.width-48,K=(H-15)/2,E=24,W=E,te=Math.max(60,Pl(e.data.question.replace("_____","________"),24,H,"bold")+20);E+=te;let G=E,z=Math.max(35,Pl("Enter your answer in the blank.",16,H)+10);E+=z;let N=E;E+=67;let _=E,Z=f?Math.max(32,Pl(g?"Right Answer, Great Job!":"Wrong Answer",14,H-40)+16):0;f&&(E+=Z+16);let ae=E;return P&&(E+=64),E+=24,{padding:24,questionY:W,questionHeight:te,questionFontSize:24,helperTextY:G,helperTextHeight:z,helperTextFontSize:16,inputY:N,inputHeight:51,feedbackY:_,feedbackHeight:Z,feedbackFontSize:14,buttonsY:ae,buttonHeight:64,buttonGap:15,buttonWidth:K,contentWidth:H,totalHeight:E}},[e.width,e.data.question,f,g,P]),b=()=>f?g?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...s,...i?{}:{onDragEnd:v=>a(v,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:C.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,n?.(v.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:C.padding,y:C.questionY,fontSize:C.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:C.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:C.padding,y:C.helperTextY,fontSize:C.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:C.contentWidth,height:C.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:C.padding,y:C.inputY,width:C.contentWidth,height:C.inputHeight,fill:"#ffffff",stroke:b(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:C.padding,y:C.inputY},divProps:{style:{width:`${C.contentWidth}px`,height:`${C.inputHeight}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:l,onChange:v=>x(v.target.value),disabled:f,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),f&&jsxs(Group,{y:C.feedbackY,children:[jsx(Rect,{x:C.padding,width:g?206:140,height:C.feedbackHeight,fill:g?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:g?"\u2713":"\u2717",x:C.padding+10,y:0,width:16,height:C.feedbackHeight,fontSize:C.feedbackFontSize,fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:g?"Right Answer, Great Job!":"Wrong Answer",x:C.padding+30,y:0,height:C.feedbackHeight,fontSize:C.feedbackFontSize,fontStyle:"600",fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),P&&jsxs(Group,{y:C.buttonsY,children:[jsxs(Group,{x:C.padding,onMouseDown:v=>{v.cancelBubble=true,y("reset");},onMouseUp:v=>{v.cancelBubble=true,y(null),I();},onMouseLeave:v=>{v.cancelBubble=true,y(null);},onTouchStart:v=>{v.cancelBubble=true,y("reset");},onTouchEnd:v=>{v.cancelBubble=true,y(null),I();},scaleX:p==="reset"?.98:1,scaleY:p==="reset"?.98:1,children:[jsx(Rect,{width:C.buttonWidth,height:C.buttonHeight,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:C.buttonWidth,height:C.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:C.padding+C.buttonWidth+C.buttonGap,onMouseDown:v=>{v.cancelBubble=true,y("submit");},onMouseUp:v=>{v.cancelBubble=true,y(null),L();},onMouseLeave:v=>{v.cancelBubble=true,y(null);},onTouchStart:v=>{v.cancelBubble=true,y("submit");},onTouchEnd:v=>{v.cancelBubble=true,y(null),L();},scaleX:p==="submit"?.98:1,scaleY:p==="submit"?.98:1,children:[jsx(Rect,{width:C.buttonWidth,height:C.buttonHeight,fill:l.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:C.buttonWidth,height:C.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Rc.displayName="FillInTheBlanks";var Fc=Rc;var Oc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,onLongPress:r,fibRefs:s})=>{let{createHandlers:u}=qe({onLongPress:r});return jsx(Fragment,{children:e.map(i=>jsx(Fc,{fillInTheBlank:i,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,fibRefs:s,touchHandlers:u(i.id,"fillInTheBlanks")},i.id))})};var Rl=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let m=i?`${i} ${c}`:c;r.measureText(m).width>t&&i!==""?(u.push(i),i=c):i=m;}),i&&u.push(i),u.length*o*1.2},Bl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,touchHandlers:r,handleDragEnd:s})=>{let u=useSelector(b=>b.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),m=useDispatch(),[l,d]=useState(""),[f,h]=useState(false),[p,y]=useState(null);useEffect(()=>{let b=c.current;if(b)return a.current.set(e.id,b),()=>{a.current.delete(e.id);}},[e.id,a]);let w=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",g=f&&l.trim().toLowerCase()===w,x=b=>{d(b);let v=b.trim();v.toLowerCase()===w;m(_a({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:v}}}));},I=()=>{h(false),d("");},L=()=>g?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",P=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},C=useMemo(()=>{let H=e.width-48,K=Math.max(60,Rl(e.data.question,20,H,"bold")+20),E=f?Math.max(60,Rl(L(),14,H)+30):0,te=Math.max(30,Rl("Answer (Extended response):",14,H)+10),G=K+E+te+120+12+12+48+24;return {padding:24,questionHeight:K,questionFontSize:20,feedbackHeight:E,feedbackFontSize:14,placeholderHeight:te,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:H,totalHeight:G}},[e.width,e.data.question,f,g,L]);return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:C.totalHeight,...r,name:"la-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:b=>{let v=c.current?.getStage()?.getPointerPosition();if(!v||!n)return;let k={x:e.x,y:e.y,width:e.width,height:C.totalHeight};v.x>=k.x&&v.x<=k.x+k.width&&v.y>=k.y&&v.y<=k.y+k.height&&n(b.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:C.totalHeight-50,onTransformEnd:b=>t(e.id,b)}),jsx(Text,{text:e.data.question,x:C.padding+8,y:C.padding,fontSize:C.questionFontSize,fontStyle:"bold",fill:"#111827",width:C.contentWidth,wrap:"word",listening:false}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:C.padding,y:C.questionHeight,width:C.contentWidth,height:C.feedbackHeight,fill:P().bg,cornerRadius:8}),jsx(Text,{x:C.padding,y:C.questionHeight,width:C.contentWidth,height:C.feedbackHeight,text:L(),fontSize:C.feedbackFontSize,fontStyle:"bold",fill:P().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),jsx(Text,{text:"Answer:",x:C.padding,y:C.questionHeight+C.feedbackHeight+C.textareaMargin,fontSize:C.placeholderFontSize,fill:"#6b7280",width:C.contentWidth,wrap:"word",listening:false}),jsx(Rect,{x:C.padding,y:C.questionHeight+C.feedbackHeight+C.placeholderHeight,width:C.contentWidth,height:C.textareaHeight,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:C.padding,y:C.questionHeight+C.feedbackHeight+C.placeholderHeight},divProps:{style:{width:`${C.contentWidth}px`,height:`${C.textareaHeight}px`,pointerEvents:f?"none":"auto"}},children:jsx("textarea",{value:l,onChange:b=>x(b.target.value),disabled:f,placeholder:"Type your extended answer here...",className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:f?"none":"auto"}})}),jsx(Group,{y:C.questionHeight+C.feedbackHeight+C.placeholderHeight+C.textareaHeight+C.textareaMargin+C.buttonTopMargin,children:f&&jsxs(Group,{onMouseDown:()=>y("reset"),onMouseUp:()=>{y(null),I();},onMouseLeave:()=>y(null),onTouchStart:()=>y("reset"),onTouchEnd:()=>{y(null),I();},scaleX:p==="reset"?.95:1,scaleY:p==="reset"?.95:1,children:[jsx(Rect,{x:C.padding,width:C.contentWidth,height:C.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:b=>b.cancelBubble=true,onTap:b=>b.cancelBubble=true}),jsx(Text,{x:C.padding,width:C.contentWidth,height:C.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Bl.displayName="LongAnswer";var Hc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=qe({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Bl,{longAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"longAnswer")},i.id))})};var io=1600,lo=900,Uc=3200,Wc=1800,yv=e=>{let o=0,t=0,a=io,n=lo;if(!e)return {minX:o,minY:t,maxX:a,maxY:n,width:io,height:lo};let r=(i,c,m,l)=>{o=Math.min(o,i),t=Math.min(t,c),a=Math.max(a,i+m),n=Math.max(n,c+l);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let c=i.x||0,m=i.y||0,l=i.scaleX||1,d=i.scaleY||1;for(let f=0;f<i.points.length;f+=2){let h=c+i.points[f]*l,p=m+i.points[f+1]*d;o=Math.min(o,h),t=Math.min(t,p),a=Math.max(a,h),n=Math.max(n,p);}}}),e.images?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>r(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>r(i.x,i.y,i.width,i.height));let s=Math.min(a-o,Uc),u=Math.min(n-t,Wc);return o=Math.max(o,a-Uc),t=Math.max(t,n-Wc),{minX:o,minY:t,maxX:a,maxY:n,width:s,height:u}},wv=(e,o,t={minX:0,minY:0,maxX:io,maxY:lo,width:io,height:lo})=>{let a=Math.max(t.width,io),n=Math.max(t.height,lo),r=e/o,s=a/n,u,i,c,l=0;if(r>s){i=n,u=Math.round(i*r),c=o/i;}else {u=a,i=Math.round(u/r),c=e/u;let d=n*c;l=(o-d)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:l,baseWidth:u,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},Kc=(e,o,t=1)=>{let a=o.contentOffsetX||0,n=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/(o.scale*t)+a,y:(e.y-o.offsetY)/(o.scale*t)+n}},Sv=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:n={enabled:true}}={})=>{let r=$e(),s=Ve(),u=J(S=>S.toolbar.selectedTool),i=J(ye),c=J(Sa),m=J(Yn),l=J(S=>S.canvas.zoomLevel),f=(i?.videos||[]).find(S=>S.isRecorded&&S.isPlaying),h=!!f,p=useCallback(()=>{f&&r(Ga(f.id));},[r,f]),y=i?.editingActivity,w=i?.showMcqForm,g=i?.lines||[],x=useRef(null),I=useRef(null),[L,P]=useState(null),[C,b]=useState(""),v=useRef(null),[k,T]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:io,stageHeight:lo,offsetX:0,offsetY:0,baseWidth:io,baseHeight:lo,contentOffsetX:0,contentOffsetY:0}),F=useMemo(()=>yv(i||null),[c]),[V,O]=useState(null),[U,H]=useState(null),[K,E]=useState(null),[W,te]=useState(null),[G,z]=useState(null),[N,_]=useState(null),[Z,ae]=useState(null),[Q,pe]=useState(false),[ue,le]=useState(null),[he,ce]=useState(false),_e=useRef(null),or=useRef(null),ga=useRef(null),{debouncedGenerateThumbnail:on}=gu(c,x);useEffect(()=>{let S=()=>{if(I.current){let D=I.current.getBoundingClientRect(),B=wv(D.width,D.height,F);T(B);}};S();let M=new ResizeObserver(S);return I.current&&M.observe(I.current),window.addEventListener("resize",S),()=>{M.disconnect(),window.removeEventListener("resize",S);}},[F]),useEffect(()=>{if(x.current){let S=x.current.container();S&&(S.style.cursor="");}},[u]);let ne=useCallback(()=>{x.current&&requestAnimationFrame(()=>{if(!x.current)return;if(x.current.getLayers().forEach(M=>M.batchDraw()),!m)try{let D=x.current.toDataURL({pixelRatio:.16666666666666666});b(D),on();}catch(M){console.warn("Preview generation failed (CORS):",M);}});},[on,m]),rn=useRef(c);useEffect(()=>{rn.current!==c&&(rn.current=c,ne());},[c,ne]);let nn=useRef(null),sn=useRef(true);useEffect(()=>{if(!i)return;let S=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),M=nn.current?.count!==S;!sn.current&&M&&setTimeout(()=>{ne();},100),nn.current={slideId:c,count:S},sn.current=false;},[i,c,ne]),useEffect(()=>{x.current&&e&&e(x);},[e]),useEffect(()=>{ga.current&&a&&a(ga);},[a]);let{startDrawing:ln,draw:dn,stopDrawing:un,setCanvasRef:Wa,tool:_s,color:$s,strokeWidth:Xs,isSketchMode:Ys}=Wd(ne),xa=useRef(new Map),{images:cn,getLoadedImage:Zs,imageRefs:go,handleDragEnd:fn,handleImageTransformEnd:Js}=Yd(ne),{videos:rr,videoRefs:xo,handleVideoClick:mn,handleVideoDragEnd:A,handleVideoTransformEnd:re}=Qd(ne),{multipleChoice:Ae,handleMcqTransform:we,mcqRefs:ie,handleDragEnd:ge}=Zd(ne),{trueFalse:He,handleTrueFalseTransform:lt,trueFalseRefs:Et,handleTrueFalseDragEnd:bt}=Jd(ne),{shortAnswers:Fe,saRefs:ze,handleShortAnswerDragEnd:oa}=nu(ne),{longAnswers:ba,handleLongAnswerDragEnd:Qs}=su(ne),{fillInTheBlanks:ei,handleFillInTheBlanksDragEnd:pn,fibRefs:dt}=Dc(ne),{transformerRef:se,boundBoxFunc:vt}=fu(),{shapes:Um,shapeRefs:hn,isDragging:Cd,handleShapeDragEnd:Wm,handleShapeResizeEnd:Km}=au(ne),{texts:nr,textRefs:va,handleDragEnd:Gm,handleTransformEnd:jm,handleDoubleClick:_m,startEditing:gn,editingTextId:ve,editingValue:kd,handleEditingChange:Td,finishEditing:ti}=ru(ne,_e);useEffect(()=>{t&&t(gn);},[t,gn]);let xn=J(S=>S.canvas.editingTextId);useEffect(()=>{xn&&xn!==ve&&gn(xn);},[xn,ve,gn]);let{flashcards:$m,flashcardRefs:bn,handleDragEnd:Xm,handleFlashcardTransformEnd:Ym,handleNext:Zm,handlePrevious:Jm}=lu(ne),{photoFrames:Md,photoFrameRefs:vn,handleDragEnd:Qm,handlePhotoFrameTransformEnd:ep,startCamera:tp,capturePhoto:ap,cameraStreams:op}=cu(ne);useEffect(()=>{if(se.current){if(ve){se.current.nodes([]),se.current.getLayer()?.batchDraw();return}if(L&&!rr.find(D=>D.id===L)?.isPlaying){let D=xa.current.get(L)||go.current.get(L)||xo.current.get(L)||hn.current.get(L)||va.current.get(L)||ie.current.get(L)||bn.current.get(L)||vn.current.get(L)||ze.current.get(L)||Et.current.get(L)||dt.current.get(L);if(D){let B=D.attrs?.locked;if(D.visible()&&B!==true){se.current.nodes([D]),se.current.getLayer()?.batchDraw();return}}}se.current.nodes([]),se.current.getLayer()?.batchDraw();}},[L,ve,rr,xa,go,xo,hn,va,bn,vn,Md,ie,Et,dt,se]);let Ue=useCallback(S=>{P(S),o?.(S);},[o]),bo=useCallback(()=>{P(null),o?.(null),se.current&&(se.current.nodes([]),se.current.getLayer()?.batchDraw());},[se,o]),Ad=useCallback(S=>i?i.lines?.some(M=>M.id===S)?"line":i.images?.some(M=>M.id===S)?"image":i.videos?.some(M=>M.id===S)?"video":i.shapes?.some(M=>M.id===S)?"shape":i.texts?.some(M=>M.id===S)?"text":i.flashcards?.some(M=>M.id===S)?"flashcard":i.photoFrames?.some(M=>M.id===S)?"photoFrame":i.multipleChoices?.some(M=>M.id===S)?"mcq":i.trueFalses?.some(M=>M.id===S)?"trueFalse":i.shortAnswers?.some(M=>M.id===S)?"shortAnswer":i.LongAnswer?.some(M=>M.id===S)?"longAnswer":i.fillInTheBlanks?.some(M=>M.id===S)?"fillInTheBlanks":null:null,[i]),Pd=useCallback((S,M)=>{switch(r(fe()),M){case "line":r($n(S));break;case "image":r(wn(S));break;case "video":r(In(S));break;case "shape":r(Tn(S));break;case "text":r(Mn(S));break;case "flashcard":r(Pn(S));break;case "photoFrame":r(Dn(S));break;case "mcq":r(Fn(S));break;case "trueFalse":r(On(S));break;case "shortAnswer":r(Hn(S));break;case "longAnswer":r(Vn(S));break;case "fillInTheBlanks":r(Un(S));break}bo(),ne();},[r,bo,ne]);useEffect(()=>{let S=M=>{if(M.key!=="Delete"||!L||ve)return;let D=document.activeElement;if(D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement||D?.getAttribute("contenteditable")==="true")return;M.preventDefault();let Ie=Ad(L);Ie&&Pd(L,Ie);};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[L,ve,Ad,Pd]),useEffect(()=>{let S=se.current;return ()=>{S&&S.nodes([]);}},[c]),useEffect(()=>{let S=M=>{ve&&M.target.tagName!=="TEXTAREA"&&ti();};return document.addEventListener("mousedown",S),()=>{document.removeEventListener("mousedown",S);}},[ve,ti]),useEffect(()=>{let S=ve||L;if(!S||L&&ve){H(null);return}let M=va.current.get(S),D=x.current;if(!M||!D){H(null);return}let B=D.container().getBoundingClientRect(),Ie=M.absolutePosition(),be=D.scaleX();H({x:B.left+(Ie.x+M.width()*be/2)*be+k.offsetX,y:B.top+Ie.y*be+k.offsetY-70});},[L,ve,nr,va,k.offsetX,k.offsetY]),useEffect(()=>{if(!ve){E(null);return}let S=va.current.get(ve),M=x.current;if(!S||!M){E(null);return}let D=S.getClientRect({relativeTo:M}),B=M.container().getBoundingClientRect(),Ie=M.scaleX(),be=M.position(),oe={top:B.top+be.y+D.y*Ie,left:B.left+be.x+D.x*Ie,scale:Ie};E(oe),r(qd(oe));},[ve,nr,va,k.offsetY,k.offsetX]);let Ed=useCallback(S=>{let M=S.target.getClassName(),D=S.target===S.target.getStage(),B=M==="Transformer"||S.target.getParent()?.getClassName()==="Transformer",Ie=M==="Image",be=M==="Text",oe=M==="Group"||S.target.getParent()?.getClassName()==="Group",ut=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&S.target.attrs.id,ct=M==="Group";if(D&&!B&&!Ie&&!be&&!oe&&!ut&&!ct&&bo(),!(u==="pen"||u==="eraser")&&(Ie||be||B||oe||ut||ct))return;let We=S.target.getStage()?.getPointerPosition();if(!We)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let q=Kc(We,k,l);ln(q);}},[u,ln,bo,k,l]),Dd=useCallback(S=>{if(Cd)return;let M=S.target.getStage()?.getPointerPosition();if(!M)return;let D=Kc(M,k,l);dn(D);},[dn,Cd,k,l]),Rd=useCallback(()=>{un();},[un]),rp=useCallback(S=>{fn(S,ne);},[fn,ne]),np=useCallback(S=>{mn(S),Ue(S);},[mn,Ue]),Dt=useCallback((S,M,D)=>{if(S.preventDefault(),!n.enabled)return;let B=S.clientX,Ie=S.clientY,be=v.current?.offsetHeight||250,oe=v.current?.offsetWidth||200,ut=window.innerHeight,ct=window.innerWidth,et=B,We=Ie;Ie+be>ut&&(We=Ie-be),B+oe>ct&&(et=B-oe),Ue(M),O({x:et,y:We,elementId:M,elementType:D});},[Ue,n.enabled]),Ka=useRef(null),sr=useRef(null),yt=useCallback((S,M)=>D=>{if(!n.enabled)return;D.preventDefault();let B=D.changedTouches[0];if(!B)return;let Ie=B.clientX,be=B.clientY,oe=v.current?.offsetHeight||200,ut=v.current?.offsetWidth||200,ct=window.innerHeight,et=window.innerWidth,We=Ie,tt=be;be+oe>ct&&(tt=be-oe),Ie+ut>et&&(We=Ie-ut),Ue(S),O({x:We,y:tt,elementId:S,elementType:M});},[Ue,n.enabled]),sp=useCallback((S,M)=>({onTouchStart:D=>{let B=D.evt.touches[0];sr.current={x:B.clientX,y:B.clientY},Ka.current=setTimeout(()=>{yt(S,M)(D.evt);},500);},onTouchMove:D=>{if(!sr.current)return;let B=D.evt.touches[0],Ie=Math.abs(B.clientX-sr.current.x),be=Math.abs(B.clientY-sr.current.y);(Ie>10||be>10)&&Ka.current&&(clearTimeout(Ka.current),Ka.current=null);},onTouchEnd:()=>{Ka.current&&(clearTimeout(Ka.current),Ka.current=null),sr.current=null;}}),[yt]),Fd=useCallback(S=>{r(mr(S)),r(wa(true));},[r]),ip=useCallback(S=>{r(fr(S)),r(Xa(true));},[r]),lp=useCallback((S,M)=>{if(!V)return;let{elementId:D,elementType:B}=V;switch(S){case "order":if(M){let R=M.target.getBoundingClientRect();te({x:R.right+5,y:R.top,type:"order"});}break;case "lock":if(M){let R=M.target.getBoundingClientRect();te({x:R.right+5,y:R.top,type:"lock"});}break;case "link":if(O(null),B==="line")break;let Ie=i?B==="image"?i.images.find(R=>R.id===D):i.videos.find(R=>R.id===D):null;z({type:"link",defaultValue:Ie?.link||""});break;case "voice":if(O(null),B==="line")break;let be=i?B==="image"?i.images.find(R=>R.id===D):B==="video"?i.videos.find(R=>R.id===D):B==="text"?i.texts.find(R=>R.id===D):B==="flashcard"?i.flashcards.find(R=>R.id===D):B==="photoFrame"?i.photoFrames.find(R=>R.id===D):B==="mcq"?i.multipleChoices.find(R=>R.id===D):B==="fillInTheBlanks"?i.fillInTheBlanks.find(R=>R.id===D):B==="longAnswer"?i.LongAnswer.find(R=>R.id===D):B==="shortAnswer"?i.shortAnswers.find(R=>R.id===D):B==="trueFalse"?i.trueFalses.find(R=>R.id===D):B==="shape"?i.shapes.find(R=>R.id===D):null:null;le({elementId:D,elementType:B,existingAudio:be?.audioData});break;case "edit":O(null);let oe=null;B==="mcq"?oe=i?.multipleChoices.find(R=>R.id===D):B==="trueFalse"?oe=i?.trueFalses.find(R=>R.id===D):B==="shortAnswer"?oe=i?.shortAnswers.find(R=>R.id===D):B==="longAnswer"?oe=i?.LongAnswer.find(R=>R.id===D):B==="fillInTheBlanks"&&(oe=i?.fillInTheBlanks.find(R=>R.id===D)),oe&&Fd(oe);break;case "editFlashcard":O(null);let ut=i?.flashcards.find(R=>R.id===D);ut&&ip(ut);break;case "color":O(null);let ct=i?.shapes.find(R=>R.id===D);_({elementId:D,elementType:"shape",defaultColor:ct?.color||"#096B76"});break;case "crop":if(O(null),B==="image"){let R=i?.images.find(hp=>hp.id===D);R&&ae({elementId:D,imageSrc:R.src});}break;case "draw":O(null),B==="image"?r(gi(D)):B==="photoFrame"&&r(bi(D));break;case "duplicate":r(fe()),B==="line"?r(Ei(D)):B==="image"?r(Sn(D)):B==="video"?r(Cn(D)):B==="shape"?r(kn(D)):B==="text"?r(An(D)):B==="flashcard"?r(En(D)):B==="photoFrame"?r(Rn(D)):B==="mcq"?r(Bn(D)):B==="trueFalse"?r(Nn(D)):B==="shortAnswer"?r(qn(D)):B==="fillInTheBlanks"?r(Wn(D)):B==="longAnswer"&&r(zn(D)),ne();break;case "infinite-clone":r(fe());let et=5;for(let R=0;R<et;R++)B==="image"?r(Sn(D)):B==="video"?r(Cn(D)):B==="shape"?r(kn(D)):B==="text"?r(An(D)):B==="flashcard"?r(En(D)):B==="photoFrame"?r(Rn(D)):B==="mcq"?r(Bn(D)):B==="trueFalse"?r(Nn(D)):B==="shortAnswer"?r(qn(D)):B==="fillInTheBlanks"?r(Wn(D)):B==="longAnswer"&&r(zn(D));ne();break;case "make-response":if(O(null),B==="line")break;let We=`#response-${D}`;r(fe()),r(Kn({id:D,type:B,link:We})),(i?B==="image"?i.images.find(R=>R.id===D):B==="video"?i.videos.find(R=>R.id===D):B==="shape"?i.shapes.find(R=>R.id===D):B==="flashcard"?i.flashcards.find(R=>R.id===D):B==="photoFrame"?i.photoFrames.find(R=>R.id===D):i.multipleChoices.find(R=>R.id===D):null)?.altText||r(Gn({id:D,type:B,altText:"Interactive response area"})),ne(),console.log(`Element ${D} marked as interactive response area`);break;case "accessibility":if(O(null),B==="line")break;let q=i?B==="image"?i.images.find(R=>R.id===D):B==="video"?i.videos.find(R=>R.id===D):B==="shape"?i.shapes.find(R=>R.id===D):null:null;z({type:"altText",defaultValue:q?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),O(null),ce(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(fe()),B==="line"?r($n(D)):B==="image"?r(wn(D)):B==="video"?r(In(D)):B==="shape"?r(Tn(D)):B==="text"?r(Mn(D)):B==="flashcard"?r(Pn(D)):B==="photoFrame"?r(Dn(D)):B==="mcq"?r(Fn(D)):B==="trueFalse"?r(On(D)):B==="shortAnswer"?r(Hn(D)):B==="longAnswer"?r(Vn(D)):B==="fillInTheBlanks"&&r(Un(D)),bo(),ne();break}},[V,r,ne,bo,i,Fd]),dp=useCallback(()=>{O(null),te(null);},[]),ai=useCallback(S=>{if(!V)return;let{elementId:M,elementType:D}=V;switch(r(fe()),S){case "bring-to-front":D!=="line"&&r(Ti({id:M,type:D}));break;case "send-to-back":D!=="line"&&r(Mi({id:M,type:D}));break;case "lock":case "unlock":D!=="line"&&r(Ai({id:M,type:D}));break}ne(),O(null),te(null);},[V,r,ne]),up=useCallback(S=>{if(!V||!G)return;let{elementId:M,elementType:D}=V;r(fe()),G.type==="link"&&D!=="line"?r(Kn({id:M,type:D,link:S})):G.type==="altText"&&D!=="line"&&r(Gn({id:M,type:D,altText:S})),ne(),z(null);},[V,G,r,ne]),cp=useCallback(S=>{if(!ue)return;let{elementId:M,elementType:D}=ue;r(fe()),r(jn({id:M,type:D,audioData:S})),ne(),le(null);},[ue,r,ne]),fp=useCallback(()=>{if(!ue)return;let{elementId:S,elementType:M}=ue;r(fe()),r(jn({id:S,type:M,audioData:""})),ne();},[ue,r,ne]),mp=useCallback(S=>{if(!N)return;let{elementId:M}=N;r(fe()),r(So({id:M,color:S})),ne(),_(null);},[N,r,ne]),pp=useCallback(S=>{if(!Z)return;let{elementId:M}=Z;r(fe()),r(yo({id:M,src:S})),ne(),ae(null);},[Z,r,ne]);return jsxs("div",{ref:I,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx($d,{ref:S=>{if(or.current=S,Wa(S),S){let M=S.getCanvasElement();M&&(ga.current=M,a&&a(ga));}},width:k.baseWidth,height:k.baseHeight,tool:_s,color:$s,strokeWidth:Xs/(k.scale*l),isSketchMode:Ys,xOffset:k.contentOffsetX,yOffset:k.contentOffsetY-k.offsetY/k.scale,style:{width:k.stageWidth,height:k.stageHeight}}),jsxs(Stage,{ref:x,width:k.stageWidth,height:k.stageHeight,scaleX:k.scaleX*l,scaleY:k.scaleY*l,x:k.offsetX,y:0,onMouseDown:Ed,onMouseMove:Dd,onMouseUp:Rd,onTouchStart:Ed,onTouchMove:Dd,onTouchEnd:Rd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:k.baseWidth,height:k.stageHeight/k.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-k.contentOffsetX,y:k.offsetY/k.scale-k.contentOffsetY,children:(()=>{let S=[];return g.forEach((M,D)=>{S.push({type:"line",timestamp:M.timestamp||D,element:{...M,id:M.id??`line-${D}`},index:D});}),Um.forEach(M=>{S.push({type:"shape",timestamp:M.timestamp||0,element:M});}),cn.forEach(M=>{S.push({type:"image",timestamp:M.timestamp||0,element:M});}),rr.forEach(M=>{S.push({type:"video",timestamp:M.timestamp||0,element:M});}),nr.forEach(M=>{S.push({type:"text",timestamp:M.timestamp||0,element:M});}),$m.forEach(M=>{S.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Md.forEach(M=>{S.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),Ae.forEach(M=>{S.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),He.forEach(M=>{S.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),Fe.forEach(M=>{S.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),ba.forEach(M=>{S.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),ei.forEach(M=>{S.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),S.sort((M,D)=>M.timestamp-D.timestamp),S.map((M,D)=>{let B=`${M.type}-${"id"in M.element&&M.element.id||M.index||D}`,Ie="id"in M.element?M.element.id:void 0,be=Ie&&L===Ie;switch(M.type){case "line":let oe=M.element,ut=M.index||0,ct=oe.tool==="eraser",et=oe.isSketch&&oe.tool==="pen",We=oe.isSketch&&ct,tt=oe.id||`line-${ut}`;return oe.x===void 0&&(oe.x=0),oe.y===void 0&&(oe.y=0),oe.scaleX===void 0&&(oe.scaleX=1),oe.scaleY===void 0&&(oe.scaleY=1),oe.rotation===void 0&&(oe.rotation=0),u==="eraser"?jsx(Group,{x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,children:jsx(Line,{points:oe.points||[],stroke:et||We?void 0:oe.color,strokeWidth:et||We?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:et||We?ct?"black":oe.color:void 0,closed:et||We,tension:0,globalCompositeOperation:ct?"destination-out":"source-over",listening:true,onClick:()=>{r(fe()),r(yn(ut));},onTap:()=>{r(fe()),r(yn(ut));},hitStrokeWidth:Math.max(20,(oe.strokeWidth??0)*2),onMouseEnter:q=>{let R=q.target.getStage();R&&(R.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:q=>{let R=q.target.getStage();R&&(R.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},B):jsxs(Le__default.Fragment,{children:[jsx(Group,{id:tt,ref:q=>{q?xa.current.set(tt,q):xa.current.delete(tt);},x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",tt),Ue(tt));},onTap:()=>{u==="select"&&(console.log("Line tapped:",tt),Ue(tt));},onDragEnd:q=>{r(fe()),r(_n({id:tt,x:q.target.x(),y:q.target.y(),scaleX:q.target.scaleX(),scaleY:q.target.scaleY(),rotation:q.target.rotation()})),ne();},onTransformEnd:q=>{r(fe()),r(_n({id:tt,x:q.target.x(),y:q.target.y(),scaleX:q.target.scaleX(),scaleY:q.target.scaleY(),rotation:q.target.rotation()})),ne();},onMouseEnter:q=>{if(u==="select"){let R=q.target.getStage();R&&(R.container().style.cursor="move");}},onMouseLeave:q=>{if(u==="select"){let R=q.target.getStage();R&&(R.container().style.cursor="default");}},onContextMenu:q=>{let R=q.evt;R.preventDefault(),Dt(R,tt,"line");},...sp(tt,"line"),children:jsx(Line,{points:oe.points||[],stroke:et||We?void 0:oe.color,strokeWidth:et||We?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:et||We?ct?"black":oe.color:void 0,closed:et||We,tension:0,globalCompositeOperation:ct?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=xa.current.get(L);console.log("Line Transformer - selectedId:",L,"node found:",!!R),R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "shape":return jsxs(Le__default.Fragment,{children:[jsx($i,{onSelect:Ue,shapes:[M.element],shapeRefs:hn,handleShapeDragEnd:Wm,handleShapeResizeEnd:Km,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=hn.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "image":return jsxs(Le__default.Fragment,{children:[jsx(Ki,{images:[M.element],getLoadedImage:Zs,imageRefs:go,onDragEnd:rp,onTransform:Js,onSelect:Ue,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=go.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "video":return jsxs(Le__default.Fragment,{children:[jsx(_i,{videos:[M.element],selectedId:L,videoRefs:xo,onVideoClick:np,onDragEnd:A,onTransformEnd:re,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=xo.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "text":return jsxs(Le__default.Fragment,{children:[jsx(Mu,{texts:[M.element],textRefs:va,onDragEnd:Gm,onTransformEnd:jm,onSelect:Ue,onContextMenu:Dt,onLongPress:yt,onDoubleClick:_m,editingTextId:ve,editingValue:kd,onEditingChange:Td}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=va.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "flashcard":return jsxs(Le__default.Fragment,{children:[jsx(Ji,{flashcards:[M.element],flashcardRefs:bn,selectedId:L,onDragEnd:Xm,onTransform:Ym,onSelect:Ue,onNext:Zm,onPrevious:Jm,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=bn.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "photoFrame":return jsxs(Le__default.Fragment,{children:[jsx(rl,{photoFrames:[M.element],photoFrameRefs:vn,selectedId:L,onDragEnd:Qm,onTransform:ep,onSelect:Ue,onStartCamera:tp,onCapture:ap,cameraStreams:op,onContextMenu:Dt,onLongPress:yt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=vn.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},boundBoxFunc:vt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "mcq":return jsxs(Le__default.Fragment,{children:[jsx(nc,{handleMcqTransform:we,multipleChoice:[M.element],handleSelect:Ue,mcqRefs:ie,handleDragEnd:ge,onContextMenu:Dt,onLongPress:yt,onUpdate:ne}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=ie.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "trueFalse":return jsxs(Le__default.Fragment,{children:[jsx(dc,{trueFalses:[M.element],handleTrueFalseTransform:lt,handleSelect:Ue,trueFalseRefs:Et,onContextMenu:Dt,onLongPress:yt,handleDragEnd:bt,onUpdate:ne}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=Et.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "shortAnswer":return jsxs(Le__default.Fragment,{children:[jsx(Ec,{shortAnswers:[M.element],handleSelect:Ue,handleTransform:we,saRefs:ze,onContextMenu:Dt,onLongPress:yt,handleDragEnd:oa}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=ze.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "longAnswer":return jsxs(Le__default.Fragment,{children:[jsx(Hc,{longAnswer:[M.element],handleSelect:Ue,handleTransform:we,saRefs:ze,onContextMenu:Dt,onLongPress:yt,handleDragEnd:Qs}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=ze.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "fillInTheBlanks":return jsxs(Le__default.Fragment,{children:[jsx(Oc,{fillInTheBlanks:[M.element],handleSelect:Ue,handleTransform:we,onContextMenu:Dt,onLongPress:yt,handleDragEnd:pn,fibRefs:dt}),be&&!ve&&L&&jsx(Transformer,{ref:q=>{if(q&&se.current!==q){se.current=q;let R=dt.current.get(L);R&&R.visible()&&(q.nodes([R]),q.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);default:return null}})})()})]}),V&&jsx(zu,{menuRef:v,x:V.x,y:V.y,type:V.elementType,onAction:lp,onClose:dp,isDrawingMode:V.elementType==="image"?i?.images.find(S=>S.id===V.elementId)?.isDrawingMode:V.elementType==="photoFrame"?i?.photoFrames.find(S=>S.id===V.elementId)?.isDrawingMode:false}),W&&V&&jsx(Uu,{x:W.x,y:W.y,items:W.type==="order"?[{label:"Bring to Front",onClick:()=>ai("bring-to-front")},{label:"Send to Back",onClick:()=>ai("send-to-back")}]:[{label:i&&(V.elementType==="image"?i.images.find(S=>S.id===V.elementId)?.locked:i.videos.find(S=>S.id===V.elementId)?.locked)?"Unlock":"Lock",onClick:()=>ai(i&&(V.elementType==="image"?i.images.find(S=>S.id===V.elementId)?.locked:i.videos.find(S=>S.id===V.elementId)?.locked)?"unlock":"lock")}],onClose:()=>te(null)}),G&&jsx(Gu,{title:G.type==="link"?"Add Link":"Add Alt Text",label:G.type==="link"?"URL":"Alternative Text",placeholder:G.type==="link"?"https://example.com":"Describe this image/video",defaultValue:G.defaultValue,onSave:up,onClose:()=>z(null)}),N&&jsx(os,{defaultColor:N.defaultColor,onConfirm:mp,onCancel:()=>_(null)}),Z&&jsx(Xu,{imageSrc:Z.imageSrc,onConfirm:pp,onCancel:()=>ae(null)}),Q&&jsx(Ya,{onClose:()=>pe(false),stageRef:x}),ue&&jsx(Qu,{elementId:ue.elementId,elementType:ue.elementType,existingAudio:ue.existingAudio,onSave:cp,onDelete:fp,onClose:()=>le(null)}),he&&jsx(ac,{selectedElementId:L||void 0,onClose:()=>ce(false),onSelectElement:S=>{Ue(S),ce(false);}}),i?.images.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.videos.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.shapes?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.texts?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.flashcards?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.photoFrames?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.multipleChoices?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.trueFalses?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.shortAnswers?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.LongAnswer?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),i?.fillInTheBlanks?.filter(S=>S.audioData).map(S=>jsx(Nt,{audioData:S.audioData,x:S.x,y:S.y,width:S.width,scale:k.scale,offsetX:k.offsetX,offsetY:k.offsetY},`audio-${S.id}`)),w&&jsx(yc,{editElement:y}),U&&(()=>{let S=ve||L;if(!S)return null;let M=nr.find(D=>D.id===S);return M?jsx(Ic,{text:M,position:U}):null})(),K&&ve&&(()=>{let S=nr.find(M=>M.id===ve);return S?jsx(kc,{text:S,editingValue:kd,onEditingChange:Td,onFinish:ti,position:{top:K.top,left:K.left},scale:K.scale,textareaRef:_e},ve):null})(),h&&s&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:f?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:p})}),jsx("button",{onClick:p,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X$1,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),s)]})},Lv=Sv;var Cv="SchooplaVideoStorage";var ea="videos",Ms=()=>new Promise((e,o)=>{let t=indexedDB.open(Cv,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(ea)||n.createObjectStore(ea,{keyPath:"id"});};}),sa=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Ms(),r=a.transaction([ea],"readwrite").objectStore(ea),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,i)=>{let c=r.put(s);c.onsuccess=()=>u(!0),c.onerror=()=>i(c.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var Gc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Ms(),t=e.transaction([ea],"readonly").objectStore(ea);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let s=r.result,u=new Map;s.forEach(i=>{u.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),a(u);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Ol=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Ms(),a=o.transaction([ea],"readwrite").objectStore(ea);await new Promise((n,r)=>{let s=a.delete(e);s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},jc=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Ms(),t=e.transaction([ea],"readwrite").objectStore(ea);await new Promise((a,n)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>n(r.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},_c=e=>URL.createObjectURL(e);function Oa(e,o=[]){let t=[];function a(r,s){let u=Le.createContext(s),i=t.length;t=[...t,s];let c=l=>{let{scope:d,children:f,...h}=l,p=d?.[e]?.[i]||u,y=Le.useMemo(()=>h,Object.values(h));return jsx(p.Provider,{value:y,children:f})};c.displayName=r+"Provider";function m(l,d){let f=d?.[e]?.[i]||u,h=Le.useContext(f);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${l}\` must be used within \`${r}\``)}return [c,m]}let n=()=>{let r=t.map(s=>Le.createContext(s));return function(u){let i=u?.[e]||r;return Le.useMemo(()=>({[`__scope${e}`]:{...u,[e]:i}}),[u,i])}};return n.scopeName=e,[a,Tv(n,...o)]}function Tv(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(n=>({useScope:n(),scopeName:n.scopeName}));return function(r){let s=a.reduce((u,{useScope:i,scopeName:c})=>{let l=i(r)[`__scope${c}`];return {...u,...l}},{});return Le.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function $c(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function _r(...e){return o=>{let t=false,a=e.map(n=>{let r=$c(n,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let n=0;n<a.length;n++){let r=a[n];typeof r=="function"?r():$c(e[n],null);}}}}function Ut(...e){return Le.useCallback(_r(...e),e)}function Zc(e){let o=Mv(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Pv);if(i){let c=i.props.children,m=u.map(l=>l===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:l);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,m):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Mv(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Dv(n),u=Ev(r,n.props);return n.type!==Le.Fragment&&(u.ref=a?_r(a,s):s),Le.cloneElement(n,u)}return Le.Children.count(n)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Av=Symbol("radix.slottable");function Pv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Av}function Ev(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let i=r(...u);return n(...u),i}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function Dv(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var Bv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gt=Bv.reduce((e,o)=>{let t=Zc(`Primitive.${o}`),a=Le.forwardRef((n,r)=>{let{asChild:s,...u}=n,i=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...u,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function ot(e,o,{checkForDefaultPrevented:t=true}={}){return function(n){if(e?.(n),t===false||!n.defaultPrevented)return o?.(n)}}function Nl(e){let o=Ov(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Hv);if(i){let c=i.props.children,m=u.map(l=>l===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:l);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,m):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Ov(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Vv(n),u=qv(r,n.props);return n.type!==Le.Fragment&&(u.ref=a?_r(a,s):s),Le.cloneElement(n,u)}return Le.Children.count(n)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Nv=Symbol("radix.slottable");function Hv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Nv}function qv(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let i=r(...u);return n(...u),i}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function Vv(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function As(e){let o=e+"CollectionProvider",[t,a]=Oa(o),[n,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=p=>{let{scope:y,children:w}=p,g=Le__default.useRef(null),x=Le__default.useRef(new Map).current;return jsx(n,{scope:y,itemMap:x,collectionRef:g,children:w})};s.displayName=o;let u=e+"CollectionSlot",i=Nl(u),c=Le__default.forwardRef((p,y)=>{let{scope:w,children:g}=p,x=r(u,w),I=Ut(y,x.collectionRef);return jsx(i,{ref:I,children:g})});c.displayName=u;let m=e+"CollectionItemSlot",l="data-radix-collection-item",d=Nl(m),f=Le__default.forwardRef((p,y)=>{let{scope:w,children:g,...x}=p,I=Le__default.useRef(null),L=Ut(y,I),P=r(m,w);return Le__default.useEffect(()=>(P.itemMap.set(I,{ref:I,...x}),()=>void P.itemMap.delete(I))),jsx(d,{[l]:"",ref:L,children:g})});f.displayName=m;function h(p){let y=r(e+"CollectionConsumer",p);return Le__default.useCallback(()=>{let g=y.collectionRef.current;if(!g)return [];let x=Array.from(g.querySelectorAll(`[${l}]`));return Array.from(y.itemMap.values()).sort((P,C)=>x.indexOf(P.ref.current)-x.indexOf(C.ref.current))},[y.collectionRef,y.itemMap])}return [{Provider:s,Slot:c,ItemSlot:f},h,a]}var _o=globalThis?.document?Le.useLayoutEffect:()=>{};var zv=Le[" useId ".trim().toString()]||(()=>{}),Uv=0;function tf(e){let[o,t]=Le.useState(zv());return _o(()=>{t(a=>a??String(Uv++));},[e]),(o?`radix-${o}`:"")}function af(e){let o=Le.useRef(e);return Le.useEffect(()=>{o.current=e;}),Le.useMemo(()=>(...t)=>o.current?.(...t),[])}var Wv=Le[" useInsertionEffect ".trim().toString()]||_o;function la({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[n,r,s]=Kv({defaultProp:o,onChange:t}),u=e!==void 0,i=u?e:n;{let m=Le.useRef(e!==void 0);Le.useEffect(()=>{let l=m.current;l!==u&&console.warn(`${a} is changing from ${l?"controlled":"uncontrolled"} to ${u?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=u;},[u,a]);}let c=Le.useCallback(m=>{if(u){let l=Gv(m)?m(e):m;l!==e&&s.current?.(l);}else r(m);},[u,e,r,s]);return [i,c]}function Kv({defaultProp:e,onChange:o}){let[t,a]=Le.useState(e),n=Le.useRef(t),r=Le.useRef(o);return Wv(()=>{r.current=o;},[o]),Le.useEffect(()=>{n.current!==t&&(r.current?.(t),n.current=t);},[t,n]),[t,a,r]}function Gv(e){return typeof e=="function"}var jv=Le.createContext(void 0);function Xo(e){let o=Le.useContext(jv);return e||o||"ltr"}var Vl="rovingFocusGroup.onEntryFocus",_v={bubbles:false,cancelable:true},$r="RovingFocusGroup",[zl,of,$v]=As($r),[Xv,Ul]=Oa($r,[$v]),[Yv,Zv]=Xv($r),rf=Le.forwardRef((e,o)=>jsx(zl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(zl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Jv,{...e,ref:o})})}));rf.displayName=$r;var Jv=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:n=false,dir:r,currentTabStopId:s,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:i,onEntryFocus:c,preventScrollOnEntryFocus:m=false,...l}=e,d=Le.useRef(null),f=Ut(o,d),h=Xo(r),[p,y]=la({prop:s,defaultProp:u??null,onChange:i,caller:$r}),[w,g]=Le.useState(false),x=af(c),I=of(t),L=Le.useRef(false),[P,C]=Le.useState(0);return Le.useEffect(()=>{let b=d.current;if(b)return b.addEventListener(Vl,x),()=>b.removeEventListener(Vl,x)},[x]),jsx(Yv,{scope:t,orientation:a,dir:h,loop:n,currentTabStopId:p,onItemFocus:Le.useCallback(b=>y(b),[y]),onItemShiftTab:Le.useCallback(()=>g(true),[]),onFocusableItemAdd:Le.useCallback(()=>C(b=>b+1),[]),onFocusableItemRemove:Le.useCallback(()=>C(b=>b-1),[]),children:jsx(gt.div,{tabIndex:w||P===0?-1:0,"data-orientation":a,...l,ref:f,style:{outline:"none",...e.style},onMouseDown:ot(e.onMouseDown,()=>{L.current=true;}),onFocus:ot(e.onFocus,b=>{let v=!L.current;if(b.target===b.currentTarget&&v&&!w){let k=new CustomEvent(Vl,_v);if(b.currentTarget.dispatchEvent(k),!k.defaultPrevented){let T=I().filter(H=>H.focusable),F=T.find(H=>H.active),V=T.find(H=>H.id===p),U=[F,V,...T].filter(Boolean).map(H=>H.ref.current);lf(U,m);}}L.current=false;}),onBlur:ot(e.onBlur,()=>g(false))})})}),nf="RovingFocusGroupItem",sf=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:n=false,tabStopId:r,children:s,...u}=e,i=tf(),c=r||i,m=Zv(nf,t),l=m.currentTabStopId===c,d=of(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:p}=m;return Le.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(zl.ItemSlot,{scope:t,id:c,focusable:a,active:n,children:jsx(gt.span,{tabIndex:l?0:-1,"data-orientation":m.orientation,...u,ref:o,onMouseDown:ot(e.onMouseDown,y=>{a?m.onItemFocus(c):y.preventDefault();}),onFocus:ot(e.onFocus,()=>m.onItemFocus(c)),onKeyDown:ot(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){m.onItemShiftTab();return}if(y.target!==y.currentTarget)return;let w=ty(y,m.orientation,m.dir);if(w!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let x=d().filter(I=>I.focusable).map(I=>I.ref.current);if(w==="last")x.reverse();else if(w==="prev"||w==="next"){w==="prev"&&x.reverse();let I=x.indexOf(y.currentTarget);x=m.loop?ay(x,I+1):x.slice(I+1);}setTimeout(()=>lf(x));}}),children:typeof s=="function"?s({isCurrentTabStop:l,hasTabStop:p!=null}):s})})});sf.displayName=nf;var Qv={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ey(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ty(e,o,t){let a=ey(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Qv[a]}function lf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function ay(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var df=rf,uf=sf;var ff="Toggle",Wl=Le.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:n,...r}=e,[s,u]=la({prop:t,onChange:n,defaultProp:a??false,caller:ff});return jsx(gt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:ot(e.onClick,()=>{e.disabled||u(!s);})})});Wl.displayName=ff;var Na="ToggleGroup",[pf]=Oa(Na,[Ul]),hf=Ul(),Kl=Le__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(ny,{...a,ref:o});if(t==="multiple")return jsx(sy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Na}\``)});Kl.displayName=Na;var[gf,xf]=pf(Na),ny=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=la({prop:t,defaultProp:a??"",onChange:n,caller:Na});return jsx(gf,{scope:e.__scopeToggleGroup,type:"single",value:Le__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:u,onItemDeactivate:Le__default.useCallback(()=>u(""),[u]),children:jsx(bf,{...r,ref:o})})}),sy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=la({prop:t,defaultProp:a??[],onChange:n,caller:Na}),i=Le__default.useCallback(m=>u((l=[])=>[...l,m]),[u]),c=Le__default.useCallback(m=>u((l=[])=>l.filter(d=>d!==m)),[u]);return jsx(gf,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:c,children:jsx(bf,{...r,ref:o})})});Kl.displayName=Na;var[iy,ly]=pf(Na),bf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:n=true,orientation:r,dir:s,loop:u=true,...i}=e,c=hf(t),m=Xo(s),l={role:"group",dir:m,...i};return jsx(iy,{scope:t,rovingFocus:n,disabled:a,children:n?jsx(df,{asChild:true,...c,orientation:r,dir:m,loop:u,children:jsx(gt.div,{...l,ref:o})}):jsx(gt.div,{...l,ref:o})})}),Ds="ToggleGroupItem",dy=Le__default.forwardRef((e,o)=>{let t=xf(Ds,e.__scopeToggleGroup),a=ly(Ds,e.__scopeToggleGroup),n=hf(e.__scopeToggleGroup),r=t.value.includes(e.value),s=a.disabled||e.disabled,u={...e,pressed:r,disabled:s},i=Le__default.useRef(null);return a.rovingFocus?jsx(uf,{asChild:true,...n,focusable:!s,active:r,ref:i,children:jsx(mf,{...u,ref:o})}):jsx(mf,{...u,ref:o})});dy.displayName=Ds;var mf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...n}=e,r=xf(Ds,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=r.type==="single"?s:void 0;return jsx(Wl,{...u,...n,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),vf=Kl;function yf(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var n=e.length;for(o=0;o<n;o++)e[o]&&(t=yf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Rs(){for(var e,o,t=0,a="",n=arguments.length;t<n;t++)(e=arguments[t])&&(o=yf(e))&&(a&&(a+=" "),a+=o);return a}var cy=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},fy=(e,o)=>({classGroupId:e,validator:o}),Cf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var wf=[],my="arbitrary..",py=e=>{let o=gy(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return hy(s);let u=s.split("-"),i=u[0]===""&&u.length>1?1:0;return kf(u,i,o)},getConflictingClassGroupIds:(s,u)=>{if(u){let i=a[s],c=t[s];return i?c?cy(c,i):i:c||wf}return t[s]||wf}}},kf=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let n=e[o],r=t.nextPart.get(n);if(r){let c=kf(e,o+1,r);if(c)return c}let s=t.validators;if(s===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),i=s.length;for(let c=0;c<i;c++){let m=s[c];if(m.validator(u))return m.classGroupId}},hy=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?my+a:void 0})(),gy=e=>{let{theme:o,classGroups:t}=e;return xy(t,o)},xy=(e,o)=>{let t=Cf();for(let a in e){let n=e[a];_l(n,t,a,o);}return t},_l=(e,o,t,a)=>{let n=e.length;for(let r=0;r<n;r++){let s=e[r];by(s,o,t,a);}},by=(e,o,t,a)=>{if(typeof e=="string"){vy(e,o,t);return}if(typeof e=="function"){yy(e,o,t,a);return}wy(e,o,t,a);},vy=(e,o,t)=>{let a=e===""?o:Tf(o,e);a.classGroupId=t;},yy=(e,o,t,a)=>{if(Sy(e)){_l(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(fy(t,e));},wy=(e,o,t,a)=>{let n=Object.entries(e),r=n.length;for(let s=0;s<r;s++){let[u,i]=n[s];_l(i,Tf(o,u),t,a);}},Tf=(e,o)=>{let t=e,a=o.split("-"),n=a.length;for(let r=0;r<n;r++){let s=a[r],u=t.nextPart.get(s);u||(u=Cf(),t.nextPart.set(s,u)),t=u;}return t},Sy=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Ly=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),n=(r,s)=>{t[r]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let s=t[r];if(s!==void 0)return s;if((s=a[r])!==void 0)return n(r,s),s},set(r,s){r in t?t[r]=s:n(r,s);}}};var Iy=[],Sf=(e,o,t,a,n)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:n}),Cy=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=n=>{let r=[],s=0,u=0,i=0,c,m=n.length;for(let p=0;p<m;p++){let y=n[p];if(s===0&&u===0){if(y===":"){r.push(n.slice(i,p)),i=p+1;continue}if(y==="/"){c=p;continue}}y==="["?s++:y==="]"?s--:y==="("?u++:y===")"&&u--;}let l=r.length===0?n:n.slice(i),d=l,f=false;l.endsWith("!")?(d=l.slice(0,-1),f=true):l.startsWith("!")&&(d=l.slice(1),f=true);let h=c&&c>i?c-i:void 0;return Sf(r,f,d,h)};if(o){let n=o+":",r=a;a=s=>s.startsWith(n)?r(s.slice(n.length)):Sf(Iy,false,s,void 0,true);}if(t){let n=a;a=r=>t({className:r,parseClassName:n});}return a},ky=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],n=[];for(let r=0;r<t.length;r++){let s=t[r],u=s[0]==="[",i=o.has(s);u||i?(n.length>0&&(n.sort(),a.push(...n),n=[]),a.push(s)):n.push(s);}return n.length>0&&(n.sort(),a.push(...n)),a}},Ty=e=>({cache:Ly(e.cacheSize),parseClassName:Cy(e),sortModifiers:ky(e),...py(e)}),My=/\s+/,Ay=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:n,sortModifiers:r}=o,s=[],u=e.trim().split(My),i="";for(let c=u.length-1;c>=0;c-=1){let m=u[c],{isExternal:l,modifiers:d,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:p}=t(m);if(l){i=m+(i.length>0?" "+i:i);continue}let y=!!p,w=a(y?h.substring(0,p):h);if(!w){if(!y){i=m+(i.length>0?" "+i:i);continue}if(w=a(h),!w){i=m+(i.length>0?" "+i:i);continue}y=false;}let g=d.length===0?"":d.length===1?d[0]:r(d).join(":"),x=f?g+"!":g,I=x+w;if(s.indexOf(I)>-1)continue;s.push(I);let L=n(w,y);for(let P=0;P<L.length;++P){let C=L[P];s.push(x+C);}i=m+(i.length>0?" "+i:i);}return i},Py=(...e)=>{let o=0,t,a,n="";for(;o<e.length;)(t=e[o++])&&(a=Mf(t))&&(n&&(n+=" "),n+=a);return n},Mf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Mf(e[a]))&&(t&&(t+=" "),t+=o);return t},Ey=(e,...o)=>{let t,a,n,r,s=i=>{let c=o.reduce((m,l)=>l(m),e());return t=Ty(c),a=t.cache.get,n=t.cache.set,r=u,u(i)},u=i=>{let c=a(i);if(c)return c;let m=Ay(i,t);return n(i,m),m};return r=s,(...i)=>r(Py(...i))},Dy=[],je=e=>{let o=t=>t[e]||Dy;return o.isThemeGetter=true,o},Af=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Pf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Ry=/^\d+\/\d+$/,Fy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,By=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Oy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Ny=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Hy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Yo=e=>Ry.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ha=e=>!!e&&Number.isInteger(Number(e)),Gl=e=>e.endsWith("%")&&de(e.slice(0,-1)),da=e=>Fy.test(e),qy=()=>true,Vy=e=>By.test(e)&&!Oy.test(e),Ef=()=>false,zy=e=>Ny.test(e),Uy=e=>Hy.test(e),Wy=e=>!X(e)&&!Y(e),Ky=e=>Zo(e,Ff,Ef),X=e=>Af.test(e),fo=e=>Zo(e,Bf,Vy),jl=e=>Zo(e,Xy,de),Lf=e=>Zo(e,Df,Ef),Gy=e=>Zo(e,Rf,Uy),Fs=e=>Zo(e,Of,zy),Y=e=>Pf.test(e),Xr=e=>Jo(e,Bf),jy=e=>Jo(e,Yy),If=e=>Jo(e,Df),_y=e=>Jo(e,Ff),$y=e=>Jo(e,Rf),Bs=e=>Jo(e,Of,true),Zo=(e,o,t)=>{let a=Af.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Jo=(e,o,t=false)=>{let a=Pf.exec(e);return a?a[1]?o(a[1]):t:false},Df=e=>e==="position"||e==="percentage",Rf=e=>e==="image"||e==="url",Ff=e=>e==="length"||e==="size"||e==="bg-size",Bf=e=>e==="length",Xy=e=>e==="number",Yy=e=>e==="family-name",Of=e=>e==="shadow";var Zy=()=>{let e=je("color"),o=je("font"),t=je("text"),a=je("font-weight"),n=je("tracking"),r=je("leading"),s=je("breakpoint"),u=je("container"),i=je("spacing"),c=je("radius"),m=je("shadow"),l=je("inset-shadow"),d=je("text-shadow"),f=je("drop-shadow"),h=je("blur"),p=je("perspective"),y=je("aspect"),w=je("ease"),g=je("animate"),x=()=>["auto","avoid","all","avoid-page","page","left","right","column"],I=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],L=()=>[...I(),Y,X],P=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],b=()=>[Y,X,i],v=()=>[Yo,"full","auto",...b()],k=()=>[Ha,"none","subgrid",Y,X],T=()=>["auto",{span:["full",Ha,Y,X]},Ha,Y,X],F=()=>[Ha,"auto",Y,X],V=()=>["auto","min","max","fr",Y,X],O=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],H=()=>["auto",...b()],K=()=>[Yo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],E=()=>[e,Y,X],W=()=>[...I(),If,Lf,{position:[Y,X]}],te=()=>["no-repeat",{repeat:["","x","y","space","round"]}],G=()=>["auto","cover","contain",_y,Ky,{size:[Y,X]}],z=()=>[Gl,Xr,fo],N=()=>["","none","full",c,Y,X],_=()=>["",de,Xr,fo],Z=()=>["solid","dashed","dotted","double"],ae=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Q=()=>[de,Gl,If,Lf],pe=()=>["","none",h,Y,X],ue=()=>["none",de,Y,X],le=()=>["none",de,Y,X],he=()=>[de,Y,X],ce=()=>[Yo,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[da],breakpoint:[da],color:[qy],container:[da],"drop-shadow":[da],ease:["in","out","in-out"],font:[Wy],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[da],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[da],shadow:[da],spacing:["px",de],text:[da],"text-shadow":[da],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Yo,X,Y,y]}],container:["container"],columns:[{columns:[de,X,Y,u]}],"break-after":[{"break-after":x()}],"break-before":[{"break-before":x()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:L()}],overflow:[{overflow:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:v()}],"inset-x":[{"inset-x":v()}],"inset-y":[{"inset-y":v()}],start:[{start:v()}],end:[{end:v()}],top:[{top:v()}],right:[{right:v()}],bottom:[{bottom:v()}],left:[{left:v()}],visibility:["visible","invisible","collapse"],z:[{z:[Ha,"auto",Y,X]}],basis:[{basis:[Yo,"full","auto",u,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Yo,"auto","initial","none",X]}],grow:[{grow:["",de,Y,X]}],shrink:[{shrink:["",de,Y,X]}],order:[{order:[Ha,"first","last","none",Y,X]}],"grid-cols":[{"grid-cols":k()}],"col-start-end":[{col:T()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":k()}],"row-start-end":[{row:T()}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":V()}],"auto-rows":[{"auto-rows":V()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...O(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...O()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":O()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:H()}],mx:[{mx:H()}],my:[{my:H()}],ms:[{ms:H()}],me:[{me:H()}],mt:[{mt:H()}],mr:[{mr:H()}],mb:[{mb:H()}],ml:[{ml:H()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:K()}],w:[{w:[u,"screen",...K()]}],"min-w":[{"min-w":[u,"screen","none",...K()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[s]},...K()]}],h:[{h:["screen","lh",...K()]}],"min-h":[{"min-h":["screen","lh","none",...K()]}],"max-h":[{"max-h":["screen","lh",...K()]}],"font-size":[{text:["base",t,Xr,fo]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,Y,jl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Gl,X]}],"font-family":[{font:[jy,X,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[n,Y,X]}],"line-clamp":[{"line-clamp":[de,"none",Y,jl]}],leading:[{leading:[r,...b()]}],"list-image":[{"list-image":["none",Y,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Y,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:E()}],"text-color":[{text:E()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Z(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",Y,fo]}],"text-decoration-color":[{decoration:E()}],"underline-offset":[{"underline-offset":[de,"auto",Y,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Y,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Y,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:W()}],"bg-repeat":[{bg:te()}],"bg-size":[{bg:G()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ha,Y,X],radial:["",Y,X],conic:[Ha,Y,X]},$y,Gy]}],"bg-color":[{bg:E()}],"gradient-from-pos":[{from:z()}],"gradient-via-pos":[{via:z()}],"gradient-to-pos":[{to:z()}],"gradient-from":[{from:E()}],"gradient-via":[{via:E()}],"gradient-to":[{to:E()}],rounded:[{rounded:N()}],"rounded-s":[{"rounded-s":N()}],"rounded-e":[{"rounded-e":N()}],"rounded-t":[{"rounded-t":N()}],"rounded-r":[{"rounded-r":N()}],"rounded-b":[{"rounded-b":N()}],"rounded-l":[{"rounded-l":N()}],"rounded-ss":[{"rounded-ss":N()}],"rounded-se":[{"rounded-se":N()}],"rounded-ee":[{"rounded-ee":N()}],"rounded-es":[{"rounded-es":N()}],"rounded-tl":[{"rounded-tl":N()}],"rounded-tr":[{"rounded-tr":N()}],"rounded-br":[{"rounded-br":N()}],"rounded-bl":[{"rounded-bl":N()}],"border-w":[{border:_()}],"border-w-x":[{"border-x":_()}],"border-w-y":[{"border-y":_()}],"border-w-s":[{"border-s":_()}],"border-w-e":[{"border-e":_()}],"border-w-t":[{"border-t":_()}],"border-w-r":[{"border-r":_()}],"border-w-b":[{"border-b":_()}],"border-w-l":[{"border-l":_()}],"divide-x":[{"divide-x":_()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":_()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Z(),"hidden","none"]}],"divide-style":[{divide:[...Z(),"hidden","none"]}],"border-color":[{border:E()}],"border-color-x":[{"border-x":E()}],"border-color-y":[{"border-y":E()}],"border-color-s":[{"border-s":E()}],"border-color-e":[{"border-e":E()}],"border-color-t":[{"border-t":E()}],"border-color-r":[{"border-r":E()}],"border-color-b":[{"border-b":E()}],"border-color-l":[{"border-l":E()}],"divide-color":[{divide:E()}],"outline-style":[{outline:[...Z(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,Y,X]}],"outline-w":[{outline:["",de,Xr,fo]}],"outline-color":[{outline:E()}],shadow:[{shadow:["","none",m,Bs,Fs]}],"shadow-color":[{shadow:E()}],"inset-shadow":[{"inset-shadow":["none",l,Bs,Fs]}],"inset-shadow-color":[{"inset-shadow":E()}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:E()}],"ring-offset-w":[{"ring-offset":[de,fo]}],"ring-offset-color":[{"ring-offset":E()}],"inset-ring-w":[{"inset-ring":_()}],"inset-ring-color":[{"inset-ring":E()}],"text-shadow":[{"text-shadow":["none",d,Bs,Fs]}],"text-shadow-color":[{"text-shadow":E()}],opacity:[{opacity:[de,Y,X]}],"mix-blend":[{"mix-blend":[...ae(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ae()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":Q()}],"mask-image-linear-to-pos":[{"mask-linear-to":Q()}],"mask-image-linear-from-color":[{"mask-linear-from":E()}],"mask-image-linear-to-color":[{"mask-linear-to":E()}],"mask-image-t-from-pos":[{"mask-t-from":Q()}],"mask-image-t-to-pos":[{"mask-t-to":Q()}],"mask-image-t-from-color":[{"mask-t-from":E()}],"mask-image-t-to-color":[{"mask-t-to":E()}],"mask-image-r-from-pos":[{"mask-r-from":Q()}],"mask-image-r-to-pos":[{"mask-r-to":Q()}],"mask-image-r-from-color":[{"mask-r-from":E()}],"mask-image-r-to-color":[{"mask-r-to":E()}],"mask-image-b-from-pos":[{"mask-b-from":Q()}],"mask-image-b-to-pos":[{"mask-b-to":Q()}],"mask-image-b-from-color":[{"mask-b-from":E()}],"mask-image-b-to-color":[{"mask-b-to":E()}],"mask-image-l-from-pos":[{"mask-l-from":Q()}],"mask-image-l-to-pos":[{"mask-l-to":Q()}],"mask-image-l-from-color":[{"mask-l-from":E()}],"mask-image-l-to-color":[{"mask-l-to":E()}],"mask-image-x-from-pos":[{"mask-x-from":Q()}],"mask-image-x-to-pos":[{"mask-x-to":Q()}],"mask-image-x-from-color":[{"mask-x-from":E()}],"mask-image-x-to-color":[{"mask-x-to":E()}],"mask-image-y-from-pos":[{"mask-y-from":Q()}],"mask-image-y-to-pos":[{"mask-y-to":Q()}],"mask-image-y-from-color":[{"mask-y-from":E()}],"mask-image-y-to-color":[{"mask-y-to":E()}],"mask-image-radial":[{"mask-radial":[Y,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":Q()}],"mask-image-radial-to-pos":[{"mask-radial-to":Q()}],"mask-image-radial-from-color":[{"mask-radial-from":E()}],"mask-image-radial-to-color":[{"mask-radial-to":E()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":I()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":Q()}],"mask-image-conic-to-pos":[{"mask-conic-to":Q()}],"mask-image-conic-from-color":[{"mask-conic-from":E()}],"mask-image-conic-to-color":[{"mask-conic-to":E()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:W()}],"mask-repeat":[{mask:te()}],"mask-size":[{mask:G()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Y,X]}],filter:[{filter:["","none",Y,X]}],blur:[{blur:pe()}],brightness:[{brightness:[de,Y,X]}],contrast:[{contrast:[de,Y,X]}],"drop-shadow":[{"drop-shadow":["","none",f,Bs,Fs]}],"drop-shadow-color":[{"drop-shadow":E()}],grayscale:[{grayscale:["",de,Y,X]}],"hue-rotate":[{"hue-rotate":[de,Y,X]}],invert:[{invert:["",de,Y,X]}],saturate:[{saturate:[de,Y,X]}],sepia:[{sepia:["",de,Y,X]}],"backdrop-filter":[{"backdrop-filter":["","none",Y,X]}],"backdrop-blur":[{"backdrop-blur":pe()}],"backdrop-brightness":[{"backdrop-brightness":[de,Y,X]}],"backdrop-contrast":[{"backdrop-contrast":[de,Y,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,Y,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,Y,X]}],"backdrop-invert":[{"backdrop-invert":["",de,Y,X]}],"backdrop-opacity":[{"backdrop-opacity":[de,Y,X]}],"backdrop-saturate":[{"backdrop-saturate":[de,Y,X]}],"backdrop-sepia":[{"backdrop-sepia":["",de,Y,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Y,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",Y,X]}],ease:[{ease:["linear","initial",w,Y,X]}],delay:[{delay:[de,Y,X]}],animate:[{animate:["none",g,Y,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,Y,X]}],"perspective-origin":[{"perspective-origin":L()}],rotate:[{rotate:ue()}],"rotate-x":[{"rotate-x":ue()}],"rotate-y":[{"rotate-y":ue()}],"rotate-z":[{"rotate-z":ue()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":["scale-3d"],skew:[{skew:he()}],"skew-x":[{"skew-x":he()}],"skew-y":[{"skew-y":he()}],transform:[{transform:[Y,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:L()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ce()}],"translate-x":[{"translate-x":ce()}],"translate-y":[{"translate-y":ce()}],"translate-z":[{"translate-z":ce()}],"translate-none":["translate-none"],accent:[{accent:E()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:E()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Y,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Y,X]}],fill:[{fill:["none",...E()]}],"stroke-w":[{stroke:[de,Xr,fo,jl]}],stroke:[{stroke:["none",...E()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var Nf=Ey(Zy);function qa(...e){return Nf(Rs(e))}var Qy=Le.createContext({size:"default",variant:"default",spacing:0});function Va({className:e,variant:o,size:t,spacing:a=1,children:n,...r}){return jsx(vf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:qa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Qy.Provider,{value:{variant:o,size:t,spacing:a},children:n})})}var tw={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Uf=createSlice({name:"toolbar",initialState:tw,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:ta,setPenColor:ua,setStrokeWidth:Yr,setFontSize:qD,setFontFamily:VD,setFontStyle:zD,setFontWeight:UD,setTextDecoration:WD,setTextColor:KD}=Uf.actions,Xl=Uf.reducer;var Os=({onClose:e,onRecordingComplete:o})=>{let t=Ve(),[a,n]=useState(false),[r,s]=useState(null),[u,i]=useState(0),[c,m]=useState(null),[l,d]=useState(false),f=useRef(null),h=useRef([]),p=useRef(null),y=useRef(null),w=useRef(null);useEffect(()=>((async()=>{try{let v=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(v),d(!0),w.current&&(w.current.srcObject=v);}catch(v){console.error("Error accessing camera:",v),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),c&&c.getTracks().forEach(v=>v.stop());}),[]);let g=()=>{c&&(c.getTracks().forEach(b=>b.stop()),m(null),d(false));},x=async()=>{try{let b=null,v=null;try{b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(O){console.error("Error accessing camera for recording:",O),alert("Failed to access camera for recording.");return}try{v=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(O){console.warn("Microphone access denied:",O);}let k=[...b.getVideoTracks()];v&&k.push(...v.getAudioTracks());let T=new MediaStream(k),F="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?F="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?F="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?F="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(F="video/webm;codecs=vp8");let V=new MediaRecorder(T,{mimeType:F,videoBitsPerSecond:25e5});f.current=V,h.current=[],V.ondataavailable=O=>{O.data.size>0&&h.current.push(O.data);},V.onstop=()=>{let O=new Blob(h.current,{type:F}),U=document.createElement("video");U.src=URL.createObjectURL(O),U.muted=!0,U.currentTime=.1,U.onseeked=()=>{let H=document.createElement("canvas");H.width=U.videoWidth,H.height=U.videoHeight;let K=H.getContext("2d");K&&(K.drawImage(U,0,0),y.current=H.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(U.src);},T.getTracks().forEach(H=>H.stop()),b&&b.getTracks().forEach(H=>H.stop()),v&&v.getTracks().forEach(H=>H.stop()),p.current&&clearInterval(p.current),s(O),g();},V.onerror=O=>{console.error("MediaRecorder error:",O);},V.start(1e3),n(!0),i(0),p.current=setInterval(()=>{i(O=>O+1);},1e3);}catch(b){console.error("Error starting camera recording:",b),alert("Failed to start recording. Please check permissions.");}},I=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),n(false));},L=()=>{if(r){let b=URL.createObjectURL(r),v=document.createElement("a");v.href=b,v.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(v),v.click(),document.body.removeChild(v),URL.revokeObjectURL(b);}},P=b=>{let v=Math.floor(b/60),k=b%60;return `${v.toString().padStart(2,"0")}:${k.toString().padStart(2,"0")}`};if(!t)return null;let C=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:b=>{b.target===b.currentTarget&&e(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:b=>b.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:w,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:x,disabled:!l,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!l&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:I,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:P(u)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",P(u)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{s(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:L,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&y.current&&(o(r,y.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(C,t)};var ca=40,Kf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,n]=useState(t?.images||[]),[r,s]=useState(t?.order||"sequential"),[u,i]=useState(false),c=useRef(null),m=Ve(),l=useRef(null);useEffect(()=>{let x=I=>{I.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let d=x=>{let I=x.target.files;if(!I||I.length===0)return;let L=ca-a.length;if(L<=0){alert(`You can only upload a maximum of ${ca} images`);return}let P=Array.from(I).slice(0,L);P.length<I.length&&alert(`Only ${L} more images can be added (max ${ca} total)`);let C=P.map(b=>new Promise((v,k)=>{let T=new FileReader;T.onload=F=>{F.target?.result?v(F.target.result):k(new Error("Failed to read file"));},T.onerror=k,T.readAsDataURL(b);}));Promise.all(C).then(b=>{n(v=>[...v,...b]),l.current&&(l.current.value="");});},f=x=>{x.preventDefault(),i(false);let I=Array.from(x.dataTransfer.files).filter(b=>b.type.startsWith("image/"));if(I.length===0)return;let L=ca-a.length;if(L<=0){alert(`You can only upload a maximum of ${ca} images`);return}let P=I.slice(0,L);P.length<I.length&&alert(`Only ${L} more images can be added (max ${ca} total)`);let C=P.map(b=>new Promise((v,k)=>{let T=new FileReader;T.onload=F=>{F.target?.result?v(F.target.result):k(new Error("Failed to read file"));},T.onerror=k,T.readAsDataURL(b);}));Promise.all(C).then(b=>{n(v=>[...v,...b]);});},h=x=>{x.preventDefault(),i(true);},p=()=>{i(false);},y=x=>{n(I=>I.filter((L,P)=>P!==x));},w=x=>{if(x.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!m)return null;let g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:w,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=ca?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ca," images"]}):jsxs("span",{children:[a.length,"/",ca," images"]})})]}),jsx("input",{ref:l,type:"file",accept:"image/*",multiple:true,onChange:d,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:f,onDragOver:h,onDragLeave:p,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>s("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>s("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((x,I)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${I+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>y(I),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:I+1})]},I))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(g,m)};var Ns={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},xw={enabled:true};function Jl(e){return e?{tools:{...Ns.tools,...e.tools},actions:{...Ns.actions,...e.actions}}:Ns}var bw={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},vw={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};function Ql(e,[o,t]){return Math.min(t,Math.max(o,e))}function Gf(e){let o=Le.useRef({value:e,previous:e});return Le.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function _f(e){let[o,t]=Le.useState(void 0);return _o(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(n=>{if(!Array.isArray(n)||!n.length)return;let r=n[0],s,u;if("borderBoxSize"in r){let i=r.borderBoxSize,c=Array.isArray(i)?i[0]:i;s=c.inlineSize,u=c.blockSize;}else s=e.offsetWidth,u=e.offsetHeight;t({width:s,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var $f=["PageUp","PageDown"],Xf=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Yf={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Qo="Slider",[ed,ww,Sw]=As(Qo),[Zf]=Oa(Qo,[Sw]),[Lw,qs]=Zf(Qo),Jf=Le.forwardRef((e,o)=>{let{name:t,min:a=0,max:n=100,step:r=1,orientation:s="horizontal",disabled:u=false,minStepsBetweenThumbs:i=0,defaultValue:c=[a],value:m,onValueChange:l=()=>{},onValueCommit:d=()=>{},inverted:f=false,form:h,...p}=e,y=Le.useRef(new Set),w=Le.useRef(0),x=s==="horizontal"?Iw:Cw,[I=[],L]=la({prop:m,defaultProp:c,onChange:T=>{[...y.current][w.current]?.focus(),l(T);}}),P=Le.useRef(I);function C(T){let F=Pw(I,T);k(T,F);}function b(T){k(T,w.current);}function v(){let T=P.current[w.current];I[w.current]!==T&&d(I);}function k(T,F,{commit:V}={commit:false}){let O=Fw(r),U=Bw(Math.round((T-a)/r)*r+a,O),H=Ql(U,[a,n]);L((K=[])=>{let E=Mw(K,H,F);if(Rw(E,i*r)){w.current=E.indexOf(H);let W=String(E)!==String(K);return W&&V&&d(E),W?E:K}else return K});}return jsx(Lw,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:n,valueIndexToChangeRef:w,thumbs:y.current,values:I,orientation:s,form:h,children:jsx(ed.Provider,{scope:e.__scopeSlider,children:jsx(ed.Slot,{scope:e.__scopeSlider,children:jsx(x,{"aria-disabled":u,"data-disabled":u?"":void 0,...p,ref:o,onPointerDown:ot(p.onPointerDown,()=>{u||(P.current=I);}),min:a,max:n,inverted:f,onSlideStart:u?void 0:C,onSlideMove:u?void 0:b,onSlideEnd:u?void 0:v,onHomeKeyDown:()=>!u&&k(a,0,{commit:true}),onEndKeyDown:()=>!u&&k(n,I.length-1,{commit:true}),onStepKeyDown:({event:T,direction:F})=>{if(!u){let U=$f.includes(T.key)||T.shiftKey&&Xf.includes(T.key)?10:1,H=w.current,K=I[H],E=r*U*F;k(K+E,H,{commit:true});}}})})})})});Jf.displayName=Qo;var[Qf,em]=Zf(Qo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Iw=Le.forwardRef((e,o)=>{let{min:t,max:a,dir:n,inverted:r,onSlideStart:s,onSlideMove:u,onSlideEnd:i,onStepKeyDown:c,...m}=e,[l,d]=Le.useState(null),f=Ut(o,x=>d(x)),h=Le.useRef(void 0),p=Xo(n),y=p==="ltr",w=y&&!r||!y&&r;function g(x){let I=h.current||l.getBoundingClientRect(),L=[0,I.width],C=od(L,w?[t,a]:[a,t]);return h.current=I,C(x-I.left)}return jsx(Qf,{scope:e.__scopeSlider,startEdge:w?"left":"right",endEdge:w?"right":"left",direction:w?1:-1,size:"width",children:jsx(tm,{dir:p,"data-orientation":"horizontal",...m,ref:f,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:x=>{let I=g(x.clientX);s?.(I);},onSlideMove:x=>{let I=g(x.clientX);u?.(I);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:x=>{let L=Yf[w?"from-left":"from-right"].includes(x.key);c?.({event:x,direction:L?-1:1});}})})}),Cw=Le.forwardRef((e,o)=>{let{min:t,max:a,inverted:n,onSlideStart:r,onSlideMove:s,onSlideEnd:u,onStepKeyDown:i,...c}=e,m=Le.useRef(null),l=Ut(o,m),d=Le.useRef(void 0),f=!n;function h(p){let y=d.current||m.current.getBoundingClientRect(),w=[0,y.height],x=od(w,f?[a,t]:[t,a]);return d.current=y,x(p-y.top)}return jsx(Qf,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(tm,{"data-orientation":"vertical",...c,ref:l,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:p=>{let y=h(p.clientY);r?.(y);},onSlideMove:p=>{let y=h(p.clientY);s?.(y);},onSlideEnd:()=>{d.current=void 0,u?.();},onStepKeyDown:p=>{let w=Yf[f?"from-bottom":"from-top"].includes(p.key);i?.({event:p,direction:w?-1:1});}})})}),tm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:n,onSlideEnd:r,onHomeKeyDown:s,onEndKeyDown:u,onStepKeyDown:i,...c}=e,m=qs(Qo,t);return jsx(gt.span,{...c,ref:o,onKeyDown:ot(e.onKeyDown,l=>{l.key==="Home"?(s(l),l.preventDefault()):l.key==="End"?(u(l),l.preventDefault()):$f.concat(Xf).includes(l.key)&&(i(l),l.preventDefault());}),onPointerDown:ot(e.onPointerDown,l=>{let d=l.target;d.setPointerCapture(l.pointerId),l.preventDefault(),m.thumbs.has(d)?d.focus():a(l);}),onPointerMove:ot(e.onPointerMove,l=>{l.target.hasPointerCapture(l.pointerId)&&n(l);}),onPointerUp:ot(e.onPointerUp,l=>{let d=l.target;d.hasPointerCapture(l.pointerId)&&(d.releasePointerCapture(l.pointerId),r(l));})})}),am="SliderTrack",om=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=qs(am,t);return jsx(gt.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...a,ref:o})});om.displayName=am;var td="SliderRange",rm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=qs(td,t),r=em(td,t),s=Le.useRef(null),u=Ut(o,s),i=n.values.length,c=n.values.map(d=>im(d,n.min,n.max)),m=i>1?Math.min(...c):0,l=100-Math.max(...c);return jsx(gt.span,{"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,...a,ref:u,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:l+"%"}})});rm.displayName=td;var ad="SliderThumb",nm=Le.forwardRef((e,o)=>{let t=ww(e.__scopeSlider),[a,n]=Le.useState(null),r=Ut(o,u=>n(u)),s=Le.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(kw,{...e,ref:r,index:s})}),kw=Le.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:n,...r}=e,s=qs(ad,t),u=em(ad,t),[i,c]=Le.useState(null),m=Ut(o,g=>c(g)),l=i?s.form||!!i.closest("form"):true,d=_f(i),f=s.values[a],h=f===void 0?0:im(f,s.min,s.max),p=Aw(a,s.values.length),y=d?.[u.size],w=y?Ew(y,h,u.direction):0;return Le.useEffect(()=>{if(i)return s.thumbs.add(i),()=>{s.thumbs.delete(i);}},[i,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${w}px)`},children:[jsx(ed.ItemSlot,{scope:e.__scopeSlider,children:jsx(gt.span,{role:"slider","aria-label":e["aria-label"]||p,"aria-valuemin":s.min,"aria-valuenow":f,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...r,ref:m,style:f===void 0?{display:"none"}:e.style,onFocus:ot(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),l&&jsx(sm,{name:n??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:f},a)]})});nm.displayName=ad;var Tw="RadioBubbleInput",sm=Le.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let n=Le.useRef(null),r=Ut(n,a),s=Gf(o);return Le.useEffect(()=>{let u=n.current;if(!u)return;let i=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==o&&m){let l=new Event("input",{bubbles:true});m.call(u,o),u.dispatchEvent(l);}},[s,o]),jsx(gt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});sm.displayName=Tw;function Mw(e=[],o,t){let a=[...e];return a[t]=o,a.sort((n,r)=>n-r)}function im(e,o,t){let r=100/(t-o)*(e-o);return Ql(r,[0,100])}function Aw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Pw(e,o){if(e.length===1)return 0;let t=e.map(n=>Math.abs(n-o)),a=Math.min(...t);return t.indexOf(a)}function Ew(e,o,t){let a=e/2,r=od([0,50],[0,a]);return (a-r(o)*t)*t}function Dw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Rw(e,o){if(o>0){let t=Dw(e);return Math.min(...t)>=o}return true}function od(e,o){return t=>{if(e[0]===e[1]||o[0]===o[1])return o[0];let a=(o[1]-o[0])/(e[1]-e[0]);return o[0]+a*(t-e[0])}}function Fw(e){return (String(e).split(".")[1]||"").length}function Bw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var lm=Jf,dm=om,um=rm,cm=nm;function Vs({className:e,defaultValue:o,value:t,min:a=0,max:n=100,rangeClassName:r,trackClassName:s,thumbClassName:u,...i}){let c=Le.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,n],[t,o,a,n]);return jsxs(lm,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:n,className:qa("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[jsx(dm,{"data-slot":"slider-track",className:qa("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",s),children:jsx(um,{"data-slot":"slider-range",className:qa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(m,l)=>jsx(cm,{"data-slot":"slider-thumb",className:qa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",u)},l))]})}var dS=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a,onVisibilityChange:n}={})=>{let r=Se(),s=J(A=>A.canvas.slides.find(re=>re.id===A.canvas.currentSlideId)),u=s?.videos||[],i=s?.editingFlashcard,c=J(A=>A.toolbar.selectedTool),m=J(A=>A.toolbar.penColor),l=J(A=>A.toolbar.strokeWidth),d=J(A=>A.canvas.editingOverlayPosition),f=s?.showMcqForm,h=s?.showFlashcardForm,p=useRef(null);useEffect(()=>{let A=re=>{(re.ctrlKey||re.metaKey)&&re.key==="z"&&!re.shiftKey&&(re.preventDefault(),r(Io())),(re.ctrlKey&&re.shiftKey&&re.key==="Z"||re.ctrlKey&&re.key==="y")&&(re.preventDefault(),r(Co()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[r]);let y=useMemo(()=>Jl(a),[a]),{tools:w,actions:g}=y,x=u.some(A=>A.isRecorded&&A.isPlaying),I=J(A=>A.toolbar.fontSize),L=J(A=>A.toolbar.fontFamily),P=J(A=>A.toolbar.fontStyle),C=J(A=>A.toolbar.fontWeight),b=J(A=>A.toolbar.textDecoration),v=J(A=>A.toolbar.textColor),[k,T]=useState(false),[F,V]=useState(false),[O,U]=useState(false),[H,K]=useState(false),[E,W]=useState(false),[te,G]=useState(false),[z,N]=useState(false),[_,Z]=useState(false),[ae,Q]=useState(true),pe=useRef(null),ue=useRef(null),le=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],he=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"style",icon:Palette,label:"Style",configKey:"style"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),ce=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),_e=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),or=useMemo(()=>he.filter(A=>{let re=w[A.configKey];return typeof re=="boolean"?re:Array.isArray(re)?re.length>0:true}),[w,he]),ga=useMemo(()=>{let A=w.shapes;return A===false?[]:A===true?ce:Array.isArray(A)?ce.filter(re=>A.includes(re.name)):ce},[w.shapes,ce]),on=useMemo(()=>{let A=w.activities;return A===false?[]:A===true?_e:Array.isArray(A)?_e.filter(re=>A.includes(re.name)):_e},[w.activities,_e]),ne=useMemo(()=>{let A=w.media;return A===false?{photoFrame:false,image:false,video:false}:A===true?{photoFrame:true,image:true,video:true}:Array.isArray(A)?{photoFrame:A.includes("photo-frame"),image:A.includes("image"),video:A.includes("video")}:{photoFrame:true,image:true,video:true}},[w.media]),rn=useMemo(()=>{let A=w.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[w.activities]),nn=A=>{let re=A.target.files;!re||re.length===0||(r(ta("select")),r(wt(false)),K(false),Array.from(re).forEach(Ae=>{let we=new FileReader;we.onload=ie=>{let ge=new window.Image;ge.src=ie.target?.result,ge.onload=()=>{let He=ge.width/ge.height,lt=300,Et=300,bt=ge.width,Fe=ge.height;bt>lt&&(bt=lt,Fe=bt/He),Fe>Et&&(Fe=Et,bt=Fe*He),r(fe());let ze=d?.left||800-bt/2,oa=d?.top||450-Fe/2;r(di({id:v4(),src:ge.src,x:ze,y:oa,width:bt,height:Fe,draggable:true,rotation:0}));};},we.readAsDataURL(Ae);}),A.target.value="");},sn=async A=>{let re=A.target.files;if(!(!re||re.length===0)){console.log("files",A),r(ta("select")),r(wt(false)),K(false);for(let Ae of Array.from(re))try{let we=URL.createObjectURL(Ae),ie=document.createElement("video");console.log("video",ie),ie.src=we,ie.muted=!0,ie.playsInline=!0,ie.preload="auto",ie.load(),await new Promise((dt,se)=>{let vt=setTimeout(()=>se(new Error("Metadata load timeout")),1e4);ie.onloadedmetadata=()=>{clearTimeout(vt),dt();},ie.onerror=()=>{clearTimeout(vt),se(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ie.duration,width:ie.videoWidth,height:ie.videoHeight}),await new Promise((dt,se)=>{let vt=setTimeout(()=>se(new Error("Video load timeout")),1e4);ie.readyState>=2?(clearTimeout(vt),dt()):ie.onloadeddata=()=>{clearTimeout(vt),dt();};});let ge=Math.min(.8,ie.duration/2);console.log("Seeking to:",ge),ie.currentTime=ge,await new Promise(dt=>{let se=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),dt();},5e3);ie.onseeked=()=>{clearTimeout(se),console.log("Seek completed"),dt();};});let He=document.createElement("canvas"),lt=ie.videoWidth/ie.videoHeight,Et=400,bt=400,Fe=ie.videoWidth,ze=ie.videoHeight;Fe>Et&&(Fe=Et,ze=Fe/lt),ze>bt&&(ze=bt,Fe=ze*lt),He.width=Fe,He.height=ze;let oa=He.getContext("2d",{willReadFrequently:!1});if(!oa)throw new Error("Failed to get canvas context");if(await new Promise(dt=>setTimeout(dt,100)),ie.videoWidth===0||ie.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Fe,height:ze}),oa.drawImage(ie,0,0,Fe,ze);let ba=He.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",ba.length),r(fe());let Qs=800-Fe/2,ei=450-ze/2,pn=v4();await sa(pn,Ae,ba),r(wo({id:pn,objectUrl:we,thumbnailDataUrl:ba,videoBlob:Ae,x:Qs,y:ei,width:Fe,height:ze,draggable:!0,isPlaying:!1,rotation:0})),ie.src="",ie.load(),console.log(`Video uploaded: ${Ae.name}`);}catch(we){console.error("Error processing video:",we),alert(`Failed to process video: ${Ae.name}`);}A.target.value="";}},ln=(A,re,Ae)=>{r(fe()),r(ta("select")),r(wt(false));let we=300,ie=300,ge=800-we/2,He=450-ie/2;r(Ae?Lo({id:Ae,images:A,order:re,x:ge,y:He,width:we,height:ie,rotation:0,draggable:true}):fi({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:re,x:ge,y:He,width:we,height:ie,rotation:0,draggable:true})),r(Xa(false));},dn=()=>{r(fe()),r(ta("select")),r(wt(false));let A=400,re=300,Ae=800-A/2,we=450-re/2;r(hi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ae,y:we,width:A,height:re,rotation:0,draggable:true,isCapturing:false})),K(false);},un=A=>{let ge={};switch(A.name){case "circle":case "ring":case "wedge":case "arc":ge.radius=50,(A.name==="ring"||A.name==="arc")&&(ge.innerRadius=25,ge.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(ge.angle=A.name==="wedge"?60:90);break;case "ellipse":ge.radiusX=60,ge.radiusY=40;break;case "triangle":ge.radius=50,ge.sides=3;break;case "polygon":ge.radius=50,ge.sides=6;break;case "star":ge.innerRadius=25,ge.outerRadius=50,ge.numPoints=5;break;case "arrow":case "line":ge.points=[0,0,100,0],A.name==="arrow"&&(ge.pointerLength=10,ge.pointerWidth=10);break}let He={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:m,...ge};r(fe()),r(wt(false)),r(ta(A.name)),r(ui(He)),U(false);},Wa=A=>{if(r(ta(A)),A==="select")r(wt(false));else if(A==="text"){r(wt(false)),r(fe());let re=200,Ae=50,we=800-re/2,ie=450-Ae/2,He=window.innerWidth<768?Math.max(I,32):I,lt=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(ci({id:lt,text:"",x:we,y:ie,width:re,height:Ae,rotation:0,draggable:true,fontSize:He,fontFamily:L,fontStyle:P,fontWeight:C,textDecoration:b,fill:v,align:"left"})),setTimeout(()=>{r(gr(lt));},100),t&&t(lt);}else r(wt(true));},_s=()=>{r(hr()),r(wt(false));},$s=()=>{e?e():o?T(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Xs=()=>{V(true);},Ys=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:dn,enabled:ne.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>pe.current?.click(),enabled:ne.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>ue.current?.click(),enabled:ne.video}],xa=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Io()),enabled:g.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(Co()),enabled:g.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:$s,enabled:g.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:Xs,enabled:g.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:_s,enabled:g.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],cn=async(A,re)=>{try{r(ta("select")),r(wt(!1));let Ae=URL.createObjectURL(A),we=document.createElement("video");we.src=Ae,we.muted=!0,we.playsInline=!0,we.preload="auto",await new Promise((ze,oa)=>{let ba=setTimeout(()=>oa(new Error("Metadata load timeout")),1e4);we.onloadedmetadata=()=>{clearTimeout(ba),ze();},we.onerror=()=>{clearTimeout(ba),oa(new Error("Failed to load video"));};});let ie=640,ge=we.videoWidth/we.videoHeight,He=ie,lt=He/ge;r(fe());let Et=800-He/2,bt=450-lt/2,Fe=v4();await sa(Fe,A,re),r(wo({id:Fe,objectUrl:Ae,thumbnailDataUrl:re,videoBlob:A,x:Et,y:bt,width:He,height:lt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),T(!1),V(!1);}catch(Ae){console.error("Error adding recorded video to canvas:",Ae),alert("Failed to add video to canvas. Please try again.");}},Zs=A=>{r(ta("select")),r(wt(false)),r(mr(null)),A&&r(ki(A)),r(wa(!f)),W(false);},go=()=>{r(fr(null)),r(Xa(true)),W(false);},fn=()=>{U(!O);},Js=()=>{K(!H);},rr=()=>{W(!E);},xo=()=>{G(!te);},mn=()=>{let A=!ae;A||(U(false),K(false),W(false),G(false),Z(false),N(false)),Q(A),n?.(A);};return useEffect(()=>{if(!_)return;let A=re=>{p.current&&!p.current.contains(re.target)&&Z(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[_]),x?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:mn,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:ae?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),ae&&jsxs("div",{className:"fixed top-[168px] left-4 z-50 flex flex-col gap-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(Va,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:or.map((A,re)=>jsx("div",{title:A.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.name===c?"bg-primary/10":A.name==="style"?"md:hidden":""}`,onClick:()=>{A.name==="image"?(Js(),U(false),W(false),G(false),Wa(A.name)):A.name==="shapes"?(fn(),K(false),W(false),G(false),Wa(A.name)):A.name==="activities"?(Wa(A.name),rr(),U(false),K(false),G(false)):A.name==="style"?(xo(),U(false),K(false),W(false),Wa(A.name)):(Wa(A.name),U(false),K(false),W(false),G(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},re))}),O&&jsx(Va,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:ga.map((A,re)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>un(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},re))}),H&&jsx(Va,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:Ys.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),E&&jsxs(Va,{type:"single",className:"mx-1 mt-auto mb-10 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl lg:mb-11",children:[rn&&jsx("div",{title:"Flashcard",onClick:()=>go(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),on.map((A,re)=>jsx("div",{title:A.label,onClick:()=>Zs(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},re))]}),te&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Vs,{value:[l],onValueChange:A=>{r(Yr(A[0]));},max:28,min:6,step:1,className:"w-28",rangeClassName:"bg-gray-300",thumbClassName:"bg-gray-600 border-none h-4 w-4"}),jsx("div",{className:"h-5 w-5 rounded-full bg-gray-800"})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"COLOR"}),jsxs("div",{className:"flex flex-wrap gap-1",children:[le.map(A=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${m===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{r(ua(A.value)),G(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:m,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>r(ua(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:m,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{r(cr(A.target.value)),G(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),xa.some(A=>A.enabled)&&jsx(Va,{type:"single",className:"hidden flex-col border bg-white p-1 shadow-xl md:flex",children:xa.filter(A=>A.enabled).map(A=>jsx("button",{onClick:A.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.colorClass}`,title:A.title,children:jsx(A.icon,{weight:A.iconWeight,className:"text-lg md:text-xl"})},A.key))})]}),jsx("input",{ref:pe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:nn}),jsx("input",{ref:ue,type:"file",accept:"video/*",className:"hidden",onChange:sn}),!e&&k&&o&&jsx(Ya,{onClose:()=>T(false),stageRef:o,onRecordingComplete:cn}),F&&jsx(Os,{onClose:()=>V(false),onRecordingComplete:cn}),h&&jsx(Kf,{editingFlashcard:i,onConfirm:ln,onCancel:()=>r(Xa(false))}),z&&jsx(os,{defaultColor:m,onConfirm:A=>{r(ua(A)),N(false);},onCancel:()=>N(false)})]})},uS=dS;var dd=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let n=Ee(La),r=Ee(Bi),s=a?r:n,u=Ee(br),m=(Ee(g=>g.canvas.slides.find(x=>x.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[l,d]=useState(false),[f,h]=useState(null),[p,y]=useState(null),w=async()=>{if(n.length===0){y({type:"error",message:"No slides to publish"});return}if(!e){y({type:"error",message:"No publish handler provided"});return}d(true),y(null);try{let g=await e(s,u,x=>{h(x);});g.success?y({type:"success",message:g.message}):y({type:"error",message:g.message});}catch(g){y({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{d(false),setTimeout(()=>{h(null),y(null);},3e3);}console.log("For checking>>>>>>>>>>>",s,"<<<<<<<<<<<<<");};return m?null:jsxs("button",{onClick:w,disabled:l||n.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var hS=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:n,onDescriptionChange:r,showPublishButton:s=true,showBackButton:u=true,editableTitle:i=true,editableDescription:c=true,className:m="",rightContent:l,leftContent:d,includeInactiveSlides:f=false})=>{let h=$e(),p=Ee(br),y=Ee(Oi),w=e??(y?p.title:"")??"Untitled",g=o??(y?p.description:"")??"Add a description...",[x,I]=useState(false),[L,P]=useState(false),[C,b]=useState(w),[v,k]=useState(g),T=useRef(null),F=useRef(null);useEffect(()=>{b(w);},[w]),useEffect(()=>{k(g);},[g]),useEffect(()=>{x&&T.current&&(T.current.focus(),T.current.select());},[x]),useEffect(()=>{L&&F.current&&(F.current.focus(),F.current.select());},[L]);let V=()=>{i&&I(true);},O=()=>{c&&P(true);},U=()=>{I(false),C.trim()&&C!==w?n?n(C.trim()):h(Di(C.trim())):C.trim()||b(w);},H=()=>{P(false),v.trim()&&v!==g?r?r(v.trim()):h(Ri(v.trim())):v.trim()||k(g);},K=W=>{W.key==="Enter"?U():W.key==="Escape"&&(b(w),I(false));},E=W=>{W.key==="Enter"?H():W.key==="Escape"&&(k(g),P(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${m}`,children:[d||jsxs("div",{className:"flex items-center gap-4",children:[u&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[x?jsx("input",{ref:T,type:"text",value:C,onChange:W=>b(W.target.value),onBlur:U,onKeyDown:K,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:V,title:C,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${i?"hover:border-primary cursor-text":""}`,children:C}),L?jsx("input",{ref:F,type:"text",value:v,onChange:W=>k(W.target.value),onBlur:H,onKeyDown:E,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:O,title:v,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${c?"hover:border-primary cursor-text":""}`,children:v})]})]}),l||s&&a&&jsx(dd,{onPublish:a,includeInactiveSlides:f})]})};var wS=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],SS=({colors:e=wS,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:n=""})=>{let[r,s]=useState(true),u=J(ye),i=J(d=>d.toolbar.penColor),c=J(d=>d.toolbar.strokeWidth),m=u?.backgroundColor,l=Se();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:r?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-16 left-1/2 z-50 hidden w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-3 shadow-2xl md:bottom-6 md:flex md:p-5 2xl:px-8 2xl:py-6 ${n}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-black md:h-3 md:w-3"}),jsx(Vs,{defaultValue:[20],max:36,min:8,step:2,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:d=>l(Yr(d[0]))}),jsx("div",{className:"h-5 w-5 rounded-full bg-black md:h-7 md:w-7 lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"COLOR"}),jsxs(Va,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(d=>jsx("button",{value:d.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${i===d.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:d.value},onClick:()=>l(ua(d.value))},d.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>l(ua("#2D2F50"))}),jsxs("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] md:h-10 md:w-10 lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:d=>l(ua(d.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:m},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:d=>l(cr(d.target.value))})})]})}),jsx("div",{className:"absolute -top-6 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2 md:-top-4",children:jsx("button",{onClick:()=>s(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{weight:"bold",className:"text-gray-600 md:text-xl"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>s(true),className:"fixed bottom-20 left-1/2 z-50 hidden -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl md:bottom-3 md:flex","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var bm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),LS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),cd=e=>{let o=LS(e);return o.charAt(0).toUpperCase()+o.slice(1)},Ks=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),vm=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var ym={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var Sm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:n="",children:r,iconNode:s,...u},i)=>createElement("svg",{ref:i,...ym,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Ks("lucide",n),...!r&&!vm(u)&&{"aria-hidden":"true"},...u},[...s.map(([c,m])=>createElement(c,m)),...Array.isArray(r)?r:[r]]));var Gs=(e,o)=>{let t=forwardRef(({className:a,...n},r)=>createElement(Sm,{ref:r,iconNode:o,className:Ks(`lucide-${bm(cd(e))}`,`lucide-${e}`,a),...n}));return t.displayName=cd(e),t};var TS=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Qr=Gs("copy",TS);var MS=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],en=Gs("trash-2",MS);var Im=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:s})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:n,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Qr,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),s();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(en,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var DS=({softDelete:e=false})=>{let o=$e(),t=Ee(La),a=Ee(Sa),n=Ee(xr),[r,s]=useState(true),c=(Ee(h=>h.canvas.slides.find(p=>p.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),m=()=>{n&&o(ir());},l=h=>{o(ur(h));},d=h=>{o(dr(h));},f=h=>{t.length>1&&o(lr({id:h,softDelete:e}));};return c?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>s(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((h,p)=>jsx(Im,{slide:h,index:p,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>l(h.id),onDuplicate:()=>d(h.id),onDelete:()=>f(h.id)},h.id))}),jsxs("button",{onClick:m,disabled:!n,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${n?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>s(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var er=20,zS=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:s})=>jsxs("div",{className:`relative h-[122px] w-[166px] shrink-0 cursor-pointer rounded-lg border bg-[#fafafa] transition-all ${t?"border-[#096b76]":"border-black/10"}`,onClick:n,children:[jsx("div",{className:"absolute top-1 right-1 bottom-1 left-1 overflow-hidden rounded bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"size-full object-contain"}):jsx("div",{className:"flex size-full items-center justify-center",children:jsx("span",{className:"text-xs text-black/20",children:"No preview"})})}),jsx("div",{className:"absolute top-3 left-3 flex h-5 w-5 items-center justify-center rounded-full bg-[#333c48]",children:jsx("span",{className:"text-xs font-bold text-white",children:o+1})}),jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"absolute top-3 right-3 flex cursor-pointer items-center justify-center rounded-md bg-[#3B75E0] p-1.5 text-white transition-colors hover:bg-[#2d5fc0]",title:"Duplicate Page",children:jsx(Copy,{size:18,weight:"bold"})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),s();},className:"absolute right-3 bottom-6 flex cursor-pointer items-center justify-center rounded-md bg-[#E53935] p-1.5 text-white transition-colors hover:bg-[#c62828]",title:"Delete Page",children:jsx(Trash,{size:18,weight:"bold"})}),jsxs("p",{className:"absolute bottom-2 left-3 text-sm text-black/40",children:["Page ",o+1]})]}),US=({softDelete:e=false})=>{let o=$e(),t=Ee(La),a=Ee(Sa),n=Ee(xr),[r,s]=useState(false),[u,i]=useState(false),[c,m]=useState(false),l=useRef(null),h=(Ee(L=>L.canvas.slides.find(P=>P.id===L.canvas.currentSlideId))?.videos||[]).some(L=>L.isRecorded&&L.isPlaying),p=()=>{n&&t.length<er&&o(ir());},y=L=>{o(ur(L));},w=L=>{t.length<er&&o(dr(L));},g=L=>{t.length>1&&o(lr({id:L,softDelete:e}));},x=()=>{if(!l.current)return;let{scrollLeft:L,scrollWidth:P,clientWidth:C}=l.current,b=P>C+5;i(b&&L>5),m(b&&L<P-C-5);},I=L=>{if(!l.current)return;let P=177,C=L==="left"?l.current.scrollLeft-P:l.current.scrollLeft+P;l.current.scrollTo({left:C,behavior:"smooth"});};return useEffect(()=>{if(r){let L=setTimeout(()=>{requestAnimationFrame(()=>{x();});},350);return ()=>clearTimeout(L)}},[t,r]),useEffect(()=>{let L=l.current;if(!(!L||!r))return L.addEventListener("scroll",x),window.addEventListener("resize",x),()=>{L.removeEventListener("scroll",x),window.removeEventListener("resize",x);}},[r]),h?null:jsx("div",{className:"fixed bottom-0 left-1/2 z-50 flex w-full -translate-x-1/2 flex-col gap-4 md:hidden",children:jsxs(AnimatePresence,{mode:"wait",children:[r&&jsxs(motion.div,{initial:{y:230,opacity:0},animate:{y:0,opacity:1},exit:{y:230,opacity:0},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},onAnimationComplete:()=>x(),className:"border bg-white md:hidden",children:[jsxs("div",{className:"flex w-full items-center justify-between px-4 py-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Cards,{size:24,weight:"fill",className:"text-[#096b76]"}),jsx("span",{className:"text-base font-bold text-black/80",children:"Pages"}),jsxs("span",{className:"text-base font-bold text-black/80",children:["(",t.length,"/",er,")"]})]}),jsx("button",{onClick:()=>s(false),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretDown,{size:16,weight:"bold",className:"text-black/60"})})]}),jsxs("div",{className:"relative",children:[u&&jsx("button",{onClick:()=>I("left"),className:"absolute top-1/2 left-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll left",children:jsx(CaretLeft,{size:20,weight:"bold",className:"text-black/80"})}),c&&jsx("button",{onClick:()=>I("right"),className:"absolute top-1/2 right-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll right",children:jsx(CaretRight,{size:20,weight:"bold",className:"text-black/80"})}),jsx("div",{ref:l,className:"scrollbar-hide flex gap-[11px] overflow-x-auto px-4 pb-4",children:t.map((L,P)=>jsx(zS,{slide:L,index:P,isSelected:L.id===a,isSingleSlide:t.length===1,onSelect:()=>y(L.id),onDuplicate:()=>w(L.id),onDelete:()=>g(L.id)},L.id))})]}),jsx("button",{onClick:p,disabled:!n||t.length>=er,className:`px-4 pb-4 text-base font-bold ${n&&t.length<er?"cursor-pointer text-[#096b76]":"cursor-not-allowed text-black/30"}`,children:"+ Add Page"})]},"open"),!r&&jsxs(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{type:"tween",duration:.2},className:"flex cursor-pointer items-center justify-between gap-2 border border-black/10 bg-white px-4 py-3 shadow-lg md:hidden",children:[jsxs("div",{className:"flex gap-2",children:[jsx(Cards,{size:20,weight:"fill",className:"text-[#096b76]"}),jsxs("span",{className:"text-sm font-bold text-black/80",children:["Pages (",t.length,"/",er,")"]})]}),jsx("button",{onClick:()=>s(true),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretUp,{size:16,weight:"bold",className:"text-black/60"})})]},"close")]})})},md=US;var YS=({stageRef:e,onScreenRecord:o,visible:t=true,config:a={}})=>{let n=$e(),[r,s]=useState(false),[u,i]=useState(false),c=Ee(I=>I.canvas.slides.find(L=>L.id===I.canvas.currentSlideId)),m=Ee(I=>I.canvas.zoomLevel),d=(c?.videos||[]).some(I=>I.isRecorded&&I.isPlaying),f={undo:a.undo??true,redo:a.redo??true,screenRecord:a.screenRecord??true,cameraRecord:a.cameraRecord??true,clear:a.clear??true,zoomOut:a.zoomOut??true,zoomIn:a.zoomIn??true,resetZoom:a.resetZoom??true},h=()=>{o?o():s(true);},p=()=>{i(true);},y=()=>{n(hr());},w=async(I,L)=>{let P=v4(),C=URL.createObjectURL(I),b=document.createElement("video");b.src=C,b.muted=true,b.playsInline=true,b.preload="auto",await new Promise((V,O)=>{let U=setTimeout(()=>O(new Error("Metadata load timeout")),1e4);b.onloadedmetadata=()=>{clearTimeout(U),V();},b.onerror=()=>{clearTimeout(U),O(new Error("Failed to load video"));};});let v=640,k=b.videoWidth/b.videoHeight,T=v,F=T/k;await sa(P,I,L),n(wo({id:P,objectUrl:C,thumbnailDataUrl:L,videoBlob:I,x:100,y:100,width:T,height:F,draggable:true,isPlaying:false,rotation:0,isRecorded:true}));},x=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>n(Io()),enabled:f.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>n(Co()),enabled:f.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:h,enabled:f.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:p,enabled:f.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:y,enabled:f.clear,iconWeight:"fill",colorClass:"text-[#E92222]"},{key:"resetZoom",title:"Reset Zoom",icon:ArrowsOut,onClick:()=>n(Vd()),enabled:f.resetZoom&&m!==1,iconWeight:"bold",colorClass:"text-primary"}].filter(I=>I.enabled);return !t||d||x.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fixed bottom-[74px] left-1/2 z-50 flex w-11/12 -translate-x-1/2 items-center justify-between rounded-md border bg-white px-4 py-1 shadow-lg md:hidden",children:x.map(I=>jsx("button",{onClick:I.onClick,className:`flex size-10 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-black/5 ${I.colorClass}`,title:I.title,children:jsx(I.icon,{weight:I.iconWeight,className:"text-xl"})},I.key))}),!o&&r&&e&&jsx(Ya,{onClose:()=>s(false),stageRef:e,onRecordingComplete:w}),u&&jsx(Os,{onClose:()=>i(false),onRecordingComplete:w})]})},pd=YS;var QS=({stageRef:e,onScreenRecord:o,softDelete:t=false,actionButtonsVisible:a=true,actionButtonsConfig:n})=>jsxs(Fragment,{children:[jsx(pd,{stageRef:e,onScreenRecord:o,visible:a,config:n}),jsx(md,{softDelete:t})]}),eL=QS;var oL="SchooplaEditorDB",rL=1,za="slides",Ua="metadata",hd="schoopla_current_slide_id",Dm="presentation_metadata",an=()=>new Promise((e,o)=>{let t=indexedDB.open(oL,rL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(za)||n.createObjectStore(za,{keyPath:"id"}),n.objectStoreNames.contains(Ua)||n.createObjectStore(Ua,{keyPath:"id"});};}),gd=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await an(),a=o.transaction([za],"readwrite").objectStore(za);await new Promise((n,r)=>{let s=a.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);});for(let n of e)await new Promise((r,s)=>{let u=a.add(n);u.onsuccess=()=>r(!0),u.onerror=()=>s(u.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},xd=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await an(),t=e.transaction([za],"readonly").objectStore(za);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let s=r.result;console.log("\u2705 Loaded from IndexedDB:",s.length,"slides"),s.length>0&&s[0].images&&console.log("First slide images:",s[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(s.length>0?s:null);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},js=async()=>{try{let e=await an(),o=e.transaction([za,Ua],"readwrite"),t=o.objectStore(za),a=o.objectStore(Ua);await new Promise((n,r)=>{let s=t.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),await new Promise((n,r)=>{let s=a.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(hd),localStorage.removeItem("schoopla_presentation_metadata"),await jc(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},bd=e=>{try{localStorage.setItem(hd,e);}catch(o){console.error("Error saving current slide ID:",o);}},vd=()=>{try{return localStorage.getItem(hd)}catch(e){return console.error("Error loading current slide ID:",e),null}},yd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},wd=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await an(),a=o.transaction([Ua],"readwrite").objectStore(Ua);await new Promise((n,r)=>{let s=a.put({id:Dm,...e});s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Sd=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await an(),t=e.transaction([Ua],"readonly").objectStore(Ua);return new Promise((a,n)=>{let r=t.get(Dm);r.onsuccess=()=>{e.close();let s=r.result;if(s){let{id:u,...i}=s;console.log("\u2705 Loaded presentation metadata:",i),a(i);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var nL=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides","canvas/updateSlideThumbnail"],sL=["canvas/clearCanvas"],iL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],lL=yd((e,o)=>{gd(e),bd(o);},500),dL=yd(e=>{wd(e);},500),uL=(e,o)=>{gd(e),bd(o);},Ld=false,Rm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Ol(r).catch(s=>{console.error("Error deleting video blob:",s);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,u=e.getState().canvas.slides.find(i=>i.id===r);u&&u.videos&&u.videos.length>0&&u.videos.forEach(i=>{Ol(i.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,s=e.getState(),i=s.canvas.slides.find(c=>c.id===s.canvas.currentSlideId)?.videos.find(c=>c.id===r);i&&i.videoBlob&&setTimeout(()=>{let c=e.getState(),l=c.canvas.slides.find(d=>d.id===c.canvas.currentSlideId)?.videos.find(d=>d.id!==r&&d.x===i.x+20&&d.y===i.y+20);l&&i.videoBlob&&sa(l.id,i.videoBlob,l.thumbnailDataUrl).catch(d=>{console.error("Error saving duplicated video blob:",d);});},0);}let a=o(t),n=e.getState();if(n.canvas.viewerMode)return a;if(t.type&&sL.includes(t.type)){if(!Ld){Ld=true;try{let{slides:r,currentSlideId:s}=n.canvas;uL(r,s);}finally{setTimeout(()=>{Ld=false;},0);}}}else if(t.type&&nL.includes(t.type)){let{slides:r,currentSlideId:s}=n.canvas;lL(r,s);}else if(t.type&&iL.includes(t.type)){let{presentationMetadata:r}=n.canvas;dL(r);}return a});new QueryClient;var fL=configureStore({reducer:{toolbar:Xl,canvas:Ni},middleware:e=>e({serializableCheck:false}).concat(Rm)}),mL=()=>configureStore({reducer:{toolbar:Xl,canvas:Ni},middleware:e=>e({serializableCheck:false})});var pL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2,fileName:r=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:s,quality:a,pixelRatio:n}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=u,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},hL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o;return new Promise((r,s)=>{try{let u=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:u,quality:a,pixelRatio:n});fetch(i).then(c=>c.blob()).then(c=>r(c)).catch(c=>s(c));}catch(u){s(u);}})},gL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:n})};var xL=(e,o,t)=>{let a=t.x-o.x,n=t.y-o.y;if(a===0&&n===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+n*n,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*n)/r)),u=o.x+s*a,i=o.y+s*n;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-i,2))},Id=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,n=e[0],r=e[e.length-1];for(let s=1;s<e.length-1;s++){let u=xL(e[s],n,r);u>t&&(t=u,a=s);}if(t>o){let s=Id(e.slice(0,a+1),o),u=Id(e.slice(a),o);return [...s.slice(0,-1),...u]}return [n,r]},bL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},vL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Bm=(e,o=1.5)=>{if(e.length<=4)return e;let t=bL(e),a=Id(t,o);return vL(a)},Om=(e,o=1.5)=>({...e,points:Bm(e.points,o)}),yL=(e,o=1.5)=>e.map(t=>Om(t,o)),wL=(e,o)=>{let t=e.length/2,a=o.length/2,n=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${n}%`}};var SL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Nm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:n=.85}=o;return new Promise((r,s)=>{let u=new Image;u.onload=()=>{let{width:i,height:c}=u;if(i>t||c>a){let h=i/c;i>c?(i=Math.min(i,t),c=i/h):(c=Math.min(c,a),i=c*h);}let m=document.createElement("canvas");m.width=i,m.height=c;let l=m.getContext("2d");if(!l){s(new Error("Failed to get canvas context"));return}l.drawImage(u,0,0,i,c);let d=SL(e),f=m.toDataURL(d,n);r(f);},u.onerror=s,u.src=e;})};var ho=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let n=0;n<t.length;n++)a[n]=t.charCodeAt(n);return a.buffer},tr=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",ar=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",LL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:n=1080,imageQuality:r=.85}=o,s=[],u=0;for(let i of e){let c=[],m=[],l=[];for(let d of i.images){let f=d.src;if(t&&f.startsWith("data:"))try{f=await Nm(f,{maxWidth:a,maxHeight:n,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=ho(f),p=tr(f);u+=h.byteLength;let y={id:d.id,x:d.x,y:d.y,width:d.width,height:d.height,draggable:d.draggable,rotation:d.rotation,locked:d.locked,link:d.link,altText:d.altText,zIndex:d.zIndex,buffer:h,mimeType:p};if(d.audioData&&d.audioData.startsWith("data:")){let w=ho(d.audioData),g=tr(d.audioData);u+=w.byteLength,y.audioBuffer=w,y.audioMimeType=g;}c.push(y);}}for(let d of i.videos){let f,h;if(d.videoBlob)f=await d.videoBlob.arrayBuffer(),h=d.videoBlob.type;else if(d.videoData&&d.videoData.startsWith("data:"))f=ho(d.videoData),h=tr(d.videoData);else {console.warn(`Video ${d.id} has no blob or videoData, skipping`);continue}u+=f.byteLength;let p={id:d.id,thumbnailDataUrl:d.thumbnailDataUrl,x:d.x,y:d.y,width:d.width,height:d.height,draggable:d.draggable,isPlaying:d.isPlaying,rotation:d.rotation,locked:d.locked,link:d.link,altText:d.altText,zIndex:d.zIndex,isRecorded:d.isRecorded,buffer:f,mimeType:h};if(d.audioData&&d.audioData.startsWith("data:")){let y=ho(d.audioData),w=tr(d.audioData);u+=y.byteLength,p.audioBuffer=y,p.audioMimeType=w;}m.push(p);}for(let d of i.photoFrames){let f={id:d.id,x:d.x,y:d.y,width:d.width,height:d.height,rotation:d.rotation,draggable:d.draggable,locked:d.locked,link:d.link,altText:d.altText,zIndex:d.zIndex,isCapturing:d.isCapturing};if(d.capturedImageUrl&&d.capturedImageUrl.startsWith("data:")){let h=ho(d.capturedImageUrl),p=tr(d.capturedImageUrl);u+=h.byteLength,f.buffer=h,f.mimeType=p;}if(d.audioData&&d.audioData.startsWith("data:")){let h=ho(d.audioData),p=tr(d.audioData);u+=h.byteLength,f.audioBuffer=h,f.audioMimeType=p;}l.push(f);}s.push({...i,images:c,videos:m,photoFrames:l});}return {slides:s,totalSize:u}},IL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},CL=e=>{let o=new FormData,t=e.slides.map((a,n)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,mimeType:r.mimeType,fileKey:`slide_${n}_image_${s}`,audioFileKey:r.audioBuffer?`slide_${n}_image_${s}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,isPlaying:r.isPlaying,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isRecorded:r.isRecorded,mimeType:r.mimeType,fileKey:`slide_${n}_video_${s}`,thumbnailFileKey:`slide_${n}_video_${s}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${n}_video_${s}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,rotation:r.rotation,draggable:r.draggable,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isCapturing:r.isCapturing,mimeType:r.mimeType,fileKey:r.buffer?`slide_${n}_photoframe_${s}`:void 0,audioFileKey:r.audioBuffer?`slide_${n}_photoframe_${s}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,n)=>{a.images.forEach((r,s)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${ar(r.mimeType)}`;if(o.append(`slide_${n}_image_${s}`,u,i),r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${ar(r.audioMimeType)}`;o.append(`slide_${n}_image_${s}_audio`,c,m);}}),a.videos.forEach((r,s)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${ar(r.mimeType)}`;if(o.append(`slide_${n}_video_${s}`,u,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let c=ho(r.thumbnailDataUrl),m=new Blob([c],{type:"image/jpeg"}),l=`${r.id}_thumbnail.jpg`;o.append(`slide_${n}_video_${s}_thumbnail`,m,l);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${ar(r.audioMimeType)}`;o.append(`slide_${n}_video_${s}_audio`,c,m);}}),a.photoFrames.forEach((r,s)=>{if(r.buffer&&r.mimeType){let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${ar(r.mimeType)}`;o.append(`slide_${n}_photoframe_${s}`,u,i);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${ar(r.audioMimeType)}`;o.append(`slide_${n}_photoframe_${s}_audio`,u,i);}});}),o};var ML=()=>{let e=$e(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let n=await xd(),r=vd(),s=await Sd();if(n&&n.length>0){let u=await Gc(),i=n.map(m=>{if(m.videos&&m.videos.length>0){let l=m.videos.map(d=>{let f=u.get(d.id);if(f){let h=_c(f.blob);return {...d,objectUrl:h,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return d});return {...m,videos:l}}return m}),c=r&&i.find(m=>m.id===r)?r:i[0].id;e(vo({slides:i,currentSlideId:c}));}e(s?Fi({title:s.title,description:s.description}):Xn(!0));}catch(n){console.error("Error loading persisted slides:",n),e(Xn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var qm=e=>e.map(o=>({...o,lines:o.lines||[],shapes:o.shapes||[],images:o.images||[],videos:o.videos||[],flashcards:o.flashcards||[],photoFrames:o.photoFrames||[],texts:o.texts||[],multipleChoices:o.multipleChoices||[],trueFalses:o.trueFalses||[],shortAnswers:o.shortAnswers||[],LongAnswer:o.LongAnswer||[],fillInTheBlanks:o.fillInTheBlanks||[],createdAt:o.createdAt||Date.now(),updatedAt:o.updatedAt||Date.now(),showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,activityType:o.activityType||""})),Vm=new WeakSet,zm=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await sa(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},AL=()=>{let e=$e(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Vm.has(a))return;Vm.add(a);let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await js(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,i=qm(n);e(vo({slides:i,currentSlideId:u})),await zm(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await js(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,i=qm(n);e(vo({slides:i,currentSlideId:u})),await zm(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
|
|
2
|
+
export{default as Konva}from'konva';import*as Le from'react';import Le__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,createContext,useState,useMemo,createElement,useContext,useId,useLayoutEffect}from'react';import {createPortal}from'react-dom';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {CameraPlus,Camera,Stop,X,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Palette,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Rectangle,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,List,Plus,Export,CaretLeft,CaretDown,CaretUp,SidebarSimple,CaretRight,ArrowsOut,SpeakerHifiIcon,NotePencilIcon,FrameCorners,PencilSimple,CopySimple,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,TextUnderline,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Copy,Pen}from'@phosphor-icons/react/dist/ssr';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import _d from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import Xu from'use-image';import {AnimatePresence,motion,Reorder}from'framer-motion';import {Stack as Stack$1,X as X$1,DotsSixVertical,Question,FrameCorners as FrameCorners$1,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Od=e=>{throw TypeError(e)};var Nd=(e,o,t)=>o.has(e)||Od("Cannot "+t);var $=(e,o,t)=>(Nd(e,o,"read from private field"),t?t.call(e):o.get(e)),Ne=(e,o,t)=>o.has(e)?Od("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),De=(e,o,t,a)=>(Nd(e,o,"write to private field"),o.set(e,t),t);var Hd=(e,o,t,a)=>({set _(n){De(e,o,n);},get _(){return $(e,o,a)}});var Se=()=>useDispatch(),J=e=>useSelector(e),_e=Se,Re=J;var oi=20,dt=(()=>{let e=0;return o=>`${o}-${Date.now()}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`})();function wp(e){let o=JSON.parse(JSON.stringify(e));return o.id=dt("slide"),o.name=`${e.name} (Copy)`,o.createdAt=Date.now(),o.updatedAt=Date.now(),o.isActive=true,o.showMcqForm=false,o.showFlashcardForm=false,o.editingActivity=null,o.editingFlashcard=null,o.lines=o.lines.map(t=>({...t,id:dt("line")})),o.shapes=o.shapes.map(t=>({...t,id:dt("shape")})),o.images=o.images.map(t=>({...t,id:dt("img"),annotations:t.annotations?.map(a=>({...a,id:dt("line")}))??[]})),o.videos=o.videos.map(t=>({...t,id:dt("vid"),isPlaying:false,videoBlob:void 0})),o.flashcards=o.flashcards.map(t=>({...t,id:dt("flashcard")})),o.photoFrames=o.photoFrames.map(t=>({...t,id:dt("photoframe"),isCapturing:false,annotations:t.annotations?.map(a=>({...a,id:dt("line")}))??[]})),o.texts=o.texts.map(t=>({...t,id:dt("text")})),o.multipleChoices=o.multipleChoices.map(t=>({...t,id:dt("mcq"),data:{...t.data,responseOptions:{...t.data.responseOptions,selectedIndices:void 0,isCorrect:void 0,attempts:void 0}}})),o.trueFalses=o.trueFalses.map(t=>({...t,id:dt("truefalse"),data:{...t.data,responseOptions:{...t.data.responseOptions,selectedResponse:void 0,isCorrect:void 0,attempts:void 0}}})),o.shortAnswers=o.shortAnswers.map(t=>({...t,id:dt("shortAnswer"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0,isCorrect:void 0,attempts:void 0}}})),o.LongAnswer=o.LongAnswer.map(t=>({...t,id:dt("longAnswer"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0}}})),o.fillInTheBlanks=o.fillInTheBlanks.map(t=>({...t,id:dt("fillInTheBlank"),data:{...t.data,responseOptions:{...t.data.responseOptions,userAnswer:void 0,isCorrect:void 0,attempts:void 0}}})),o}var ni=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now(),isActive:true}),ai=ni("Page 1"),Sp={slides:[ai],currentSlideId:ai.id,history:{[ai.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false,editingOverlayPosition:null,zoomLevel:1},qd=createSlice({name:"canvas",initialState:Sp,reducers:{addSlide:e=>{if(e.slides.length>=oi)return;let o=ni(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(u=>u.isActive).length<=1)return;let r=e.slides.findIndex(u=>u.id===t);if(r===-1)return;let s=e.slides[r];if(a?(s.isActive=false,s.updatedAt=Date.now()):(e.slides.splice(r,1),delete e.history[t]),e.currentSlideId===t){let u=e.slides.filter(i=>i.isActive);u.length>0&&(e.currentSlideId=u[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=oi)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],n=wp(a);e.slides.splice(t+1,0,n),e.currentSlideId=n.id,e.history[n.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},setViewerMode:(e,o)=>{e.viewerMode=o.payload;},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[n]=e.slides.splice(t,1);e.slides.splice(a,0,n);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(n=>n.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(n=>n.id===o.payload);if(a){let n={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(n),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,newTimestamp:r}=o.payload;switch(n){case "image":let s=t.images.find(b=>b.id===a);s&&(s.timestamp=r);break;case "video":let u=t.videos.find(b=>b.id===a);u&&(u.timestamp=r);break;case "shape":let i=t.shapes.find(b=>b.id===a);i&&(i.timestamp=r);break;case "text":let c=t.texts.find(b=>b.id===a);c&&(c.timestamp=r);break;case "flashcard":let f=t.flashcards.find(b=>b.id===a);f&&(f.timestamp=r);break;case "photoFrame":let d=t.photoFrames.find(b=>b.id===a);d&&(d.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(b=>b.id===a);l&&(l.timestamp=r);break;case "trueFalse":let m=t.trueFalses.find(b=>b.id===a);m&&(m.timestamp=r);break;case "shortAnswer":let h=t.shortAnswers.find(b=>b.id===a);h&&(h.timestamp=r);break;case "longAnswer":let p=t.LongAnswer.find(b=>b.id===a);p&&(p.timestamp=r);break;case "fillInTheBlanks":let v=t.fillInTheBlanks.find(b=>b.id===a);v&&(v.timestamp=r);break;case "line":let y=t.lines.find(b=>b.id===a);y&&(y.timestamp=r);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);if(a){let n={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(n),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(n=>n.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(n=>n.id===o.payload);if(a){let n={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(n),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(n=>n.id===o.payload);if(a){let n={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(n),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let n=t.multipleChoices[t.multipleChoices.length-1];a.x=n.x+20,a.y=n.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},updateMultipleChoiceDragAndDrop(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a].dragDropPos=o.payload.dragDropPos,t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(n=>n.id===o.payload);if(a){let n={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(n),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let n=t.trueFalses[t.trueFalses.length-1];a.x=n.x+20,a.y=n.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(n=>n.id===o.payload);if(a){let n={...JSON.parse(JSON.stringify(a)),id:`truefalse-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(n),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let n=t.shortAnswers[t.shortAnswers.length-1];a.x=n.x+20,a.y=n.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(n=>n.id===o.payload);if(a){let n={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(n),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let n=t.LongAnswer[t.LongAnswer.length-1];a.x=n.x+20,a.y=n.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(n=>n.id===o.payload);if(a){let n={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(n),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let n=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=n.x+20,a.y=n.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(n=>n.id===o.payload);if(a){let n={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(n),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.images.splice(r,1);t.images.push(s);}}else if(n==="video"){let r=t.videos.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.videos.splice(r,1);t.videos.push(s);}}else if(n==="shape"){let r=t.shapes.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shapes.splice(r,1);t.shapes.push(s);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.flashcards.splice(r,1);t.flashcards.push(s);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.photoFrames.splice(r,1);t.photoFrames.push(s);}}else if(n==="text"){let r=t.texts.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.texts.splice(r,1);t.texts.push(s);}}else if(n==="trueFalse"){let r=t.trueFalses.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.trueFalses.splice(r,1);t.trueFalses.push(s);}}else if(n==="shortAnswer"){let r=t.shortAnswers.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shortAnswers.splice(r,1);t.shortAnswers.push(s);}}else if(n==="fillInTheBlanks"){let r=t.fillInTheBlanks.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.fillInTheBlanks.splice(r,1);t.fillInTheBlanks.push(s);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload;if(n==="image"){let r=t.images.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.images.splice(r,1);t.images.unshift(s);}}else if(n==="video"){let r=t.videos.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.videos.splice(r,1);t.videos.unshift(s);}}else if(n==="shape"){let r=t.shapes.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.shapes.splice(r,1);t.shapes.unshift(s);}}else if(n==="flashcard"){let r=t.flashcards.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.flashcards.splice(r,1);t.flashcards.unshift(s);}}else if(n==="photoFrame"){let r=t.photoFrames.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.photoFrames.splice(r,1);t.photoFrames.unshift(s);}}else if(n==="text"){let r=t.texts.findIndex(s=>s.id===a);if(r!==-1){let[s]=t.texts.splice(r,1);t.texts.unshift(s);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n}=o.payload,s=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);s&&(s.locked=!s.locked,"draggable"in s&&(s.draggable=!s.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,link:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="mcq"?t.multipleChoices:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.link=r,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,altText:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.altText=r,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:n,audioData:r}=o.payload,u=(n==="image"?t.images:n==="video"?t.videos:n==="shape"?t.shapes:n==="flashcard"?t.flashcards:n==="photoFrame"?t.photoFrames:n==="trueFalse"?t.trueFalses:n==="shortAnswer"?t.shortAnswers:n==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);u&&(u.audioData=r,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},editingOverlayPosition:(e,o)=>{e.editingOverlayPosition=o.payload;},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(n=>n.id===o.payload);if(a){let n={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(n),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);if(a){let n={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(n),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let n=a.images.map((r,s)=>s).filter(r=>r!==a.currentIndex);if(n.length>0){let r=n[Math.floor(Math.random()*n.length)];a.navigationHistory.push(r),a.currentIndex=r;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(n=>n.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(n=>n.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);if(a){let n={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(n),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(n=>n.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(n=>n.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let n=o.past.pop();e.slides[t]=n;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let n=o.future.shift();e.slides[t]=n;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let n=JSON.parse(JSON.stringify(t));a.past.push(n),a.future=[],a.past.length>20&&a.past.shift();}catch(n){console.warn("Failed to save to history - data too large:",n),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;},setZoomLevel:(e,o)=>{e.zoomLevel=Math.max(.5,Math.min(2,o.payload));},zoomIn:e=>{e.zoomLevel=Math.min(2,e.zoomLevel+.25);},zoomOut:e=>{e.zoomLevel=Math.max(.5,e.zoomLevel-.25);},resetZoom:e=>{e.zoomLevel=1;}}}),{addSlide:ur,deleteSlide:cr,duplicateSlide:fr,setCurrentSlide:mr,setViewerMode:Lp,updateSlideThumbnail:si,setBackgroundColor:pr,reorderSlides:Ip,loadSlides:Io,addLine:ii,removeLine:xn,addImage:li,updateImage:Co,deleteImage:bn,duplicateImage:vn,addVideo:ko,updateVideo:yn,deleteVideo:wn,duplicateVideo:Sn,toggleVideoPlaying:Xa,addShape:di,updateShape:Ya,duplicateShape:Ln,deleteShape:In,addText:ui,editingOverlayPosition:Vd,updateText:Ft,deleteText:Cn,duplicateText:kn,addFlashcard:ci,updateFlashcard:To,deleteFlashcard:Tn,duplicateFlashcard:Mn,editFlashcard:hr,nextFlashcard:fi,previousFlashcard:mi,addPhotoFrame:pi,updatePhotoFrame:Za,deletePhotoFrame:An,duplicatePhotoFrame:Pn,toggleImageDrawingMode:hi,addImageAnnotation:gi,updateImageAnnotation:Cp,clearImageAnnotations:kp,togglePhotoFrameDrawingMode:xi,addPhotoFrameAnnotation:bi,updatePhotoFrameAnnotation:Tp,clearPhotoFrameAnnotations:Mp,addMultipleChoice:vi,updateMultipleChoice:gt,updateMultipleChoiceDragAndDrop:yi,editMultipleChoice:Ap,deleteMultipleChoice:En,duplicateMultipleChoice:Dn,addTrueFalse:wi,updateTrueFalse:ot,deleteTrueFalse:Rn,duplicateTrueFalse:Fn,addShortAnswer:Si,updateShortAnswer:sa,deleteShortAnswer:Bn,duplicateShortAnswer:On,addLongAnswer:Li,updateLongAnswer:Ja,deleteLongAnswer:Nn,duplicateLongAnswer:Hn,addFillInTheBlanks:Ii,updateFillInTheBlanks:Sa,deleteFillInTheBlanks:qn,duplicateFillInTheBlanks:Vn,setShowMcqForm:La,setShowFlashcardForm:Qa,setActivityType:Ci,setEditingActivity:gr,bringToFront:ki,sendToBack:Ti,toggleLock:Mi,setLink:zn,setAltText:Wn,setAudioData:Un,updateLastLine:Pp,finalizeDrawing:Ai,setLines:Ep,updateLinePosition:Dp,updateLineTransform:Kn,deleteLineById:Gn,duplicateLine:Pi,updateElementOrder:xr,clearCanvas:br,undo:Mo,redo:Ao,saveToHistory:de,toggleSketchMode:Rp,setSketchMode:It,setEditingTextId:vr,setPresentationTitle:Ei,setPresentationDescription:Di,loadPresentationMetadata:Ri,setMetadataLoaded:jn,setZoomLevel:WL,zoomIn:UL,zoomOut:KL,resetZoom:zd}=qd.actions;var Wd=e=>e.canvas.slides,Ia=e=>e.canvas.currentSlideId,ve=createSelector([Wd,Ia],(e,o)=>e.find(t=>t.id===o)),Ca=createSelector([Wd],e=>e.filter(o=>o.isActive!==false)),Fi=e=>e.canvas.slides,yr=createSelector([Ca],e=>e.length<oi),Fp=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},wr=e=>e.canvas.presentationMetadata,Bi=e=>e.canvas.metadataLoaded,_n=e=>e.canvas.viewerMode,Oi=qd.reducer;var Kd=e=>{let o=Se(),t=useRef(null),a=useRef(false),n=J(m=>m.toolbar.selectedTool),r=J(m=>m.toolbar.penColor),s=J(m=>m.toolbar.strokeWidth),u=J(m=>m.canvas.isSketchMode),i=J(m=>m.canvas.slides.find(p=>p.id===m.canvas.currentSlideId)?.lines||[]),c=useCallback(m=>{t.current=m;},[]),f=useCallback(m=>{n==="pen"&&t.current&&(o(de()),t.current.startDrawing(m),a.current=true);},[n,o]),d=useCallback(m=>{!t.current||!a.current||t.current.draw(m);},[]),l=useCallback(()=>{if(!t.current||!a.current)return;let m=t.current.stopDrawing();a.current=false,m&&m.points.length>=4&&o(ii(m)),o(Ai()),e?.();},[o,e]);return {lines:i,tool:n,color:r,strokeWidth:s,isSketchMode:u,setCanvasRef:c,startDrawing:f,draw:d,stopDrawing:l}};var $d=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:n,isSketchMode:r,style:s,xOffset:u=0,yOffset:i=0},c)=>{let f=useRef(null),d=useRef(false),l=useRef([]),m=useRef([]),h=useRef(null),p=useRef(t),v=useRef(a),y=useRef(n),b=useRef(r),g=useRef(u),C=useRef(i);useEffect(()=>{p.current=t,v.current=a,y.current=n,b.current=r,g.current=u,C.current=i;},[t,a,n,r,u,i]);let I=useCallback(()=>{let k=f.current;if(!k)return;let x=k.getContext("2d");x&&x.clearRect(0,0,k.width,k.height);},[]),B=useCallback(()=>{let k=f.current,x=m.current;if(!k||x.length<1)return;let S=k.getContext("2d");if(!S)return;if(S.clearRect(0,0,k.width,k.height),p.current==="eraser"?(S.globalCompositeOperation="destination-out",S.fillStyle="rgba(0,0,0,1)"):(S.globalCompositeOperation="source-over",S.fillStyle=v.current),x.length===1){S.beginPath(),S.arc(x[0].x,x[0].y,y.current/2,0,Math.PI*2),S.fill();return}let T=_d(x,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:q=>q,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(T.length<2)){S.beginPath(),S.moveTo(T[0][0],T[0][1]);for(let q=1;q<T.length;q++)S.lineTo(T[q][0],T[q][1]);S.closePath(),S.fill();}},[]);return useImperativeHandle(c,()=>({startDrawing:k=>{d.current=true;let x={x:k.x-g.current,y:k.y-C.current};l.current=[{x:k.x,y:k.y}],m.current=[x],h.current=k,B();},draw:k=>{if(!d.current||!h.current)return;let x=k.x-h.current.x,S=k.y-h.current.y;if(Math.sqrt(x*x+S*S)<2)return;let T={x:k.x-g.current,y:k.y-C.current};l.current.push({x:k.x,y:k.y}),m.current.push(T),h.current=k,B();},stopDrawing:()=>{if(!d.current)return null;if(d.current=false,l.current.length<2)return l.current=[],m.current=[],h.current=null,I(),null;let x=_d(l.current,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:w=>w,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(w=>[w[0],w[1]]),S={tool:p.current,points:x,color:v.current,strokeWidth:y.current,isSketch:true};return l.current=[],m.current=[],h.current=null,I(),S},clear:()=>{I(),l.current=[],m.current=[],h.current=null,d.current=false;},isDrawing:()=>d.current,getCanvasElement:()=>f.current}),[I,B]),useEffect(()=>{let k=f.current;k&&(k.width=e,k.height=o);},[e,o]),jsx("canvas",{ref:f,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});$d.displayName="DirectDrawingCanvas";var Xd=$d;var Zd=e=>{let o=Se(),a=J(ve)?.images||[],n=useRef(new Map),r=useRef(new Map),s=useRef(new Set);useEffect(()=>{let f=new Set(a.map(d=>d.id));s.current.forEach(d=>{if(!f.has(d)){let l=r.current.get(d);l&&(l.src="",r.current.delete(d)),n.current.delete(d);}}),s.current=f;},[a]),useEffect(()=>()=>{r.current.forEach(f=>{f.src="";}),r.current.clear(),n.current.clear();},[]);let u=useCallback(f=>{if(r.current.has(f.id))return r.current.get(f.id);let d=new window.Image;return (f.src.startsWith("http://")||f.src.startsWith("https://"))&&(d.crossOrigin="anonymous"),d.src=f.src,r.current.set(f.id,d),d},[]),i=useCallback((f,d)=>{let l=f.target,m=l.id();a.find(p=>p.id===m)&&(o(Co({id:m,x:l.x(),y:l.y(),width:l.width(),height:l.height(),rotation:l.rotation()})),d?.());},[a,o]),c=useCallback((f,d)=>{let l=d.target,m=n.current.get(f);if(!m){console.error("\u274C Image node not found for id:",f);return}let h=l.scaleX(),p=l.scaleY(),v=l.rotation(),y=m.width(),b=m.height(),g=Math.max(5,y*h),C=Math.max(5,b*p);l.scaleX(1),l.scaleY(1),m.width(g),m.height(C),o(Co({id:f,width:g,height:C,x:l.x(),y:l.y(),rotation:v})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:u,imageRefs:n,handleDragEnd:i,handleImageTransformEnd:c}};var Jd=e=>{let o=useDispatch(),t=useSelector(ve),a=useRef(new Map),n=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((u,i)=>{let c=i.target,f=c.scaleX(),d=c.scaleY(),l=c.rotation();o(gt({id:u,scaleX:f,scaleY:d,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:n,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(u,i)=>{o(gt({id:i,x:u.target.x(),y:u.target.y()})),e?.();}}};var Qd=e=>{let o=useDispatch(),t=useSelector(ve),a=useRef(new Map),n=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((u,i)=>{let c=i.target,f=c.scaleX(),d=c.scaleY(),l=c.rotation(),m=Math.max(5,c.width()*f),h=Math.max(5,c.height()*d);c.scaleX(1),c.scaleY(1),c.width(m),c.height(h),o(ot({id:u,width:m,height:h,x:c.x(),y:c.y(),rotation:l})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:n,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(u,i)=>{o(ot({id:i,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:a}};var eu=e=>{let o=Se(),a=J(ve)?.videos||[],n=useRef(new Map),r=useCallback(i=>{o(Xa(i));},[o]),s=useCallback((i,c)=>{let f=c.target;o(yn({id:i,x:f.x(),y:f.y()})),e?.();},[o,e]),u=useCallback((i,c)=>{let f=c.target,d=f.scaleX(),l=f.scaleY(),m=f.rotation(),h=Math.max(5,f.width()*d),p=Math.max(5,f.height()*l);f.scaleX(1),f.scaleY(1),f.width(h),f.height(p),o(yn({id:i,width:h,height:p,x:f.x(),y:f.y(),rotation:m})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:n,handleVideoClick:r,handleVideoDragEnd:s,handleVideoTransformEnd:u}};var ou=e=>{let o=Se(),a=J(ve)?.shapes||[],n=useRef(new Map),r=useRef(new Map),[s,u]=useState(false),i=useCallback((f,d)=>{let l=d.target;o(Ya({id:f,x:l.x(),y:l.y()})),e?.();},[o,e]),c=useCallback((f,d)=>{let l=d.target,m=a.find(g=>g.id===f);if(!m)return;let h=l.scaleX(),p=l.scaleY(),v=m.type?.toLowerCase();v==="arrow"||v==="line"||(l.scaleX(1),l.scaleY(1));let b={id:f,x:l.x(),y:l.y(),width:Math.max(5,l.width()*h),height:Math.max(5,l.height()*p),rotation:l.rotation()};switch(v){case "circle":b.radius=l.width()*h/2;break;case "star":b.innerRadius=l.width()*h/4,b.outerRadius=l.width()*h/2;break;case "triangle":b.radius=l.width()*h/2;break;case "ellipse":b.radiusX=l.width()*h/2,b.radiusY=l.height()*p/2;break;case "polygon":b.radius=l.width()*h/2;break;case "ring":let g=h;b.innerRadius=m.innerRadius&&m.innerRadius*g,b.outerRadius=m.outerRadius&&m.outerRadius*g;break;case "wedge":b.radius=m.radius&&m.radius*h;break;case "arc":b.innerRadius=m.innerRadius&&m.innerRadius*h,b.outerRadius=m.outerRadius&&m.outerRadius*h;break;case "arrow":case "line":{b.scaleX=h,b.scaleY=p,delete b.width,delete b.height;break}}o(Ya(b)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:n,isDragging:s,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:c}};var nu=(e,o)=>{let t=_e(),n=J(ve)?.texts||[],r=useRef(new Map),[s,u]=useState(null),[i,c]=useState("");return {texts:n,textRefs:r,handleDragEnd:(v,y)=>{let b=v.target;t(de()),t(Ft({id:y,x:b.x(),y:b.y()})),e();},handleTransformEnd:v=>{let y=r.current.get(v);if(!y)return;let b=y.scaleX(),g=y.scaleY(),C=n.find(B=>B.id===v);if(!C)return;let I=(b+g)/2;y.scaleX(1),y.scaleY(1),t(de()),t(Ft({id:v,x:y.x(),y:y.y(),width:Math.max(5,(C.width||100)*b),height:Math.max(5,(C.height||50)*g),fontSize:Math.round(Math.max(8,C.fontSize*I)),rotation:y.rotation()})),e();},handleDoubleClick:v=>{let y=n.find(b=>b.id===v);y&&!y.locked&&(u(v),c(y.text));},startEditing:v=>{let y=n.find(b=>b.id===v);y&&!y.locked&&(u(v),c(y.text));},editingTextId:s,editingValue:i,handleEditingChange:v=>{c(v);},finishEditing:()=>{if(s){let v=r.current.get(s),y=n.find(g=>g.id===s);t(de());let b={id:s,text:i};if(y&&(y.fontWeight!==void 0&&(b.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(b.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(b.textDecoration=y.textDecoration)),o?.current&&i.trim()){let g=o.current,C=g.offsetWidth,I=g.offsetHeight,B=1;if(v){let V=v.getStage();V&&(B=V.scaleX());}let k=14,x=(C-k)/B,S=(I-k)/B,w=i.split(`
|
|
3
|
+
`).length,q=n.find(V=>V.id===s)?.fontSize||24,F=w*q*1.2+10;b.width=Math.max(200,x),b.height=Math.max(50,S,F);}else if(v&&i.trim()){let g=v.text(),C=v.width();v.text(i),v.width(void 0);let I=v.width(),B=v.height();v.text(g),v.width(C),b.width=Math.max(200,I+20),b.height=Math.max(50,B+20);}t(Ft(b)),u(null),c(""),t(vr(null)),e();}}}};var su=e=>{let o=useDispatch(),a=useSelector(ve)?.shortAnswers||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(sa({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:n,handleShortAnswerDragEnd:r}};var iu=e=>{let o=useDispatch(),t=useSelector(ve),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),n=useCallback((r,s)=>{let u=r.target;o(Ja({id:s,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:n}};var du=e=>{let o=Se(),a=J(ve)?.flashcards||[],n=useRef(new Map),r=useRef(new Map),s=useCallback((d,l)=>{if(r.current.has(l))return r.current.get(l);let m=new window.Image;return (d.startsWith("http://")||d.startsWith("https://"))&&(m.crossOrigin="anonymous"),m.src=d,r.current.set(l,m),m},[]),u=useCallback(d=>{let l=d.target,m=l.id();a.find(p=>p.id===m)&&(o(To({id:m,x:l.x(),y:l.y()})),e?.());},[a,o,e]),i=useCallback((d,l)=>{let m=l.target,h=m.scaleX(),p=m.scaleY(),v=m.rotation(),y=Math.max(50,m.width()*h),b=Math.max(50,m.height()*p);m.scaleX(1),m.scaleY(1),m.width(y),m.height(b),o(To({id:d,width:y,height:b,x:m.x(),y:m.y(),rotation:v})),m.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(d=>{o(fi(d)),e?.();},[o,e]),f=useCallback(d=>{o(mi(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:n,handleDragEnd:u,handleFlashcardTransformEnd:i,handleNext:c,handlePrevious:f}};var fu=e=>{let o=Se(),a=J(ve)?.photoFrames||[],n=useRef(new Map),[r,s]=useState(new Map),u=useCallback((m,h)=>{console.log("handleDragEnd"),o(Za({id:h,x:m.target.x(),y:m.target.y()})),e?.();},[o,e]),i=useCallback((m,h)=>{let p=h.target,v=p.scaleX(),y=p.scaleY(),b=p.rotation(),g=a.find(B=>B.id===m);if(!g)return;let C=Math.max(100,g.width*v),I=Math.max(100,g.height*y);p.scaleX(1),p.scaleY(1),o(Za({id:m,width:C,height:I,x:p.x(),y:p.y(),rotation:b})),p.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async m=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(p=>{let v=new Map(p);return v.set(m,h),v}),o(Za({id:m,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),f=useCallback(m=>{let h=r.get(m);h&&(h.getTracks().forEach(p=>p.stop()),s(p=>{let v=new Map(p);return v.delete(m),v}),o(Za({id:m,isCapturing:false})),e?.());},[r,o,e]),d=useCallback((m,h)=>{let p=document.createElement("canvas");p.width=h.videoWidth,p.height=h.videoHeight;let v=p.getContext("2d");if(v){v.drawImage(h,0,0,p.width,p.height);let y=p.toDataURL("image/jpeg",.8);return o(Za({id:m,capturedImageUrl:y,isCapturing:false})),f(m),e?.(),y}return null},[o,f,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(m=>{m.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:n,handleDragEnd:u,handlePhotoFrameTransformEnd:i,startCamera:c,stopCamera:f,capturePhoto:d,cameraStreams:r}};var mu=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,s)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...s,width:Math.max(o.minWidth,Math.min(s.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(s.height,o.maxHeight))}:s,[o]),a=useCallback((r,s,u,i,c,f,d,l=[])=>{if(e.current){if(r&&!l.find(p=>p.id===r)?.isPlaying){let p=s.get(r)||u.get(r)||i.get(r)||c.get(r)||f.get(r)||(d?d.get(r):null);if(p){e.current.boundBoxFunc(t),e.current.nodes([p]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),n=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:n,boundBoxFunc:t}};var lh=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},xu=(e,o)=>{let t=_e(),a=Re(_n),n=useRef(e);useEffect(()=>{n.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(si({id:n.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),s=lh(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var uh=e=>e.flatMap(o=>[o[0],o[1]]),Xn=(e,o)=>{let t=_d(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:a=>a,start:{taper:0,cap:true},end:{taper:0,cap:true}});return uh(t)};var bu=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null),u=J(g=>g.toolbar.selectedTool),i=J(g=>g.toolbar.penColor),c=J(g=>g.toolbar.strokeWidth),f=J(g=>g.canvas.isSketchMode),d=J(g=>g.canvas.slides.find(I=>I.id===g.canvas.currentSlideId)?.images.find(I=>I.id===e)),l=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(g=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,n.current=[{x:g.x,y:g.y}];let C=g.x/h,I=g.y/p;s({tool:u,points:[C,I],color:i,strokeWidth:c/h,isSketch:f});},[u,i,c,f,h,p]),y=useCallback(g=>{if(!t.current||!r)return;a.current=true;let C=n.current[n.current.length-1];if(Math.sqrt(Math.pow(g.x-C.x,2)+Math.pow(g.y-C.y,2))<2)return;n.current.push({x:g.x,y:g.y});let B;if(f)B=Xn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,S)=>S%2===0?x/h:x/p);else {let k=g.x/h,x=g.y/p;B=[...r.points,k,x];}s(k=>k?{...k,points:B}:null);},[f,c,r,h,p]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(gi({imageId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:m,startDrawing:v,draw:y,stopDrawing:b,tool:u}};function Ve({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),n=useRef(null);return {createHandlers:useCallback((s,u)=>({onTouchStart:i=>{let c=i.evt.touches[0];n.current={x:c.clientX,y:c.clientY},a.current=setTimeout(()=>{e(s,u)(i.evt);},o);},onTouchMove:i=>{if(!n.current)return;let c=i.evt.touches[0],f=Math.abs(c.clientX-n.current.x),d=Math.abs(c.clientY-n.current.y);(f>t||d>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),n.current=null;}}),[e,o,t])}}var Lu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u})=>{let{annotations:i,activeLine:c,stopDrawing:l,tool:m}=bu(e.id),{createHandlers:h}=Ve({onLongPress:u});useEffect(()=>{let g=t.current.get(e.id);g&&(g.width()!==e.width||g.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:g.width(),konvaHeight:g.height()}),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[l,p]);let v=g=>{{r(e.id);return}},y=g=>{return;},b=g=>{};return jsxs(Group,{listening:m!=="pen"&&m!=="eraser",children:[jsx(Image$1,{id:e.id,ref:g=>{if(g)t.current.set(e.id,g),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw();else {let C=t.current.get(e.id);C?._contextMenuCleanup&&C._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:m!=="pen"&&m!=="eraser",onDragEnd:a,onTransformEnd:g=>n(e.id,g),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:g=>{g.evt.preventDefault();let C=g.evt;s(C,e.id,"image");},...m!=="pen"&&m!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onMouseMove:y,onMouseUp:b,...h(e.id,"image")}:{}}),i?.map((g,C)=>{let I=g.points.map((k,x)=>x%2===0?k*e.width+e.x:k*e.height+e.y),B=g.strokeWidth*e.width;return jsx(Line,{points:I,stroke:g.tool==="eraser"?"white":g.color,strokeWidth:B,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:g.tool==="eraser"?"destination-out":"source-over",fill:g.isSketch?g.color:void 0,closed:g.isSketch,listening:false},C)}),c&&jsx(Line,{points:c.points.map((g,C)=>C%2===0?g*e.width+e.x:g*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});Lu.displayName="ImageWithDrawing";var Ui=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u})=>jsx(Fragment,{children:e.map(i=>{let c=o(i);return c?jsx(Lu,{img:i,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:n,onSelect:r,onContextMenu:s,onLongPress:u},i.id):null})}));Ui.displayName="ImageLayer";var wh=({src:e,x:o,id:t,y:a,width:n,height:r,isSelected:s,rotation:u=0,onTransformEnd:i,onDragEnd:c})=>{let f=Se(),d=useRef(null),l=m=>{f(Xa(m));};return jsxs(Group,{draggable:true,x:o,y:a,width:n,height:r,rotation:u,onDragEnd:c,onTransformEnd:i,children:[jsx(Rect,{width:n,height:r,fill:"black",stroke:s?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${n}px`,height:`${r}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>l(t),onSeeking:m=>m.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Iu=wh;var Ah=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,nodeRef:s})=>{let[u,i]=useState(null),c=useSelector(p=>p.toolbar.selectedTool),f=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let p=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(p.crossOrigin="anonymous"),p.src=e.thumbnailDataUrl,p.onload=()=>{i(p);};}},[e.thumbnailDataUrl]),!u)return null;let d=e.width/2,l=e.height/2,m=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(m,80));return jsxs(Group,{draggable:!f,listening:!f,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...f?{}:{onDragEnd:a,onTransformEnd:n},ref:p=>{if(s(p),p){let v=p.getStage()?.container();if(v){let y=b=>{let g=p.getStage()?.getPointerPosition();if(g){let C={x:e.x,y:e.y,width:e.width,height:e.height};g.x>=C.x&&g.x<=C.x+C.width&&g.y>=C.y&&g.y<=C.y+C.height&&r(b);}};v.addEventListener("contextmenu",y),p._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",y);};}}},children:[jsx(Image$1,{image:u,width:e.width,height:e.height,listening:!f,...f?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:d,y:l,radius:h,fill:"white",listening:!f,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...f?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:l,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!f,...f?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:l,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!f,...f?{}:{onClick:t,onTap:t}})]})},ku=Ah;var ji=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:n,onTransformEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(u=>jsxs(Le__default.Fragment,{children:[jsx(ku,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>a(u.id),onDragEnd:i=>n(u.id,i),onTransformEnd:i=>r(u.id,i),onContextMenu:i=>s(i,u.id,"video"),nodeRef:i=>{i?t.current.set(u.id,i):t.current.delete(u.id);}}),u.isPlaying&&!u.isRecorded&&jsx(Iu,{id:u.id,src:u.objectUrl,x:u.x,y:u.y,width:u.width,height:u.height,isSelected:false,rotation:u.rotation,onTransformEnd:i=>r(u.id,i),onDragEnd:i=>n(u.id,i)})]},u.id))}));ji.displayName="VideoLayer";var _i=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:n,handleShapeDragStart:r,onContextMenu:s,onLongPress:u})=>{let i=useSelector(d=>d.toolbar.selectedTool),c=i==="pen"||i==="eraser",{createHandlers:f}=Ve({onLongPress:u});return jsx(Fragment,{children:e.map((d,l)=>{let m=d.id||l,h={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!c,listening:!c,fill:d.color||"#096B76",stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?2:0,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radius:d.radius||d.width/2,width:d.width,height:d.width},m);case "star":return jsx(Star,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},m);case "triangle":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},sides:3,radius:d.radius||d.width/2},m);case "polygon":return jsx(RegularPolygon,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},sides:d.sides||6,radius:d.radius||d.width/2},m);case "ellipse":return jsx(Ellipse,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},m);case "ring":return jsx(Ring,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},m);case "wedge":return jsx(Wedge,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},radius:d.radius||d.width/2,angle:d.angle||60},m);case "arrow":return jsx(Arrow,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?d.strokeWidth||3:0,fill:"transparent"},m);case "line":return jsx(Line,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},points:d.points||[0,0,d.width,0],stroke:d.hasBorder!==false?"#000000":"transparent",strokeWidth:d.hasBorder!==false?d.strokeWidth||3:0,fill:"transparent"},m);case "arc":return jsx(Arc,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},m);case "rectangle":default:return jsx(Rect,{ref:p=>{p?o.current.set(d.id,p):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:p=>{r?.();},onDragEnd:p=>t(d.id,p),onTransformEnd:p=>a(d.id,p),onClick:()=>n(d.id),onContextMenu:p=>{p.evt.preventDefault(),s(p.evt,d.id,"shape");},...f(d.id,"shape")},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},m)}})})});_i.displayName="ShapeLayer";var Au=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:n,onContextMenu:r,onDoubleClick:s,editingTextId:u,onLongPress:i})=>{useEffect(()=>{e.forEach(l=>{let m=o.current.get(l.id);m&&(m.cache(),m.getLayer()?.batchDraw());});},[e,o]);let c=useSelector(l=>l.toolbar.selectedTool),f=c==="pen"||c==="eraser",{createHandlers:d}=Ve({onLongPress:i});return jsx(Fragment,{children:e.map(l=>{let m=l.id===u,h=l.fontWeight==="bold",p=h?Math.max(1,l.fontSize/25):0;return jsx(Text,{id:l.id,ref:v=>{v?o.current.set(l.id,v):o.current.delete(l.id);},text:l.text,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:!l.locked&&!m&&!f,listening:!f,fontSize:l.fontSize,fontFamily:l.fontFamily,fontStyle:l.fontStyle,fontWeight:l.fontWeight,textDecoration:l.textDecoration,fill:l.fill,stroke:h?l.fill:void 0,strokeWidth:p,align:l.align,wrap:"word",lineHeight:1.2,opacity:m?0:1,visible:!m,...f?{}:{onClick:()=>n(l.id),onTap:()=>n(l.id),onDblClick:()=>s(l.id),onDblTap:()=>s(l.id),onDragEnd:v=>t(v,l.id),onTransformEnd:()=>a(l.id),onContextMenu:v=>{v.evt.preventDefault();let y=v.evt;r(y,l.id,"text");},...d(l.id,"text")}},l.id)})})};var tg=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onNext:s,onPrevious:u,nodeRef:i,touchHandlers:c,currentTool:f})=>{let[d,l]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let b=new window.Image,g=e.images[e.currentIndex];(g.startsWith("http://")||g.startsWith("https://"))&&(b.crossOrigin="anonymous"),b.src=g,b.onload=()=>{l(b);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let m=8,h=2,p=Math.min(e.width,e.height)*.08,v=Math.max(16,Math.min(p,32)),y=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked&&f==="select",x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:n,...c,ref:b=>{if(i(b),b){let g=b.getStage()?.container();if(g){let C=I=>{let B=b.getStage()?.getPointerPosition();if(B){let k={x:e.x,y:e.y,width:e.width,height:e.height};B.x>=k.x&&B.x<=k.x+k.width&&B.y>=k.y&&B.y<=k.y+k.height&&r(I);}};g.addEventListener("contextmenu",C),b._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",C);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:m,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:m,stroke:"#E5E7EB",strokeWidth:h,listening:false}),jsx(Image$1,{x:h+4,y:h+4,image:d,width:e.width-(h+4)*2,height:e.height-(h+4)*2,cornerRadius:m-h,onClick:t,onTap:t}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:y+v,y:e.height/2,onClick:b=>{b.cancelBubble=true,u();},onTap:b=>{b.cancelBubble=true,u();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-y-v,y:e.height/2,onClick:b=>{b.cancelBubble=true,s();},onTap:b=>{b.cancelBubble=true,s();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Du=tg;var Zi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onNext:s,onPrevious:u,onContextMenu:i,onLongPress:c})=>{let{createHandlers:f}=Ve({onLongPress:c}),d=J(l=>l.toolbar.selectedTool);return jsx(Fragment,{children:e.map(l=>jsx(Du,{flashcard:l,isSelected:t===l.id,onClick:()=>r(l.id),currentTool:d,onDragEnd:a,onTransformEnd:m=>n(l.id,m),onContextMenu:m=>i(m,l.id,"flashcard"),onNext:()=>s(l.id),onPrevious:()=>u(l.id),touchHandlers:f(l.id,"flashcard"),nodeRef:m=>{m?o.current.set(l.id,m):o.current.delete(l.id);}},l.id))})});Zi.displayName="FlashcardLayer";var Fu=e=>{let o=Se(),t=useRef(false),a=useRef(false),n=useRef([]),[r,s]=useState(null);J(g=>g.toolbar.selectedTool);let i=J(g=>g.toolbar.penColor),c=J(g=>g.toolbar.strokeWidth),f=J(g=>g.canvas.isSketchMode),d=J(g=>g.canvas.slides.find(I=>I.id===g.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),l=d?.annotations||[],m=d?.isDrawingMode||false,h=d?.width||1,p=d?.height||1,v=useCallback(g=>{if(!m)return;t.current=true,a.current=false,n.current=[{x:g.x,y:g.y}];let C=g.x/h,I=g.y/p;s({tool:"pen",points:[C,I],color:i,strokeWidth:c/h,isSketch:f});},[m,i,c,f,h,p]),y=useCallback(g=>{if(!t.current||!r)return;a.current=true;let C=n.current[n.current.length-1];if(Math.sqrt(Math.pow(g.x-C.x,2)+Math.pow(g.y-C.y,2))<2)return;n.current.push({x:g.x,y:g.y});let B;if(f)B=Xn(n.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,S)=>S%2===0?x/h:x/p);else {let k=g.x/h,x=g.y/p;B=[...r.points,k,x];}s(k=>k?{...k,points:B}:null);},[f,c,r,h,p]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(bi({frameId:e,line:r})),s(null),t.current=false,a.current=false,n.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:m,startDrawing:v,draw:y,stopDrawing:b}};var dg=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:n,onContextMenu:r,onStartCamera:s,onCapture:u,cameraStream:i,nodeRef:c,touchHandlers:f})=>{let[d,l]=useState(null),[m,h]=useState(null),p=useRef(null),v=useRef(null),y=useRef(null),b=useRef(null),g=useRef(0),C=33,I=useSelector(P=>P.toolbar.selectedTool),B=I==="pen"||I==="eraser",{annotations:k,activeLine:x,isDrawingMode:S,startDrawing:w,draw:T,stopDrawing:q}=Fu(e.id);useEffect(()=>{if(!S)return;let P=()=>{q();},N=()=>{q();};return window.addEventListener("mouseup",P),window.addEventListener("touchend",N),()=>{window.removeEventListener("mouseup",P),window.removeEventListener("touchend",N);}},[q,S]),useEffect(()=>{if(e.capturedImageUrl){let P=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(P.crossOrigin="anonymous"),P.src=e.capturedImageUrl,P.onload=()=>{l(P);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),v.current||(v.current=document.createElement("canvas"));let P=p.current,N=v.current;P.srcObject=i;let _=()=>{N.width=P.videoWidth||640,N.height=P.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",N.width,N.height);let Q=re=>{if(re-g.current<C){y.current=requestAnimationFrame(Q);return}g.current=re;let j=N.getContext("2d");if(j&&P.readyState===P.HAVE_ENOUGH_DATA){j.drawImage(P,0,0,N.width,N.height);let pe=N.toDataURL("image/jpeg",.6),ge=new window.Image;ge.onload=()=>{h(ge);},ge.src=pe;}y.current=requestAnimationFrame(Q);};y.current=requestAnimationFrame(Q);};return P.onloadedmetadata=_,P.readyState>=P.HAVE_METADATA&&_(),P.play().catch(Q=>console.error("Error playing video:",Q)),()=>{y.current&&(cancelAnimationFrame(y.current),y.current=null);}}return ()=>{h(null),b.current&&(b.current.src="");}},[e.isCapturing,i]);let H=()=>{p.current&&e.isCapturing&&u(p.current);},F=P=>{if(e.capturedImageUrl){if(!S){t();return}let N=P.currentTarget,_=N.getAbsoluteTransform().copy(),re=N.getStage()?.getPointerPosition();if(re){_.invert();let j=_.point(re);w(j);}P.cancelBubble=true;}else t();},V=P=>{if(!S||!e.capturedImageUrl)return;let N=P.currentTarget,_=N.getAbsoluteTransform().copy(),re=N.getStage()?.getPointerPosition();if(re){_.invert();let j=_.point(re);T(j);}},U=()=>{!S||!e.capturedImageUrl||q();},K=e.isCapturing?m:d,R=Math.min(e.width,e.height)*.12,z=Math.max(25,Math.min(R,50)),ne=e.width/2,X=e.height/2;return jsxs(Group,{id:e.id,draggable:!S&&!B,listening:true,onClick:t,onTap:t,x:e.x,y:e.y,...f,...B?{}:{onDragEnd:a,onTransformEnd:n},rotation:e.rotation,width:e.width,height:e.height,ref:P=>{if(c(P),P){let N=P.getStage()?.container();if(N){let _=Q=>{let re=P.getStage()?.getPointerPosition();if(re){let j={x:e.x,y:e.y,width:e.width,height:e.height};re.x>=j.x&&re.x<=j.x+j.width&&re.y>=j.y&&re.y<=j.y+j.height&&r(Q);}};N.addEventListener("contextmenu",_),P._contextMenuCleanup=()=>{N.removeEventListener("contextmenu",_);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:K?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),K&&jsx(Image$1,{image:K,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:F,onTap:F,onMouseDown:F,onTouchStart:F,onMouseMove:V,onTouchMove:V,onMouseUp:U,onTouchEnd:U,...B?{}:{onDragEnd:a,onTransformEnd:n}}),k?.map((P,N)=>{let _=P.points.map((re,j)=>j%2===0?re*e.width:re*e.height),Q=P.strokeWidth*e.width;return jsx(Line,{points:_,stroke:P.tool==="eraser"?"white":P.color,strokeWidth:Q,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:P.tool==="eraser"?"destination-out":"source-over",fill:P.isSketch?P.color:void 0,closed:P.isSketch,listening:false},N)}),x&&jsx(Line,{points:x.points.map((P,N)=>N%2===0?P*e.width:P*e.height),stroke:x.tool==="eraser"?"white":x.color,strokeWidth:x.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},"active"),!K&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:X-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:ne-z+6,y:X-60,width:z*1.6,height:z*1.6,radius:z,fill:"white",cornerRadius:8,listening:true,onClick:P=>{P.cancelBubble=true,e.isCapturing?H():s();},onTap:P=>{P.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:ne-12,y:X-40,width:z*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:P=>{P.stopPropagation(),e.isCapturing?H():s();}})})]}),jsx(Text,{x:0,y:X,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:X+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:ne-24,y:X+104,width:z*1.6,height:z*1.6,radius:z,fill:"#096B76",cornerRadius:z,listening:true,onClick:P=>{P.cancelBubble=true,e.isCapturing?H():s();},onTap:P=>{P.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:ne-8,y:X+120,width:z*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:P=>{P.stopPropagation(),e.isCapturing?H():s();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:ne-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:P=>{P.stopPropagation(),H();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},Hu=dg;var ol=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:n,onSelect:r,onStartCamera:s,onCapture:u,cameraStreams:i,onContextMenu:c,onLongPress:f})=>{let{createHandlers:d}=Ve({onLongPress:f});return jsx(Fragment,{children:e.map(l=>jsx(Hu,{photoFrame:l,isSelected:t===l.id,onClick:()=>r(l.id),onDragEnd:m=>a(m,l.id),onContextMenu:m=>c(m,l.id,"photoFrame"),onStartCamera:()=>s(l.id),onCapture:m=>u(l.id,m),cameraStream:i.get(l.id),touchHandlers:d(l.id,"photoFrame"),nodeRef:m=>{m?o.current.set(l.id,m):o.current.delete(l.id);}},l.id))})});ol.displayName="PhotoFrameLayer";var Wu=({x:e,y:o,onAction:t,onClose:a,type:n,isDrawingMode:r,menuRef:s})=>{useEffect(()=>{let f=l=>{s?.current&&!s.current.contains(l.target)&&a();},d=l=>{l.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",d);}},[a]);let u=useMemo(()=>[{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"border",label:"Toggle Border",icon:jsx(FrameCorners,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"draw",label:r?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line","video"]},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(d=>!(d.showForTypes&&!d.showForTypes.includes(n)||d.hideForTypes&&d.hideForTypes.includes(n))),[n,r]),i=(f,d)=>{f==="order"||f==="lock"?t(f,d):(t(f),a());},c=jsx("div",{ref:s,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:u.map((f,d)=>jsxs("button",{onClick:l=>i(f.action,l),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${f.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[f.icon,jsx("span",{className:`font-medium ${f.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:f.label})]}),f.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},d))})});return createPortal(c,document.body)};var Uu=({x:e,y:o,items:t,onClose:a})=>{let n=useRef(null);return useEffect(()=>{let r=s=>{n.current&&!n.current.contains(s.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:n,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((r,s)=>jsx("button",{onClick:()=>{r.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:r.label})},s))})})};var Gu=createContext(null),rl=()=>useContext(Gu);function Pg({children:e,className:o="",style:t}){let a=useRef(null),[n,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Gu.Provider,{value:n,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function ze(){let e=rl();return typeof document>"u"?null:e||document.body}var ju=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:n,onClose:r})=>{let[s,u]=useState(a),i=useRef(null),c=ze();useEffect(()=>{i.current?.focus();},[]);let f=()=>{n(s),r();},d=m=>{m.key==="Enter"?f():m.key==="Escape"&&r();};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:i,type:"text",value:s,onChange:m=>u(m.target.value),onKeyDown:d,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:r,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:f,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),c):null};var es=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,n]=useState(e),r=useRef(null),s=ze();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let u=d=>{d.preventDefault(),o(a);},i=(d,l,m)=>{m/=100;let h=l*Math.min(m,1-m)/100,p=v=>{let y=(v+d/30)%12,b=m-h*Math.max(Math.min(y-3,9-y,1),-1);return Math.round(255*b).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!s)return null;let f=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:r,className:"max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:u,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:d=>n(d.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:d=>n(d.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:d=>{let l=parseInt(d.target.value),m=i(l,100,50);n(m);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(d=>jsx("button",{type:"button",onClick:()=>n(d),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===d.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:d},title:d},d))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(f,s)};var Xg=({imageSrc:e,onCrop:o})=>{let[t]=Xu(e),a=useRef(null),n=useRef(null),r=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),u=useMemo(()=>{let l=s.width*.5,m=s.height*.5,h=(s.width-l)/2,p=(s.height-m)/2;return {x:h,y:p,width:l,height:m}},[s]),[i,c]=useState(u);useEffect(()=>{c(u);},[u]),useEffect(()=>{r.current&&n.current&&(r.current.nodes([n.current]),r.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let f=()=>{let l=n.current;if(!l)return;let m=l.scaleX(),h=l.scaleY();l.scaleX(1),l.scaleY(1),c({x:l.x(),y:l.y(),width:Math.max(20,l.width()*m),height:Math.max(20,l.height()*h)});},d=()=>{let l=n.current;l&&c({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:s.width,height:s.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:s.width,height:s.height}),jsx(Rect,{x:0,y:0,width:s.width,height:s.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:n,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:f,dragBoundFunc:l=>{let m=Math.max(0,Math.min(l.x,s.width-i.width)),h=Math.max(0,Math.min(l.y,s.height-i.height));return {x:m,y:h}}}),jsx(Transformer,{ref:r,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(l,m)=>m.width<20||m.height<20||m.x<0||m.y<0||m.x+m.width>s.width||m.y+m.height>s.height?l:m})]})})},Yu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[n,r]=useState({x:0,y:0,width:0,height:0}),[s]=Xu(e),u=ze();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let i=(d,l,m,h)=>{r({x:d,y:l,width:m,height:h});},c=()=>{if(!s)return;let m=Math.min(600/s.width,400/s.height),h=n.x/m,p=n.y/m,v=n.width/m,y=n.height/m,b=document.createElement("canvas");b.width=v,b.height=y;let g=b.getContext("2d");if(!g)return;g.drawImage(s,h,p,v,y,0,0,v,y);let C=b.toDataURL("image/png");o(C);};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(Xg,{imageSrc:e,onCrop:i})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:c,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),u):null};var eo=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let n=ze(),[r,s]=useState(false),[u,i]=useState(null),[c,f]=useState(0),[d,l]=useState(true),m=useRef(null),h=useRef([]),p=useRef(null),v=useRef(null),y=useRef(null),b=useRef(null),g=useRef(null),C=useRef(null);useEffect(()=>()=>{y.current&&cancelAnimationFrame(y.current),p.current&&clearInterval(p.current),v.current&&v.current.getTracks().forEach(w=>w.stop());},[]);let I=async()=>{try{let w,T=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let U=o.current.getLayers();console.log("Konva layers:",U.length),U.forEach((_,Q)=>{let re=_.getChildren();console.log(`Layer ${Q} children count:`,re.length);});let K=document.createElement("canvas");K.width=o.current.width(),K.height=o.current.height();let R=K.getContext("2d",{willReadFrequently:!1});if(!R){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",K.width,"x",K.height),g.current=K;let z=()=>{if(R.clearRect(0,0,K.width,K.height),U.forEach(_=>{let Q=_.getCanvas()._canvas;Q&&R.drawImage(Q,0,0);}),a?.current){let _=a.current;R.drawImage(_,0,0);}};C.current=z,o.current.draw(),z(),await new Promise(_=>setTimeout(_,100)),console.log("Creating captureStream..."),w=K.captureStream(30),console.log("Canvas stream created, tracks:",w.getTracks().length);let X=w.getVideoTracks()[0];X&&console.log("Video track:",X.label,"state:",X.readyState);let P=0,N=()=>{z(),o?.current&&(o.current.getLayers().forEach(Q=>{Q.batchDraw();}),P++,P%60===0&&console.log("Drawing frame:",P)),y.current=requestAnimationFrame(N);};N();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{T=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let q=[...w.getVideoTracks()];T&&q.push(...T.getAudioTracks());let H=new MediaStream(q);v.current=H;let F="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?F="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?F="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?F="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(F="video/webm;codecs=vp8"),console.log("Using mimeType:",F);let V=new MediaRecorder(H,{mimeType:F,videoBitsPerSecond:25e5});m.current=V,h.current=[],V.ondataavailable=U=>{console.log("Data available, size:",U.data.size),U.data.size>0&&h.current.push(U.data);},V.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let U=new Blob(h.current,{type:F});console.log("Final blob size:",U.size),o?.current&&C.current&&g.current&&(o.current.draw(),o.current.getLayers().forEach(R=>{R.batchDraw();}),C.current(),b.current=g.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",b.current.length)),H.getTracks().forEach(K=>K.stop()),p.current&&clearInterval(p.current),y.current&&(cancelAnimationFrame(y.current),y.current=null),i(U);},V.onerror=U=>{console.error("MediaRecorder error:",U);},console.log("Starting recording..."),V.start(1e3),s(!0),f(0),p.current=setInterval(()=>{f(U=>U+1);},1e3);}catch(w){console.error("Error starting screen recording:",w),alert("Failed to start recording. Please ensure you granted permission.");}},B=()=>{m.current&&r&&(console.log("Stopping recording, state:",m.current.state),m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),s(false));},k=()=>{if(u){let w=URL.createObjectURL(u),T=document.createElement("a");T.href=w,T.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(w);}},x=w=>{let T=Math.floor(w/60),q=w%60;return `${T.toString().padStart(2,"0")}:${q.toString().padStart(2,"0")}`};if(!n)return null;if(r){let w=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:x(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:B,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(w,n)}let S=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!u&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>l(!d),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${d?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:d?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:I,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),u&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(u),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",x(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&b.current&&(t(u,b.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:k,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),f(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})});return createPortal(S,n)};var ec=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:n})=>{let r=ze(),[s,u]=useState(false),[i,c]=useState(null),[f,d]=useState(false),[l,m]=useState(0),h=useRef(null),p=useRef([]),v=useRef(null),y=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(w=>w.blob()).then(w=>c(w)).catch(w=>console.error("Error loading audio:",w));},[o,i]);let b=async()=>{try{let w=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),T=new MediaRecorder(w);h.current=T,p.current=[],T.ondataavailable=q=>{q.data.size>0&&p.current.push(q.data);},T.onstop=()=>{let q=new Blob(p.current,{type:"audio/webm"});c(q),w.getTracks().forEach(H=>H.stop()),v.current&&clearInterval(v.current);},T.start(),u(!0),m(0),v.current=setInterval(()=>{m(q=>q+1);},1e3);}catch(w){console.error("Error starting audio recording:",w),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{h.current&&s&&(h.current.stop(),u(false));},C=()=>{if(i){let w=URL.createObjectURL(i),T=new Audio(w);y.current=T,T.onended=()=>{d(false),URL.revokeObjectURL(w);},T.play(),d(true);}},I=()=>{y.current&&(y.current.pause(),y.current.currentTime=0,d(false));},B=async()=>{if(i){let w=new FileReader;w.onloadend=()=>{let T=w.result;t(T),n();},w.readAsDataURL(i);}},k=()=>{c(null),a();},x=w=>{let T=Math.floor(w/60),q=w%60;return `${T.toString().padStart(2,"0")}:${q.toString().padStart(2,"0")}`};if(!r)return null;if(s){let w=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:x(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:g,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(w,r)}let S=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:b,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:f?I:C,className:"flex w-full cursor-pointer items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),f?"Playing...":"Play Audio"]}),jsxs("button",{onClick:k,className:"flex w-full cursor-pointer items-center gap-2 rounded-lg border border-red-300 bg-red-600 px-4 py-3 text-white transition-colors hover:bg-red-700",children:[jsx(Trash,{className:"h-5 w-5",weight:"fill"}),"Delete Audio"]})]}),jsx("button",{onClick:B,className:"w-full cursor-pointer rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:n,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})});return createPortal(S,r)};var Nt=({audioData:e,x:o,y:t,width:a,scale:n=1,offsetX:r=0,offsetY:s=0,containerTop:u=90,containerRight:i=320})=>{let[c,f]=useState(false),d=useRef(null),l=p=>{if(p.stopPropagation(),c&&d.current)d.current.pause(),d.current.currentTime=0,f(false);else {let v=new Audio(e);d.current=v,v.onended=()=>{f(false);},v.onerror=()=>{console.error("Error playing audio"),f(false);},v.play(),f(true);}},m=(o+a)*n+r-15,h=t*n+s+u-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${c?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${m}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var oc=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=Se(),n=J(ve),r=ze(),s=useMemo(()=>{if(!n)return [];let y=[];return n.images?.forEach(b=>{y.push({id:b.id,type:"image",name:"Image",timestamp:b.timestamp||0});}),n.videos?.forEach(b=>{y.push({id:b.id,type:"video",name:"Video",timestamp:b.timestamp||0});}),n.shapes?.forEach(b=>{y.push({id:b.id,type:"shape",name:`${b.type} Shape`,timestamp:b.timestamp||0});}),n.texts?.forEach(b=>{y.push({id:b.id,type:"text",name:b.text.substring(0,20)+(b.text.length>20?"...":""),timestamp:b.timestamp||0});}),n.flashcards?.forEach(b=>{y.push({id:b.id,type:"flashcard",name:`Flashcard (${b.images.length} images)`,timestamp:b.timestamp||0});}),n.photoFrames?.forEach(b=>{y.push({id:b.id,type:"photoFrame",name:"Photo Frame",timestamp:b.timestamp||0});}),n.multipleChoices?.forEach(b=>{y.push({id:b.id,type:"mcq",name:"Multiple Choice",timestamp:b.timestamp||0});}),n.trueFalses?.forEach(b=>{y.push({id:b.id,type:"trueFalse",name:"True/False",timestamp:b.timestamp||0});}),n.shortAnswers?.forEach(b=>{y.push({id:b.id,type:"shortAnswer",name:"Short Answer",timestamp:b.timestamp||0});}),n.LongAnswer?.forEach(b=>{y.push({id:b.id,type:"longAnswer",name:"Long Answer",timestamp:b.timestamp||0});}),n.fillInTheBlanks?.forEach(b=>{y.push({id:b.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:b.timestamp||0});}),n.lines?.forEach(b=>{b.id&&y.push({id:b.id,type:"line",name:"Drawn Line",timestamp:b.timestamp||0});}),y.sort((b,g)=>g.timestamp-b.timestamp)},[n]),[u,i]=useState(s),[c,f]=useState(false);useEffect(()=>{c||i(s);},[s]);let d=y=>{let b="h-5 w-5";switch(y){case "image":return jsx(Image$3,{className:b});case "video":return jsx(VideoCamera,{className:b});case "shape":return jsx(Shapes$1,{className:b});case "text":return jsx(TextT,{className:b});case "flashcard":return jsx(Cards$1,{className:b});case "photoFrame":return jsx(FrameCorners$1,{className:b});case "line":return jsx(Pen,{className:b});default:return jsx(Question,{className:b})}},h=y=>{f(true),i(y);},p=()=>{f(false);let y=Date.now();u.forEach((b,g)=>{let C=y-g;a(xr({id:b.id,type:b.type,newTimestamp:C}));});};if(!r)return null;let v=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-50 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-50 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:u.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:u,onReorder:h,className:"space-y-1",children:u.map(y=>{let b=y.id===e;return jsxs(Reorder.Item,{value:y,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${b?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(y.id,y.type),className:`font-medium ${b?"text-[#096B76]":"text-[#00000099]"}`,children:y.name})}),jsx("div",{className:`${b?"text-[#096B76]":"text-[#00000099]"}`,children:d(y.type)})]},y.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[u.length," Layers"]})]})]})]});return createPortal(v,r)};var ss=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},rc=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,touchHandlers:s,onUpdate:u})=>{let i=useSelector(F=>F.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(null),l=e.data.responseOptions.attempts||0,m=useRef(null),h=useDispatch(),[p,v]=useState(new Set(e.data.responseOptions.selectedIndices||[])),[y,b]=useState(false);useEffect(()=>{let F=m.current;if(F)return a.current.set(e.id,F),()=>{a.current.delete(e.id);}},[e.id,a]);let g=new Set(e.data.responseOptions.correctIndex),C=g.size>1,I=F=>{if(y)return;let V;C?(V=new Set(p),V.has(F)?V.delete(F):V.add(F)):V=new Set([F]),v(V);let U=Array.from(V),K=U.length===e.data.responseOptions.correctIndex.length&&U.every(R=>e.data.responseOptions.correctIndex.includes(R));h(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:U,isCorrect:K}}})),u?.();},B=()=>{p.size>0&&(b(true),h(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},k=()=>{b(false),v(new Set);},x=p.size===g.size&&Array.from(p).every(F=>g.has(F)),S=Array.from(p).filter(F=>g.has(F)),w=C&&S.length>0&&!x,T=()=>x?"\u2713 Correct! Great job! \u{1F389}":w?`\u26A0 Partially correct (${S.length}/${g.size})`:"\u2717 Try again!",q=()=>x?{bg:"#dcfce7",text:"#166534"}:w?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},H=useMemo(()=>{let X=e.data.feedbackMode==="practice"?48:0,P=12,N=e.width-48,_=N-80,Q=Math.max(60,ss(e.data.question,20,N,"bold")+20),re=`Select ${g.size} answers (${p.size}/${g.size} selected)`,j=C&&!y&&e.data.feedbackMode==="practice"?ss(re,14,N)+10:0,pe=y&&e.data.feedbackMode==="practice"?Math.max(60,ss(T(),16,N-40)+30):0,ge=e.data.responseOptions.options.map(xe=>{let St=ss(xe,16,_);return Math.max(55,St+20)}),le=Q+j+pe,ye=ge.reduce((xe,St)=>xe+St+8,-8),we=le+ye+P+X+24;return {padding:24,questionHeight:Q,instructionHeight:j,feedbackHeight:pe,optionsStartY:le,optionHeights:ge,totalHeight:we,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:X,buttonTopMargin:P,availableWidth:N,optionTextWidth:_}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,y,p.size,g.size,C,T]);return jsxs(Group,{ref:m,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:H.totalHeight,onTransformEnd:F=>o(e.id,F),...s,...c?{}:{onDragEnd:n,onClick:F=>t&&t(e.id),onTap:F=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:H.totalHeight,width:e.width,onContextMenu:F=>{F.cancelBubble=true,r(F.evt,e.id,"mcq");}}),jsx(Text,{x:H.padding+8,y:H.padding,text:e.data.question,fontSize:H.questionFontSize,fontStyle:"bold",fill:"#111827",width:H.availableWidth,height:H.questionHeight-H.padding,wrap:"word",ellipsis:true,listening:false}),H.instructionHeight>0&&jsx(Text,{x:H.padding,y:H.questionHeight,text:`Select ${g.size} answers (${p.size}/${g.size} selected)`,fontSize:H.instructionFontSize,fill:"#6b7280",width:H.availableWidth,wrap:"word",listening:false}),y&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:H.padding+24,y:H.questionHeight+H.instructionHeight+10,width:H.availableWidth-40,height:H.feedbackHeight-20,fill:q().bg,cornerRadius:8}),jsx(Text,{x:H.padding+24,y:H.questionHeight+H.instructionHeight+10,width:H.availableWidth-40,height:H.feedbackHeight-20,text:T()+` (${l} attempts)`,fontSize:H.feedbackFontSize,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((F,V)=>{let U=g.has(V),K=p.has(V),R=H.optionsStartY;for(let N=0;N<V;N++)R+=H.optionHeights[N]+H.optionGap;let z=H.optionHeights[V],ne="#e5e7eb",X="#ffffff",P="#111827";return y&&K&&!U?(ne="#ef4444",X="#fee2e2",P="#ef4444"):K&&(ne="#096B76",X="#ECFFF8",P="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:H.padding+12,y:R+(z-20)/2,width:20,height:20,fill:K?"#096B76":"white",stroke:K?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:C?4:10,onClick:N=>{N.cancelBubble=true,I(V);},onTap:N=>{N.cancelBubble=true,I(V);}}),K&&jsx(Text,{x:H.padding+12,y:R+(z-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:H.padding+44,y:R,width:H.availableWidth-60,height:z,fill:X,stroke:ne,strokeWidth:2,cornerRadius:8,onClick:N=>{N.cancelBubble=true,I(V);},onTap:N=>{N.cancelBubble=true,I(V);}}),jsx(Text,{x:H.padding+60,y:R+10,width:H.optionTextWidth,height:z-20,text:F,fontSize:H.optionFontSize,fill:P,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},V)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:H.optionsStartY+H.optionHeights.reduce((F,V)=>F+V+H.optionGap,-H.optionGap)+H.buttonTopMargin,children:[jsxs(Group,{onMouseDown:F=>{F.cancelBubble=true,d("check");},onMouseUp:F=>{F.cancelBubble=true,d(null),B();},onMouseLeave:F=>{F.cancelBubble=true,d(null);},onTouchStart:F=>{F.cancelBubble=true,d("check");},onTouchEnd:F=>{F.cancelBubble=true,d(null),B();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:H.padding+14,width:(H.availableWidth-24)/(y?2:1),height:H.buttonHeight,fill:p.size===0||y?"#9ca3af":"#096B76",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:H.padding+14,width:(H.availableWidth-24)/(y?2:1),height:H.buttonHeight,text:y?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),y&&jsxs(Group,{x:(e.width-H.padding*2)/2+8,onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),k();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),k();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:H.padding,width:(H.availableWidth-8)/2,height:H.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:H.padding,width:(H.availableWidth-8)/2,height:H.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});rc.displayName="MultipleChoice";var nc=rc;var Vx=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},dl=({multipleChoice:e,onContextMenu:o,handleSelect:t,mcqRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(R=>R.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,f]=useState(false),d=e.data.responseOptions.selectedIndices??[],l=useMemo(()=>new Set(d),[d]),m=e.data.responseOptions.attempts??0,h=m>0,[p,v]=useState(false),[y,b]=useState(0),g=new Set(e.data.responseOptions.correctIndex),C=Array.from(l).filter(R=>g.has(R)),I=l.size===g.size&&Array.from(l).every(R=>g.has(R)),B=C.length>0&&!I,k=()=>I?"\u2713 Correct! Great job!":B?`\u26A0 Partially correct (${C.length}/${g.size})`:"\u2717 Try again!",x=useCallback(R=>{let z=R.target;s(yi({id:e.id,dragDropPos:{x:z.x(),y:z.y()}})),r?.();},[s,e.id,r]),S=useMemo(()=>{let z=Math.max(window.innerWidth*.3,500),ne=20,X=18,P=28,N=40,_=50,Q=20,re=60,j=Math.max(z-40,400),pe=Math.max(60,Vx(e.data.question,ne,j,"bold")),ge=Math.max(z-Q*2,400),le=Math.max(150,window.innerHeight*.2),ye=e.data.feedbackMode==="practice",we=pe+20+le+(h?re+18:0)+(ye?N+(h?_:0)+20:0),xe=we+100;return {screenWidth:z,screenHeight:xe,dropZoneWidth:ge,dropZoneHeight:le,questionFontSize:ne,questionHeight:pe,feedbackFontSize:X,feedbackHeight:re,dropHereFontSize:P,buttonHeight:N,buttonGap:_,padding:Q,contentWidth:j,totalContentHeight:we,isPracticeMode:ye}},[e.data.question,e.data.feedbackMode,h]),w=useRef(null);useEffect(()=>{let R=w.current;if(R)return a.current.set(e.id,R),()=>{a.current.delete(e.id);}},[e.id,a]);let T=R=>{s(yi({id:e.id,dragDropPos:{x:R.target.x(),y:R.target.y()}})),r?.();},q=R=>{let z=R.target,ne=z.x(),X=z.y(),P=window.innerWidth*.2,N=50,_=S.padding,Q=S.padding+S.dropZoneWidth,re=S.questionHeight+20,j=S.questionHeight+20+S.dropZoneHeight,pe=ne+P>_&&ne<Q&&X+N>re&&X<j;f(pe),r?.();},H=(R,z)=>{let ne=z.target,X=ne.x(),P=ne.y(),N=window.innerWidth*.2,_=50;s(gt({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[R]:{x:X,y:P}}}));let Q=S.padding,re=S.padding+S.dropZoneWidth,j=S.questionHeight+20,pe=S.questionHeight+20+S.dropZoneHeight,ge=X+N>Q&&X<re&&P+_>j&&P<pe,le;ge?le=new Set(l).add(R):(le=new Set(l),le.delete(R)),f(false);let ye=Array.from(le),we=ye.length===g.size&&ye.every(xe=>g.has(xe));s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:ye,isCorrect:we}}})),r?.();},F=()=>{s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},V=()=>{s(gt({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedIndices:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),f(false),b(R=>R+1),r?.();},U=()=>I?{bg:"#dcfce7",text:"#166534"}:B?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},K=()=>h?I?"#4CAF50":B?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:w,x:e.dragDropPos?.x,y:e.dragDropPos?.y,name:"mcq-element",width:S.screenWidth,height:S.screenHeight,draggable:!i,listening:!i,onDragMove:x,...n,...i?{}:{onClick:R=>t&&t(e.id),onTap:R=>t&&t(e.id),onContextMenu:R=>{R.evt.preventDefault(),o(R.evt,e.id,"mcq");}},children:[jsxs(Group,{rotation:e.rotation,onDragEnd:T,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:S.totalContentHeight+20,width:S.screenWidth,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:S.padding,y:S.padding,width:S.contentWidth,height:S.questionHeight-S.padding,text:e.data.question,fontSize:S.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:S.padding,y:S.questionHeight+20,width:S.dropZoneWidth,height:S.dropZoneHeight,fill:"#EBF6F7",stroke:K(),strokeWidth:3,dash:[10,10],cornerRadius:8}),h&&jsxs(Fragment,{children:[jsx(Rect,{x:S.padding+3,y:S.questionHeight+20+S.dropZoneHeight+18,width:S.dropZoneWidth-5,height:S.feedbackHeight,fill:U().bg,cornerRadius:8}),jsx(Text,{x:S.padding,y:S.questionHeight+20+S.dropZoneHeight+20,width:S.dropZoneWidth,height:S.feedbackHeight,text:k()+` (${m} attempts)`,fontSize:S.feedbackFontSize,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),l.size===0&&!h&&jsx(Text,{x:S.padding,y:S.questionHeight+20,width:S.dropZoneWidth,height:S.dropZoneHeight,text:g.size>1?`Drop ${g.size} Correct Answers Here`:"Drop Here",fontSize:S.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),S.isPracticeMode?jsxs(Group,{x:S.padding,y:S.questionHeight+20+S.dropZoneHeight+(h?S.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,!(h||l.size===0)&&(v(true),F());},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),F();},onTouchEnd:()=>v(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:h||l.size===0?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:S.buttonHeight,width:S.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:h||l.size===0?"#9ca3af":"white",width:S.dropZoneWidth,height:S.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),h&&jsxs(Group,{y:S.buttonGap,onMouseDown:V,onTouchStart:V,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:S.buttonHeight,width:S.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:S.dropZoneWidth,height:S.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((R,z)=>{let ne=z%2,X=Math.floor(z/2),P=S.dropZoneWidth/2+25,N=50,_=10,Q=l.has(z),re=g.has(z),j=h&&Q,pe="transparent";j?pe=re?"#4CAF50":"#ef4444":Q&&(pe="#4CAF50");let ge=h&&!Q?0:1,le=e.optionDragDropPos?.[z],ye=le?.x??ne*(P+_),we=le?.y??S.totalContentHeight+30+X*(N+_);return jsxs(Group,{x:ye,y:we,draggable:!h,onDragStart:xe=>{xe.cancelBubble=true;},onDragMove:xe=>{xe.cancelBubble=true,q(xe);},onDragEnd:xe=>{xe.cancelBubble=true,H(z,xe);},opacity:ge,children:[jsx(Rect,{width:P-20,height:N,fill:"white",stroke:pe,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:P-20,height:N,text:R,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${z}-${y}`)})]})};dl.displayName="MultipleChoiceDragAndDrop";var ic=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(nc,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:f=>n(f,c.id),onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id):jsx(dl,{multipleChoice:c,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r,touchHandlers:i(c.id,"mcq"),onUpdate:u},c.id))})};var lc=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o*1.2;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},dc=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s,onUpdate:u})=>{let i=useSelector(T=>T.toolbar.selectedTool),c=i==="pen"||i==="eraser",[f,d]=useState(false),l=e.data.responseOptions.attempts||0,[m,h]=useState(null),p=useDispatch(),[v,y]=useState(e.data.responseOptions.selectedResponse??null),b=useRef(null);useEffect(()=>{let T=b.current;if(T)return a.current.set(e.id,T),()=>{a.current.delete(e.id);}},[e.id]);let g=()=>{v!==null&&d(true),p(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},C=()=>{d(false),y(null);},I=e.data.responseOptions.correctAnswer,B=v===I,k=T=>{if(f)return;y(T);let q=T===e.data.responseOptions.correctAnswer;p(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:T,isCorrect:q}}})),u?.();},x=()=>B?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",S=()=>B?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},w=useMemo(()=>{let K=e.data.feedbackMode==="practice"?48:0,R=12,z=e.width-48,ne=Math.max(60,lc(e.data.question,20,z,"bold")+20),X=f&&e.data.feedbackMode==="practice"?Math.max(60,lc(x(),16,z-40)+30):0,P=ne+X,N=164,_=P+N+R+K+24;return {padding:24,questionHeight:ne,feedbackHeight:X,optionsStartY:P,optionsHeight:N,totalHeight:_,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:K,buttonTopMargin:R,availableWidth:z}},[e.width,e.data.question,e.data.feedbackMode,f,x]);return jsxs(Group,{ref:b,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:w.totalHeight,...s,...c?{}:{onDragEnd:T=>r(T,e.id),onClick:T=>t&&t(e.id),onTap:T=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:w.totalHeight,width:e.width,onTransformEnd:T=>o(e.id,T),onContextMenu:T=>{T.cancelBubble=true,n(T.evt,e.id,"trueFalse");}}),jsx(Text,{x:w.padding+8,y:w.padding,text:e.data.question,fontSize:w.questionFontSize,fontStyle:"bold",fill:"#111827",width:w.availableWidth,height:w.questionHeight-w.padding,wrap:"word",ellipsis:true,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:w.padding+24,y:w.questionHeight+10,width:w.availableWidth-40,height:w.feedbackHeight-20,fill:S().bg,cornerRadius:8}),jsx(Text,{x:w.padding+24,y:w.questionHeight+10,width:w.availableWidth-40,height:w.feedbackHeight-20,text:x()+` (${l} attempts)`,fontSize:w.feedbackFontSize,fontStyle:"bold",fill:S().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((T,q)=>{let H=I===T.value,F=v===T.value,V=(e.width-w.padding*3)/2,U=w.padding+q*(V+w.padding),K=w.optionsStartY,R=T.value===true,z=R?"#10b981":"#ef4444",ne="#ffffff",X="#ffffff",P="#e5e7eb";return f&&F&&(H?(X=R?"#f0fdf4":"#fef2f2",P=R?"#86efac":"#fecaca"):(X="#fee2e2",P="#ef4444")),F&&!f&&(P="#096B76",X="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:U,y:K,width:V,height:w.optionHeight+50,fill:X,stroke:P,strokeWidth:2,cornerRadius:12,onClick:N=>{N.cancelBubble=true,k(T.value);},onTap:N=>{N.cancelBubble=true,k(T.value);}}),jsx(Circle,{x:U+V/2,y:K+40,radius:28,fill:z,listening:false}),R?jsx(Text,{x:U+V/2-14,y:K+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:ne,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:U+V/2-14,y:K+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:ne,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:U,y:K+85,width:V,height:30,text:T.label,fontSize:w.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},T.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:w.optionsStartY+2*(w.optionHeight+w.optionGap)+w.buttonTopMargin,children:[jsxs(Group,{onMouseDown:T=>{T.cancelBubble=true,h("check");},onMouseUp:T=>{T.cancelBubble=true,h(null),g();},onMouseLeave:T=>{T.cancelBubble=true,h(null);},onTouchStart:T=>{T.cancelBubble=true,h("check");},onTouchEnd:T=>{T.cancelBubble=true,h(null),g();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:w.padding+14,width:(w.availableWidth-24)/(f?2:1),height:w.buttonHeight,fill:v===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:w.padding+14,width:(w.availableWidth-24)/(f?2:1),height:w.buttonHeight,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-w.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),C();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),C();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:w.padding,width:(w.availableWidth-8)/2,height:w.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:w.padding,width:(w.availableWidth-8)/2,height:w.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});dc.displayName="TrueFalse";var uc=dc;var ab="#FFFFFF",ml=({trueFalse:e,onContextMenu:o,handleSelect:t,trueFalseRefs:a,touchHandlers:n,onUpdate:r})=>{let s=useDispatch(),u=useSelector(P=>P.toolbar.selectedTool),i=u==="pen"||u==="eraser",[c,f]=useState(false),d=e.data.responseOptions.selectedResponse??null,l=(e.data.responseOptions.attempts??0)>0,[m,h]=useState(false),[p,v]=useState(0),y=e.data.responseOptions.attempts||0,b=340,g=100,C=Math.max(window.innerWidth*.3,400),I=window.innerHeight*.5,B=useRef(null);useEffect(()=>{let P=B.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id]);let x=Math.max(60,((P,N,_,Q)=>{let j=document.createElement("canvas").getContext("2d");if(!j)return N;j.font=`${Q} ${N}px Arial, sans-serif`;let pe=P.split(" "),ge=[],le="";return pe.forEach(ye=>{let we=le?`${le} ${ye}`:ye;j.measureText(we).width>_&&le!==""?(ge.push(le),le=ye):le=we;}),le&&ge.push(le),ge.length*N*1.2})(e.data.question,20,C-40,"bold")+20),S=x+10,w=C-40,T=I-x-250,q=useCallback(P=>{let N=P.target;s(ot({id:e.id,dragDropPos:{x:N.x(),y:N.y()}})),r?.();},[s,e.id,r]),H=P=>{s(ot({id:e.id,dragDropPos:{x:P.target.x(),y:P.target.y()}})),r?.();},F=P=>{let N=P.target,_=N.x(),Q=N.y(),re=window.innerWidth*.2-40,j=50,pe=20,ge=20+w,le=S,ye=S+T,we=_+re>pe&&_<ge&&Q+j>le&&Q<ye;f(we),r?.();},V=(P,N)=>{let _=P?"true":"false",Q=N.target;s(ot({id:e.id,optionDragDropPos:{...e.optionDragDropPos??{},[_]:{x:Q.x(),y:Q.y()}}}));let re=Q.x(),j=Q.y(),pe=window.innerWidth*.2-40,ge=50,le=20,ye=20+w,we=S,xe=S+T;if(!(re+pe>le&&re<ye&&j+ge>we&&j<xe)){f(false);return}f(false);let ae=P===e.data.responseOptions.correctAnswer;s(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:P,isCorrect:ae}}}));},U=()=>{s(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}}));},K=()=>{s(ot({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,selectedResponse:void 0,isCorrect:void 0,attempts:0}},optionDragDropPos:void 0})),f(false),v(P=>P+1),r?.();},R=e.data.responseOptions.correctAnswer,z=d===R,ne=()=>z?"\u2713 Correct! Great job!":"\u2717 Try again!",X=()=>z?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:B,name:"trueFalse-element",width:C,height:I,x:e.dragDropPos?.x,y:e.dragDropPos?.y,draggable:!i,listening:!i,onDragMove:q,...n,...i?{}:{onClick:P=>t&&t(e.id),onTap:P=>t&&t(e.id),onContextMenu:P=>{P.evt.preventDefault(),o(P.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:g,rotation:e.rotation,onDragEnd:H,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:l?I:e.data.feedbackMode==="practice"?I-50:I-100,width:C,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:C-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:S,width:w,height:T,fill:"transparent",stroke:c?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:S,width:w,height:60,fill:X().bg,cornerRadius:8}),jsx(Text,{x:20,y:S,width:w,height:60,text:ne()+" ("+y+" attempts)",fontSize:18,fontStyle:"bold",fill:X().text,align:"center",verticalAlign:"middle"})]}),d===null&&!l&&jsx(Text,{x:20,y:S,width:w,height:T,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),[{value:true,label:"True"},{value:false,label:"False"}].map((P,N)=>{let _=w/2+20,Q=50,re=10,j=d===P.value,pe=R===P.value,ge=l&&j,le=P.value?"true":"false",ye=16+N*(_+re),we=g+I-300,xe=e.optionDragDropPos?.[le],St="transparent";return ge?St=pe?"#4CAF50":"#ef4444":j&&(St="#4CAF50"),jsxs(Group,{x:xe?.x??ye,y:xe?.y??we,draggable:!l,onDragStart:ae=>{ae.cancelBubble=true;},onDragMove:ae=>{ae.cancelBubble=true,F(ae);},onDragEnd:ae=>{ae.cancelBubble=true,V(P.value,ae);},opacity:l&&!j?.5:1,children:[jsx(Rect,{width:_-40,height:Q,fill:"#075560",stroke:St,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:_-40,height:Q,text:P.label,fontSize:18,fontStyle:"bold",fill:ab,align:"center",verticalAlign:"middle",listening:false})]},`${P.value}-${p}`)}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:I-100,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,!(l||d===null)&&d!==null&&(h(true),U());},onMouseUp:()=>h(false),onMouseLeave:()=>h(false),onTouchStart:()=>{d!==null&&(h(true),U());},onTouchEnd:()=>h(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:l||d===null?"#e5e7eb":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:w}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:l||d===null?"#9ca3af":"white",width:w,height:40,align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{y:50,onMouseDown:K,onTouchStart:K,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:w}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:w,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]})})};ml.displayName="TrueFalseDragAndDrop";var cc=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:n,onContextMenu:r,onLongPress:s,onUpdate:u})=>{let{createHandlers:i}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(c=>c.data.responseType==="classic"?jsx(uc,{trueFalse:c,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id):jsx(ml,{trueFalse:c,handleSelect:t,trueFalseRefs:a,onContextMenu:r,touchHandlers:i(c.id,"trueFalse"),onUpdate:u},c.id))})};var Aa=new WeakMap,zo=new WeakMap,Rr={current:[]},hl=false,Dr=0,Er=new Set,is=new Map;function fc(e){let o=Array.from(e).sort((t,a)=>t instanceof jt&&t.options.deps.includes(a)?1:a instanceof jt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(Rr.current.includes(t))continue;Rr.current.push(t),t.recompute();let a=zo.get(t);if(a)for(let n of a){let r=Aa.get(n);r&&fc(r);}}}function nb(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function sb(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function ls(e){if(Dr>0&&!is.has(e)&&is.set(e,e.prevState),Er.add(e),!(Dr>0)&&!hl)try{for(hl=!0;Er.size>0;){let o=Array.from(Er);Er.clear();for(let t of o){let a=is.get(t)??t.prevState;t.prevState=a,nb(t);}for(let t of o){let a=Aa.get(t);a&&(Rr.current.push(t),fc(a));}for(let t of o){let a=Aa.get(t);if(a)for(let n of a)sb(n);}}}finally{hl=false,Rr.current=[],is.clear();}}function Mt(e){Dr++;try{e();}finally{if(Dr--,Dr===0){let o=Er.values().next().value;o&&ls(o);}}}function mc(e){return typeof e=="function"}var ea=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var n,r;this.listeners.add(a);let s=(r=(n=this.options)==null?void 0:n.onSubscribe)==null?void 0:r.call(n,a,this);return ()=>{this.listeners.delete(a),s?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,n;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):mc(o)?this.state=o(this.prevState):this.state=o,(n=(a=this.options)==null?void 0:a.onUpdate)==null||n.call(a),ls(this);}};var jt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),n=new Array(t);for(let r=0;r<t;r++){let s=this.options.deps[r];a[r]=s.prevState,n[r]=s.state;}return this.lastSeenDepValues=n,{prevDepVals:a,currDepVals:n,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let n=this.getDepVals();this.state=this.options.fn(n),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let r of this.options.deps)r instanceof e&&r.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:n}=this.getDepVals();for(let r=0;r<n.length;r++)if(n[r]!==a[r]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,n;this.listeners.add(t);let r=(n=(a=this.options).onSubscribe)==null?void 0:n.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof ea){let a=Aa.get(t);a||(a=new Set,Aa.set(t,a)),a.add(this);let n=zo.get(this);n||(n=new Set,zo.set(this,n)),n.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof ea){let a=Aa.get(t);a&&a.delete(this);let n=zo.get(this);n&&n.delete(t);}}};function ib(e){return typeof e=="function"}function gl(e,...o){return ib(e)?e(...o):e}function pc(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Pa,bt,ft,Fr,Ea,ro,la,Wo,Br,ds,Or,Uo,no=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:n=1e3}){Ne(this,Pa,true);Ne(this,bt);Ne(this,ft);Ne(this,Fr);Ne(this,Ea);Ne(this,ro);Ne(this,la);Ne(this,Wo);Ne(this,Br,0);Ne(this,ds,5);Ne(this,Or,()=>{this.debugLog("Connected to event bus"),De(this,ro,true),this.debugLog("Emitting queued events",$(this,Ea)),$(this,Ea).forEach(o=>this.emitEventToBus(o)),De(this,Ea,[]),this.stopConnectLoop(),$(this,ft).call(this).removeEventListener("tanstack-connect-success",$(this,Or));});Ne(this,Uo,()=>{if($(this,ft).call(this).addEventListener("tanstack-connect-success",$(this,Or)),$(this,Br)<$(this,ds)){Hd(this,Br)._++,this.dispatchCustomEvent("tanstack-connect",{});return}$(this,ft).call(this).removeEventListener("tanstack-connect",$(this,Uo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});De(this,bt,o),De(this,Pa,a),De(this,ft,this.getGlobalTarget),De(this,Fr,t),this.debugLog(" Initializing event subscription for plugin",$(this,bt)),De(this,Ea,[]),De(this,ro,false),De(this,la,null),De(this,Wo,n);}startConnectLoop(){$(this,la)!==null||$(this,ro)||(this.debugLog(`Starting connect loop (every ${$(this,Wo)}ms)`),De(this,la,setInterval($(this,Uo),$(this,Wo))));}stopConnectLoop(){$(this,la)!==null&&(clearInterval($(this,la)),De(this,la,null),this.debugLog("Stopped connect loop"));}debugLog(...o){$(this,Fr)&&console.log(`\u{1F334} [tanstack-devtools:${$(this,bt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return $(this,bt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});$(this,ft).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{$(this,ft).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!$(this,Pa)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!$(this,ro)){this.debugLog("Bus not available, will be pushed as soon as connected"),$(this,Ea).push({type:`${$(this,bt)}:${o}`,payload:t,pluginId:$(this,bt)}),typeof CustomEvent<"u"&&($(this,Uo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${$(this,bt)}:${o}`,payload:t,pluginId:$(this,bt)})}on(o,t){let a=`${$(this,bt)}:${o}`;if(!$(this,Pa))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let n=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return $(this,ft).call(this).addEventListener(a,n),this.debugLog("Registered event to bus",a),()=>{$(this,ft).call(this).removeEventListener(a,n);}}onAll(o){if(!$(this,Pa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;o(n);};return $(this,ft).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,ft).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!$(this,Pa))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let n=a.detail;$(this,bt)&&n.pluginId!==$(this,bt)||o(n);};return $(this,ft).call(this).addEventListener("tanstack-devtools-global",t),()=>$(this,ft).call(this).removeEventListener("tanstack-devtools-global",t)}};Pa=new WeakMap,bt=new WeakMap,ft=new WeakMap,Fr=new WeakMap,Ea=new WeakMap,ro=new WeakMap,la=new WeakMap,Wo=new WeakMap,Br=new WeakMap,ds=new WeakMap,Or=new WeakMap,Uo=new WeakMap;var xl=class extends no{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},hc=(e,o)=>{bl.emit(e,o);},bl=new xl;function gc(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var lb={enabled:true,leading:true,trailing:true,wait:0},Da,At,so,io,lo,Ko,us=class{constructor(o,t){Ne(this,Da);Ne(this,At);Ne(this,so);Ne(this,io);Ne(this,lo);Ne(this,Ko);this.fn=o,this.store=new ea(gc()),this.setOptions=a=>{this.options={...this.options,...a},$(this,so).call(this)||this.cancel();},De(this,At,a=>{this.store.setState(n=>{let r={...n,...a},{isPending:s}=r;return {...r,status:$(this,so).call(this)?s?"pending":"idle":"disabled"}}),hc("Throttler",this);}),De(this,so,()=>!!gl(this.options.enabled,this)),De(this,io,()=>gl(this.options.wait,this)),this.maybeExecute=(...a)=>{$(this,At).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let n=Date.now(),r=n-this.store.state.lastExecutionTime,s=$(this,io).call(this);if(this.options.leading&&r>=s)$(this,lo).call(this,...a);else if($(this,At).call(this,{lastArgs:a}),!$(this,Da)&&this.options.trailing){let u=this.store.state.lastExecutionTime?n-this.store.state.lastExecutionTime:0,i=s-u;$(this,At).call(this,{isPending:true}),De(this,Da,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&$(this,lo).call(this,...c);},i));}},De(this,lo,(...a)=>{if(!$(this,so).call(this))return;this.fn(...a);let n=Date.now(),r=n+$(this,io).call(this);$(this,Ko).call(this),$(this,At).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:n,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||$(this,At).call(this,{nextExecutionTime:void 0});},$(this,io).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&$(this,lo).call(this,...this.store.state.lastArgs);},De(this,Ko,()=>{$(this,Da)&&(clearTimeout($(this,Da)),De(this,Da,void 0));}),this.cancel=()=>{$(this,Ko).call(this),$(this,At).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{$(this,At).call(this,gc());},this.key=pc(t.key),this.options={...lb,...t},$(this,At).call(this,this.options.initialState??{}),bl.on("d-Throttler",a=>{a.payload.key===this.key&&($(this,At).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Da=new WeakMap,At=new WeakMap,so=new WeakMap,io=new WeakMap,lo=new WeakMap,Ko=new WeakMap;function vl(e,o){return new us(e,o).maybeExecute}function Ra(e,o){return typeof e=="function"?e(o):e}function Fa(e,o){return ps(o).reduce((a,n)=>{if(a===null)return null;if(typeof a<"u")return a[n]},e)}function Go(e,o,t){let a=ps(o);function n(r){if(!a.length)return Ra(t,r);let s=a.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[s]:n(r[s])}):{[s]:n()};if(Array.isArray(r)&&typeof s=="number"){let u=r.slice(0,s);return [...u.length?u:new Array(s),n(r[s]),...r.slice(s+1)]}return [...new Array(s),n()]}return n(e)}function wl(e,o){let t=ps(o);function a(n){if(!n)return;if(t.length===1){let s=t[0];if(Array.isArray(n)&&typeof s=="number")return n.filter((c,f)=>f!==s);let{[s]:u,...i}=n;return i}let r=t.shift();if(typeof r=="string"&&typeof n=="object")return {...n,[r]:a(n[r])};if(typeof r=="number"&&Array.isArray(n)){if(r>=n.length)return n;let s=n.slice(0,r);return [...s.length?s:new Array(r),a(n[r]),...n.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var db=/^(\d+)$/gm,ub=/\.(\d+)(?=\.)/gm,cb=/^(\d+)\./gm,fb=/\.(\d+$)/gm,mb=/\.{2,}/gm,yl="__int__",cs=`${yl}$1`;function ps(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(db,cs).replace(ub,`.${cs}.`).replace(cb,`${cs}.`).replace(fb,`.${cs}`).replace(mb,".").split(".").map(o=>{if(o.startsWith(yl)){let t=o.substring(yl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Sl(e){return !(Array.isArray(e)&&e.length===0)}function jo(e,o){let t=a=>a.validators.filter(Boolean).map(n=>({cause:n.cause,validate:n.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function _o(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:n,onDynamicAsyncDebounceMs:r}=o.validators||{},s=t??0,u=i=>i.validators.filter(Boolean).map(c=>{let f=c?.cause||e,d=s;switch(f){case "change":d=n??s;break;case "blur":d=a??s;break;case "dynamic":d=r??s;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:f,validate:c.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var Nr=e=>!!e&&typeof e=="object"&&"fields"in e;function Ba(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[n,r]of e)if(!o.has(n)||!Object.is(r,o.get(n)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let n of e)if(!o.has(n))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let n of t)if(!a.includes(n)||!Ba(e[n],o[n]))return false;return true}var hs=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},gs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Qe(e,o){return e==null?o:{...e,...o}}var uo=256,ms=[],fs;for(;uo--;)ms[uo]=(uo+256).toString(16).substring(1);function Ll(){let e=0,o,t="";if(!fs||uo+16>256){for(fs=new Array(256),e=256;e--;)fs[e]=256*Math.random()|0;e=0,uo=0;}for(;e<16;e++)o=fs[uo+e],e===6?t+=ms[o&15|64]:e===8?t+=ms[o&63|128]:t+=ms[o],e&1&&e>1&&e<11&&(t+="-");return uo++,t}var Oa=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},n={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},s=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,n,r,s],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[n,s],form:e.form});case "change":return e.runValidation({validators:[a,s],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function pb(e,o){let t=new Map;for(let a of e){let n=a.path??[],r=o,s="";for(let u=0;u<n.length;u++){let i=n[u];if(i===void 0)continue;let c=typeof i=="object"?i.key:i,f=Number(c);Array.isArray(r)&&!Number.isNaN(f)?s+=`[${f}]`:s+=(u>0?".":"")+String(c),typeof r=="object"&&r!==null?r=r[c]:r=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var xc=(e,o)=>{let t=pb(e,o);return {form:t,fields:t}},Na={validate({value:e,validationSource:o},t){let a=t["~standard"].validate(e);if(a instanceof Promise)throw new Error("async function passed to sync validator");if(a.issues)return o==="field"?a.issues:xc(a.issues,e)},async validateAsync({value:e,validationSource:o},t){let a=await t["~standard"].validate(e);if(a.issues)return o==="field"?a.issues:xc(a.issues,e)}},xs=e=>!!e&&"~standard"in e;var $o={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function Hr(e){function o(d,l,m,h){let p=a(d,l,m,h);({insert:()=>u(p,d,l),remove:()=>i(p),swap:()=>h!==void 0&&f(p,d,l,h),move:()=>h!==void 0&&c(p,d,l,h)})[m]();}function t(d,l){return `${d}[${l}]`}function a(d,l,m,h){let p=[t(d,l)];if(m==="swap")p.push(t(d,h));else if(m==="move"){let[v,y]=[Math.min(l,h),Math.max(l,h)];for(let b=v;b<=y;b++)p.push(t(d,b));}else {let v=e.getFieldValue(d),y=Array.isArray(v)?v.length:0;for(let b=l+1;b<y;b++)p.push(t(d,b));}return Object.keys(e.fieldInfo).filter(v=>p.some(y=>v.startsWith(y)))}function n(d,l){return d.replace(/\[(\d+)\]/,(m,h)=>{let p=parseInt(h,10);return `[${l==="up"?p+1:Math.max(0,p-1)}]`})}function r(d,l){(l==="up"?d:[...d].reverse()).forEach(h=>{let p=n(h.toString(),l),v=e.getFieldMeta(p);v?e.setFieldMeta(h,v):e.setFieldMeta(h,s());});}let s=()=>$o,u=(d,l,m)=>{r(d,"down"),d.forEach(h=>{h.toString().startsWith(t(l,m))&&e.setFieldMeta(h,s());});},i=d=>{r(d,"up");},c=(d,l,m,h)=>{let p=new Map(Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,m))).map(v=>[v,e.getFieldMeta(v)]));r(d,m<h?"up":"down"),Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,h))).forEach(v=>{let y=v.replace(t(l,h),t(l,m)),b=p.get(y);b&&e.setFieldMeta(v,b);});},f=(d,l,m,h)=>{d.forEach(p=>{if(!p.toString().startsWith(t(l,m)))return;let v=p.toString().replace(t(l,m),t(l,h)),[y,b]=[e.getFieldMeta(p),e.getFieldMeta(v)];y&&e.setFieldMeta(v,y),b&&e.setFieldMeta(p,b);});};return {handleArrayFieldMetaShift:o}}var Il=class extends no{constructor(){super({pluginId:"form-devtools"});}},Pt=new Il;function Cl(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var Vr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),n=this.store.mount(),r=()=>{a(),n(),Pt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return Pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),s&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let n=this.options;this.options=a;let r=!!a.transform?.deps?.some((i,c)=>i!==this.prevTransformArray[c]),s=a.defaultValues&&!Ba(a.defaultValues,n.defaultValues)&&!this.state.isTouched,u=!Ba(a.defaultState,n.defaultState)&&!this.state.isTouched;!s&&!u&&!r||(Mt(()=>{this.baseStore.setState(()=>Cl(Object.assign({},this.state,u?a.defaultState:{},s?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),Pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,n)=>{let{fieldMeta:r}=this.state,s=this.resetFieldMeta(r);a&&!n?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Cl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let n=[];return Mt(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;let u=s.instance;n.push(Promise.resolve().then(()=>u.validate(a,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(n)).flat()},this.validateArrayFieldsStartingFrom=async(a,n,r)=>{let s=this.getFieldValue(a),u=Array.isArray(s)?Math.max(s.length-1,0):null,i=[`${a}[${n}]`];for(let l=n+1;l<=(u??0);l++)i.push(`${a}[${l}]`);let c=Object.keys(this.fieldInfo).filter(l=>i.some(m=>l.startsWith(m))),f=[];return Mt(()=>{c.forEach(l=>{f.push(Promise.resolve().then(()=>this.validateField(l,r)));});}),(await Promise.all(f)).flat()},this.validateField=(a,n)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(s=>({...s,isTouched:true})),r.validate(n)):[]},this.validateSync=a=>{let n=jo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Oa}),r=false,s={};return Mt(()=>{for(let c of n){if(!c.validate)continue;let f=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:l}=bs(f),m=qr(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let p=this.getFieldMeta(h);if(!p)continue;let{errorMap:v,errorSourceMap:y}=p,b=l?.[h],{newErrorValue:g,newSource:C}=hs({newFormValidatorError:b,isPreviousErrorFromFormValidator:y?.[m]==="form",previousErrorValue:v?.[m]});C==="form"&&(s[h]={...s[h],[m]:b}),v?.[m]!==g&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[m]:g},errorSourceMap:{...I.errorSourceMap,[m]:C}}));}this.state.errorMap?.[m]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[m]:d}})),(d||l)&&(r=!0);}let u=qr("submit");this.state.errorMap?.[u]&&a!=="submit"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let i=qr("server");this.state.errorMap?.[i]&&a!=="server"&&!r&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[i]:void 0}}));}),{hasErrored:r,fieldsErrorMap:s}},this.validateAsync=async a=>{let n=_o(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Oa});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let r=[],s;for(let c of n){if(!c.validate)continue;let f=qr(c.cause);this.state.validationMetaMap[f]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[f]={lastAbortController:l},r.push(new Promise(async m=>{let h;try{h=await new Promise((b,g)=>{setTimeout(async()=>{if(l.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(C){g(C);}},c.debounceMs);});}catch(b){h=b;}let{formError:p,fieldErrors:v}=bs(h);v&&(s=s?{...s,...v}:v);let y=qr(c.cause);for(let b of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[b]===void 0)continue;let g=this.getFieldMeta(b);if(!g)continue;let{errorMap:C,errorSourceMap:I}=g,B=s?.[b],{newErrorValue:k,newSource:x}=hs({newFormValidatorError:B,isPreviousErrorFromFormValidator:I?.[y]==="form",previousErrorValue:C?.[y]});C?.[y]!==k&&this.setFieldMeta(b,S=>({...S,errorMap:{...S.errorMap,[y]:k},errorSourceMap:{...S.errorSourceMap,[y]:x}}));}this.baseStore.setState(b=>({...b,errorMap:{...b.errorMap,[y]:p}})),m(s?{fieldErrors:s,errorMapKey:y}:void 0);}));}let u=[],i={};if(r.length){u=await Promise.all(r);for(let c of u)if(c?.fieldErrors){let{errorMapKey:f}=c;for(let[d,l]of Object.entries(c.fieldErrors)){let h={...i[d]||{},[f]:l};i[d]=h;}}}return this.baseStore.setState(c=>({...c,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(a);return n&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Fa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var n;return (n=this.fieldInfo)[a]||(n[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,n)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Ra(n,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((n,r)=>{let s=r;return n[s]=$o,n},{}),this.setFieldValue=(a,n,r)=>{let s=r?.dontUpdateMeta??false,u=r?.dontRunListeners??false,i=r?.dontValidate??false;Mt(()=>{s||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:Go(c.values,a,n)}));}),u||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(s=>{let u=a.toString();return s!==u&&s.startsWith(u)}),a];this.baseStore.setState(s=>{let u={...s};return r.forEach(i=>{u.values=wl(u.values,i),delete this.fieldInfo[i],delete u.fieldMetaBase[i];}),u});},this.pushFieldValue=(a,n,r)=>{this.setFieldValue(a,s=>[...Array.isArray(s)?s:[],n],r);},this.insertFieldValue=async(a,n,r,s)=>{this.setFieldValue(a,i=>[...i.slice(0,n),r,...i.slice(n)],Qe(s,{dontValidate:true}));let u=s?.dontValidate??false;u||await this.validateField(a,"change"),Hr(this).handleArrayFieldMetaShift(a,n,"insert"),u||await this.validateArrayFieldsStartingFrom(a,n,"change");},this.replaceFieldValue=async(a,n,r,s)=>{this.setFieldValue(a,i=>i.map((c,f)=>f===n?r:c),Qe(s,{dontValidate:true})),(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.removeFieldValue=async(a,n,r)=>{let s=this.getFieldValue(a),u=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,c=>c.filter((f,d)=>d!==n),Qe(r,{dontValidate:true})),Hr(this).handleArrayFieldMetaShift(a,n,"remove"),u!==null){let c=`${a}[${u}]`;this.deleteField(c);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,n,"change"));},this.swapFieldValues=(a,n,r,s)=>{this.setFieldValue(a,i=>{let c=i[n],f=i[r];return Go(Go(i,`${n}`,f),`${r}`,c)},Qe(s,{dontValidate:true})),Hr(this).handleArrayFieldMetaShift(a,n,"swap",r),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,n,r,s)=>{this.setFieldValue(a,i=>{let c=[...i];return c.splice(r,0,c.splice(n,1)[0]),c},Qe(s,{dontValidate:true})),Hr(this).handleArrayFieldMetaShift(a,n,"move",r),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${n}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,n)=>{let r=this.getFieldValue(a),s=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],Qe(n,{dontValidate:true})),s!==null)for(let i=0;i<=s;i++){let c=`${a}[${i}]`;this.deleteField(c);}(n?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:$o},values:this.options.defaultValues?Go(n.values,a,Fa(this.options.defaultValues,a)):n.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[n,r])=>(Object.keys(r).length&&r.errors.length&&(a[n]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Na.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Na.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Ll(),this._devtoolsSubmissionOverride=false,this.baseStore=new ea(Cl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new jt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=0,f={};for(let d of Object.keys(i.fieldMetaBase)){let l=i.fieldMetaBase[d],m=u?.fieldMetaBase[d],h=s?.[d],p=Fa(i.values,d),v=h?.errors;if(!m||l.errorMap!==m.errorMap){v=Object.values(l.errorMap??{}).filter(I=>I!==void 0);let C=this.getFieldInfo(d)?.instance;C&&!C.options.disableErrorFlat&&(v=v?.flat(1));}let y=!Sl(v??[]),b=!l.isDirty,g=Ba(p,Fa(this.options.defaultValues,d))||Ba(p,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===b&&h.isValid===y&&h.isDefaultValue===g&&h.errors===v&&l===m){f[d]=h,c++;continue}f[d]={...l,errors:v,isPristine:b,isValid:y,isDefaultValue:g};}return Object.keys(i.fieldMetaBase).length&&s&&c===Object.keys(i.fieldMetaBase).length?s:f}}),this.store=new jt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:n,prevVal:r})=>{let s=r,u=a?.[0],i=n[0],c=n[1],f=Object.values(c).filter(Boolean),d=f.some(F=>F.isValidating),l=f.every(F=>F.isValid),m=f.some(F=>F.isTouched),h=f.some(F=>F.isBlurred),p=f.every(F=>F.isDefaultValue),v=m&&i.errorMap?.onMount,y=f.some(F=>F.isDirty),b=!y,g=!!(i.errorMap?.onMount||f.some(F=>F?.errorMap?.onMount)),C=!!d,I=s?.errors??[];(!u||i.errorMap!==u.errorMap)&&(I=Object.values(i.errorMap).reduce((F,V)=>V===void 0?F:V&&Nr(V)?(F.push(V.form),F):(F.push(V),F),[]));let B=I.length===0,k=l&&B,x=this.options.canSubmitWhenInvalid??false,S=i.submissionAttempts===0&&!m&&!g||!C&&!i.isSubmitting&&k||x,w=i.errorMap;if(v&&(I=I.filter(F=>F!==i.errorMap.onMount),w=Object.assign(w,{onMount:void 0})),s&&u&&s.errorMap===w&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===I&&s.isFieldsValidating===d&&s.isFieldsValid===l&&s.isFormValid===B&&s.isValid===k&&s.canSubmit===S&&s.isTouched===m&&s.isBlurred===h&&s.isPristine===b&&s.isDefaultValue===p&&s.isDirty===y&&Ba(u,i))return s;let T={...i,errorMap:w,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:l,isFormValid:B,isValid:k,canSubmit:S,isTouched:m,isBlurred:h,isPristine:b,isDefaultValue:p,isDirty:y},q=this.options.transform?.deps??[];if(q.length!==this.prevTransformArray.length||q.some((F,V)=>F!==this.prevTransformArray[V])){let F=Object.assign({},this,{state:T});this.options.transform?.fn(F),T=F.state,this.prevTransformArray=q;}return T}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=vl(a=>Pt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),Pt.on("request-form-state",a=>{a.payload.id===this._formId&&Pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Pt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),Pt.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return xs(o.validate)?Na[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(n=>({...n,isSubmitted:false,submissionAttempts:n.submissionAttempts+1,isSubmitSuccessful:false})),Mt(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance&&(n.instance.state.meta.isTouched||n.instance.setMeta(r=>({...r,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(n=>({...n,isSubmitting:true}));let a=()=>{this.baseStore.setState(n=>({...n,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(n=>n.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}Mt(()=>{Object.values(this.fieldInfo).forEach(n=>{n.instance?.options.listeners?.onSubmit?.({value:n.instance.state.value,fieldApi:n.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),Mt(()=>{this.baseStore.setState(n=>({...n,isSubmitted:!0,isSubmitSuccessful:!0})),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(n){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),Pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:n}),a(),n}}setErrorMap(o){Mt(()=>{Object.entries(o).forEach(([t,a])=>{let n=t;if(Nr(a)){let{formError:r,fieldErrors:s}=bs(a);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,c=>({...c,errorMap:{...c.errorMap,[n]:s?.[u]},errorSourceMap:{...c.errorSourceMap,[n]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[n]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[n]:a}}));});});}};function bs(e){if(e){if(Nr(e)){let o=bs(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function qr(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}var zr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:n}=this.options.validators||{};if(n){let r=this.runValidator({validate:n,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:r},errorSourceMap:{...s?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let n=Fa(t.form.options.defaultValues,t.name),r=t.defaultValue??n;a?this.setValue(s=>s||r,{dontUpdateMeta:true}):r!==void 0&&this.setValue(r,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Qe(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Qe(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,n)=>{this.form.insertFieldValue(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,n)=>{this.form.replaceFieldValue(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Qe(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,n)=>{this.form.swapFieldValues(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,n)=>{this.form.moveFieldValues(this.name,t,a,Qe(n,{dontRunListeners:true})),n?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Qe(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),n=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:s,onBlurListenTo:u}=r.instance.options.validators||{};t==="change"&&s?.includes(this.name)&&n.push(r.instance),t==="blur"&&u?.includes(this.name)&&n.push(r.instance);}return n},this.validateSync=(t,a)=>{let n=jo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Oa}),s=this.getLinkedFields(t).reduce((c,f)=>{let d=jo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Oa});return d.forEach(l=>{l.field=f;}),c.concat(d)},[]),u=false;Mt(()=>{let c=(f,d)=>{let l=vs(d.cause),m=d.validate?bc(f.runValidator({validate:d.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,h=a[l],{newErrorValue:p,newSource:v}=gs({formLevelError:h,fieldLevelError:m});f.state.meta.errorMap?.[l]!==p&&f.setMeta(y=>({...y,errorMap:{...y.errorMap,[l]:p},errorSourceMap:{...y.errorSourceMap,[l]:v}})),p&&(u=!0);};for(let f of n)c(this,f);for(let f of s)f.validate&&c(f.field,f);});let i=vs("submit");return this.state.meta.errorMap?.[i]&&t!=="submit"&&!u&&this.setMeta(c=>({...c,errorMap:{...c.errorMap,[i]:void 0},errorSourceMap:{...c.errorSourceMap,[i]:void 0}})),{hasErrored:u}},this.validateAsync=async(t,a)=>{let n=_o(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Oa}),r=await a,s=this.getLinkedFields(t),u=s.reduce((l,m)=>{let h=_o(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Oa});return h.forEach(p=>{p.field=m;}),l.concat(h)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of s)l.setMeta(m=>({...m,isValidating:true}));let i=[],c=[],f=(l,m,h)=>{let p=vs(m.cause);l.getInfo().validationMetaMap[p]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[p]={lastAbortController:y},h.push(new Promise(async b=>{let g;try{g=await new Promise((x,S)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(y.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:m.validate,value:{value:l.store.state.value,fieldApi:l,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(w){S(w);}},m.debounceMs);});}catch(x){g=x;}if(y.signal.aborted)return b(void 0);let C=bc(g),I=r[this.name]?.[p],{newErrorValue:B,newSource:k}=gs({formLevelError:I,fieldLevelError:C});l.setMeta(x=>({...x,errorMap:{...x?.errorMap,[p]:B},errorSourceMap:{...x.errorSourceMap,[p]:k}})),b(B);}));};for(let l of n)l.validate&&f(this,l,i);for(let l of u)l.validate&&f(l.field,l,c);let d=[];(i.length||c.length)&&(d=await Promise.all(i),await Promise.all(c)),this.setMeta(l=>({...l,isValidating:false}));for(let l of s)l.setMeta(m=>({...m,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:n}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,n[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[vs(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Na.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Na.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new jt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...$o,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return xs(o.validate)?Na[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function bc(e){if(e)return e}function vs(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function ys(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,gb)}function gb(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,n]of e)if(!o.has(a)||!Object.is(n,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=vc(e);if(t.length!==vc(o).length)return false;for(let a=0;a<t.length;a++)if(!Object.prototype.hasOwnProperty.call(o,t[a])||!Object.is(e[t[a]],o[t[a]]))return false;return true}function vc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Xo=typeof window<"u"?useLayoutEffect:useEffect;function Lb(e){let[o]=useState(()=>{let a=new zr({...e,form:e.form,name:e.name});return a.Field=kl,a});return Xo(o.mount,[o]),Xo(()=>{o.update(e);}),ys(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var kl=(({children:e,...o})=>{let t=Lb(o),a=useMemo(()=>Ra(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function kb({form:e,selector:o,children:t}){let a=ys(e.store,o);return Ra(t,a)}function Tl(e){let o=useId(),[t]=useState(()=>{let a=new Vr({...e,formId:o}),n=a;return n.Field=function(s){return jsx(kl,{...s,form:a})},n.Subscribe=function(s){return jsx(kb,{form:a,selector:s.selector,children:s.children})},n});return Xo(t.mount,[]),Xo(()=>{t.update(e);}),t}function Ml({field:e}){return jsxs(Fragment,{children:[e.state.meta.isTouched&&!e.state.meta.isValid?jsx("em",{children:e.state.meta.errors.join(", ")}):null,e.state.meta.isValidating?"Validating...":null]})}var Ob=({editElement:e})=>{let o=useDispatch(),t=useSelector(ve),a=useRef(null),n=ze(),r=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[u,i]=useState(s),c=Tl({defaultValues:{questionType:s,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:l})=>{if(l.questionType==="true-false"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctAnswer:l.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,dragDropPos:{x:r&&"dragDropPos"in e?e.dragDropPos?.x??400:200,y:r&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?ot(m):wi(m));}else if(l.questionType==="multiple-choice"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctIndex:l.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,dragDropPos:{x:r&&"dragDropPos"in e?e.dragDropPos?.x??400:400,y:r&&"dragDropPos"in e?e.dragDropPos?.y??100:100},width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?gt(m):vi(m));}else if(l.questionType==="short-answer"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?sa(m):Si(m));}else if(l.questionType==="fill-in-the-blank"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Sa(m):Ii(m));}else if(l.questionType==="long-answer"){let m={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctLongAnswer:l.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Ja(m):Li(m));}o(La(false));}}),f=()=>{o(La(false));};if(!n)return null;let d=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:l=>{l.preventDefault(),l.stopPropagation(),c.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{f();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(c.Field,{name:"questionType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:m=>{l.handleChange(m.target.value),i(m.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(Ml,{field:l})]})}),u&&!["short-answer","fill-in-the-blank","long-answer"].includes(u)&&jsx(c.Field,{name:"responseType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:m=>l.handleChange(m.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(Ml,{field:l})]})})]}),jsx(c.Field,{name:"feedbackMode",children:l=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${u==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>l.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>l.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),u==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(Ml,{field:l})]})}),jsx(c.Field,{name:"question",validators:{onChange:({value:l})=>l?void 0:"A question is required"},children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:l.state.value,onChange:m=>l.handleChange(m.target.value),onBlur:l.handleBlur,placeholder:"Enter Your Question"})}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),u==="true-false"&&jsx(c.Field,{name:"responseOptions.correctAnswer",children:l=>{let m=l.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>l.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${m===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),m===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>l.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${m===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),m===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value:l})=>{if(l.options.filter(h=>!h.trim()).length>0)return "All options must have text";if(!l.correctIndex||l.correctIndex.length===0)return "Please select at least one correct answer"}},children:l=>{let m=(y,b)=>{let g=[...l.state.value.options];g[y]=b,l.handleChange({...l.state.value,options:g});},h=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},p=y=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let b=l.state.value.options.filter((C,I)=>I!==y),g=l.state.value.correctIndex?.filter(C=>C!==y).map(C=>C>y?C-1:C);l.handleChange({...l.state.value,options:b,correctIndex:g});},v=y=>{let b=l.state.value.correctIndex||[];if(b.includes(y))l.handleChange({...l.state.value,correctIndex:b.filter(C=>C!==y)});else {if(b.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...b,y]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:l.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:l.state.value.options.map((y,b)=>{let g=!y.trim(),C=l.state.value.correctIndex?.includes(b),I=l.state.meta.isTouched&&g;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>v(b),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${C?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:C&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${I?"border-red-500 bg-red-50":C?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${b+1}`,value:y,onChange:B=>m(b,B.target.value),onBlur:l.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),l.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>p(b),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},b)})}),jsx("button",{type:"button",onClick:h,disabled:l.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),l.state.value.correctIndex.length===0||l.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:l.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.Field,{name:"responseOptions.correctShortAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:l.state.value,onChange:m=>{l.handleChange(m.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),u==="long-answer"&&jsx(c.Field,{name:"responseOptions.correctLongAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:l.state.value,onChange:m=>{l.handleChange(m.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),jsx(c.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,m])=>jsx("button",{type:"submit",disabled:!l,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:m?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(d,n)},Sc=Ob;var kc=({text:e,position:o})=>{let t=Se(),a=(f,d,l,m,h)=>{let v=document.createElement("canvas").getContext("2d");if(!v)return {width:e.width,height:e.height};v.font=`${h} ${m} ${d}px ${l}`;let y=f.split(`
|
|
4
|
+
`),b=0;for(let I of y){let B=v.measureText(I||" ");B.width>b&&(b=B.width);}let C=y.length*d*1.2;return {width:Math.max(200,b+40),height:Math.max(50,C+20)}},n=f=>{let d=Math.max(12,Math.min(72,e.fontSize+f)),l=a(e.text,d,e.fontFamily,e.fontWeight,e.fontStyle);t(de()),t(Ft({id:e.id,fontSize:d,width:l.width,height:l.height}));},r=f=>{t(de()),t(Ft({id:e.id,fill:f}));},s=()=>{let f=e.fontWeight==="bold"?"normal":"bold",d=a(e.text,e.fontSize,e.fontFamily,f,e.fontStyle);t(de()),t(Ft({id:e.id,fontWeight:f,width:d.width,height:d.height}));},u=()=>{let f=e.fontStyle==="italic"?"normal":"italic",d=a(e.text,e.fontSize,e.fontFamily,e.fontWeight,f);t(de()),t(Ft({id:e.id,fontStyle:f,width:d.width,height:d.height}));},i=()=>{t(de()),t(Ft({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},c=f=>{let d=a(e.text,e.fontSize,f,e.fontWeight,e.fontStyle);t(de()),t(Ft({id:e.id,fontFamily:f,width:d.width,height:d.height}));};return jsxs("div",{className:"absolute z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:"50%",top:100,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:f=>f.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:f=>c(f.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>n(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>n(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:s,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:[jsx(TextB,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextB,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:u,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:i,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:[jsx(TextUnderline,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextUnderline,{size:16,weight:"bold",className:"hidden sm:block"})]})]}),jsx("div",{className:"border-l border-gray-200 pl-1",children:jsx("input",{type:"color",value:e.fill,onChange:f=>r(f.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var Mc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:n,scale:r,textareaRef:s})=>{let u=useRef(null),i=useMemo(()=>({fontSize:`${e.fontSize*r}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,r]),c=useCallback(f=>{f.style.height="auto",f.style.height=`${f.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(f).font,d.style.fontSize=f.style.fontSize,d.style.fontFamily=f.style.fontFamily,d.style.fontWeight=f.style.fontWeight,d.style.fontStyle=f.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let l=f.value.split(`
|
|
5
|
+
`),m=0;document.body.appendChild(d);for(let p of l){d.textContent=p||" ";let v=d.offsetWidth;v>m&&(m=v);}document.body.removeChild(d);let h=10;f.style.width=`${Math.max(200,m+h+20)}px`;},[]);return useEffect(()=>{let f=u.current;f&&(f.style.fontSize=`${e.fontSize*r}px`,f.style.fontFamily=e.fontFamily,f.style.fontStyle=e.fontStyle,f.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",f.style.textDecoration=e.textDecoration,f.style.color=e.fill,c(f));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,c]),jsx("div",{style:{position:"absolute",top:`${n.top}px`,left:`${n.left}px`,zIndex:1e3},children:jsx("textarea",{ref:f=>{if(u.current=f,s.current=f,f){f.focus();let d=f.value.length;f.setSelectionRange(d,d),c(f);}},value:o,onChange:f=>{t(f.target.value);},onKeyDown:f=>{f.key==="Escape"&&a();},style:i},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Xb=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},Ac=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:s})=>{let u=useSelector(w=>w.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useDispatch(),f=useRef(null),[d,l]=useState(null),m=e.data.responseOptions.attempts||0,[h,p]=useState(e.data.responseOptions.userAnswer||""),[v,y]=useState(false);useEffect(()=>{let w=f.current;if(w)return a.current.set(e.id,w),()=>{a.current.delete(e.id);}},[e.id,a]);let b=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=v&&h.trim().toLowerCase()===b,C=w=>{p(w);let T=w.trim(),q=T.toLowerCase()===b;c(sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:T,isCorrect:q}}}));},I=()=>{y(false),p(""),c(sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:"",isCorrect:false}}}));},B=()=>g?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",k=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},x=e.data.feedbackMode==="practice",S=useMemo(()=>{let V=x?48:0,U=12,K=30,R=e.width-48,z=Math.max(60,Xb(e.data.question,18,R,"bold")+20),ne=v?40:0,X=v?54:20,P=z+ne+K+50+12+U+V+24;return {padding:24,questionHeight:z,questionFontSize:18,feedbackHeight:ne,feedbackFontSize:12,inputY:X,inputHeight:50,inputMargin:12,buttonHeight:V,buttonTopMargin:U,placeholderHeight:K,contentWidth:R,totalHeight:P}},[e.width,e.data.question,v,g,x,B]);return jsxs(Group,{ref:f,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:S.totalHeight,name:"sa-element",...s,...i?{}:{onDragEnd:r,onClick:()=>o&&o(e.id),onTap:()=>o&&o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:S.totalHeight,onTransformEnd:w=>t(e.id,w),onContextMenu:w=>{w.cancelBubble=true,n(w.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:S.padding+8,y:S.padding,fontSize:S.questionFontSize,fontStyle:"bold",fill:"#111827",width:S.contentWidth,height:S.questionHeight-S.padding,wrap:"word",listening:false}),jsx(Rect,{x:S.padding,y:S.questionHeight+S.feedbackHeight+S.placeholderHeight-S.inputY,width:S.contentWidth+4,height:S.inputHeight+6,fill:"#ffffff",stroke:g?"#22c55e":v?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:S.padding,y:S.questionHeight+S.feedbackHeight+S.placeholderHeight-S.inputY},divProps:{style:{width:`${S.contentWidth-4}px`,height:`${S.inputHeight}px`,pointerEvents:v?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:w=>C(w.target.value),disabled:v,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:v?"none":"auto"}})}),v&&jsxs(Fragment,{children:[jsx(Rect,{x:S.padding,y:S.questionHeight+80,width:S.contentWidth,height:S.feedbackHeight,fill:k().bg,cornerRadius:8}),jsx(Text,{x:36,y:S.questionHeight+80,width:S.contentWidth,height:S.feedbackHeight,text:B()+` (${m} attempts)`,fontSize:S.feedbackFontSize,fontStyle:"bold",fill:k().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:S.questionHeight+S.feedbackHeight+S.placeholderHeight+S.inputHeight+S.inputMargin+S.buttonTopMargin,children:[jsxs(Group,{onMouseDown:w=>{w.cancelBubble=true,l("check");},onMouseUp:w=>{w.cancelBubble=true,l(null),h.length>0&&(y(true),c(sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},onMouseLeave:w=>{w.cancelBubble=true,l(null);},onTouchStart:w=>{w.cancelBubble=true,l("check");},onTouchEnd:w=>{w.cancelBubble=true,l(null),h.length>0&&y(true);},scaleX:d==="check"?.95:1,scaleY:d==="check"?.95:1,children:[jsx(Rect,{x:S.padding+14,width:(S.contentWidth-24)/(v?2:1),height:S.buttonHeight,fill:h.length===0||v?"#9ca3af":"#096B76",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:S.padding+14,width:(S.contentWidth-24)/(v?2:1),height:S.buttonHeight,text:v?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),v&&jsxs(Group,{x:(e.width-S.padding*2)/2+8,onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),I();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),I();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:S.padding,width:(S.contentWidth-8)/2,height:S.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true}),jsx(Text,{x:S.padding,width:(S.contentWidth-8)/2,height:S.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ac.displayName="ShortAnswer";var Pc=Ac;var Dc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Pc,{shortAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"shortAnswer")},i.id))})};var Rc=e=>{let o=useDispatch(),a=useSelector(ve)?.fillInTheBlanks||[],n=useRef(new Map),r=useCallback((s,u)=>{let i=s.target;o(Sa({id:u,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:n,handleFillInTheBlanksDragEnd:r}};var El=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},Fc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:n,fibRefs:r,touchHandlers:s})=>{let u=useSelector(w=>w.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),f=useDispatch(),[d,l]=useState(null),m=e.data.responseOptions.attempts||0,[h,p]=useState(e.data.responseOptions.userAnswer||""),[v,y]=useState(false);useEffect(()=>{let w=c.current;if(w)return r.current.set(e.id,w),()=>{r.current.delete(e.id);}},[e.id,r]);let b=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=v&&h.trim().toLowerCase()===b,C=w=>{p(w);let T=w.trim(),q=T.toLowerCase()===b;f(Sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:T,isCorrect:q}}}));},I=()=>{y(false),p("");},B=()=>{h.length>0&&(y(true),f(Sa({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,attempts:(e.data.responseOptions.attempts||0)+1}}})));},k=e.data.feedbackMode==="practice",x=useMemo(()=>{let K=e.width-48,R=(K-15)/2,z=24,ne=z,X=Math.max(60,El(e.data.question.replace("_____","________"),24,K,"bold")+20);z+=X;let P=z,N=Math.max(35,El("Enter your answer in the blank.",16,K)+10);z+=N;let _=z;z+=67;let Q=z,re=v?Math.max(32,El(g?"Right Answer, Great Job!":"Wrong Answer",14,K-40)+16):0;v&&(z+=re+16);let j=z;return k&&(z+=64),z+=24,{padding:24,questionY:ne,questionHeight:X,questionFontSize:24,helperTextY:P,helperTextHeight:N,helperTextFontSize:16,inputY:_,inputHeight:51,feedbackY:Q,feedbackHeight:re,feedbackFontSize:14,buttonsY:j,buttonHeight:64,buttonGap:15,buttonWidth:R,contentWidth:K,totalHeight:z}},[e.width,e.data.question,v,g,k]),S=()=>v?g?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...s,...i?{}:{onDragEnd:w=>a(w,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:x.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:w=>t(e.id,w),onContextMenu:w=>{w.cancelBubble=true,n?.(w.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:x.padding,y:x.questionY,fontSize:x.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:x.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:x.padding,y:x.helperTextY,fontSize:x.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:x.contentWidth,height:x.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:x.padding,y:x.inputY,width:x.contentWidth,height:x.inputHeight,fill:"#ffffff",stroke:S(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:x.padding,y:x.inputY},divProps:{style:{width:`${x.contentWidth}px`,height:`${x.inputHeight}px`,pointerEvents:v?"none":"auto"}},children:jsx("input",{type:"text",value:h,onChange:w=>C(w.target.value),disabled:v,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),v&&jsxs(Group,{y:x.feedbackY,children:[jsx(Rect,{x:x.padding,width:x.contentWidth,height:x.feedbackHeight,fill:g?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:g?"\u2713":"\u2717",x:x.padding+10,y:0,width:16,height:x.feedbackHeight,fontSize:x.feedbackFontSize,fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:g?`Right Answer, Great Job! (${m} attempts)`:`Wrong Answer (${m} attempts)`,x:x.padding+30,y:0,height:x.feedbackHeight,fontSize:x.feedbackFontSize,fontStyle:"600",fill:g?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),k&&jsxs(Group,{y:x.buttonsY,children:[jsxs(Group,{x:x.padding,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true,onMouseDown:w=>{w.cancelBubble=true,l("reset");},onMouseUp:w=>{w.cancelBubble=true,l(null),I();},onMouseLeave:w=>{w.cancelBubble=true,l(null);},onTouchStart:w=>{w.cancelBubble=true,l("reset");},onTouchEnd:w=>{w.cancelBubble=true,l(null),I();},scaleX:d==="reset"?.98:1,scaleY:d==="reset"?.98:1,children:[jsx(Rect,{width:x.buttonWidth,height:x.buttonHeight,fill:v?"#096b76":"#9ca3af",cornerRadius:8}),jsx(Text,{width:x.buttonWidth,height:x.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:x.padding+x.buttonWidth+x.buttonGap,onClick:w=>w.cancelBubble=true,onTap:w=>w.cancelBubble=true,onMouseDown:w=>{w.cancelBubble=true,!v&&l("submit");},onMouseUp:w=>{w.cancelBubble=true,!v&&(l(null),B());},onMouseLeave:w=>{w.cancelBubble=true,l(null);},onTouchStart:w=>{w.cancelBubble=true,!v&&l("submit");},onTouchEnd:w=>{w.cancelBubble=true,!v&&(l(null),B());},scaleX:d==="submit"?.98:1,scaleY:d==="submit"?.98:1,children:[jsx(Rect,{width:x.buttonWidth,height:x.buttonHeight,fill:h.length===0||v?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:x.buttonWidth,height:x.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Fc.displayName="FillInTheBlanks";var Bc=Fc;var Nc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,onLongPress:r,fibRefs:s})=>{let{createHandlers:u}=Ve({onLongPress:r});return jsx(Fragment,{children:e.map(i=>jsx(Bc,{fillInTheBlank:i,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:n,fibRefs:s,touchHandlers:u(i.id,"fillInTheBlanks")},i.id))})};var Fl=(e,o,t,a)=>{let r=document.createElement("canvas").getContext("2d");if(!r)return o;r.font=`${a||""} ${o}px Arial, sans-serif`;let s=e.split(" "),u=[],i="";return s.forEach(c=>{let f=i?`${i} ${c}`:c;r.measureText(f).width>t&&i!==""?(u.push(i),i=c):i=f;}),i&&u.push(i),u.length*o*1.2},Ol=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,touchHandlers:r,handleDragEnd:s})=>{let u=useSelector(x=>x.toolbar.selectedTool),i=u==="pen"||u==="eraser",c=useRef(null),f=useDispatch(),[d,l]=useState(null),[m,h]=useState(e.data.responseOptions.userAnswer||""),[p,v]=useState(false);useEffect(()=>{let x=c.current;if(x)return a.current.set(e.id,x),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",b=p&&m.trim().toLowerCase()===y,g=x=>{h(x);let S=x.trim();S.toLowerCase()===y;f(Ja({id:e.id,data:{...e.data,responseOptions:{...e.data.responseOptions,userAnswer:S}}}));},C=()=>{v(false),h("");},I=()=>b?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",B=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},k=useMemo(()=>{let U=e.width-48,K=Math.max(60,Fl(e.data.question,20,U,"bold")+20),R=p?Math.max(60,Fl(I(),14,U)+30):0,ne=Math.max(30,Fl("Answer (Extended response):",14,U)+10),X=K+R+ne+120+12+12+48+24;return {padding:24,questionHeight:K,questionFontSize:20,feedbackHeight:R,feedbackFontSize:14,placeholderHeight:ne,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:U,totalHeight:X}},[e.width,e.data.question,p,b,I]);return jsxs(Group,{ref:c,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:k.totalHeight,...r,name:"la-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:x=>{let S=c.current?.getStage()?.getPointerPosition();if(!S||!n)return;let w={x:e.x,y:e.y,width:e.width,height:k.totalHeight};S.x>=w.x&&S.x<=w.x+w.width&&S.y>=w.y&&S.y<=w.y+w.height&&n(x.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:k.totalHeight-50,onTransformEnd:x=>t(e.id,x)}),jsx(Text,{text:e.data.question,x:k.padding+8,y:k.padding,fontSize:k.questionFontSize,fontStyle:"bold",fill:"#111827",width:k.contentWidth,wrap:"word",listening:false}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:k.padding,y:k.questionHeight,width:k.contentWidth,height:k.feedbackHeight,fill:B().bg,cornerRadius:8}),jsx(Text,{x:k.padding,y:k.questionHeight,width:k.contentWidth,height:k.feedbackHeight,text:I(),fontSize:k.feedbackFontSize,fontStyle:"bold",fill:B().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),jsx(Text,{text:"Answer:",x:k.padding,y:k.questionHeight+k.feedbackHeight+k.textareaMargin,fontSize:k.placeholderFontSize,fill:"#6b7280",width:k.contentWidth,wrap:"word",listening:false}),jsx(Rect,{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight,width:k.contentWidth,height:k.textareaHeight,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight},divProps:{style:{width:`${k.contentWidth}px`,height:`${k.textareaHeight}px`,pointerEvents:p?"none":"auto"}},children:jsx("textarea",{value:m,onChange:x=>g(x.target.value),disabled:p,placeholder:"Type your extended answer here...",className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"18px",pointerEvents:p?"none":"auto"}})}),jsx(Group,{y:k.questionHeight+k.feedbackHeight+k.placeholderHeight+k.textareaHeight+k.textareaMargin+k.buttonTopMargin,children:p&&jsxs(Group,{onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),C();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),C();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:k.padding,width:k.contentWidth,height:k.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:x=>x.cancelBubble=true,onTap:x=>x.cancelBubble=true}),jsx(Text,{x:k.padding,width:k.contentWidth,height:k.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Ol.displayName="LongAnswer";var qc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:r,onLongPress:s})=>{let{createHandlers:u}=Ve({onLongPress:s});return jsx(Fragment,{children:e.map(i=>jsx(Ol,{longAnswer:i,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:n,handleDragEnd:c=>r(c,i.id),touchHandlers:u(i.id,"longAnswer")},i.id))})};var fo=1600,mo=900,Uc=3200,Kc=1800,Iv=e=>{let o=0,t=0,a=fo,n=mo;if(!e)return {minX:o,minY:t,maxX:a,maxY:n,width:fo,height:mo};let r=(i,c,f,d)=>{o=Math.min(o,i),t=Math.min(t,c),a=Math.max(a,i+f),n=Math.max(n,c+d);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let c=i.x||0,f=i.y||0,d=i.scaleX||1,l=i.scaleY||1;for(let m=0;m<i.points.length;m+=2){let h=c+i.points[m]*d,p=f+i.points[m+1]*l;o=Math.min(o,h),t=Math.min(t,p),a=Math.max(a,h),n=Math.max(n,p);}}}),e.images?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>r(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>r(i.x,i.y,i.width,i.height));let s=Math.min(a-o,Uc),u=Math.min(n-t,Kc);return o=Math.max(o,a-Uc),t=Math.max(t,n-Kc),{minX:o,minY:t,maxX:a,maxY:n,width:s,height:u}},Cv=(e,o,t={minX:0,minY:0,maxX:fo,maxY:mo,width:fo,height:mo})=>{let a=Math.max(t.width,fo),n=Math.max(t.height,mo),r=e/o,s=a/n,u,i,c,f=0;if(r>s)i=n,u=Math.round(i*r),c=o/i;else {u=a,i=Math.round(u/r),c=e/u;let d=n*c;f=(o-d)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:u,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},Gc=(e,o,t=1)=>{let a=o.contentOffsetX||0,n=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/(o.scale*t)+a,y:(e.y-o.offsetY)/(o.scale*t)+n}},kv=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:n={enabled:true}}={})=>{let r=_e(),s=ze(),u=J(L=>L.toolbar.selectedTool),i=J(ve),c=J(Ia),f=J(_n),d=J(L=>L.canvas.zoomLevel),m=(i?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),h=!!m,p=useCallback(()=>{m&&r(Xa(m.id));},[r,m]),v=i?.editingActivity,y=i?.showMcqForm,b=i?.lines||[],g=useRef(null),C=useRef(null),[I,B]=useState(null),k=useRef(null),[x,S]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:fo,stageHeight:mo,offsetX:0,offsetY:0,baseWidth:fo,baseHeight:mo,contentOffsetX:0,contentOffsetY:0}),w=useMemo(()=>Iv(i||null),[c]),[T,q]=useState(null),[H,F]=useState(null),[V,U]=useState(null),[K,R]=useState(null),[z,ne]=useState(null),[X$1,P]=useState(null),[N,_]=useState(null),[Q,re]=useState(false),[j,pe]=useState(null),[ge,le]=useState(false),ye=useRef(null),we=useRef(null),xe=useRef(null),{debouncedGenerateThumbnail:St}=xu(c,g);useEffect(()=>{let L=()=>{if(C.current){let E=C.current.getBoundingClientRect(),O=Cv(E.width,E.height,w);S(O);}};L();let M=new ResizeObserver(L);return C.current&&M.observe(C.current),window.addEventListener("resize",L),()=>{M.disconnect(),window.removeEventListener("resize",L);}},[w]),useEffect(()=>{if(g.current){let L=g.current.container();L&&(L.style.cursor="");}},[u]);let ae=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(M=>M.batchDraw()),!f)try{St();}catch(M){console.warn("Preview generation failed (CORS):",M);}});},[St,f]),rn=useRef(c);useEffect(()=>{rn.current!==c&&(rn.current=c,ae());},[c,ae]);let yo=useRef(null),nn=useRef(true);useEffect(()=>{if(!i)return;let L=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),M=yo.current?.count!==L;!nn.current&&M&&setTimeout(()=>{ae();},100),yo.current={slideId:c,count:L},nn.current=false;},[i,c,ae]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{xe.current&&a&&a(xe);},[a]);let{startDrawing:sn,draw:ln,stopDrawing:dn,setCanvasRef:Ks,tool:Gs,color:Ga,strokeWidth:js,isSketchMode:_s}=Kd(ae),ja=useRef(new Map),{images:$s,getLoadedImage:un,imageRefs:_a,handleDragEnd:cn,handleImageTransformEnd:Xs}=Zd(ae),{videos:ir,videoRefs:wo,handleVideoClick:fn,handleVideoDragEnd:Ys,handleVideoTransformEnd:Zs}=eu(ae),{multipleChoice:A,handleMcqTransform:te,mcqRefs:ke,handleDragEnd:Ie}=Jd(ae),{trueFalse:ce,handleTrueFalseTransform:se,trueFalseRefs:Ee,handleTrueFalseDragEnd:it}=Qd(ae),{shortAnswers:ra,saRefs:Ye,handleShortAnswerDragEnd:Oe}=su(ae),{longAnswers:lt,handleLongAnswerDragEnd:na}=iu(ae),{fillInTheBlanks:va,handleFillInTheBlanksDragEnd:Js,fibRefs:So}=Rc(ae),{transformerRef:ie,boundBoxFunc:Ze}=mu(),{shapes:ya,shapeRefs:Jt,isDragging:Cd,handleShapeDragEnd:_m,handleShapeResizeEnd:$m}=ou(ae),{texts:lr,textRefs:wa,handleDragEnd:Xm,handleTransformEnd:Ym,handleDoubleClick:Zm,startEditing:mn,editingTextId:be,editingValue:kd,handleEditingChange:Td,finishEditing:Qs}=nu(ae,ye);useEffect(()=>{t&&t(mn);},[t,mn]);let pn=J(L=>L.canvas.editingTextId);useEffect(()=>{pn&&pn!==be&&mn(pn);},[pn,be,mn]);let{flashcards:Jm,flashcardRefs:hn,handleDragEnd:Qm,handleFlashcardTransformEnd:ep,handleNext:tp,handlePrevious:ap}=du(ae),{photoFrames:Md,photoFrameRefs:gn,handleDragEnd:op,handlePhotoFrameTransformEnd:rp,startCamera:np,capturePhoto:sp,cameraStreams:ip}=fu(ae);useEffect(()=>{if(ie.current){if(be){ie.current.nodes([]),ie.current.getLayer()?.batchDraw();return}if(I&&!ir.find(E=>E.id===I)?.isPlaying){let E=ja.current.get(I)||_a.current.get(I)||wo.current.get(I)||Jt.current.get(I)||wa.current.get(I)||ke.current.get(I)||hn.current.get(I)||gn.current.get(I)||Ye.current.get(I)||Ee.current.get(I)||So.current.get(I);if(E){let O=E.attrs?.locked;if(E.visible()&&O!==true){ie.current.nodes([E]),ie.current.getLayer()?.batchDraw();return}}}ie.current.nodes([]),ie.current.getLayer()?.batchDraw();}},[I,be,ir,ja,_a,wo,Jt,wa,hn,gn,Md,ke,Ee,So,ie]);let We=useCallback(L=>{B(L),o?.(L);},[o]),Lo=useCallback(()=>{B(null),o?.(null),ie.current&&(ie.current.nodes([]),ie.current.getLayer()?.batchDraw());},[ie,o]),Ad=useCallback(L=>i?i.lines?.some(M=>M.id===L)?"line":i.images?.some(M=>M.id===L)?"image":i.videos?.some(M=>M.id===L)?"video":i.shapes?.some(M=>M.id===L)?"shape":i.texts?.some(M=>M.id===L)?"text":i.flashcards?.some(M=>M.id===L)?"flashcard":i.photoFrames?.some(M=>M.id===L)?"photoFrame":i.multipleChoices?.some(M=>M.id===L)?"mcq":i.trueFalses?.some(M=>M.id===L)?"trueFalse":i.shortAnswers?.some(M=>M.id===L)?"shortAnswer":i.LongAnswer?.some(M=>M.id===L)?"longAnswer":i.fillInTheBlanks?.some(M=>M.id===L)?"fillInTheBlanks":null:null,[i]),Pd=useCallback((L,M)=>{switch(r(de()),M){case "line":r(Gn(L));break;case "image":r(bn(L));break;case "video":r(wn(L));break;case "shape":r(In(L));break;case "text":r(Cn(L));break;case "flashcard":r(Tn(L));break;case "photoFrame":r(An(L));break;case "mcq":r(En(L));break;case "trueFalse":r(Rn(L));break;case "shortAnswer":r(Bn(L));break;case "longAnswer":r(Nn(L));break;case "fillInTheBlanks":r(qn(L));break}Lo(),ae();},[r,Lo,ae]);useEffect(()=>{let L=M=>{if(M.key!=="Delete"&&M.key!=="Backspace"||!I||be)return;let E=document.activeElement;if(E instanceof HTMLInputElement||E instanceof HTMLTextAreaElement||E?.getAttribute("contenteditable")==="true")return;M.preventDefault();let Ce=Ad(I);Ce&&Pd(I,Ce);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[I,be,Ad,Pd]),useEffect(()=>{let L=ie.current;return ()=>{L&&L.nodes([]);}},[c]),useEffect(()=>{let L=M=>{be&&M.target.tagName!=="TEXTAREA"&&Qs();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[be,Qs]),useEffect(()=>{let L=be||I;if(!L||I&&be){F(null);return}let M=wa.current.get(L),E=g.current;if(!M||!E){F(null);return}let O=E.container().getBoundingClientRect(),Ce=M.absolutePosition(),he=E.scaleX();F({x:O.left+(Ce.x+M.width()*he/2)*he+x.offsetX,y:O.top+Ce.y*he+x.offsetY-70});},[I,be,lr,wa,x.offsetX,x.offsetY]),useEffect(()=>{if(!be){U(null);return}let L=wa.current.get(be),M=g.current;if(!L||!M){U(null);return}let E=L.getClientRect({relativeTo:M}),O=M.container().getBoundingClientRect(),Ce=M.scaleX(),he=M.position(),oe={top:O.top+he.y+E.y*Ce,left:O.left+he.x+E.x*Ce,scale:Ce};U(oe),r(Vd(oe));},[be,lr,wa,x.offsetY,x.offsetX]);let Ed=useCallback(L=>{let M=L.target.getClassName(),E=L.target===L.target.getStage(),O=M==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",Ce=M==="Image",he=M==="Text",oe=M==="Group"||L.target.getParent()?.getClassName()==="Group",pt=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&L.target.attrs.id,ht=M==="Group";if(E&&!O&&!Ce&&!he&&!oe&&!pt&&!ht&&Lo(),!(u==="pen"||u==="eraser")&&(Ce||he||O||oe||pt||ht))return;let Ue=L.target.getStage()?.getPointerPosition();if(!Ue)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let W=Gc(Ue,x,d);sn(W);}},[u,sn,Lo,x,d]),Dd=useCallback(L=>{if(Cd)return;let M=L.target.getStage()?.getPointerPosition();if(!M)return;let E=Gc(M,x,d);ln(E);},[ln,Cd,x,d]),Rd=useCallback(()=>{dn();},[dn]),lp=useCallback(L=>{cn(L,ae);},[cn,ae]),dp=useCallback(L=>{fn(L),We(L);},[fn,We]),Rt=useCallback((L,M,E)=>{if(L.preventDefault(),!n.enabled)return;let O=L.clientX,Ce=L.clientY,he=k.current?.offsetHeight||250,oe=k.current?.offsetWidth||200,pt=window.innerHeight,ht=window.innerWidth,tt=O,Ue=Ce;Ce+he>pt&&(Ue=Ce-he),O+oe>ht&&(tt=O-oe),We(M),q({x:tt,y:Ue,elementId:M,elementType:E});},[We,n.enabled]),$a=useRef(null),dr=useRef(null),Lt=useCallback((L,M)=>E=>{if(!n.enabled)return;E.preventDefault();let O=E.changedTouches[0];if(!O)return;let Ce=O.clientX,he=O.clientY,oe=k.current?.offsetHeight||200,pt=k.current?.offsetWidth||200,ht=window.innerHeight,tt=window.innerWidth,Ue=Ce,at=he;he+oe>ht&&(at=he-oe),Ce+pt>tt&&(Ue=Ce-pt),We(L),q({x:Ue,y:at,elementId:L,elementType:M});},[We,n.enabled]),up=useCallback((L,M)=>({onTouchStart:E=>{let O=E.evt.touches[0];dr.current={x:O.clientX,y:O.clientY},$a.current=setTimeout(()=>{Lt(L,M)(E.evt);},500);},onTouchMove:E=>{if(!dr.current)return;let O=E.evt.touches[0],Ce=Math.abs(O.clientX-dr.current.x),he=Math.abs(O.clientY-dr.current.y);(Ce>10||he>10)&&$a.current&&(clearTimeout($a.current),$a.current=null);},onTouchEnd:()=>{$a.current&&(clearTimeout($a.current),$a.current=null),dr.current=null;}}),[Lt]),Fd=useCallback(L=>{r(gr(L)),r(La(true));},[r]),Bd=useCallback(L=>{r(hr(L)),r(Qa(true));},[r]),cp=useCallback((L,M)=>{if(!T)return;let{elementId:E,elementType:O}=T;switch(L){case "order":if(M){let D=M.target.getBoundingClientRect();R({x:D.right+5,y:D.top,type:"order"});}break;case "lock":if(M){let D=M.target.getBoundingClientRect();R({x:D.right+5,y:D.top,type:"lock"});}break;case "link":if(q(null),O==="line")break;let Ce=i?O==="image"?i.images.find(D=>D.id===E):i.videos.find(D=>D.id===E):null;ne({type:"link",defaultValue:Ce?.link||""});break;case "voice":if(q(null),O==="line")break;let he=i?O==="image"?i.images.find(D=>D.id===E):O==="video"?i.videos.find(D=>D.id===E):O==="text"?i.texts.find(D=>D.id===E):O==="flashcard"?i.flashcards.find(D=>D.id===E):O==="photoFrame"?i.photoFrames.find(D=>D.id===E):O==="mcq"?i.multipleChoices.find(D=>D.id===E):O==="fillInTheBlanks"?i.fillInTheBlanks.find(D=>D.id===E):O==="longAnswer"?i.LongAnswer.find(D=>D.id===E):O==="shortAnswer"?i.shortAnswers.find(D=>D.id===E):O==="trueFalse"?i.trueFalses.find(D=>D.id===E):O==="shape"?i.shapes.find(D=>D.id===E):null:null;pe({elementId:E,elementType:O,existingAudio:he?.audioData});break;case "edit":q(null);let oe=null;O==="mcq"?oe=i?.multipleChoices.find(D=>D.id===E):O==="trueFalse"?oe=i?.trueFalses.find(D=>D.id===E):O==="shortAnswer"?oe=i?.shortAnswers.find(D=>D.id===E):O==="longAnswer"?oe=i?.LongAnswer.find(D=>D.id===E):O==="fillInTheBlanks"&&(oe=i?.fillInTheBlanks.find(D=>D.id===E)),oe&&Fd(oe);break;case "editFlashcard":q(null);let pt=i?.flashcards.find(D=>D.id===E);pt&&Bd(pt);break;case "color":q(null);let ht=i?.shapes.find(D=>D.id===E);P({elementId:E,elementType:"shape",defaultColor:ht?.color||"#096B76"});break;case "border":if(q(null),O==="shape"){r(de());let D=i?.shapes.find(ti=>ti.id===E);D&&r(Ya({id:E,hasBorder:!D.hasBorder})),ae();}break;case "crop":if(q(null),O==="image"){let D=i?.images.find(ti=>ti.id===E);D&&_({elementId:E,imageSrc:D.src});}break;case "draw":q(null),O==="image"?r(hi(E)):O==="photoFrame"&&r(xi(E));break;case "duplicate":r(de()),O==="line"?r(Pi(E)):O==="image"?r(vn(E)):O==="video"?r(Sn(E)):O==="shape"?r(Ln(E)):O==="text"?r(kn(E)):O==="flashcard"?r(Mn(E)):O==="photoFrame"?r(Pn(E)):O==="mcq"?r(Dn(E)):O==="trueFalse"?r(Fn(E)):O==="shortAnswer"?r(On(E)):O==="fillInTheBlanks"?r(Vn(E)):O==="longAnswer"&&r(Hn(E)),ae();break;case "infinite-clone":r(de());let tt=5;for(let D=0;D<tt;D++)O==="image"?r(vn(E)):O==="video"?r(Sn(E)):O==="shape"?r(Ln(E)):O==="text"?r(kn(E)):O==="flashcard"?r(Mn(E)):O==="photoFrame"?r(Pn(E)):O==="mcq"?r(Dn(E)):O==="trueFalse"?r(Fn(E)):O==="shortAnswer"?r(On(E)):O==="fillInTheBlanks"?r(Vn(E)):O==="longAnswer"&&r(Hn(E));ae();break;case "make-response":if(q(null),O==="line")break;let Ue=`#response-${E}`;r(de()),r(zn({id:E,type:O,link:Ue})),(i?O==="image"?i.images.find(D=>D.id===E):O==="video"?i.videos.find(D=>D.id===E):O==="shape"?i.shapes.find(D=>D.id===E):O==="flashcard"?i.flashcards.find(D=>D.id===E):O==="photoFrame"?i.photoFrames.find(D=>D.id===E):i.multipleChoices.find(D=>D.id===E):null)?.altText||r(Wn({id:E,type:O,altText:"Interactive response area"})),ae(),console.log(`Element ${E} marked as interactive response area`);break;case "accessibility":if(q(null),O==="line")break;let W=i?O==="image"?i.images.find(D=>D.id===E):O==="video"?i.videos.find(D=>D.id===E):O==="shape"?i.shapes.find(D=>D.id===E):null:null;ne({type:"altText",defaultValue:W?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),q(null),le(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(de()),O==="line"?r(Gn(E)):O==="image"?r(bn(E)):O==="video"?r(wn(E)):O==="shape"?r(In(E)):O==="text"?r(Cn(E)):O==="flashcard"?r(Tn(E)):O==="photoFrame"?r(An(E)):O==="mcq"?r(En(E)):O==="trueFalse"?r(Rn(E)):O==="shortAnswer"?r(Bn(E)):O==="longAnswer"?r(Nn(E)):O==="fillInTheBlanks"&&r(qn(E)),Lo(),ae();break}},[T,r,ae,Lo,i,Fd,Bd]),fp=useCallback(()=>{q(null),R(null);},[]),ei=useCallback(L=>{if(!T)return;let{elementId:M,elementType:E}=T;switch(r(de()),L){case "bring-to-front":E!=="line"&&r(ki({id:M,type:E}));break;case "send-to-back":E!=="line"&&r(Ti({id:M,type:E}));break;case "lock":case "unlock":E!=="line"&&r(Mi({id:M,type:E}));break}ae(),q(null),R(null);},[T,r,ae]),mp=useCallback(L=>{if(!T||!z)return;let{elementId:M,elementType:E}=T;r(de()),z.type==="link"&&E!=="line"?r(zn({id:M,type:E,link:L})):z.type==="altText"&&E!=="line"&&r(Wn({id:M,type:E,altText:L})),ae(),ne(null);},[T,z,r,ae]),pp=useCallback(L=>{if(!j)return;let{elementId:M,elementType:E}=j;r(de()),r(Un({id:M,type:E,audioData:L})),ae(),pe(null);},[j,r,ae]),hp=useCallback(()=>{if(!j)return;let{elementId:L,elementType:M}=j;r(de()),r(Un({id:L,type:M,audioData:""})),ae();},[j,r,ae]),gp=useCallback(L=>{if(!X$1)return;let{elementId:M}=X$1;r(de()),r(Ya({id:M,color:L})),ae(),P(null);},[X$1,r,ae]),xp=useCallback(L=>{if(!N)return;let{elementId:M}=N;r(de()),r(Co({id:M,src:L})),ae(),_(null);},[N,r,ae]);return jsxs("div",{ref:C,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Xd,{ref:L=>{if(we.current=L,Ks(L),L){let M=L.getCanvasElement();M&&(xe.current=M,a&&a(xe));}},width:x.baseWidth,height:x.baseHeight,tool:Gs,color:Ga,strokeWidth:js/(x.scale*d),isSketchMode:_s,xOffset:x.contentOffsetX,yOffset:x.contentOffsetY-x.offsetY/x.scale,style:{width:x.stageWidth,height:x.stageHeight}}),jsxs(Stage,{ref:g,width:x.stageWidth,height:x.stageHeight,scaleX:x.scaleX*d,scaleY:x.scaleY*d,x:x.offsetX,y:0,onMouseDown:Ed,onMouseMove:Dd,onMouseUp:Rd,onTouchStart:Ed,onTouchMove:Dd,onTouchEnd:Rd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:x.baseWidth,height:x.stageHeight/x.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-x.contentOffsetX,y:x.offsetY/x.scale-x.contentOffsetY,children:(()=>{let L=[];return b.forEach((M,E)=>{L.push({type:"line",timestamp:M.timestamp||E,element:{...M,id:M.id??`line-${E}`},index:E});}),ya.forEach(M=>{L.push({type:"shape",timestamp:M.timestamp||0,element:M});}),$s.forEach(M=>{L.push({type:"image",timestamp:M.timestamp||0,element:M});}),ir.forEach(M=>{L.push({type:"video",timestamp:M.timestamp||0,element:M});}),lr.forEach(M=>{L.push({type:"text",timestamp:M.timestamp||0,element:M});}),Jm.forEach(M=>{L.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Md.forEach(M=>{L.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),A.forEach(M=>{L.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),ce.forEach(M=>{L.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),ra.forEach(M=>{L.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),lt.forEach(M=>{L.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),va.forEach(M=>{L.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),L.sort((M,E)=>M.timestamp-E.timestamp),L.map((M,E)=>{let O=`${M.type}-${"id"in M.element&&M.element.id||M.index||E}`,Ce="id"in M.element?M.element.id:void 0,he=Ce&&I===Ce;switch(M.type){case "line":let oe=M.element,pt=M.index||0,ht=oe.tool==="eraser",tt=oe.isSketch&&oe.tool==="pen",Ue=oe.isSketch&&ht,at=oe.id||`line-${pt}`;return oe.x===void 0&&(oe.x=0),oe.y===void 0&&(oe.y=0),oe.scaleX===void 0&&(oe.scaleX=1),oe.scaleY===void 0&&(oe.scaleY=1),oe.rotation===void 0&&(oe.rotation=0),u==="eraser"?jsx(Group,{x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,children:jsx(Line,{points:oe.points||[],stroke:tt||Ue?void 0:oe.color,strokeWidth:tt||Ue?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Ue?ht?"black":oe.color:void 0,closed:tt||Ue,tension:0,globalCompositeOperation:ht?"destination-out":"source-over",listening:true,onClick:()=>{r(de()),r(xn(pt));},onTap:()=>{r(de()),r(xn(pt));},hitStrokeWidth:Math.max(20,(oe.strokeWidth??0)*2),onMouseEnter:W=>{let D=W.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:W=>{let D=W.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},O):jsxs(Le__default.Fragment,{children:[jsx(Group,{id:at,ref:W=>{W?ja.current.set(at,W):ja.current.delete(at);},x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",at),We(at));},onTap:()=>{u==="select"&&(console.log("Line tapped:",at),We(at));},onDragEnd:W=>{r(de()),r(Kn({id:at,x:W.target.x(),y:W.target.y(),scaleX:W.target.scaleX(),scaleY:W.target.scaleY(),rotation:W.target.rotation()})),ae();},onTransformEnd:W=>{r(de()),r(Kn({id:at,x:W.target.x(),y:W.target.y(),scaleX:W.target.scaleX(),scaleY:W.target.scaleY(),rotation:W.target.rotation()})),ae();},onMouseEnter:W=>{if(u==="select"){let D=W.target.getStage();D&&(D.container().style.cursor="move");}},onMouseLeave:W=>{if(u==="select"){let D=W.target.getStage();D&&(D.container().style.cursor="default");}},onContextMenu:W=>{let D=W.evt;D.preventDefault(),Rt(D,at,"line");},...up(at,"line"),children:jsx(Line,{points:oe.points||[],stroke:tt||Ue?void 0:oe.color,strokeWidth:tt||Ue?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Ue?ht?"black":oe.color:void 0,closed:tt||Ue,tension:0,globalCompositeOperation:ht?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=ja.current.get(I);console.log("Line Transformer - selectedId:",I,"node found:",!!D),D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shape":return jsxs(Le__default.Fragment,{children:[jsx(_i,{onSelect:We,shapes:[M.element],shapeRefs:Jt,handleShapeDragEnd:_m,handleShapeResizeEnd:$m,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Jt.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "image":return jsxs(Le__default.Fragment,{children:[jsx(Ui,{images:[M.element],getLoadedImage:un,imageRefs:_a,onDragEnd:lp,onTransform:Xs,onSelect:We,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=_a.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "video":return jsxs(Le__default.Fragment,{children:[jsx(ji,{videos:[M.element],selectedId:I,videoRefs:wo,onVideoClick:dp,onDragEnd:Ys,onTransformEnd:Zs,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=wo.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "text":return jsxs(Le__default.Fragment,{children:[jsx(Au,{texts:[M.element],textRefs:wa,onDragEnd:Xm,onTransformEnd:Ym,onSelect:We,onContextMenu:Rt,onLongPress:Lt,onDoubleClick:Zm,editingTextId:be,editingValue:kd,onEditingChange:Td}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=wa.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "flashcard":return jsxs(Le__default.Fragment,{children:[jsx(Zi,{flashcards:[M.element],flashcardRefs:hn,selectedId:I,onDragEnd:Qm,onTransform:ep,onSelect:We,onNext:tp,onPrevious:ap,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=hn.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "photoFrame":return jsxs(Le__default.Fragment,{children:[jsx(ol,{photoFrames:[M.element],photoFrameRefs:gn,selectedId:I,onDragEnd:op,onTransform:rp,onSelect:We,onStartCamera:np,onCapture:sp,cameraStreams:ip,onContextMenu:Rt,onLongPress:Lt}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=gn.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},boundBoxFunc:Ze,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "mcq":return jsxs(Le__default.Fragment,{children:[jsx(ic,{handleMcqTransform:te,multipleChoice:[M.element],handleSelect:We,mcqRefs:ke,handleDragEnd:Ie,onContextMenu:Rt,onLongPress:Lt,onUpdate:ae}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=ke.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "trueFalse":return jsxs(Le__default.Fragment,{children:[jsx(cc,{trueFalses:[M.element],handleTrueFalseTransform:se,handleSelect:We,trueFalseRefs:Ee,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:it,onUpdate:ae}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Ee.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shortAnswer":return jsxs(Le__default.Fragment,{children:[jsx(Dc,{shortAnswers:[M.element],handleSelect:We,handleTransform:te,saRefs:Ye,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:Oe}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Ye.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "longAnswer":return jsxs(Le__default.Fragment,{children:[jsx(qc,{longAnswer:[M.element],handleSelect:We,handleTransform:te,saRefs:Ye,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:na}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=Ye.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "fillInTheBlanks":return jsxs(Le__default.Fragment,{children:[jsx(Nc,{fillInTheBlanks:[M.element],handleSelect:We,handleTransform:te,onContextMenu:Rt,onLongPress:Lt,handleDragEnd:Js,fibRefs:So}),he&&!be&&I&&jsx(Transformer,{ref:W=>{if(W&&ie.current!==W){ie.current=W;let D=So.current.get(I);D&&D.visible()&&(W.nodes([D]),W.getLayer()?.batchDraw());}},borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);default:return null}})})()})]}),T&&jsx(Wu,{menuRef:k,x:T.x,y:T.y,type:T.elementType,onAction:cp,onClose:fp,isDrawingMode:T.elementType==="image"?i?.images.find(L=>L.id===T.elementId)?.isDrawingMode:T.elementType==="photoFrame"?i?.photoFrames.find(L=>L.id===T.elementId)?.isDrawingMode:false}),K&&T&&jsx(Uu,{x:K.x,y:K.y,items:K.type==="order"?[{label:"Bring to Front",onClick:()=>ei("bring-to-front")},{label:"Send to Back",onClick:()=>ei("send-to-back")}]:[{label:i&&(T.elementType==="image"?i.images.find(L=>L.id===T.elementId)?.locked:i.videos.find(L=>L.id===T.elementId)?.locked)?"Unlock":"Lock",onClick:()=>ei(i&&(T.elementType==="image"?i.images.find(L=>L.id===T.elementId)?.locked:i.videos.find(L=>L.id===T.elementId)?.locked)?"unlock":"lock")}],onClose:()=>R(null)}),z&&jsx(ju,{title:z.type==="link"?"Add Link":"Add Alt Text",label:z.type==="link"?"URL":"Alternative Text",placeholder:z.type==="link"?"https://example.com":"Describe this image/video",defaultValue:z.defaultValue,onSave:mp,onClose:()=>ne(null)}),X$1&&jsx(es,{defaultColor:X$1.defaultColor,onConfirm:gp,onCancel:()=>P(null)}),N&&jsx(Yu,{imageSrc:N.imageSrc,onConfirm:xp,onCancel:()=>_(null)}),Q&&jsx(eo,{onClose:()=>re(false),stageRef:g}),j&&jsx(ec,{elementId:j.elementId,elementType:j.elementType,existingAudio:j.existingAudio,onSave:pp,onDelete:hp,onClose:()=>pe(null)}),ge&&jsx(oc,{selectedElementId:I||void 0,onClose:()=>le(false),onSelectElement:L=>{We(L),le(false);}}),i?.images.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.videos.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.shapes?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.texts?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),i?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Nt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:x.scale,offsetX:x.offsetX,offsetY:x.offsetY},`audio-${L.id}`)),y&&jsx(Sc,{editElement:v}),H&&(()=>{let L=be||I;if(!L)return null;let M=lr.find(E=>E.id===L);return M?jsx(kc,{text:M,position:H}):null})(),V&&be&&(()=>{let L=lr.find(M=>M.id===be);return L?jsx(Mc,{text:L,editingValue:kd,onEditingChange:Td,onFinish:Qs,position:{top:V.top,left:V.left},scale:V.scale,textareaRef:ye},be):null})(),h&&s&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:m?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:p})}),jsx("button",{onClick:p,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),s)]})},Tv=kv;var Av="SchooplaVideoStorage";var ta="videos",Cs=()=>new Promise((e,o)=>{let t=indexedDB.open(Av,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(ta)||n.createObjectStore(ta,{keyPath:"id"});};}),da=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Cs(),r=a.transaction([ta],"readwrite").objectStore(ta),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,i)=>{let c=r.put(s);c.onsuccess=()=>u(!0),c.onerror=()=>i(c.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var jc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Cs(),t=e.transaction([ta],"readonly").objectStore(ta);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let s=r.result,u=new Map;s.forEach(i=>{u.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),a(u);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Nl=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Cs(),a=o.transaction([ta],"readwrite").objectStore(ta);await new Promise((n,r)=>{let s=a.delete(e);s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},_c=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Cs(),t=e.transaction([ta],"readwrite").objectStore(ta);await new Promise((a,n)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>n(r.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},$c=e=>URL.createObjectURL(e);function Ha(e,o=[]){let t=[];function a(r,s){let u=Le.createContext(s),i=t.length;t=[...t,s];let c=d=>{let{scope:l,children:m,...h}=d,p=l?.[e]?.[i]||u,v=Le.useMemo(()=>h,Object.values(h));return jsx(p.Provider,{value:v,children:m})};c.displayName=r+"Provider";function f(d,l){let m=l?.[e]?.[i]||u,h=Le.useContext(m);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${r}\``)}return [c,f]}let n=()=>{let r=t.map(s=>Le.createContext(s));return function(u){let i=u?.[e]||r;return Le.useMemo(()=>({[`__scope${e}`]:{...u,[e]:i}}),[u,i])}};return n.scopeName=e,[a,Ev(n,...o)]}function Ev(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(n=>({useScope:n(),scopeName:n.scopeName}));return function(r){let s=a.reduce((u,{useScope:i,scopeName:c})=>{let d=i(r)[`__scope${c}`];return {...u,...d}},{});return Le.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function Xc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function $r(...e){return o=>{let t=false,a=e.map(n=>{let r=Xc(n,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let n=0;n<a.length;n++){let r=a[n];typeof r=="function"?r():Xc(e[n],null);}}}}function Ut(...e){return Le.useCallback($r(...e),e)}function Jc(e){let o=Dv(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Fv);if(i){let c=i.props.children,f=u.map(d=>d===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Dv(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Ov(n),u=Bv(r,n.props);return n.type!==Le.Fragment&&(u.ref=a?$r(a,s):s),Le.cloneElement(n,u)}return Le.Children.count(n)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Rv=Symbol("radix.slottable");function Fv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Rv}function Bv(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let i=r(...u);return n(...u),i}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function Ov(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var qv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],yt=qv.reduce((e,o)=>{let t=Jc(`Primitive.${o}`),a=Le.forwardRef((n,r)=>{let{asChild:s,...u}=n,i=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...u,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function nt(e,o,{checkForDefaultPrevented:t=true}={}){return function(n){if(e?.(n),t===false||!n.defaultPrevented)return o?.(n)}}function Hl(e){let o=Vv(e),t=Le.forwardRef((a,n)=>{let{children:r,...s}=a,u=Le.Children.toArray(r),i=u.find(Wv);if(i){let c=i.props.children,f=u.map(d=>d===i?Le.Children.count(c)>1?Le.Children.only(null):Le.isValidElement(c)?c.props.children:null:d);return jsx(o,{...s,ref:n,children:Le.isValidElement(c)?Le.cloneElement(c,void 0,f):null})}return jsx(o,{...s,ref:n,children:r})});return t.displayName=`${e}.Slot`,t}function Vv(e){let o=Le.forwardRef((t,a)=>{let{children:n,...r}=t;if(Le.isValidElement(n)){let s=Kv(n),u=Uv(r,n.props);return n.type!==Le.Fragment&&(u.ref=a?$r(a,s):s),Le.cloneElement(n,u)}return Le.Children.count(n)>1?Le.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var zv=Symbol("radix.slottable");function Wv(e){return Le.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===zv}function Uv(e,o){let t={...o};for(let a in o){let n=e[a],r=o[a];/^on[A-Z]/.test(a)?n&&r?t[a]=(...u)=>{let i=r(...u);return n(...u),i}:n&&(t[a]=n):a==="style"?t[a]={...n,...r}:a==="className"&&(t[a]=[n,r].filter(Boolean).join(" "));}return {...e,...t}}function Kv(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function ks(e){let o=e+"CollectionProvider",[t,a]=Ha(o),[n,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=p=>{let{scope:v,children:y}=p,b=Le__default.useRef(null),g=Le__default.useRef(new Map).current;return jsx(n,{scope:v,itemMap:g,collectionRef:b,children:y})};s.displayName=o;let u=e+"CollectionSlot",i=Hl(u),c=Le__default.forwardRef((p,v)=>{let{scope:y,children:b}=p,g=r(u,y),C=Ut(v,g.collectionRef);return jsx(i,{ref:C,children:b})});c.displayName=u;let f=e+"CollectionItemSlot",d="data-radix-collection-item",l=Hl(f),m=Le__default.forwardRef((p,v)=>{let{scope:y,children:b,...g}=p,C=Le__default.useRef(null),I=Ut(v,C),B=r(f,y);return Le__default.useEffect(()=>(B.itemMap.set(C,{ref:C,...g}),()=>void B.itemMap.delete(C))),jsx(l,{[d]:"",ref:I,children:b})});m.displayName=f;function h(p){let v=r(e+"CollectionConsumer",p);return Le__default.useCallback(()=>{let b=v.collectionRef.current;if(!b)return [];let g=Array.from(b.querySelectorAll(`[${d}]`));return Array.from(v.itemMap.values()).sort((B,k)=>g.indexOf(B.ref.current)-g.indexOf(k.ref.current))},[v.collectionRef,v.itemMap])}return [{Provider:s,Slot:c,ItemSlot:m},h,a]}var Zo=globalThis?.document?Le.useLayoutEffect:()=>{};var Gv=Le[" useId ".trim().toString()]||(()=>{}),jv=0;function af(e){let[o,t]=Le.useState(Gv());return Zo(()=>{t(a=>a??String(jv++));},[e]),(o?`radix-${o}`:"")}function of(e){let o=Le.useRef(e);return Le.useEffect(()=>{o.current=e;}),Le.useMemo(()=>(...t)=>o.current?.(...t),[])}var _v=Le[" useInsertionEffect ".trim().toString()]||Zo;function ca({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[n,r,s]=$v({defaultProp:o,onChange:t}),u=e!==void 0,i=u?e:n;{let f=Le.useRef(e!==void 0);Le.useEffect(()=>{let d=f.current;d!==u&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${u?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=u;},[u,a]);}let c=Le.useCallback(f=>{if(u){let d=Xv(f)?f(e):f;d!==e&&s.current?.(d);}else r(f);},[u,e,r,s]);return [i,c]}function $v({defaultProp:e,onChange:o}){let[t,a]=Le.useState(e),n=Le.useRef(t),r=Le.useRef(o);return _v(()=>{r.current=o;},[o]),Le.useEffect(()=>{n.current!==t&&(r.current?.(t),n.current=t);},[t,n]),[t,a,r]}function Xv(e){return typeof e=="function"}var Yv=Le.createContext(void 0);function Qo(e){let o=Le.useContext(Yv);return e||o||"ltr"}var zl="rovingFocusGroup.onEntryFocus",Zv={bubbles:false,cancelable:true},Xr="RovingFocusGroup",[Wl,rf,Jv]=ks(Xr),[Qv,Ul]=Ha(Xr,[Jv]),[ey,ty]=Qv(Xr),nf=Le.forwardRef((e,o)=>jsx(Wl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Wl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(ay,{...e,ref:o})})}));nf.displayName=Xr;var ay=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:n=false,dir:r,currentTabStopId:s,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:i,onEntryFocus:c,preventScrollOnEntryFocus:f=false,...d}=e,l=Le.useRef(null),m=Ut(o,l),h=Qo(r),[p,v]=ca({prop:s,defaultProp:u??null,onChange:i,caller:Xr}),[y,b]=Le.useState(false),g=of(c),C=rf(t),I=Le.useRef(false),[B,k]=Le.useState(0);return Le.useEffect(()=>{let x=l.current;if(x)return x.addEventListener(zl,g),()=>x.removeEventListener(zl,g)},[g]),jsx(ey,{scope:t,orientation:a,dir:h,loop:n,currentTabStopId:p,onItemFocus:Le.useCallback(x=>v(x),[v]),onItemShiftTab:Le.useCallback(()=>b(true),[]),onFocusableItemAdd:Le.useCallback(()=>k(x=>x+1),[]),onFocusableItemRemove:Le.useCallback(()=>k(x=>x-1),[]),children:jsx(yt.div,{tabIndex:y||B===0?-1:0,"data-orientation":a,...d,ref:m,style:{outline:"none",...e.style},onMouseDown:nt(e.onMouseDown,()=>{I.current=true;}),onFocus:nt(e.onFocus,x=>{let S=!I.current;if(x.target===x.currentTarget&&S&&!y){let w=new CustomEvent(zl,Zv);if(x.currentTarget.dispatchEvent(w),!w.defaultPrevented){let T=C().filter(U=>U.focusable),q=T.find(U=>U.active),H=T.find(U=>U.id===p),V=[q,H,...T].filter(Boolean).map(U=>U.ref.current);df(V,f);}}I.current=false;}),onBlur:nt(e.onBlur,()=>b(false))})})}),sf="RovingFocusGroupItem",lf=Le.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:n=false,tabStopId:r,children:s,...u}=e,i=af(),c=r||i,f=ty(sf,t),d=f.currentTabStopId===c,l=rf(t),{onFocusableItemAdd:m,onFocusableItemRemove:h,currentTabStopId:p}=f;return Le.useEffect(()=>{if(a)return m(),()=>h()},[a,m,h]),jsx(Wl.ItemSlot,{scope:t,id:c,focusable:a,active:n,children:jsx(yt.span,{tabIndex:d?0:-1,"data-orientation":f.orientation,...u,ref:o,onMouseDown:nt(e.onMouseDown,v=>{a?f.onItemFocus(c):v.preventDefault();}),onFocus:nt(e.onFocus,()=>f.onItemFocus(c)),onKeyDown:nt(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){f.onItemShiftTab();return}if(v.target!==v.currentTarget)return;let y=ny(v,f.orientation,f.dir);if(y!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let g=l().filter(C=>C.focusable).map(C=>C.ref.current);if(y==="last")g.reverse();else if(y==="prev"||y==="next"){y==="prev"&&g.reverse();let C=g.indexOf(v.currentTarget);g=f.loop?sy(g,C+1):g.slice(C+1);}setTimeout(()=>df(g));}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:p!=null}):s})})});lf.displayName=sf;var oy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ry(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ny(e,o,t){let a=ry(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return oy[a]}function df(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function sy(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var uf=nf,cf=lf;var mf="Toggle",Kl=Le.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:n,...r}=e,[s,u]=ca({prop:t,onChange:n,defaultProp:a??false,caller:mf});return jsx(yt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:nt(e.onClick,()=>{e.disabled||u(!s);})})});Kl.displayName=mf;var qa="ToggleGroup",[hf]=Ha(qa,[Ul]),gf=Ul(),Gl=Le__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(dy,{...a,ref:o});if(t==="multiple")return jsx(uy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${qa}\``)});Gl.displayName=qa;var[xf,bf]=hf(qa),dy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=ca({prop:t,defaultProp:a??"",onChange:n,caller:qa});return jsx(xf,{scope:e.__scopeToggleGroup,type:"single",value:Le__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:u,onItemDeactivate:Le__default.useCallback(()=>u(""),[u]),children:jsx(vf,{...r,ref:o})})}),uy=Le__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:n=()=>{},...r}=e,[s,u]=ca({prop:t,defaultProp:a??[],onChange:n,caller:qa}),i=Le__default.useCallback(f=>u((d=[])=>[...d,f]),[u]),c=Le__default.useCallback(f=>u((d=[])=>d.filter(l=>l!==f)),[u]);return jsx(xf,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:c,children:jsx(vf,{...r,ref:o})})});Gl.displayName=qa;var[cy,fy]=hf(qa),vf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:n=true,orientation:r,dir:s,loop:u=true,...i}=e,c=gf(t),f=Qo(s),d={role:"group",dir:f,...i};return jsx(cy,{scope:t,rovingFocus:n,disabled:a,children:n?jsx(uf,{asChild:true,...c,orientation:r,dir:f,loop:u,children:jsx(yt.div,{...d,ref:o})}):jsx(yt.div,{...d,ref:o})})}),As="ToggleGroupItem",my=Le__default.forwardRef((e,o)=>{let t=bf(As,e.__scopeToggleGroup),a=fy(As,e.__scopeToggleGroup),n=gf(e.__scopeToggleGroup),r=t.value.includes(e.value),s=a.disabled||e.disabled,u={...e,pressed:r,disabled:s},i=Le__default.useRef(null);return a.rovingFocus?jsx(cf,{asChild:true,...n,focusable:!s,active:r,ref:i,children:jsx(pf,{...u,ref:o})}):jsx(pf,{...u,ref:o})});my.displayName=As;var pf=Le__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...n}=e,r=bf(As,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=r.type==="single"?s:void 0;return jsx(Kl,{...u,...n,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),yf=Gl;function wf(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var n=e.length;for(o=0;o<n;o++)e[o]&&(t=wf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Ps(){for(var e,o,t=0,a="",n=arguments.length;t<n;t++)(e=arguments[t])&&(o=wf(e))&&(a&&(a+=" "),a+=o);return a}var hy=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},gy=(e,o)=>({classGroupId:e,validator:o}),kf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Sf=[],xy="arbitrary..",by=e=>{let o=yy(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return vy(s);let u=s.split("-"),i=u[0]===""&&u.length>1?1:0;return Tf(u,i,o)},getConflictingClassGroupIds:(s,u)=>{if(u){let i=a[s],c=t[s];return i?c?hy(c,i):i:c||Sf}return t[s]||Sf}}},Tf=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let n=e[o],r=t.nextPart.get(n);if(r){let c=Tf(e,o+1,r);if(c)return c}let s=t.validators;if(s===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),i=s.length;for(let c=0;c<i;c++){let f=s[c];if(f.validator(u))return f.classGroupId}},vy=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?xy+a:void 0})(),yy=e=>{let{theme:o,classGroups:t}=e;return wy(t,o)},wy=(e,o)=>{let t=kf();for(let a in e){let n=e[a];$l(n,t,a,o);}return t},$l=(e,o,t,a)=>{let n=e.length;for(let r=0;r<n;r++){let s=e[r];Sy(s,o,t,a);}},Sy=(e,o,t,a)=>{if(typeof e=="string"){Ly(e,o,t);return}if(typeof e=="function"){Iy(e,o,t,a);return}Cy(e,o,t,a);},Ly=(e,o,t)=>{let a=e===""?o:Mf(o,e);a.classGroupId=t;},Iy=(e,o,t,a)=>{if(ky(e)){$l(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(gy(t,e));},Cy=(e,o,t,a)=>{let n=Object.entries(e),r=n.length;for(let s=0;s<r;s++){let[u,i]=n[s];$l(i,Mf(o,u),t,a);}},Mf=(e,o)=>{let t=e,a=o.split("-"),n=a.length;for(let r=0;r<n;r++){let s=a[r],u=t.nextPart.get(s);u||(u=kf(),t.nextPart.set(s,u)),t=u;}return t},ky=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Ty=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),n=(r,s)=>{t[r]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let s=t[r];if(s!==void 0)return s;if((s=a[r])!==void 0)return n(r,s),s},set(r,s){r in t?t[r]=s:n(r,s);}}};var My=[],Lf=(e,o,t,a,n)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:n}),Ay=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=n=>{let r=[],s=0,u=0,i=0,c,f=n.length;for(let p=0;p<f;p++){let v=n[p];if(s===0&&u===0){if(v===":"){r.push(n.slice(i,p)),i=p+1;continue}if(v==="/"){c=p;continue}}v==="["?s++:v==="]"?s--:v==="("?u++:v===")"&&u--;}let d=r.length===0?n:n.slice(i),l=d,m=false;d.endsWith("!")?(l=d.slice(0,-1),m=true):d.startsWith("!")&&(l=d.slice(1),m=true);let h=c&&c>i?c-i:void 0;return Lf(r,m,l,h)};if(o){let n=o+":",r=a;a=s=>s.startsWith(n)?r(s.slice(n.length)):Lf(My,false,s,void 0,true);}if(t){let n=a;a=r=>t({className:r,parseClassName:n});}return a},Py=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],n=[];for(let r=0;r<t.length;r++){let s=t[r],u=s[0]==="[",i=o.has(s);u||i?(n.length>0&&(n.sort(),a.push(...n),n=[]),a.push(s)):n.push(s);}return n.length>0&&(n.sort(),a.push(...n)),a}},Ey=e=>({cache:Ty(e.cacheSize),parseClassName:Ay(e),sortModifiers:Py(e),...by(e)}),Dy=/\s+/,Ry=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:n,sortModifiers:r}=o,s=[],u=e.trim().split(Dy),i="";for(let c=u.length-1;c>=0;c-=1){let f=u[c],{isExternal:d,modifiers:l,hasImportantModifier:m,baseClassName:h,maybePostfixModifierPosition:p}=t(f);if(d){i=f+(i.length>0?" "+i:i);continue}let v=!!p,y=a(v?h.substring(0,p):h);if(!y){if(!v){i=f+(i.length>0?" "+i:i);continue}if(y=a(h),!y){i=f+(i.length>0?" "+i:i);continue}v=false;}let b=l.length===0?"":l.length===1?l[0]:r(l).join(":"),g=m?b+"!":b,C=g+y;if(s.indexOf(C)>-1)continue;s.push(C);let I=n(y,v);for(let B=0;B<I.length;++B){let k=I[B];s.push(g+k);}i=f+(i.length>0?" "+i:i);}return i},Fy=(...e)=>{let o=0,t,a,n="";for(;o<e.length;)(t=e[o++])&&(a=Af(t))&&(n&&(n+=" "),n+=a);return n},Af=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Af(e[a]))&&(t&&(t+=" "),t+=o);return t},By=(e,...o)=>{let t,a,n,r,s=i=>{let c=o.reduce((f,d)=>d(f),e());return t=Ey(c),a=t.cache.get,n=t.cache.set,r=u,u(i)},u=i=>{let c=a(i);if(c)return c;let f=Ry(i,t);return n(i,f),f};return r=s,(...i)=>r(Fy(...i))},Oy=[],je=e=>{let o=t=>t[e]||Oy;return o.isThemeGetter=true,o},Pf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Ef=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Ny=/^\d+\/\d+$/,Hy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,qy=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Vy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,zy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Wy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,er=e=>Ny.test(e),ue=e=>!!e&&!Number.isNaN(Number(e)),Va=e=>!!e&&Number.isInteger(Number(e)),jl=e=>e.endsWith("%")&&ue(e.slice(0,-1)),fa=e=>Hy.test(e),Uy=()=>true,Ky=e=>qy.test(e)&&!Vy.test(e),Df=()=>false,Gy=e=>zy.test(e),jy=e=>Wy.test(e),_y=e=>!Y(e)&&!Z(e),$y=e=>tr(e,Bf,Df),Y=e=>Pf.test(e),go=e=>tr(e,Of,Ky),_l=e=>tr(e,Qy,ue),If=e=>tr(e,Rf,Df),Xy=e=>tr(e,Ff,jy),Es=e=>tr(e,Nf,Gy),Z=e=>Ef.test(e),Yr=e=>ar(e,Of),Yy=e=>ar(e,ew),Cf=e=>ar(e,Rf),Zy=e=>ar(e,Bf),Jy=e=>ar(e,Ff),Ds=e=>ar(e,Nf,true),tr=(e,o,t)=>{let a=Pf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},ar=(e,o,t=false)=>{let a=Ef.exec(e);return a?a[1]?o(a[1]):t:false},Rf=e=>e==="position"||e==="percentage",Ff=e=>e==="image"||e==="url",Bf=e=>e==="length"||e==="size"||e==="bg-size",Of=e=>e==="length",Qy=e=>e==="number",ew=e=>e==="family-name",Nf=e=>e==="shadow";var tw=()=>{let e=je("color"),o=je("font"),t=je("text"),a=je("font-weight"),n=je("tracking"),r=je("leading"),s=je("breakpoint"),u=je("container"),i=je("spacing"),c=je("radius"),f=je("shadow"),d=je("inset-shadow"),l=je("text-shadow"),m=je("drop-shadow"),h=je("blur"),p=je("perspective"),v=je("aspect"),y=je("ease"),b=je("animate"),g=()=>["auto","avoid","all","avoid-page","page","left","right","column"],C=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...C(),Z,Y],B=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],x=()=>[Z,Y,i],S=()=>[er,"full","auto",...x()],w=()=>[Va,"none","subgrid",Z,Y],T=()=>["auto",{span:["full",Va,Z,Y]},Va,Z,Y],q=()=>[Va,"auto",Z,Y],H=()=>["auto","min","max","fr",Z,Y],F=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],V=()=>["start","end","center","stretch","center-safe","end-safe"],U=()=>["auto",...x()],K=()=>[er,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...x()],R=()=>[e,Z,Y],z=()=>[...C(),Cf,If,{position:[Z,Y]}],ne=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",Zy,$y,{size:[Z,Y]}],P=()=>[jl,Yr,go],N=()=>["","none","full",c,Z,Y],_=()=>["",ue,Yr,go],Q=()=>["solid","dashed","dotted","double"],re=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],j=()=>[ue,jl,Cf,If],pe=()=>["","none",h,Z,Y],ge=()=>["none",ue,Z,Y],le=()=>["none",ue,Z,Y],ye=()=>[ue,Z,Y],we=()=>[er,"full",...x()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[fa],breakpoint:[fa],color:[Uy],container:[fa],"drop-shadow":[fa],ease:["in","out","in-out"],font:[_y],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[fa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[fa],shadow:[fa],spacing:["px",ue],text:[fa],"text-shadow":[fa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",er,Y,Z,v]}],container:["container"],columns:[{columns:[ue,Y,Z,u]}],"break-after":[{"break-after":g()}],"break-before":[{"break-before":g()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:I()}],overflow:[{overflow:B()}],"overflow-x":[{"overflow-x":B()}],"overflow-y":[{"overflow-y":B()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:S()}],"inset-x":[{"inset-x":S()}],"inset-y":[{"inset-y":S()}],start:[{start:S()}],end:[{end:S()}],top:[{top:S()}],right:[{right:S()}],bottom:[{bottom:S()}],left:[{left:S()}],visibility:["visible","invisible","collapse"],z:[{z:[Va,"auto",Z,Y]}],basis:[{basis:[er,"full","auto",u,...x()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ue,er,"auto","initial","none",Y]}],grow:[{grow:["",ue,Z,Y]}],shrink:[{shrink:["",ue,Z,Y]}],order:[{order:[Va,"first","last","none",Z,Y]}],"grid-cols":[{"grid-cols":w()}],"col-start-end":[{col:T()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":w()}],"row-start-end":[{row:T()}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":H()}],"auto-rows":[{"auto-rows":H()}],gap:[{gap:x()}],"gap-x":[{"gap-x":x()}],"gap-y":[{"gap-y":x()}],"justify-content":[{justify:[...F(),"normal"]}],"justify-items":[{"justify-items":[...V(),"normal"]}],"justify-self":[{"justify-self":["auto",...V()]}],"align-content":[{content:["normal",...F()]}],"align-items":[{items:[...V(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...V(),{baseline:["","last"]}]}],"place-content":[{"place-content":F()}],"place-items":[{"place-items":[...V(),"baseline"]}],"place-self":[{"place-self":["auto",...V()]}],p:[{p:x()}],px:[{px:x()}],py:[{py:x()}],ps:[{ps:x()}],pe:[{pe:x()}],pt:[{pt:x()}],pr:[{pr:x()}],pb:[{pb:x()}],pl:[{pl:x()}],m:[{m:U()}],mx:[{mx:U()}],my:[{my:U()}],ms:[{ms:U()}],me:[{me:U()}],mt:[{mt:U()}],mr:[{mr:U()}],mb:[{mb:U()}],ml:[{ml:U()}],"space-x":[{"space-x":x()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":x()}],"space-y-reverse":["space-y-reverse"],size:[{size:K()}],w:[{w:[u,"screen",...K()]}],"min-w":[{"min-w":[u,"screen","none",...K()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[s]},...K()]}],h:[{h:["screen","lh",...K()]}],"min-h":[{"min-h":["screen","lh","none",...K()]}],"max-h":[{"max-h":["screen","lh",...K()]}],"font-size":[{text:["base",t,Yr,go]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,Z,_l]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",jl,Y]}],"font-family":[{font:[Yy,Y,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[n,Z,Y]}],"line-clamp":[{"line-clamp":[ue,"none",Z,_l]}],leading:[{leading:[r,...x()]}],"list-image":[{"list-image":["none",Z,Y]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Z,Y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:R()}],"text-color":[{text:R()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Q(),"wavy"]}],"text-decoration-thickness":[{decoration:[ue,"from-font","auto",Z,go]}],"text-decoration-color":[{decoration:R()}],"underline-offset":[{"underline-offset":[ue,"auto",Z,Y]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:x()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Z,Y]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Z,Y]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:ne()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Va,Z,Y],radial:["",Z,Y],conic:[Va,Z,Y]},Jy,Xy]}],"bg-color":[{bg:R()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:R()}],"gradient-via":[{via:R()}],"gradient-to":[{to:R()}],rounded:[{rounded:N()}],"rounded-s":[{"rounded-s":N()}],"rounded-e":[{"rounded-e":N()}],"rounded-t":[{"rounded-t":N()}],"rounded-r":[{"rounded-r":N()}],"rounded-b":[{"rounded-b":N()}],"rounded-l":[{"rounded-l":N()}],"rounded-ss":[{"rounded-ss":N()}],"rounded-se":[{"rounded-se":N()}],"rounded-ee":[{"rounded-ee":N()}],"rounded-es":[{"rounded-es":N()}],"rounded-tl":[{"rounded-tl":N()}],"rounded-tr":[{"rounded-tr":N()}],"rounded-br":[{"rounded-br":N()}],"rounded-bl":[{"rounded-bl":N()}],"border-w":[{border:_()}],"border-w-x":[{"border-x":_()}],"border-w-y":[{"border-y":_()}],"border-w-s":[{"border-s":_()}],"border-w-e":[{"border-e":_()}],"border-w-t":[{"border-t":_()}],"border-w-r":[{"border-r":_()}],"border-w-b":[{"border-b":_()}],"border-w-l":[{"border-l":_()}],"divide-x":[{"divide-x":_()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":_()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Q(),"hidden","none"]}],"divide-style":[{divide:[...Q(),"hidden","none"]}],"border-color":[{border:R()}],"border-color-x":[{"border-x":R()}],"border-color-y":[{"border-y":R()}],"border-color-s":[{"border-s":R()}],"border-color-e":[{"border-e":R()}],"border-color-t":[{"border-t":R()}],"border-color-r":[{"border-r":R()}],"border-color-b":[{"border-b":R()}],"border-color-l":[{"border-l":R()}],"divide-color":[{divide:R()}],"outline-style":[{outline:[...Q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ue,Z,Y]}],"outline-w":[{outline:["",ue,Yr,go]}],"outline-color":[{outline:R()}],shadow:[{shadow:["","none",f,Ds,Es]}],"shadow-color":[{shadow:R()}],"inset-shadow":[{"inset-shadow":["none",d,Ds,Es]}],"inset-shadow-color":[{"inset-shadow":R()}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:R()}],"ring-offset-w":[{"ring-offset":[ue,go]}],"ring-offset-color":[{"ring-offset":R()}],"inset-ring-w":[{"inset-ring":_()}],"inset-ring-color":[{"inset-ring":R()}],"text-shadow":[{"text-shadow":["none",l,Ds,Es]}],"text-shadow-color":[{"text-shadow":R()}],opacity:[{opacity:[ue,Z,Y]}],"mix-blend":[{"mix-blend":[...re(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":re()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ue]}],"mask-image-linear-from-pos":[{"mask-linear-from":j()}],"mask-image-linear-to-pos":[{"mask-linear-to":j()}],"mask-image-linear-from-color":[{"mask-linear-from":R()}],"mask-image-linear-to-color":[{"mask-linear-to":R()}],"mask-image-t-from-pos":[{"mask-t-from":j()}],"mask-image-t-to-pos":[{"mask-t-to":j()}],"mask-image-t-from-color":[{"mask-t-from":R()}],"mask-image-t-to-color":[{"mask-t-to":R()}],"mask-image-r-from-pos":[{"mask-r-from":j()}],"mask-image-r-to-pos":[{"mask-r-to":j()}],"mask-image-r-from-color":[{"mask-r-from":R()}],"mask-image-r-to-color":[{"mask-r-to":R()}],"mask-image-b-from-pos":[{"mask-b-from":j()}],"mask-image-b-to-pos":[{"mask-b-to":j()}],"mask-image-b-from-color":[{"mask-b-from":R()}],"mask-image-b-to-color":[{"mask-b-to":R()}],"mask-image-l-from-pos":[{"mask-l-from":j()}],"mask-image-l-to-pos":[{"mask-l-to":j()}],"mask-image-l-from-color":[{"mask-l-from":R()}],"mask-image-l-to-color":[{"mask-l-to":R()}],"mask-image-x-from-pos":[{"mask-x-from":j()}],"mask-image-x-to-pos":[{"mask-x-to":j()}],"mask-image-x-from-color":[{"mask-x-from":R()}],"mask-image-x-to-color":[{"mask-x-to":R()}],"mask-image-y-from-pos":[{"mask-y-from":j()}],"mask-image-y-to-pos":[{"mask-y-to":j()}],"mask-image-y-from-color":[{"mask-y-from":R()}],"mask-image-y-to-color":[{"mask-y-to":R()}],"mask-image-radial":[{"mask-radial":[Z,Y]}],"mask-image-radial-from-pos":[{"mask-radial-from":j()}],"mask-image-radial-to-pos":[{"mask-radial-to":j()}],"mask-image-radial-from-color":[{"mask-radial-from":R()}],"mask-image-radial-to-color":[{"mask-radial-to":R()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":C()}],"mask-image-conic-pos":[{"mask-conic":[ue]}],"mask-image-conic-from-pos":[{"mask-conic-from":j()}],"mask-image-conic-to-pos":[{"mask-conic-to":j()}],"mask-image-conic-from-color":[{"mask-conic-from":R()}],"mask-image-conic-to-color":[{"mask-conic-to":R()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:ne()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Z,Y]}],filter:[{filter:["","none",Z,Y]}],blur:[{blur:pe()}],brightness:[{brightness:[ue,Z,Y]}],contrast:[{contrast:[ue,Z,Y]}],"drop-shadow":[{"drop-shadow":["","none",m,Ds,Es]}],"drop-shadow-color":[{"drop-shadow":R()}],grayscale:[{grayscale:["",ue,Z,Y]}],"hue-rotate":[{"hue-rotate":[ue,Z,Y]}],invert:[{invert:["",ue,Z,Y]}],saturate:[{saturate:[ue,Z,Y]}],sepia:[{sepia:["",ue,Z,Y]}],"backdrop-filter":[{"backdrop-filter":["","none",Z,Y]}],"backdrop-blur":[{"backdrop-blur":pe()}],"backdrop-brightness":[{"backdrop-brightness":[ue,Z,Y]}],"backdrop-contrast":[{"backdrop-contrast":[ue,Z,Y]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ue,Z,Y]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ue,Z,Y]}],"backdrop-invert":[{"backdrop-invert":["",ue,Z,Y]}],"backdrop-opacity":[{"backdrop-opacity":[ue,Z,Y]}],"backdrop-saturate":[{"backdrop-saturate":[ue,Z,Y]}],"backdrop-sepia":[{"backdrop-sepia":["",ue,Z,Y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":x()}],"border-spacing-x":[{"border-spacing-x":x()}],"border-spacing-y":[{"border-spacing-y":x()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Z,Y]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ue,"initial",Z,Y]}],ease:[{ease:["linear","initial",y,Z,Y]}],delay:[{delay:[ue,Z,Y]}],animate:[{animate:["none",b,Z,Y]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,Z,Y]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:ge()}],"rotate-x":[{"rotate-x":ge()}],"rotate-y":[{"rotate-y":ge()}],"rotate-z":[{"rotate-z":ge()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":["scale-3d"],skew:[{skew:ye()}],"skew-x":[{"skew-x":ye()}],"skew-y":[{"skew-y":ye()}],transform:[{transform:[Z,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:we()}],"translate-x":[{"translate-x":we()}],"translate-y":[{"translate-y":we()}],"translate-z":[{"translate-z":we()}],"translate-none":["translate-none"],accent:[{accent:R()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:R()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Z,Y]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":x()}],"scroll-mx":[{"scroll-mx":x()}],"scroll-my":[{"scroll-my":x()}],"scroll-ms":[{"scroll-ms":x()}],"scroll-me":[{"scroll-me":x()}],"scroll-mt":[{"scroll-mt":x()}],"scroll-mr":[{"scroll-mr":x()}],"scroll-mb":[{"scroll-mb":x()}],"scroll-ml":[{"scroll-ml":x()}],"scroll-p":[{"scroll-p":x()}],"scroll-px":[{"scroll-px":x()}],"scroll-py":[{"scroll-py":x()}],"scroll-ps":[{"scroll-ps":x()}],"scroll-pe":[{"scroll-pe":x()}],"scroll-pt":[{"scroll-pt":x()}],"scroll-pr":[{"scroll-pr":x()}],"scroll-pb":[{"scroll-pb":x()}],"scroll-pl":[{"scroll-pl":x()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Z,Y]}],fill:[{fill:["none",...R()]}],"stroke-w":[{stroke:[ue,Yr,go,_l]}],stroke:[{stroke:["none",...R()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var Hf=By(tw);function za(...e){return Hf(Ps(e))}var ow=Le.createContext({size:"default",variant:"default",spacing:0});function Wa({className:e,variant:o,size:t,spacing:a=1,children:n,...r}){return jsx(yf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:za("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(ow.Provider,{value:{variant:o,size:t,spacing:a},children:n})})}var nw={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Uf=createSlice({name:"toolbar",initialState:nw,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:aa,setPenColor:ma,setStrokeWidth:Zr,setFontSize:zD,setFontFamily:WD,setFontStyle:UD,setFontWeight:KD,setTextDecoration:GD,setTextColor:jD}=Uf.actions,Yl=Uf.reducer;var Gf=e=>jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",...e,children:jsx("ellipse",{cx:"12",cy:"12",rx:"10.5",ry:"7.5"})});var _f=e=>jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",...e,children:[jsx("circle",{cx:"12",cy:"12",r:"10",fill:"currentColor"}),jsx("circle",{cx:"12",cy:"12",r:"6",fill:"white"})]});var Rs=({onClose:e,onRecordingComplete:o})=>{let t=ze(),[a,n]=useState(false),[r,s]=useState(null),[u,i]=useState(0),[c,f]=useState(null),[d,l]=useState(false),m=useRef(null),h=useRef([]),p=useRef(null),v=useRef(null),y=useRef(null);useEffect(()=>((async()=>{try{let S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});f(S),l(!0),y.current&&(y.current.srcObject=S);}catch(S){console.error("Error accessing camera:",S),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),c&&c.getTracks().forEach(S=>S.stop());}),[]);let b=()=>{c&&(c.getTracks().forEach(x=>x.stop()),f(null),l(false));},g=async()=>{try{let x=null,S=null;try{x=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(F){console.error("Error accessing camera for recording:",F),alert("Failed to access camera for recording.");return}try{S=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(F){console.warn("Microphone access denied:",F);}let w=[...x.getVideoTracks()];S&&w.push(...S.getAudioTracks());let T=new MediaStream(w),q="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?q="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?q="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?q="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(q="video/webm;codecs=vp8");let H=new MediaRecorder(T,{mimeType:q,videoBitsPerSecond:25e5});m.current=H,h.current=[],H.ondataavailable=F=>{F.data.size>0&&h.current.push(F.data);},H.onstop=()=>{let F=new Blob(h.current,{type:q}),V=document.createElement("video");V.src=URL.createObjectURL(F),V.muted=!0,V.currentTime=.1,V.onseeked=()=>{let U=document.createElement("canvas");U.width=V.videoWidth,U.height=V.videoHeight;let K=U.getContext("2d");K&&(K.drawImage(V,0,0),v.current=U.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(V.src);},T.getTracks().forEach(U=>U.stop()),x&&x.getTracks().forEach(U=>U.stop()),S&&S.getTracks().forEach(U=>U.stop()),p.current&&clearInterval(p.current),s(F),b();},H.onerror=F=>{console.error("MediaRecorder error:",F);},H.start(1e3),n(!0),i(0),p.current=setInterval(()=>{i(F=>F+1);},1e3);}catch(x){console.error("Error starting camera recording:",x),alert("Failed to start recording. Please check permissions.");}},C=()=>{m.current&&a&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),n(false));},I=()=>{if(r){let x=URL.createObjectURL(r),S=document.createElement("a");S.href=x,S.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(S),S.click(),document.body.removeChild(S),URL.revokeObjectURL(x);}},B=x=>{let S=Math.floor(x/60),w=x%60;return `${S.toString().padStart(2,"0")}:${w.toString().padStart(2,"0")}`};if(!t)return null;let k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:x=>{x.target===x.currentTarget&&e(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:x=>x.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:y,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:g,disabled:!d,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!d&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:C,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:B(u)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",B(u)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{s(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&v.current&&(o(r,v.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(k,t)};var pa=40,Xf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,n]=useState(t?.images||[]),[r,s]=useState(t?.order||"sequential"),[u,i]=useState(false),c=useRef(null),f=ze(),d=useRef(null);useEffect(()=>{let g=C=>{C.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let l=g=>{let C=g.target.files;if(!C||C.length===0)return;let I=pa-a.length;if(I<=0){alert(`You can only upload a maximum of ${pa} images`);return}let B=Array.from(C).slice(0,I);B.length<C.length&&alert(`Only ${I} more images can be added (max ${pa} total)`);let k=B.map(x=>new Promise((S,w)=>{let T=new FileReader;T.onload=q=>{q.target?.result?S(q.target.result):w(new Error("Failed to read file"));},T.onerror=w,T.readAsDataURL(x);}));Promise.all(k).then(x=>{n(S=>[...S,...x]),d.current&&(d.current.value="");});},m=g=>{g.preventDefault(),i(false);let C=Array.from(g.dataTransfer.files).filter(x=>x.type.startsWith("image/"));if(C.length===0)return;let I=pa-a.length;if(I<=0){alert(`You can only upload a maximum of ${pa} images`);return}let B=C.slice(0,I);B.length<C.length&&alert(`Only ${I} more images can be added (max ${pa} total)`);let k=B.map(x=>new Promise((S,w)=>{let T=new FileReader;T.onload=q=>{q.target?.result?S(q.target.result):w(new Error("Failed to read file"));},T.onerror=w,T.readAsDataURL(x);}));Promise.all(k).then(x=>{n(S=>[...S,...x]);});},h=g=>{g.preventDefault(),i(true);},p=()=>{i(false);},v=g=>{n(C=>C.filter((I,B)=>B!==g));},y=g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!f)return null;let b=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:y,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=pa?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",pa," images"]}):jsxs("span",{children:[a.length,"/",pa," images"]})})]}),jsx("input",{ref:d,type:"file",accept:"image/*",multiple:true,onChange:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:h,onDragLeave:p,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>s("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>s("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,C)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${C+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(C),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:C+1})]},C))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(b,f)};var Fs={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},Sw={enabled:true};function Ql(e){return e?{tools:{...Fs.tools,...e.tools},actions:{...Fs.actions,...e.actions}}:Fs}var Lw={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Iw={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};function ed(e,[o,t]){return Math.min(t,Math.max(o,e))}function Yf(e){let o=Le.useRef({value:e,previous:e});return Le.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Jf(e){let[o,t]=Le.useState(void 0);return Zo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(n=>{if(!Array.isArray(n)||!n.length)return;let r=n[0],s,u;if("borderBoxSize"in r){let i=r.borderBoxSize,c=Array.isArray(i)?i[0]:i;s=c.inlineSize,u=c.blockSize;}else s=e.offsetWidth,u=e.offsetHeight;t({width:s,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var Qf=["PageUp","PageDown"],em=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],tm={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},or="Slider",[td,kw,Tw]=ks(or),[am]=Ha(or,[Tw]),[Mw,Os]=am(or),om=Le.forwardRef((e,o)=>{let{name:t,min:a=0,max:n=100,step:r=1,orientation:s="horizontal",disabled:u=false,minStepsBetweenThumbs:i=0,defaultValue:c=[a],value:f,onValueChange:d=()=>{},onValueCommit:l=()=>{},inverted:m=false,form:h,...p}=e,v=Le.useRef(new Set),y=Le.useRef(0),g=s==="horizontal"?Aw:Pw,[C=[],I]=ca({prop:f,defaultProp:c,onChange:T=>{[...v.current][y.current]?.focus(),d(T);}}),B=Le.useRef(C);function k(T){let q=Bw(C,T);w(T,q);}function x(T){w(T,y.current);}function S(){let T=B.current[y.current];C[y.current]!==T&&l(C);}function w(T,q,{commit:H}={commit:false}){let F=qw(r),V=Vw(Math.round((T-a)/r)*r+a,F),U=ed(V,[a,n]);I((K=[])=>{let R=Rw(K,U,q);if(Hw(R,i*r)){y.current=R.indexOf(U);let z=String(R)!==String(K);return z&&H&&l(R),z?R:K}else return K});}return jsx(Mw,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:n,valueIndexToChangeRef:y,thumbs:v.current,values:C,orientation:s,form:h,children:jsx(td.Provider,{scope:e.__scopeSlider,children:jsx(td.Slot,{scope:e.__scopeSlider,children:jsx(g,{"aria-disabled":u,"data-disabled":u?"":void 0,...p,ref:o,onPointerDown:nt(p.onPointerDown,()=>{u||(B.current=C);}),min:a,max:n,inverted:m,onSlideStart:u?void 0:k,onSlideMove:u?void 0:x,onSlideEnd:u?void 0:S,onHomeKeyDown:()=>!u&&w(a,0,{commit:true}),onEndKeyDown:()=>!u&&w(n,C.length-1,{commit:true}),onStepKeyDown:({event:T,direction:q})=>{if(!u){let V=Qf.includes(T.key)||T.shiftKey&&em.includes(T.key)?10:1,U=y.current,K=C[U],R=r*V*q;w(K+R,U,{commit:true});}}})})})})});om.displayName=or;var[rm,nm]=am(or,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Aw=Le.forwardRef((e,o)=>{let{min:t,max:a,dir:n,inverted:r,onSlideStart:s,onSlideMove:u,onSlideEnd:i,onStepKeyDown:c,...f}=e,[d,l]=Le.useState(null),m=Ut(o,g=>l(g)),h=Le.useRef(void 0),p=Qo(n),v=p==="ltr",y=v&&!r||!v&&r;function b(g){let C=h.current||d.getBoundingClientRect(),I=[0,C.width],k=rd(I,y?[t,a]:[a,t]);return h.current=C,k(g-C.left)}return jsx(rm,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx(sm,{dir:p,"data-orientation":"horizontal",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:g=>{let C=b(g.clientX);s?.(C);},onSlideMove:g=>{let C=b(g.clientX);u?.(C);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:g=>{let I=tm[y?"from-left":"from-right"].includes(g.key);c?.({event:g,direction:I?-1:1});}})})}),Pw=Le.forwardRef((e,o)=>{let{min:t,max:a,inverted:n,onSlideStart:r,onSlideMove:s,onSlideEnd:u,onStepKeyDown:i,...c}=e,f=Le.useRef(null),d=Ut(o,f),l=Le.useRef(void 0),m=!n;function h(p){let v=l.current||f.current.getBoundingClientRect(),y=[0,v.height],g=rd(y,m?[a,t]:[t,a]);return l.current=v,g(p-v.top)}return jsx(rm,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:jsx(sm,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:p=>{let v=h(p.clientY);r?.(v);},onSlideMove:p=>{let v=h(p.clientY);s?.(v);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:p=>{let y=tm[m?"from-bottom":"from-top"].includes(p.key);i?.({event:p,direction:y?-1:1});}})})}),sm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:n,onSlideEnd:r,onHomeKeyDown:s,onEndKeyDown:u,onStepKeyDown:i,...c}=e,f=Os(or,t);return jsx(yt.span,{...c,ref:o,onKeyDown:nt(e.onKeyDown,d=>{d.key==="Home"?(s(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):Qf.concat(em).includes(d.key)&&(i(d),d.preventDefault());}),onPointerDown:nt(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),f.thumbs.has(l)?l.focus():a(d);}),onPointerMove:nt(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&n(d);}),onPointerUp:nt(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),r(d));})})}),im="SliderTrack",lm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Os(im,t);return jsx(yt.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...a,ref:o})});lm.displayName=im;var ad="SliderRange",dm=Le.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,n=Os(ad,t),r=nm(ad,t),s=Le.useRef(null),u=Ut(o,s),i=n.values.length,c=n.values.map(l=>fm(l,n.min,n.max)),f=i>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(yt.span,{"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,...a,ref:u,style:{...e.style,[r.startEdge]:f+"%",[r.endEdge]:d+"%"}})});dm.displayName=ad;var od="SliderThumb",um=Le.forwardRef((e,o)=>{let t=kw(e.__scopeSlider),[a,n]=Le.useState(null),r=Ut(o,u=>n(u)),s=Le.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(Ew,{...e,ref:r,index:s})}),Ew=Le.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:n,...r}=e,s=Os(od,t),u=nm(od,t),[i,c]=Le.useState(null),f=Ut(o,b=>c(b)),d=i?s.form||!!i.closest("form"):true,l=Jf(i),m=s.values[a],h=m===void 0?0:fm(m,s.min,s.max),p=Fw(a,s.values.length),v=l?.[u.size],y=v?Ow(v,h,u.direction):0;return Le.useEffect(()=>{if(i)return s.thumbs.add(i),()=>{s.thumbs.delete(i);}},[i,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${y}px)`},children:[jsx(td.ItemSlot,{scope:e.__scopeSlider,children:jsx(yt.span,{role:"slider","aria-label":e["aria-label"]||p,"aria-valuemin":s.min,"aria-valuenow":m,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...r,ref:f,style:m===void 0?{display:"none"}:e.style,onFocus:nt(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),d&&jsx(cm,{name:n??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:m},a)]})});um.displayName=od;var Dw="RadioBubbleInput",cm=Le.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let n=Le.useRef(null),r=Ut(n,a),s=Yf(o);return Le.useEffect(()=>{let u=n.current;if(!u)return;let i=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==o&&f){let d=new Event("input",{bubbles:true});f.call(u,o),u.dispatchEvent(d);}},[s,o]),jsx(yt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});cm.displayName=Dw;function Rw(e=[],o,t){let a=[...e];return a[t]=o,a.sort((n,r)=>n-r)}function fm(e,o,t){let r=100/(t-o)*(e-o);return ed(r,[0,100])}function Fw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Bw(e,o){if(e.length===1)return 0;let t=e.map(n=>Math.abs(n-o)),a=Math.min(...t);return t.indexOf(a)}function Ow(e,o,t){let a=e/2,r=rd([0,50],[0,a]);return (a-r(o)*t)*t}function Nw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Hw(e,o){if(o>0){let t=Nw(e);return Math.min(...t)>=o}return true}function rd(e,o){return t=>{if(e[0]===e[1]||o[0]===o[1])return o[0];let a=(o[1]-o[0])/(e[1]-e[0]);return o[0]+a*(t-e[0])}}function qw(e){return (String(e).split(".")[1]||"").length}function Vw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var mm=om,pm=lm,hm=dm,gm=um;function Ns({className:e,defaultValue:o,value:t,min:a=0,max:n=100,rangeClassName:r,trackClassName:s,thumbClassName:u,...i}){let c=Le.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,n],[t,o,a,n]);return jsxs(mm,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:n,className:za("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[jsx(pm,{"data-slot":"slider-track",className:za("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",s),children:jsx(hm,{"data-slot":"slider-range",className:za("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:c.length},(f,d)=>jsx(gm,{"data-slot":"slider-thumb",className:za("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",u)},d))]})}var gS=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a,onVisibilityChange:n}={})=>{let r=Se(),s=J(A=>A.canvas.slides.find(te=>te.id===A.canvas.currentSlideId)),u=s?.videos||[],i=s?.editingFlashcard,c=J(A=>A.toolbar.selectedTool),f=J(A=>A.toolbar.penColor),d=J(A=>A.toolbar.strokeWidth),l=J(A=>A.canvas.editingOverlayPosition),m=s?.showMcqForm,h=s?.showFlashcardForm,p=useRef(null);useEffect(()=>{let A=te=>{(te.ctrlKey||te.metaKey)&&te.key==="z"&&!te.shiftKey&&(te.preventDefault(),r(Mo())),(te.ctrlKey&&te.shiftKey&&te.key==="Z"||te.ctrlKey&&te.key==="y")&&(te.preventDefault(),r(Ao()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[r]);let v=useMemo(()=>Ql(a),[a]),{tools:y,actions:b}=v,g=u.some(A=>A.isRecorded&&A.isPlaying),C=J(A=>A.toolbar.fontSize),I=J(A=>A.toolbar.fontFamily),B=J(A=>A.toolbar.fontStyle),k=J(A=>A.toolbar.fontWeight),x=J(A=>A.toolbar.textDecoration),S=J(A=>A.toolbar.textColor),[w,T]=useState(false),[q,H]=useState(false),[F,V]=useState(false),[U,K]=useState(false),[R,z]=useState(false),[ne,X]=useState(false),[P,N]=useState(false),[_,Q]=useState(false),[re,j]=useState(true),pe=useRef(null),ge=useRef(null),le=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],ye=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"style",icon:Palette,label:"Style",configKey:"style"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),we=useMemo(()=>[{name:"rectangle",icon:Square,label:"Square"},{name:"rectangle",icon:Rectangle,label:"Rectangle"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Gf,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:_f,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),xe=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),St=useMemo(()=>ye.filter(A=>{let te=y[A.configKey];return typeof te=="boolean"?te:Array.isArray(te)?te.length>0:true}),[y,ye]),ae=useMemo(()=>{let A=y.shapes;return A===false?[]:A===true?we:Array.isArray(A)?we.filter(te=>A.includes(te.name)):we},[y.shapes,we]),rn=useMemo(()=>{let A=y.activities;return A===false?[]:A===true?xe:Array.isArray(A)?xe.filter(te=>A.includes(te.name)):xe},[y.activities,xe]),yo=useMemo(()=>{let A=y.media;return A===false?{photoFrame:false,image:false,video:false}:A===true?{photoFrame:true,image:true,video:true}:Array.isArray(A)?{photoFrame:A.includes("photo-frame"),image:A.includes("image"),video:A.includes("video")}:{photoFrame:true,image:true,video:true}},[y.media]),nn=useMemo(()=>{let A=y.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[y.activities]),sn=A=>{let te=A.target.files;!te||te.length===0||(r(aa("select")),r(It(false)),K(false),Array.from(te).forEach(ke=>{let Ie=new FileReader;Ie.onload=ce=>{let se=new window.Image;se.src=ce.target?.result,se.onload=()=>{let Ee=se.width/se.height,it=300,ra=300,Ye=se.width,Oe=se.height;Ye>it&&(Ye=it,Oe=Ye/Ee),Oe>ra&&(Oe=ra,Ye=Oe*Ee),r(de());let lt=l?.left||800-Ye/2,na=l?.top||450-Oe/2;r(li({id:v4(),src:se.src,x:lt,y:na,width:Ye,height:Oe,draggable:true,rotation:0}));};},Ie.readAsDataURL(ke);}),A.target.value="");},ln=async A=>{let te=A.target.files;if(!(!te||te.length===0)){console.log("files",A),r(aa("select")),r(It(false)),K(false);for(let ke of Array.from(te))try{let Ie=URL.createObjectURL(ke),ce=document.createElement("video");console.log("video",ce),ce.src=Ie,ce.muted=!0,ce.playsInline=!0,ce.preload="auto",ce.load(),await new Promise((Ze,ya)=>{let Jt=setTimeout(()=>ya(new Error("Metadata load timeout")),1e4);ce.onloadedmetadata=()=>{clearTimeout(Jt),Ze();},ce.onerror=()=>{clearTimeout(Jt),ya(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ce.duration,width:ce.videoWidth,height:ce.videoHeight}),await new Promise((Ze,ya)=>{let Jt=setTimeout(()=>ya(new Error("Video load timeout")),1e4);ce.readyState>=2?(clearTimeout(Jt),Ze()):ce.onloadeddata=()=>{clearTimeout(Jt),Ze();};});let se=Math.min(.8,ce.duration/2);console.log("Seeking to:",se),ce.currentTime=se,await new Promise(Ze=>{let ya=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ze();},5e3);ce.onseeked=()=>{clearTimeout(ya),console.log("Seek completed"),Ze();};});let Ee=document.createElement("canvas"),it=ce.videoWidth/ce.videoHeight,ra=400,Ye=400,Oe=ce.videoWidth,lt=ce.videoHeight;Oe>ra&&(Oe=ra,lt=Oe/it),lt>Ye&&(lt=Ye,Oe=lt*it),Ee.width=Oe,Ee.height=lt;let na=Ee.getContext("2d",{willReadFrequently:!1});if(!na)throw new Error("Failed to get canvas context");if(await new Promise(Ze=>setTimeout(Ze,100)),ce.videoWidth===0||ce.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Oe,height:lt}),na.drawImage(ce,0,0,Oe,lt);let va=Ee.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",va.length),r(de());let Js=800-Oe/2,So=450-lt/2,ie=v4();await da(ie,ke,va),r(ko({id:ie,objectUrl:Ie,thumbnailDataUrl:va,videoBlob:ke,x:Js,y:So,width:Oe,height:lt,draggable:!0,isPlaying:!1,rotation:0})),ce.src="",ce.load(),console.log(`Video uploaded: ${ke.name}`);}catch(Ie){console.error("Error processing video:",Ie),alert(`Failed to process video: ${ke.name}`);}A.target.value="";}},dn=(A,te,ke)=>{r(de()),r(aa("select")),r(It(false));let Ie=300,ce=300,se=800-Ie/2,Ee=450-ce/2;r(ke?To({id:ke,images:A,order:te,x:se,y:Ee,width:Ie,height:ce,rotation:0,draggable:true}):ci({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:te,x:se,y:Ee,width:Ie,height:ce,rotation:0,draggable:true})),r(Qa(false));},Ks=()=>{r(de()),r(aa("select")),r(It(false));let A=400,te=300,ke=800-A/2,Ie=450-te/2;r(pi({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ke,y:Ie,width:A,height:te,rotation:0,draggable:true,isCapturing:false})),K(false);},Gs=A=>{let se={};switch(A.name){case "rectangle":A.label==="Rectangle"?(se.width=120,se.height=80):(se.width=100,se.height=100);break;case "circle":case "ring":case "wedge":case "arc":se.radius=50,(A.name==="ring"||A.name==="arc")&&(se.innerRadius=25,se.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(se.angle=A.name==="wedge"?60:90);break;case "ellipse":se.radiusX=60,se.radiusY=40;break;case "triangle":se.radius=50,se.sides=3;break;case "polygon":se.radius=50,se.sides=6;break;case "star":se.innerRadius=25,se.outerRadius=50,se.numPoints=5;break;case "arrow":case "line":se.points=[0,0,100,0],A.name==="arrow"&&(se.pointerLength=10,se.pointerWidth=10);break}let Ee={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:f,...se};r(de()),r(It(false)),r(aa(A.name)),r(di(Ee)),V(false);},Ga=A=>{if(r(aa(A)),A==="select")r(It(false));else if(A==="text"){r(It(false)),r(de());let te=200,ke=50,Ie=800-te/2,ce=450-ke/2,Ee=window.innerWidth<768?Math.max(C,32):C,it=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(ui({id:it,text:"",x:Ie,y:ce,width:te,height:ke,rotation:0,draggable:true,fontSize:Ee,fontFamily:I,fontStyle:B,fontWeight:k,textDecoration:x,fill:S,align:"left"})),setTimeout(()=>{r(vr(it));},100),t&&t(it);}else r(It(true));},js=()=>{r(br()),r(It(false));},_s=()=>{e?e():o?T(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},ja=()=>{H(true);},$s=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:Ks,enabled:yo.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>pe.current?.click(),enabled:yo.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>ge.current?.click(),enabled:yo.video}],un=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Mo()),enabled:b.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(Ao()),enabled:b.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:_s,enabled:b.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:ja,enabled:b.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:js,enabled:b.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],_a=async(A,te)=>{try{r(aa("select")),r(It(!1));let ke=URL.createObjectURL(A),Ie=document.createElement("video");Ie.src=ke,Ie.muted=!0,Ie.playsInline=!0,Ie.preload="auto",await new Promise((lt,na)=>{let va=setTimeout(()=>na(new Error("Metadata load timeout")),1e4);Ie.onloadedmetadata=()=>{clearTimeout(va),lt();},Ie.onerror=()=>{clearTimeout(va),na(new Error("Failed to load video"));};});let ce=640,se=Ie.videoWidth/Ie.videoHeight,Ee=ce,it=Ee/se;r(de());let ra=800-Ee/2,Ye=450-it/2,Oe=v4();await da(Oe,A,te),r(ko({id:Oe,objectUrl:ke,thumbnailDataUrl:te,videoBlob:A,x:ra,y:Ye,width:Ee,height:it,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),T(!1),H(!1);}catch(ke){console.error("Error adding recorded video to canvas:",ke),alert("Failed to add video to canvas. Please try again.");}},cn=A=>{r(aa("select")),r(It(false)),r(gr(null)),A&&r(Ci(A)),r(La(!m)),z(false);},Xs=()=>{r(hr(null)),r(Qa(true)),z(false);},ir=()=>{V(!F);},wo=()=>{K(!U);},fn=()=>{z(!R);},Ys=()=>{X(!ne);},Zs=()=>{let A=!re;A||(V(false),K(false),z(false),X(false),Q(false),N(false)),j(A),n?.(A);};return useEffect(()=>{if(!_)return;let A=te=>{p.current&&!p.current.contains(te.target)&&Q(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[_]),g?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:Zs,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:re?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),re&&jsxs("div",{className:"fixed scrollbar-hide top-[168px] bottom-4 left-4 z-50 flex flex-col gap-4 overflow-y-auto",children:[jsxs("div",{className:"flex items-center",children:[jsx(Wa,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:St.map((A,te)=>jsx("div",{title:A.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.name===c?"bg-primary/10":A.name==="style"?"md:hidden":""}`,onClick:()=>{A.name==="image"?(wo(),V(false),z(false),X(false),Ga(A.name)):A.name==="shapes"?(ir(),K(false),z(false),X(false),Ga(A.name)):A.name==="activities"?(Ga(A.name),fn(),V(false),K(false),X(false)):A.name==="style"?(Ys(),V(false),K(false),z(false),Ga(A.name)):(Ga(A.name),V(false),K(false),z(false),X(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},te))}),F&&jsx(Wa,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:ae.map((A,te)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Gs(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},te))}),U&&jsx(Wa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:$s.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),R&&jsxs(Wa,{type:"single",className:"mx-1 mt-auto mb-10 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl lg:mb-11",children:[nn&&jsx("div",{title:"Flashcard",onClick:()=>Xs(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),rn.map((A,te)=>jsx("div",{title:A.label,onClick:()=>cn(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},te))]}),ne&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Ns,{value:[d],onValueChange:A=>{r(Zr(A[0]));},max:28,min:6,step:1,className:"w-28",rangeClassName:"bg-gray-300",thumbClassName:"bg-gray-600 border-none h-4 w-4"}),jsx("div",{className:"h-5 w-5 rounded-full bg-gray-800"})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"COLOR"}),jsxs("div",{className:"flex flex-wrap gap-1",children:[le.map(A=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${f===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{r(ma(A.value)),X(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:f,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>r(ma(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:f,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{r(pr(A.target.value)),X(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),un.some(A=>A.enabled)&&jsx(Wa,{type:"single",className:"hidden flex-col border bg-white p-1 shadow-xl md:flex",children:un.filter(A=>A.enabled).map(A=>jsx("button",{onClick:A.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.colorClass}`,title:A.title,children:jsx(A.icon,{weight:A.iconWeight,className:"text-lg md:text-xl"})},A.key))})]}),jsx("input",{ref:pe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:sn}),jsx("input",{ref:ge,type:"file",accept:"video/*",className:"hidden",onChange:ln}),!e&&w&&o&&jsx(eo,{onClose:()=>T(false),stageRef:o,onRecordingComplete:_a}),q&&jsx(Rs,{onClose:()=>H(false),onRecordingComplete:_a}),h&&jsx(Xf,{editingFlashcard:i,onConfirm:dn,onCancel:()=>r(Qa(false))}),P&&jsx(es,{defaultColor:f,onConfirm:A=>{r(ma(A)),N(false);},onCancel:()=>N(false)})]})},xS=gS;var dd=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let n=Re(Ca),r=Re(Fi),s=a?r:n,u=Re(wr),f=(Re(b=>b.canvas.slides.find(g=>g.id===b.canvas.currentSlideId))?.videos||[]).some(b=>b.isRecorded&&b.isPlaying),[d,l]=useState(false),[m,h]=useState(null),[p,v]=useState(null),y=async()=>{if(n.length===0){v({type:"error",message:"No slides to publish"});return}if(!e){v({type:"error",message:"No publish handler provided"});return}l(true),v(null);try{let b=await e(s,u,g=>{h(g);});b.success?v({type:"success",message:b.message}):v({type:"error",message:b.message});}catch(b){v({type:"error",message:b instanceof Error?b.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),v(null);},3e3);}console.log("For checking>>>>>>>>>>>",s,"<<<<<<<<<<<<<");};return f?null:jsxs("button",{onClick:y,disabled:d||n.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var SS=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:n,onDescriptionChange:r,showPublishButton:s=true,showBackButton:u=true,editableTitle:i=true,editableDescription:c=true,className:f="",rightContent:d,leftContent:l,includeInactiveSlides:m=false})=>{let h=_e(),p=Re(wr),v=Re(Bi),y=e??(v?p.title:"")??"Untitled",b=o??(v?p.description:"")??"Add a description...",[g,C]=useState(false),[I,B]=useState(false),[k,x]=useState(y),[S,w]=useState(b),T=useRef(null),q=useRef(null);useEffect(()=>{x(y);},[y]),useEffect(()=>{w(b);},[b]),useEffect(()=>{g&&T.current&&(T.current.focus(),T.current.select());},[g]),useEffect(()=>{I&&q.current&&(q.current.focus(),q.current.select());},[I]);let H=()=>{i&&C(true);},F=()=>{c&&B(true);},V=()=>{C(false),k.trim()&&k!==y?n?n(k.trim()):h(Ei(k.trim())):k.trim()||x(y);},U=()=>{B(false),S.trim()&&S!==b?r?r(S.trim()):h(Di(S.trim())):S.trim()||w(b);},K=z=>{z.key==="Enter"?V():z.key==="Escape"&&(x(y),C(false));},R=z=>{z.key==="Enter"?U():z.key==="Escape"&&(w(b),B(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${f}`,children:[l||jsxs("div",{className:"flex items-center gap-4",children:[u&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[g?jsx("input",{ref:T,type:"text",value:k,onChange:z=>x(z.target.value),onBlur:V,onKeyDown:K,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:H,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${i?"hover:border-primary cursor-text":""}`,children:k}),I?jsx("input",{ref:q,type:"text",value:S,onChange:z=>w(z.target.value),onBlur:U,onKeyDown:R,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:F,title:S,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${c?"hover:border-primary cursor-text":""}`,children:S})]})]}),d||s&&a&&jsx(dd,{onPublish:a,includeInactiveSlides:m})]})};var MS=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],AS=({colors:e=MS,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:n=""})=>{let[r,s]=useState(true),u=J(ve),i=J(l=>l.toolbar.penColor),c=J(l=>l.toolbar.strokeWidth),f=u?.backgroundColor,d=Se();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:r?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-16 left-1/2 z-50 hidden w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-3 shadow-2xl md:bottom-6 md:flex md:p-5 2xl:px-8 2xl:py-6 ${n}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-black md:h-3 md:w-3"}),jsx(Ns,{defaultValue:[20],max:36,min:8,step:2,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:l=>d(Zr(l[0]))}),jsx("div",{className:"h-5 w-5 rounded-full bg-black md:h-7 md:w-7 lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"COLOR"}),jsxs(Wa,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${i===l.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:l.value},onClick:()=>d(ma(l.value))},l.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>d(ma("#2D2F50"))}),jsxs("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] md:h-10 md:w-10 lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(ma(l.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:f},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(pr(l.target.value))})})]})}),jsx("div",{className:"absolute -top-6 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2 md:-top-4",children:jsx("button",{onClick:()=>s(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{weight:"bold",className:"text-gray-600 md:text-xl"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>s(true),className:"fixed bottom-20 left-1/2 z-50 hidden -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl md:bottom-3 md:flex","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var Lm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),PS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),cd=e=>{let o=PS(e);return o.charAt(0).toUpperCase()+o.slice(1)},zs=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Im=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Cm={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var Tm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:n="",children:r,iconNode:s,...u},i)=>createElement("svg",{ref:i,...Cm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:zs("lucide",n),...!r&&!Im(u)&&{"aria-hidden":"true"},...u},[...s.map(([c,f])=>createElement(c,f)),...Array.isArray(r)?r:[r]]));var Ws=(e,o)=>{let t=forwardRef(({className:a,...n},r)=>createElement(Tm,{ref:r,iconNode:o,className:zs(`lucide-${Lm(cd(e))}`,`lucide-${e}`,a),...n}));return t.displayName=cd(e),t};var FS=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],en=Ws("copy",FS);var BS=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],tn=Ws("trash-2",BS);var Am=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:s})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:n,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(en,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),s();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(tn,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var qS=({softDelete:e=false})=>{let o=_e(),t=Re(Ca),a=Re(Ia),n=Re(yr),[r,s]=useState(true),c=(Re(h=>h.canvas.slides.find(p=>p.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),f=()=>{n&&o(ur());},d=h=>{o(mr(h));},l=h=>{o(fr(h));},m=h=>{t.length>1&&o(cr({id:h,softDelete:e}));};return c?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>s(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((h,p)=>jsx(Am,{slide:h,index:p,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>l(h.id),onDelete:()=>m(h.id)},h.id))}),jsxs("button",{onClick:f,disabled:!n,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${n?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>s(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var rr=20,$S=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:n,onDuplicate:r,onDelete:s})=>jsxs("div",{className:`relative h-[122px] w-[166px] shrink-0 cursor-pointer rounded-lg border bg-[#fafafa] transition-all ${t?"border-[#096b76]":"border-black/10"}`,onClick:n,children:[jsx("div",{className:"absolute top-1 right-1 bottom-1 left-1 overflow-hidden rounded bg-white",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"size-full object-contain"}):jsx("div",{className:"flex size-full items-center justify-center",children:jsx("span",{className:"text-xs text-black/20",children:"No preview"})})}),jsx("div",{className:"absolute top-3 left-3 flex h-5 w-5 items-center justify-center rounded-full bg-[#333c48]",children:jsx("span",{className:"text-xs font-bold text-white",children:o+1})}),jsx("button",{onClick:u=>{u.stopPropagation(),r();},className:"absolute top-3 right-3 flex cursor-pointer items-center justify-center rounded-md bg-[#3B75E0] p-1.5 text-white transition-colors hover:bg-[#2d5fc0]",title:"Duplicate Page",children:jsx(Copy,{size:18,weight:"bold"})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),s();},className:"absolute right-3 bottom-6 flex cursor-pointer items-center justify-center rounded-md bg-[#E53935] p-1.5 text-white transition-colors hover:bg-[#c62828]",title:"Delete Page",children:jsx(Trash,{size:18,weight:"bold"})}),jsxs("p",{className:"absolute bottom-2 left-3 text-sm text-black/40",children:["Page ",o+1]})]}),XS=({softDelete:e=false})=>{let o=_e(),t=Re(Ca),a=Re(Ia),n=Re(yr),[r,s]=useState(false),[u,i]=useState(false),[c,f]=useState(false),d=useRef(null),h=(Re(I=>I.canvas.slides.find(B=>B.id===I.canvas.currentSlideId))?.videos||[]).some(I=>I.isRecorded&&I.isPlaying),p=()=>{n&&t.length<rr&&o(ur());},v=I=>{o(mr(I));},y=I=>{t.length<rr&&o(fr(I));},b=I=>{t.length>1&&o(cr({id:I,softDelete:e}));},g=()=>{if(!d.current)return;let{scrollLeft:I,scrollWidth:B,clientWidth:k}=d.current,x=B>k+5;i(x&&I>5),f(x&&I<B-k-5);},C=I=>{if(!d.current)return;let B=177,k=I==="left"?d.current.scrollLeft-B:d.current.scrollLeft+B;d.current.scrollTo({left:k,behavior:"smooth"});};return useEffect(()=>{if(r){let I=setTimeout(()=>{requestAnimationFrame(()=>{g();});},350);return ()=>clearTimeout(I)}},[t,r]),useEffect(()=>{let I=d.current;if(!(!I||!r))return I.addEventListener("scroll",g),window.addEventListener("resize",g),()=>{I.removeEventListener("scroll",g),window.removeEventListener("resize",g);}},[r]),h?null:jsx("div",{className:"fixed bottom-0 left-1/2 z-50 flex w-full -translate-x-1/2 flex-col gap-4 md:hidden",children:jsxs(AnimatePresence,{mode:"wait",children:[r&&jsxs(motion.div,{initial:{y:230,opacity:0},animate:{y:0,opacity:1},exit:{y:230,opacity:0},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},onAnimationComplete:()=>g(),className:"border bg-white md:hidden",children:[jsxs("div",{className:"flex w-full items-center justify-between px-4 py-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Cards,{size:24,weight:"fill",className:"text-[#096b76]"}),jsx("span",{className:"text-base font-bold text-black/80",children:"Pages"}),jsxs("span",{className:"text-base font-bold text-black/80",children:["(",t.length,"/",rr,")"]})]}),jsx("button",{onClick:()=>s(false),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretDown,{size:16,weight:"bold",className:"text-black/60"})})]}),jsxs("div",{className:"relative",children:[u&&jsx("button",{onClick:()=>C("left"),className:"absolute top-1/2 left-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll left",children:jsx(CaretLeft,{size:20,weight:"bold",className:"text-black/80"})}),c&&jsx("button",{onClick:()=>C("right"),className:"absolute top-1/2 right-2 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-white shadow-xl transition-all hover:bg-gray-50 hover:shadow-2xl","aria-label":"Scroll right",children:jsx(CaretRight,{size:20,weight:"bold",className:"text-black/80"})}),jsx("div",{ref:d,className:"scrollbar-hide flex gap-[11px] overflow-x-auto px-4 pb-4",children:t.map((I,B)=>jsx($S,{slide:I,index:B,isSelected:I.id===a,isSingleSlide:t.length===1,onSelect:()=>v(I.id),onDuplicate:()=>y(I.id),onDelete:()=>b(I.id)},I.id))})]}),jsx("button",{onClick:p,disabled:!n||t.length>=rr,className:`px-4 pb-4 text-base font-bold ${n&&t.length<rr?"cursor-pointer text-[#096b76]":"cursor-not-allowed text-black/30"}`,children:"+ Add Page"})]},"open"),!r&&jsxs(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{type:"tween",duration:.2},className:"flex cursor-pointer items-center justify-between gap-2 border border-black/10 bg-white px-4 py-3 shadow-lg md:hidden",children:[jsxs("div",{className:"flex gap-2",children:[jsx(Cards,{size:20,weight:"fill",className:"text-[#096b76]"}),jsxs("span",{className:"text-sm font-bold text-black/80",children:["Pages (",t.length,"/",rr,")"]})]}),jsx("button",{onClick:()=>s(true),className:"flex size-8 cursor-pointer items-center justify-center rounded-full bg-black/5 transition-colors hover:bg-black/10",children:jsx(CaretUp,{size:16,weight:"bold",className:"text-black/60"})})]},"close")]})})},md=XS;var oL=({stageRef:e,onScreenRecord:o,visible:t=true,config:a={}})=>{let n=_e(),[r,s]=useState(false),[u,i]=useState(false),c=Re(C=>C.canvas.slides.find(I=>I.id===C.canvas.currentSlideId)),f=Re(C=>C.canvas.zoomLevel),l=(c?.videos||[]).some(C=>C.isRecorded&&C.isPlaying),m={undo:a.undo??true,redo:a.redo??true,screenRecord:a.screenRecord??true,cameraRecord:a.cameraRecord??true,clear:a.clear??true,zoomOut:a.zoomOut??true,zoomIn:a.zoomIn??true,resetZoom:a.resetZoom??true},h=()=>{o?o():s(true);},p=()=>{i(true);},v=()=>{n(br());},y=async(C,I)=>{let B=v4(),k=URL.createObjectURL(C),x=document.createElement("video");x.src=k,x.muted=true,x.playsInline=true,x.preload="auto",await new Promise((H,F)=>{let V=setTimeout(()=>F(new Error("Metadata load timeout")),1e4);x.onloadedmetadata=()=>{clearTimeout(V),H();},x.onerror=()=>{clearTimeout(V),F(new Error("Failed to load video"));};});let S=640,w=x.videoWidth/x.videoHeight,T=S,q=T/w;await da(B,C,I),n(ko({id:B,objectUrl:k,thumbnailDataUrl:I,videoBlob:C,x:100,y:100,width:T,height:q,draggable:true,isPlaying:false,rotation:0,isRecorded:true}));},g=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>n(Mo()),enabled:m.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>n(Ao()),enabled:m.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:h,enabled:m.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:p,enabled:m.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:v,enabled:m.clear,iconWeight:"fill",colorClass:"text-[#E92222]"},{key:"resetZoom",title:"Reset Zoom",icon:ArrowsOut,onClick:()=>n(zd()),enabled:m.resetZoom&&f!==1,iconWeight:"bold",colorClass:"text-primary"}].filter(C=>C.enabled);return !t||l||g.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fixed bottom-[74px] left-1/2 z-50 flex w-11/12 -translate-x-1/2 items-center justify-between rounded-md border bg-white px-4 py-1 shadow-lg md:hidden",children:g.map(C=>jsx("button",{onClick:C.onClick,className:`flex size-10 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-black/5 ${C.colorClass}`,title:C.title,children:jsx(C.icon,{weight:C.iconWeight,className:"text-xl"})},C.key))}),!o&&r&&e&&jsx(eo,{onClose:()=>s(false),stageRef:e,onRecordingComplete:y}),u&&jsx(Rs,{onClose:()=>i(false),onRecordingComplete:y})]})},pd=oL;var sL=({stageRef:e,onScreenRecord:o,softDelete:t=false,actionButtonsVisible:a=true,actionButtonsConfig:n})=>jsxs(Fragment,{children:[jsx(pd,{stageRef:e,onScreenRecord:o,visible:a,config:n}),jsx(md,{softDelete:t})]}),iL=sL;var uL="SchooplaEditorDB",cL=1,Ua="slides",Ka="metadata",hd="schoopla_current_slide_id",Nm="presentation_metadata",on=()=>new Promise((e,o)=>{let t=indexedDB.open(uL,cL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let n=a.target.result;n.objectStoreNames.contains(Ua)||n.createObjectStore(Ua,{keyPath:"id"}),n.objectStoreNames.contains(Ka)||n.createObjectStore(Ka,{keyPath:"id"});};}),gd=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await on(),a=o.transaction([Ua],"readwrite").objectStore(Ua);await new Promise((n,r)=>{let s=a.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);});for(let n of e)await new Promise((r,s)=>{let u=a.add(n);u.onsuccess=()=>r(!0),u.onerror=()=>s(u.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},xd=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await on(),t=e.transaction([Ua],"readonly").objectStore(Ua);return new Promise((a,n)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let s=r.result;console.log("\u2705 Loaded from IndexedDB:",s.length,"slides"),s.length>0&&s[0].images&&console.log("First slide images:",s[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(s.length>0?s:null);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Us=async()=>{try{let e=await on(),o=e.transaction([Ua,Ka],"readwrite"),t=o.objectStore(Ua),a=o.objectStore(Ka);await new Promise((n,r)=>{let s=t.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),await new Promise((n,r)=>{let s=a.clear();s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(hd),localStorage.removeItem("schoopla_presentation_metadata"),await _c(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},bd=e=>{try{localStorage.setItem(hd,e);}catch(o){console.error("Error saving current slide ID:",o);}},vd=()=>{try{return localStorage.getItem(hd)}catch(e){return console.error("Error loading current slide ID:",e),null}},yd=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},wd=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await on(),a=o.transaction([Ka],"readwrite").objectStore(Ka);await new Promise((n,r)=>{let s=a.put({id:Nm,...e});s.onsuccess=()=>n(!0),s.onerror=()=>r(s.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Sd=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await on(),t=e.transaction([Ka],"readonly").objectStore(Ka);return new Promise((a,n)=>{let r=t.get(Nm);r.onsuccess=()=>{e.close();let s=r.result;if(s){let{id:u,...i}=s;console.log("\u2705 Loaded presentation metadata:",i),a(i);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),n(r.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var fL=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides","canvas/updateSlideThumbnail"],mL=["canvas/clearCanvas"],pL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],hL=yd((e,o)=>{gd(e),bd(o);},500),gL=yd(e=>{wd(e);},500),xL=(e,o)=>{gd(e),bd(o);},Ld=false,Hm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Nl(r).catch(s=>{console.error("Error deleting video blob:",s);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,u=e.getState().canvas.slides.find(i=>i.id===r);u&&u.videos&&u.videos.length>0&&u.videos.forEach(i=>{Nl(i.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,s=e.getState(),i=s.canvas.slides.find(c=>c.id===s.canvas.currentSlideId)?.videos.find(c=>c.id===r);i&&i.videoBlob&&setTimeout(()=>{let c=e.getState(),d=c.canvas.slides.find(l=>l.id===c.canvas.currentSlideId)?.videos.find(l=>l.id!==r&&l.x===i.x+20&&l.y===i.y+20);d&&i.videoBlob&&da(d.id,i.videoBlob,d.thumbnailDataUrl).catch(l=>{console.error("Error saving duplicated video blob:",l);});},0);}let a=o(t),n=e.getState();if(n.canvas.viewerMode)return a;if(t.type&&mL.includes(t.type)){if(!Ld){Ld=true;try{let{slides:r,currentSlideId:s}=n.canvas;xL(r,s);}finally{setTimeout(()=>{Ld=false;},0);}}}else if(t.type&&fL.includes(t.type)){let{slides:r,currentSlideId:s}=n.canvas;hL(r,s);}else if(t.type&&pL.includes(t.type)){let{presentationMetadata:r}=n.canvas;gL(r);}return a});new QueryClient;var vL=configureStore({reducer:{toolbar:Yl,canvas:Oi},middleware:e=>e({serializableCheck:false}).concat(Hm)}),yL=()=>configureStore({reducer:{toolbar:Yl,canvas:Oi},middleware:e=>e({serializableCheck:false})});var wL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2,fileName:r=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:s,quality:a,pixelRatio:n}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=u,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},SL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o;return new Promise((r,s)=>{try{let u=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:u,quality:a,pixelRatio:n});fetch(i).then(c=>c.blob()).then(c=>r(c)).catch(c=>s(c));}catch(u){s(u);}})},LL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:n=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:n})};var IL=(e,o,t)=>{let a=t.x-o.x,n=t.y-o.y;if(a===0&&n===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+n*n,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*n)/r)),u=o.x+s*a,i=o.y+s*n;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-i,2))},Id=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,n=e[0],r=e[e.length-1];for(let s=1;s<e.length-1;s++){let u=IL(e[s],n,r);u>t&&(t=u,a=s);}if(t>o){let s=Id(e.slice(0,a+1),o),u=Id(e.slice(a),o);return [...s.slice(0,-1),...u]}return [n,r]},CL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},kL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Vm=(e,o=1.5)=>{if(e.length<=4)return e;let t=CL(e),a=Id(t,o);return kL(a)},zm=(e,o=1.5)=>({...e,points:Vm(e.points,o)}),TL=(e,o=1.5)=>e.map(t=>zm(t,o)),ML=(e,o)=>{let t=e.length/2,a=o.length/2,n=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${n}%`}};var AL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Wm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:n=.85}=o;return new Promise((r,s)=>{let u=new Image;u.onload=()=>{let{width:i,height:c}=u;if(i>t||c>a){let h=i/c;i>c?(i=Math.min(i,t),c=i/h):(c=Math.min(c,a),i=c*h);}let f=document.createElement("canvas");f.width=i,f.height=c;let d=f.getContext("2d");if(!d){s(new Error("Failed to get canvas context"));return}d.drawImage(u,0,0,i,c);let l=AL(e),m=f.toDataURL(l,n);r(m);},u.onerror=s,u.src=e;})};var vo=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let n=0;n<t.length;n++)a[n]=t.charCodeAt(n);return a.buffer},nr=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",sr=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",PL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:n=1080,imageQuality:r=.85}=o,s=[],u=0;for(let i of e){let c=[],f=[],d=[];for(let l of i.images){let m=l.src;if(t&&m.startsWith("data:"))try{m=await Wm(m,{maxWidth:a,maxHeight:n,quality:r});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(m.startsWith("data:")){let h=vo(m),p=nr(m);u+=h.byteLength;let v={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,buffer:h,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let y=vo(l.audioData),b=nr(l.audioData);u+=y.byteLength,v.audioBuffer=y,v.audioMimeType=b;}c.push(v);}}for(let l of i.videos){let m,h;if(l.videoBlob)m=await l.videoBlob.arrayBuffer(),h=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))m=vo(l.videoData),h=nr(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}u+=m.byteLength;let p={id:l.id,thumbnailDataUrl:l.thumbnailDataUrl,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,isPlaying:l.isPlaying,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isRecorded:l.isRecorded,buffer:m,mimeType:h};if(l.audioData&&l.audioData.startsWith("data:")){let v=vo(l.audioData),y=nr(l.audioData);u+=v.byteLength,p.audioBuffer=v,p.audioMimeType=y;}f.push(p);}for(let l of i.photoFrames){let m={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:l.draggable,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isCapturing:l.isCapturing};if(l.capturedImageUrl&&l.capturedImageUrl.startsWith("data:")){let h=vo(l.capturedImageUrl),p=nr(l.capturedImageUrl);u+=h.byteLength,m.buffer=h,m.mimeType=p;}if(l.audioData&&l.audioData.startsWith("data:")){let h=vo(l.audioData),p=nr(l.audioData);u+=h.byteLength,m.audioBuffer=h,m.audioMimeType=p;}d.push(m);}s.push({...i,images:c,videos:f,photoFrames:d});}return {slides:s,totalSize:u}},EL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},DL=e=>{let o=new FormData,t=e.slides.map((a,n)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,mimeType:r.mimeType,fileKey:`slide_${n}_image_${s}`,audioFileKey:r.audioBuffer?`slide_${n}_image_${s}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,isPlaying:r.isPlaying,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isRecorded:r.isRecorded,mimeType:r.mimeType,fileKey:`slide_${n}_video_${s}`,thumbnailFileKey:`slide_${n}_video_${s}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${n}_video_${s}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,s)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,rotation:r.rotation,draggable:r.draggable,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isCapturing:r.isCapturing,mimeType:r.mimeType,fileKey:r.buffer?`slide_${n}_photoframe_${s}`:void 0,audioFileKey:r.audioBuffer?`slide_${n}_photoframe_${s}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,n)=>{a.images.forEach((r,s)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${sr(r.mimeType)}`;if(o.append(`slide_${n}_image_${s}`,u,i),r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),f=`${r.id}_audio.${sr(r.audioMimeType)}`;o.append(`slide_${n}_image_${s}_audio`,c,f);}}),a.videos.forEach((r,s)=>{let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${sr(r.mimeType)}`;if(o.append(`slide_${n}_video_${s}`,u,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let c=vo(r.thumbnailDataUrl),f=new Blob([c],{type:"image/jpeg"}),d=`${r.id}_thumbnail.jpg`;o.append(`slide_${n}_video_${s}_thumbnail`,f,d);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),f=`${r.id}_audio.${sr(r.audioMimeType)}`;o.append(`slide_${n}_video_${s}_audio`,c,f);}}),a.photoFrames.forEach((r,s)=>{if(r.buffer&&r.mimeType){let u=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${sr(r.mimeType)}`;o.append(`slide_${n}_photoframe_${s}`,u,i);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${sr(r.audioMimeType)}`;o.append(`slide_${n}_photoframe_${s}_audio`,u,i);}});}),o};var BL=()=>{let e=_e(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let n=await xd(),r=vd(),s=await Sd();if(n&&n.length>0){let u=await jc(),i=n.map(f=>{if(f.videos&&f.videos.length>0){let d=f.videos.map(l=>{let m=u.get(l.id);if(m){let h=$c(m.blob);return {...l,objectUrl:h,thumbnailDataUrl:m.thumbnailDataUrl,videoBlob:m.blob}}else return l});return {...f,videos:d}}return f}),c=r&&i.find(f=>f.id===r)?r:i[0].id;e(Io({slides:i,currentSlideId:c}));}e(s?Ri({title:s.title,description:s.description}):jn(!0));}catch(n){console.error("Error loading persisted slides:",n),e(jn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var Km=e=>e.map(o=>({...o,lines:o.lines||[],shapes:o.shapes||[],images:o.images||[],videos:o.videos||[],flashcards:o.flashcards||[],photoFrames:o.photoFrames||[],texts:o.texts||[],multipleChoices:o.multipleChoices||[],trueFalses:o.trueFalses||[],shortAnswers:o.shortAnswers||[],LongAnswer:o.LongAnswer||[],fillInTheBlanks:o.fillInTheBlanks||[],createdAt:o.createdAt||Date.now(),updatedAt:o.updatedAt||Date.now(),showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,activityType:o.activityType||""})),Gm=new WeakSet,jm=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await da(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},OL=()=>{let e=_e(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Gm.has(a))return;Gm.add(a);let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await Us(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,i=Km(n);e(Io({slides:i,currentSlideId:u})),await jm(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:n,currentSlideId:r,skipLocalPersistence:s=true}=a;if(s)try{await Us(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=r&&n.find(c=>c.id===r)?r:n[0].id,i=Km(n);e(Io({slides:i,currentSlideId:u})),await jm(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
|
|
6
6
|
|
|
7
7
|
lucide-react/dist/esm/shared/src/utils.js:
|
|
8
8
|
lucide-react/dist/esm/defaultAttributes.js:
|
|
@@ -17,5 +17,5 @@ lucide-react/dist/esm/lucide-react.js:
|
|
|
17
17
|
* This source code is licensed under the ISC license.
|
|
18
18
|
* See the LICENSE file in the root directory of this source tree.
|
|
19
19
|
*)
|
|
20
|
-
*/export{
|
|
20
|
+
*/export{Iw as BASIC_EDITOR_TOOLBAR_CONFIG,AS as BottomToolbar,Tv as Canvas,Sw as DEFAULT_CONTEXT_MENU_CONFIG,Fs as DEFAULT_TOOLBAR_CONFIG,Pg as EditorRoot,pd as MobileActionButtons,iL as MobileBottomSection,md as MobilePrevPanel,dd as PublishButton,eo as ScreenRecorder,qS as SlideNavigation,xS as Toolbar,SS as TopNavBar,Lw as VIEWER_TOOLBAR_CONFIG,Ii as addFillInTheBlanks,ci as addFlashcard,li as addImage,gi as addImageAnnotation,ii as addLine,Li as addLongAnswer,vi as addMultipleChoice,pi as addPhotoFrame,bi as addPhotoFrameAnnotation,di as addShape,Si as addShortAnswer,ur as addSlide,ui as addText,wi as addTrueFalse,ko as addVideo,EL as arrayBufferToBase64,ki as bringToFront,br as clearCanvas,kp as clearImageAnnotations,Us as clearLocalData,Mp as clearPhotoFrameAnnotations,ni as createEmptySlide,yL as createViewerStore,qn as deleteFillInTheBlanks,Tn as deleteFlashcard,bn as deleteImage,Gn as deleteLineById,Nn as deleteLongAnswer,En as deleteMultipleChoice,An as deletePhotoFrame,In as deleteShape,Bn as deleteShortAnswer,cr as deleteSlide,Cn as deleteText,Rn as deleteTrueFalse,wn as deleteVideo,Vn as duplicateFillInTheBlanks,Mn as duplicateFlashcard,vn as duplicateImage,Pi as duplicateLine,Hn as duplicateLongAnswer,Dn as duplicateMultipleChoice,Pn as duplicatePhotoFrame,Ln as duplicateShape,On as duplicateShortAnswer,fr as duplicateSlide,kn as duplicateText,Fn as duplicateTrueFalse,Sn as duplicateVideo,hr as editFlashcard,Ap as editMultipleChoice,SL as exportSlideAsBlob,wL as exportSlideAsImage,Ai as finalizeDrawing,ML as getCompressionStats,LL as getSlideDataURL,vd as loadCurrentSlideId,xd as loadFromIndexedDB,Ri as loadPresentationMetadata,Sd as loadPresentationMetadataFromDB,Io as loadSlides,Ql as mergeToolbarConfig,fi as nextFlashcard,DL as prepareFormData,PL as prepareSlidesForPublishing,mi as previousFlashcard,Ao as redo,xn as removeLine,Ip as reorderSlides,wd as savePresentationMetadata,de as saveToHistory,Ca as selectAllSlides,Fi as selectAllSlidesIncludingInactive,yr as selectCanAddSlide,ve as selectCurrentSlide,Ia as selectCurrentSlideId,Bi as selectMetadataLoaded,wr as selectPresentationMetadata,Fp as selectSlideById,Ti as sendToBack,Ci as setActivityType,Wn as setAltText,Un as setAudioData,pr as setBackgroundColor,mr as setCurrentSlide,gr as setEditingActivity,vr as setEditingTextId,Ep as setLines,zn as setLink,jn as setMetadataLoaded,ma as setPenColor,Di as setPresentationDescription,Ei as setPresentationTitle,Qa as setShowFlashcardForm,La as setShowMcqForm,It as setSketchMode,Zr as setStrokeWidth,aa as setTool,Lp as setViewerMode,Vm as simplifyFlatPoints,zm as simplifyLine,TL as simplifyLines,vL as store,hi as toggleImageDrawingMode,Mi as toggleLock,xi as togglePhotoFrameDrawingMode,Rp as toggleSketchMode,Xa as toggleVideoPlaying,Mo as undo,xr as updateElementOrder,Sa as updateFillInTheBlanks,To as updateFlashcard,Co as updateImage,Cp as updateImageAnnotation,Pp as updateLastLine,Dp as updateLinePosition,Kn as updateLineTransform,Ja as updateLongAnswer,gt as updateMultipleChoice,Za as updatePhotoFrame,Tp as updatePhotoFrameAnnotation,Ya as updateShape,sa as updateShortAnswer,si as updateSlideThumbnail,Ft as updateText,ot as updateTrueFalse,yn as updateVideo,Se as useDispatch,OL as useInitialSlides,rl as useModalPortal,J as useSelector,BL as useSlidesPersistence};//# sourceMappingURL=index.js.map
|
|
21
21
|
//# sourceMappingURL=index.js.map
|