@turnix-co/konva-editor 3.0.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +8 -7
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ export{default as Konva}from'konva';import*as be from'react';import be__default,
|
|
|
3
3
|
`).length,H=r.find(W=>W.id===s)?.fontSize||24,P=V*H*1.2+10;x.width=Math.max(200,b),x.height=Math.max(50,A,P);}else if(p&&i.trim()){let v=p.text(),L=p.width();p.text(i),p.width(void 0);let I=p.width(),k=p.height();p.text(v),p.width(L),x.width=Math.max(200,I+20),x.height=Math.max(50,k+20);}t(wt(x)),c(null),d(""),t(jo(null)),e();}}}};var ld=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],r=useRef(new Map),n=useCallback((s,c)=>{let i=s.target;o(Wo({id:c,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:n}};var dd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((n,s)=>{let c=n.target;o(zo({id:s,x:c.x(),y:c.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var cd=e=>{let o=xe(),a=ee(ge)?.flashcards||[],r=useRef(new Map),n=useRef(new Map),s=useCallback((u,m)=>{if(n.current.has(m))return n.current.get(m);let l=new window.Image;return l.src=u,n.current.set(m,l),l},[]),c=useCallback((u,m)=>{let l=u.target,h=l.id();a.find(p=>p.id===h)&&(o(ro({id:h,x:l.x(),y:l.y()})),m?.());},[a,o]),i=useCallback((u,m)=>{let l=m.target,h=l.scaleX(),g=l.scaleY(),p=l.rotation(),w=Math.max(50,l.width()*h),x=Math.max(50,l.height()*g);l.scaleX(1),l.scaleY(1),l.width(w),l.height(x),o(ro({id:u,width:w,height:x,x:l.x(),y:l.y(),rotation:p})),l.getLayer()?.batchDraw(),e?.();},[o,e]),d=useCallback(u=>{o(Ds(u)),e?.();},[o,e]),f=useCallback(u=>{o(Es(u)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:r,handleDragEnd:c,handleFlashcardTransformEnd:i,handleNext:d,handlePrevious:f}};var pd=e=>{let o=xe(),a=ee(ge)?.photoFrames||[],r=useRef(new Map),[n,s]=useState(new Map),c=useCallback((l,h)=>{console.log("handleDragEnd"),o(Pa({id:h,x:l.target.x(),y:l.target.y()})),e?.();},[o,e]),i=useCallback((l,h)=>{let g=h.target,p=g.scaleX(),w=g.scaleY(),x=g.rotation(),v=a.find(k=>k.id===l);if(!v)return;let L=Math.max(100,v.width*p),I=Math.max(100,v.height*w);g.scaleX(1),g.scaleY(1),o(Pa({id:l,width:L,height:I,x:g.x(),y:g.y(),rotation:x})),g.getLayer()?.batchDraw(),e?.();},[o,e,a]),d=useCallback(async l=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(g=>{let p=new Map(g);return p.set(l,h),p}),o(Pa({id:l,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),f=useCallback(l=>{let h=n.get(l);h&&(h.getTracks().forEach(g=>g.stop()),s(g=>{let p=new Map(g);return p.delete(l),p}),o(Pa({id:l,isCapturing:false})),e?.());},[n,o,e]),u=useCallback((l,h)=>{let g=document.createElement("canvas");g.width=h.videoWidth,g.height=h.videoHeight;let p=g.getContext("2d");if(p){p.drawImage(h,0,0,g.width,g.height);let w=g.toDataURL("image/jpeg",.8);return o(Pa({id:l,capturedImageUrl:w,isCapturing:false})),f(l),e?.(),w}return null},[o,f,e]),m=useRef(n);return useEffect(()=>{m.current=n;},[n]),useEffect(()=>()=>{m.current.forEach(l=>{l.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:c,handlePhotoFrameTransformEnd:i,startCamera:d,stopCamera:f,capturePhoto:u,cameraStreams:n}};var hd=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((n,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((n,s,c,i,d,f,u,m=[])=>{if(e.current){if(n&&!m.find(g=>g.id===n)?.isPlaying){let g=s.get(n)||c.get(n)||i.get(n)||d.get(n)||f.get(n)||(u?u.get(n):null);if(g){e.current.boundBoxFunc(t),e.current.nodes([g]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var Zm=(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])},vd=(e,o)=>{let t=yt(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let s=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});s&&s.startsWith("data:")&&t(Cs({id:a.current,thumbnail:s}));}catch(s){console.warn("Could not generate thumbnail (likely CORS issue with images):",s);}},[o,t]),n=Zm(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var ep=e=>e.flatMap(o=>[o[0],o[1]]),vn=(e,o)=>{let t=Xl(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 ep(t)};var yd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null),c=ee(v=>v.toolbar.selectedTool),i=ee(v=>v.toolbar.penColor),d=ee(v=>v.toolbar.strokeWidth),f=ee(v=>v.canvas.isSketchMode),u=ee(v=>v.canvas.slides.find(I=>I.id===v.canvas.currentSlideId)?.images.find(I=>I.id===e)),m=u?.annotations||[],l=u?.isDrawingMode||false,h=u?.width||1,g=u?.height||1,p=useCallback(v=>{if(c!=="pen"&&c!=="eraser")return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/h,I=v.y/g;s({tool:c,points:[L,I],color:i,strokeWidth:d/h,isSketch:f});},[c,i,d,f,h,g]),w=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let k;if(f)k=vn(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,A)=>A%2===0?b/h:b/g);else {let S=v.x/h,b=v.y/g;k=[...n.points,S,b];}s(S=>S?{...S,points:k}:null);},[f,d,n,h,g]),x=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Os({imageId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:m,activeLine:n,isDrawingMode:l,startDrawing:p,draw:w,stopDrawing:x,tool:c}};var Sd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>{let{annotations:c,activeLine:i,stopDrawing:m,tool:l}=yd(e.id);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 h=false;useEffect(()=>{return;},[m,h]);let g=x=>{{n(e.id);return}},p=x=>{return;},w=x=>{};return jsxs(Group,{listening:l!=="pen"&&l!=="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();let v=x.getStage()?.container();if(v){let L=I=>{let k=x.getStage()?.getPointerPosition();if(k){let S={x:e.x,y:e.y,width:e.width,height:e.height};k.x>=S.x&&k.x<=S.x+S.width&&k.y>=S.y&&k.y<=S.y+S.height&&s(I,e.id,"image");}};v.addEventListener("contextmenu",L),x._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",L);};}}else {let v=t.current.get(e.id);v?._contextMenuCleanup&&v._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:l!=="pen"&&l!=="eraser",onDragEnd:a,onTransformEnd:x=>r(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...l!=="pen"&&l!=="eraser"?{onClick:g,onTap:g,onMouseDown:g,onTouchStart:g,onMouseMove:p,onTouchMove:p,onMouseUp:w,onTouchEnd:w}:{}}),c?.map((x,v)=>{let L=x.points.map((k,S)=>S%2===0?k*e.width+e.x:k*e.height+e.y),I=x.strokeWidth*e.width;return jsx(Line,{points:L,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:I,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},v)}),i&&jsx(Line,{points:i.points.map((x,v)=>v%2===0?x*e.width+e.x:x*e.height+e.y),stroke:i.tool==="eraser"?"white":i.color,strokeWidth:i.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:i.tool==="eraser"?"destination-out":"source-over",fill:i.isSketch?i.color:void 0,closed:i.isSketch,listening:false},"active")]})});Sd.displayName="ImageWithDrawing";var si=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(c=>{let i=o(c);return i?jsx(Sd,{img:c,loadedImage:i,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s},c.id):null})}));si.displayName="ImageLayer";var up=({src:e,x:o,id:t,y:a,width:r,height:n,isSelected:s,rotation:c=0,onTransformEnd:i,onDragEnd:d})=>{let f=xe(),u=useRef(null),m=l=>{f(Ho(l));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:n,rotation:c,onDragEnd:d,onTransformEnd:i,children:[jsx(Rect,{width:r,height:n,fill:"black",stroke:s?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${n}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:u,src:e,controls:true,autoPlay:true,onClick:()=>m(t),onSeeking:l=>l.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Cd=up;var bp=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,nodeRef:s})=>{let[c,i]=useState(null),d=useSelector(g=>g.toolbar.selectedTool),f=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let g=new window.Image;g.src=e.thumbnailDataUrl,g.onload=()=>{i(g);};}},[e.thumbnailDataUrl]),!c)return null;let u=e.width/2,m=e.height/2,l=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(l,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:r},ref:g=>{if(s(g),g){let p=g.getStage()?.container();if(p){let w=x=>{let v=g.getStage()?.getPointerPosition();if(v){let L={x:e.x,y:e.y,width:e.width,height:e.height};v.x>=L.x&&v.x<=L.x+L.width&&v.y>=L.y&&v.y<=L.y+L.height&&n(x);}};p.addEventListener("contextmenu",w),g._contextMenuCleanup=()=>{p.removeEventListener("contextmenu",w);};}}},children:[jsx(Image$1,{image:c,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:u,y:m,radius:h,fill:"white",listening:!f,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...f?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:u,y:m,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!f,...f?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:u+h*.1,y:m,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!f,...f?{}:{onClick:t,onTap:t}})]})},Md=bp;var di=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(c=>jsxs(be__default.Fragment,{children:[jsx(Md,{video:c,isSelected:!c.isPlaying&&o===c.id,onClick:()=>a(c.id),onDragEnd:i=>r(c.id,i),onTransformEnd:i=>n(c.id,i),onContextMenu:i=>s(i,c.id,"video"),nodeRef:i=>{i?t.current.set(c.id,i):t.current.delete(c.id);}}),c.isPlaying&&(()=>{let i=c.x,d=c.y;if(c.isRecorded){let f=typeof window<"u"?window.innerWidth:c.width,u=typeof window<"u"?window.innerHeight:c.height;i=(f-c.width)/2,d=(u-c.height)/2;}return jsx(Cd,{id:c.id,src:c.objectUrl,x:i,y:d,width:c.width,height:c.height,isSelected:false,rotation:c.rotation,onTransformEnd:f=>n(c.id,f),onDragEnd:f=>r(c.id,f)})})()]},c.id))}));di.displayName="VideoLayer";var ui=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:n,onContextMenu:s})=>{let c=useSelector(d=>d.toolbar.selectedTool),i=c==="pen"||c==="eraser";return jsx(Fragment,{children:e.map((d,f)=>{let u=d.id||f,m={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!i,listening:!i,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},radius:d.radius||d.width/2,width:d.width,height:d.width},u);case "star":return jsx(Star,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "triangle":return jsx(RegularPolygon,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},sides:3,radius:d.radius||d.width/2},u);case "polygon":return jsx(RegularPolygon,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},sides:d.sides||6,radius:d.radius||d.width/2},u);case "ellipse":return jsx(Ellipse,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},u);case "ring":return jsx(Ring,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "wedge":return jsx(Wedge,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},radius:d.radius||d.width/2,angle:d.angle||60},u);case "arrow":return jsx(Arrow,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "line":return jsx(Line,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "arc":return jsx(Arc,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},u);case "rectangle":default:return jsx(Rect,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},u)}})})});ui.displayName="ShapeLayer";var Pd=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:n,onDoubleClick:s,editingTextId:c})=>{let i=useSelector(f=>f.toolbar.selectedTool),d=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map(f=>{let u=f.id===c,m=f.fontWeight==="bold",l=m?Math.max(1,f.fontSize/25):0;return jsx(Text,{id:f.id,ref:h=>{h?o.current.set(f.id,h):o.current.delete(f.id);},text:f.text,x:f.x,y:f.y,width:f.width,height:f.height,rotation:f.rotation,draggable:!f.locked&&!u&&!d,listening:!d,fontSize:f.fontSize,fontFamily:f.fontFamily,fontStyle:f.fontStyle,fontWeight:f.fontWeight,textDecoration:f.textDecoration,fill:f.fill,stroke:m?f.fill:void 0,strokeWidth:l,align:f.align,wrap:"none",lineHeight:1.2,opacity:u?0:1,visible:!u,...d?{}:{onClick:()=>r(f.id),onTap:()=>r(f.id),onDblClick:()=>s(f.id),onDblTap:()=>s(f.id),onDragEnd:h=>t(h,f.id),onTransformEnd:()=>a(f.id),onContextMenu:h=>{h.evt.preventDefault();let g=h.evt;n(g,f.id,"text");}}},f.id)})})};var zp=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onNext:s,onPrevious:c,nodeRef:i})=>{let[d,f]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let p=new window.Image;p.src=e.images[e.currentIndex],p.onload=()=>{f(p);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let u=8,m=2,l=Math.min(e.width,e.height)*.08,h=Math.max(16,Math.min(l,32)),g=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:r,ref:p=>{if(i(p),p){let w=p.getStage()?.container();if(w){let x=v=>{let L=p.getStage()?.getPointerPosition();if(L){let I={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=I.x&&L.x<=I.x+I.width&&L.y>=I.y&&L.y<=I.y+I.height&&n(v);}};w.addEventListener("contextmenu",x),p._contextMenuCleanup=()=>{w.removeEventListener("contextmenu",x);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:u,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:u,stroke:"#E5E7EB",strokeWidth:m,listening:false}),jsx(Image$1,{x:m+4,y:m+4,image:d,width:e.width-(m+4)*2,height:e.height-(m+4)*2,cornerRadius:u-m,onClick:t,onTap:t}),jsx(Rect,{x:m,y:e.height-50,width:e.width-m*2,height:50,cornerRadius:[0,0,u-m,u-m],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:g+h,y:e.height/2,onClick:p=>{p.cancelBubble=true,c();},onTap:p=>{p.cancelBubble=true,c();},children:[jsx(Circle,{radius:h,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-g-h,y:e.height/2,onClick:p=>{p.cancelBubble=true,s();},onTap:p=>{p.cancelBubble=true,s();},children:[jsx(Circle,{radius:h,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"})]})},Ed=zp;var mi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onNext:s,onPrevious:c,onContextMenu:i})=>jsx(Fragment,{children:e.map(d=>jsx(Ed,{flashcard:d,isSelected:t===d.id,onClick:()=>n(d.id),onDragEnd:a,onTransformEnd:f=>r(d.id,f),onContextMenu:f=>i(f,d.id,"flashcard"),onNext:()=>s(d.id),onPrevious:()=>c(d.id),nodeRef:f=>{f?o.current.set(d.id,f):o.current.delete(d.id);}},d.id))}));mi.displayName="FlashcardLayer";var Bd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null);ee(v=>v.toolbar.selectedTool);let i=ee(v=>v.toolbar.penColor),d=ee(v=>v.toolbar.strokeWidth),f=ee(v=>v.canvas.isSketchMode),u=ee(v=>v.canvas.slides.find(I=>I.id===v.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),m=u?.annotations||[],l=u?.isDrawingMode||false,h=u?.width||1,g=u?.height||1,p=useCallback(v=>{if(!l)return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/h,I=v.y/g;s({tool:"pen",points:[L,I],color:i,strokeWidth:d/h,isSketch:f});},[l,i,d,f,h,g]),w=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let k;if(f)k=vn(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,A)=>A%2===0?b/h:b/g);else {let S=v.x/h,b=v.y/g;k=[...n.points,S,b];}s(S=>S?{...S,points:k}:null);},[f,d,n,h,g]),x=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Vs({frameId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:m,activeLine:n,isDrawingMode:l,startDrawing:p,draw:w,stopDrawing:x}};var Zp=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onStartCamera:s,onCapture:c,cameraStream:i,nodeRef:d})=>{let[f,u]=useState(null),[m,l]=useState(null),h=useRef(null),g=useRef(null),p=useRef(null),w=useRef(null),x=useRef(0),v=33,L=useSelector(O=>O.toolbar.selectedTool),I=L==="pen"||L==="eraser",{annotations:k,activeLine:S,isDrawingMode:b,startDrawing:A,draw:V,stopDrawing:R}=Bd(e.id);useEffect(()=>{if(!b)return;let O=()=>{R();},X=()=>{R();};return window.addEventListener("mouseup",O),window.addEventListener("touchend",X),()=>{window.removeEventListener("mouseup",O),window.removeEventListener("touchend",X);}},[R,b]),useEffect(()=>{if(e.capturedImageUrl){let O=new window.Image;O.src=e.capturedImageUrl,O.onload=()=>{u(O);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){h.current||(h.current=document.createElement("video"),h.current.autoplay=true,h.current.playsInline=true),g.current||(g.current=document.createElement("canvas"));let O=h.current,X=g.current;O.srcObject=i;let U=()=>{X.width=O.videoWidth||640,X.height=O.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",X.width,X.height);let K=Q=>{if(Q-x.current<v){p.current=requestAnimationFrame(K);return}x.current=Q;let te=X.getContext("2d");if(te&&O.readyState===O.HAVE_ENOUGH_DATA){te.drawImage(O,0,0,X.width,X.height);let J=X.toDataURL("image/jpeg",.6),de=new window.Image;de.onload=()=>{l(de);},de.src=J;}p.current=requestAnimationFrame(K);};p.current=requestAnimationFrame(K);};return O.onloadedmetadata=U,O.readyState>=O.HAVE_METADATA&&U(),O.play().catch(K=>console.error("Error playing video:",K)),()=>{p.current&&(cancelAnimationFrame(p.current),p.current=null);}}return ()=>{l(null),w.current&&(w.current.src="");}},[e.isCapturing,i]);let H=()=>{h.current&&e.isCapturing&&c(h.current);},q=O=>{if(e.capturedImageUrl){if(!b){t();return}let X=O.currentTarget,U=X.getAbsoluteTransform().copy(),Q=X.getStage()?.getPointerPosition();if(Q){U.invert();let te=U.point(Q);A(te);}O.cancelBubble=true;}else t();},P=O=>{if(!b||!e.capturedImageUrl)return;let X=O.currentTarget,U=X.getAbsoluteTransform().copy(),Q=X.getStage()?.getPointerPosition();if(Q){U.invert();let te=U.point(Q);V(te);}},W=()=>{!b||!e.capturedImageUrl||R();},E=e.isCapturing?m:f,oe=Math.min(e.width,e.height)*.12,N=Math.max(25,Math.min(oe,50)),fe=e.width/2,z=e.height/2;return jsxs(Group,{id:e.id,draggable:!b&&!I,listening:true,x:e.x,y:e.y,...I?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:O=>{if(d(O),O){let X=O.getStage()?.container();if(X){let U=K=>{let Q=O.getStage()?.getPointerPosition();if(Q){let te={x:e.x,y:e.y,width:e.width,height:e.height};Q.x>=te.x&&Q.x<=te.x+te.width&&Q.y>=te.y&&Q.y<=te.y+te.height&&n(K);}};X.addEventListener("contextmenu",U),O._contextMenuCleanup=()=>{X.removeEventListener("contextmenu",U);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:E?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),E&&jsx(Image$1,{image:E,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:q,onTap:q,onMouseDown:q,onTouchStart:q,onMouseMove:P,onTouchMove:P,onMouseUp:W,onTouchEnd:W,...I?{}:{onDragEnd:a,onTransformEnd:r}}),k?.map((O,X)=>{let U=O.points.map((Q,te)=>te%2===0?Q*e.width:Q*e.height),K=O.strokeWidth*e.width;return jsx(Line,{points:U,stroke:O.tool==="eraser"?"white":O.color,strokeWidth:K,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:O.tool==="eraser"?"destination-out":"source-over",fill:O.isSketch?O.color:void 0,closed:O.isSketch,listening:false},X)}),S&&jsx(Line,{points:S.points.map((O,X)=>X%2===0?O*e.width:O*e.height),stroke:S.tool==="eraser"?"white":S.color,strokeWidth:S.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:S.tool==="eraser"?"destination-out":"source-over",fill:S.isSketch?S.color:void 0,closed:S.isSketch,listening:false},"active"),!E&&!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:z-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:fe-N+6,y:z-60,width:N*1.6,height:N*1.6,radius:N,fill:"white",cornerRadius:8,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?H():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:fe-12,y:z-40,width:N*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:O=>{O.stopPropagation(),e.isCapturing?H():s();}})})]}),jsx(Text,{x:0,y:z,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:z+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:fe-24,y:z+104,width:N*1.6,height:N*1.6,radius:N,fill:"#096B76",cornerRadius:N,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?H():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:fe-8,y:z+120,width:N*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:O=>{O.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"})]})]})},qd=Zp;var bi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onStartCamera:s,onCapture:c,cameraStreams:i,onContextMenu:d})=>jsx(Fragment,{children:e.map(f=>jsx(qd,{photoFrame:f,isSelected:t===f.id,onClick:()=>n(f.id),onDragEnd:u=>a(u,f.id),onTransformEnd:u=>r(f.id,u),onContextMenu:u=>d(u,f.id,"photoFrame"),onStartCamera:()=>s(f.id),onCapture:u=>c(f.id,u),cameraStream:i.get(f.id),nodeRef:u=>{u?o.current.set(f.id,u):o.current.delete(f.id);}},f.id))}));bi.displayName="PhotoFrameLayer";var zd=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:n="",isDrawingMode:s,menuRef:c})=>{useEffect(()=>{let u=l=>{c?.current&&!c.current.contains(l.target)&&a();},m=l=>{l.key==="Escape"&&a();};return document.addEventListener("mousedown",u),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",u),document.removeEventListener("keydown",m);}},[a]);let i=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:s?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(m=>!(m.showForTypes&&!m.showForTypes.includes(r)||m.hideForTypes&&m.hideForTypes.includes(r))),[r,s]),d=(u,m)=>{u==="order"||u==="lock"?t(u,m):(t(u),a());},f=jsx("div",{ref:c,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:i.map((u,m)=>jsxs("button",{onClick:l=>d(u.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] ${u.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[u.icon,jsx("span",{className:`font-medium ${u.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:u.label})]}),u.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"})})]},m))})});return createPortal(f,document.body)};var Gd=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let n=s=>{r.current&&!r.current.contains(s.target)&&a();};return document.addEventListener("mousedown",n),()=>{document.removeEventListener("mousedown",n);}},[a]),jsx("div",{ref:r,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((n,s)=>jsx("button",{onClick:()=>{n.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:n.label})},s))})})};var Kd=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:n})=>{let[s,c]=useState(a),i=useRef(null);useEffect(()=>{i.current?.focus();},[]);let d=()=>{r(s),n();};return jsx("div",{className:"fixed inset-0 z-102 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-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:n,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:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"?d():u.key==="Escape"&&n();},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:n,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:d,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})})};var _d=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),n=useRef(null);useEffect(()=>{let f=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let s=f=>{f.preventDefault(),o(a);},c=(f,u,m)=>{m/=100;let l=u*Math.min(m,1-m)/100,h=g=>{let p=(g+f/30)%12,w=m-l*Math.max(Math.min(p-3,9-p,1),-1);return Math.round(255*w).toString(16).padStart(2,"0")};return `#${h(0)}${h(8)}${h(4)}`},d=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:n,className:"pointer-events-auto max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.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 Shape 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:s,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:f=>r(f.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:f=>r(f.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:f=>{let u=parseInt(f.target.value),m=c(u,100,50);r(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:["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"].map(f=>jsx("button",{type:"button",onClick:()=>r(f),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===f.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:f},title:f},f))})]})]}),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(d,document.body)};var Bh=({imageSrc:e,onCrop:o})=>{let[t]=Xd(e),a=useRef(null),r=useRef(null),n=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]),c=useMemo(()=>{let m=s.width*.5,l=s.height*.5,h=(s.width-m)/2,g=(s.height-l)/2;return {x:h,y:g,width:m,height:l}},[s]),[i,d]=useState(c);useEffect(()=>{d(c);},[c]),useEffect(()=>{n.current&&r.current&&(n.current.nodes([r.current]),n.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let f=()=>{let m=r.current;if(!m)return;let l=m.scaleX(),h=m.scaleY();m.scaleX(1),m.scaleY(1),d({x:m.x(),y:m.y(),width:Math.max(20,m.width()*l),height:Math.max(20,m.height()*h)});},u=()=>{let m=r.current;m&&d({x:m.x(),y:m.y(),width:m.width(),height:m.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:r,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:u,onTransformEnd:f,dragBoundFunc:m=>{let l=Math.max(0,Math.min(m.x,s.width-i.width)),h=Math.max(0,Math.min(m.y,s.height-i.height));return {x:l,y:h}}}),jsx(Transformer,{ref:n,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:(m,l)=>l.width<20||l.height<20||l.x<0||l.y<0||l.x+l.width>s.width||l.y+l.height>s.height?m:l})]})})},Yd=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,n]=useState({x:0,y:0,width:0,height:0}),[s]=Xd(e);return useEffect(()=>{let f=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:a,className:"pointer-events-auto max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.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(Bh,{imageSrc:e,onCrop:(f,u,m,l)=>{n({x:f,y:u,width:m,height:l});}})}),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:()=>{if(!s)return;let m=Math.min(600/s.width,400/s.height),l=r.x/m,h=r.y/m,g=r.width/m,p=r.height/m,w=document.createElement("canvas");w.width=g,w.height=p;let x=w.getContext("2d");if(!x)return;x.drawImage(s,l,h,g,p,0,0,g,p);let v=w.toDataURL("image/png");o(v);},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"]})]})]})}),document.body)};var or=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[r,n]=useState(false),[s,c]=useState(null),[i,d]=useState(0),[f,u]=useState(true),m=useRef(null),l=useRef([]),h=useRef(null),g=useRef(null),p=useRef(null),w=useRef(null),x=useRef(null),v=useRef(null);useEffect(()=>()=>{p.current&&cancelAnimationFrame(p.current),h.current&&clearInterval(h.current),g.current&&g.current.getTracks().forEach(b=>b.stop());},[]);let L=async()=>{try{let b,A=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let P=o.current.getLayers();console.log("Konva layers:",P.length),P.forEach((X,U)=>{let K=X.getChildren();console.log(`Layer ${U} children count:`,K.length);});let W=document.createElement("canvas");W.width=o.current.width(),W.height=o.current.height();let E=W.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:",W.width,"x",W.height),x.current=W;let oe=()=>{if(E.clearRect(0,0,W.width,W.height),P.forEach(X=>{let U=X.getCanvas()._canvas;U&&E.drawImage(U,0,0);}),a?.current){let X=a.current;E.drawImage(X,0,0);}};v.current=oe,o.current.draw(),oe(),await new Promise(X=>setTimeout(X,100)),console.log("Creating captureStream..."),b=W.captureStream(30),console.log("Canvas stream created, tracks:",b.getTracks().length);let fe=b.getVideoTracks()[0];fe&&console.log("Video track:",fe.label,"state:",fe.readyState);let z=0,O=()=>{oe(),o?.current&&(o.current.getLayers().forEach(U=>{U.batchDraw();}),z++,z%60===0&&console.log("Drawing frame:",z)),p.current=requestAnimationFrame(O);};O();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{A=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(P){console.warn("Microphone access denied:",P);}let V=[...b.getVideoTracks()];A&&V.push(...A.getAudioTracks());let R=new MediaStream(V);g.current=R;let H="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?H="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?H="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?H="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(H="video/webm;codecs=vp8"),console.log("Using mimeType:",H);let q=new MediaRecorder(R,{mimeType:H,videoBitsPerSecond:25e5});m.current=q,l.current=[],q.ondataavailable=P=>{console.log("Data available, size:",P.data.size),P.data.size>0&&l.current.push(P.data);},q.onstop=()=>{console.log("Recording stopped, chunks:",l.current.length);let P=new Blob(l.current,{type:H});console.log("Final blob size:",P.size),o?.current&&v.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(E=>{E.batchDraw();}),v.current(),w.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",w.current.length)),R.getTracks().forEach(W=>W.stop()),h.current&&clearInterval(h.current),p.current&&(cancelAnimationFrame(p.current),p.current=null),c(P);},q.onerror=P=>{console.error("MediaRecorder error:",P);},console.log("Starting recording..."),q.start(1e3),n(!0),d(0),h.current=setInterval(()=>{d(P=>P+1);},1e3);}catch(b){console.error("Error starting screen recording:",b),alert("Failed to start recording. Please ensure you granted permission.");}},I=()=>{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)),n(false));},k=()=>{if(s){let b=URL.createObjectURL(s),A=document.createElement("a");A.href=b,A.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(b);}},S=b=>{let A=Math.floor(b/60),V=b%60;return `${A.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return r?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:S(i)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:I,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"]})]}):jsx("div",{className:"fixed inset-0 z-102 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:[!s&&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:()=>u(!f),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${f?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:f?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"]})]})]}),s&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(s),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",S(i)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&s&&w.current&&(t(s,w.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:()=>{c(null),d(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."]})})]})})};var Zd=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let[n,s]=useState(false),[c,i]=useState(null),[d,f]=useState(false),[u,m]=useState(0),l=useRef(null),h=useRef([]),g=useRef(null),p=useRef(null);useEffect(()=>{o&&!c&&fetch(o).then(b=>b.blob()).then(b=>i(b)).catch(b=>console.error("Error loading audio:",b));},[o,c]);let w=async()=>{try{let b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),A=new MediaRecorder(b);l.current=A,h.current=[],A.ondataavailable=V=>{V.data.size>0&&h.current.push(V.data);},A.onstop=()=>{let V=new Blob(h.current,{type:"audio/webm"});i(V),b.getTracks().forEach(R=>R.stop()),g.current&&clearInterval(g.current);},A.start(),s(!0),m(0),g.current=setInterval(()=>{m(V=>V+1);},1e3);}catch(b){console.error("Error starting audio recording:",b),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{l.current&&n&&(l.current.stop(),s(false));},v=()=>{if(c){let b=URL.createObjectURL(c),A=new Audio(b);p.current=A,A.onended=()=>{f(false),URL.revokeObjectURL(b);},A.play(),f(true);}},L=()=>{p.current&&(p.current.pause(),p.current.currentTime=0,f(false));},I=async()=>{if(c){let b=new FileReader;b.onloadend=()=>{let A=b.result;t(A),r();},b.readAsDataURL(c);}},k=()=>{i(null),a();},S=b=>{let A=Math.floor(b/60),V=b%60;return `${A.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return n?jsxs("div",{className:"fixed top-4 left-1/2 z-103 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:S(u)})]}),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"]})]}):jsx("div",{className:"fixed inset-0 z-103 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:[!c&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:w,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"]})}),c&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:d?L:v,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),d?"Playing...":"Play Audio"]}),jsx("button",{onClick:k,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:I,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:r,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"})]})]})})};var It=({audioData:e,x:o,y:t,width:a})=>{let[r,n]=useState(false),s=useRef(null);return jsx("button",{onClick:i=>{if(i.stopPropagation(),r&&s.current)s.current.pause(),s.current.currentTime=0,n(false);else {let d=new Audio(e);s.current=d,d.onended=()=>{n(false);},d.onerror=()=>{console.error("Error playing audio"),n(false);},d.play(),n(true);}},className:`absolute flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${r?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${o+a-35}px`,top:`${t+5}px`,width:"30px",height:"30px",zIndex:99},title:r?"Stop Audio":"Play Audio",children:r?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var tu=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=ee(ge),n=useMemo(()=>{if(!r)return [];let g=[];return r.images?.forEach(p=>{g.push({id:p.id,type:"image",name:"Image",timestamp:p.timestamp||0});}),r.videos?.forEach(p=>{g.push({id:p.id,type:"video",name:"Video",timestamp:p.timestamp||0});}),r.shapes?.forEach(p=>{g.push({id:p.id,type:"shape",name:`${p.type} Shape`,timestamp:p.timestamp||0});}),r.texts?.forEach(p=>{g.push({id:p.id,type:"text",name:p.text.substring(0,20)+(p.text.length>20?"...":""),timestamp:p.timestamp||0});}),r.flashcards?.forEach(p=>{g.push({id:p.id,type:"flashcard",name:`Flashcard (${p.images.length} images)`,timestamp:p.timestamp||0});}),r.photoFrames?.forEach(p=>{g.push({id:p.id,type:"photoFrame",name:"Photo Frame",timestamp:p.timestamp||0});}),r.multipleChoices?.forEach(p=>{g.push({id:p.id,type:"mcq",name:"Multiple Choice",timestamp:p.timestamp||0});}),r.trueFalses?.forEach(p=>{g.push({id:p.id,type:"trueFalse",name:"True/False",timestamp:p.timestamp||0});}),r.shortAnswers?.forEach(p=>{g.push({id:p.id,type:"shortAnswer",name:"Short Answer",timestamp:p.timestamp||0});}),r.LongAnswer?.forEach(p=>{g.push({id:p.id,type:"longAnswer",name:"Long Answer",timestamp:p.timestamp||0});}),r.fillInTheBlanks?.forEach(p=>{g.push({id:p.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:p.timestamp||0});}),r.lines?.forEach(p=>{p.id&&g.push({id:p.id,type:"line",name:"Drawn Line",timestamp:p.timestamp||0});}),g.sort((p,w)=>w.timestamp-p.timestamp)},[r]),[s,c]=useState(n),[i,d]=useState(false);useEffect(()=>{i||c(n);},[n]);let f=g=>{let p="h-5 w-5";switch(g){case "image":return jsx(Image$3,{className:p});case "video":return jsx(VideoCamera,{className:p});case "shape":return jsx(Shapes$1,{className:p});case "text":return jsx(TextT,{className:p});case "flashcard":return jsx(Cards$1,{className:p});case "photoFrame":return jsx(FrameCorners,{className:p});case "line":return jsx("span",{className:p,children:"\u270F\uFE0F"});default:return jsx(Question,{className:p})}},u=g=>{if(g===0)return;let p=s[g],w=s[g-1];a(_o({id:p.id,type:p.type,newTimestamp:w.timestamp+1}));},m=g=>{if(g===s.length-1)return;let p=s[g],w=s[g+1];a(_o({id:p.id,type:p.type,newTimestamp:w.timestamp-1}));},l=g=>{d(true),c(g);},h=()=>{d(false);let g=Date.now();s.forEach((p,w)=>{let x=g-w;a(_o({id:p.id,type:p.type,newTimestamp:x}));});};return jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9998 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-9999 w-96 -translate-x-1/2 -translate-y-1/2 rounded-lg border border-gray-200 bg-white shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 p-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Stack$1,{className:"h-5 w-5 text-gray-700",weight:"bold"}),jsx("h3",{className:"font-semibold text-gray-900",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"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto p-2",children:s.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:s,onReorder:l,className:"space-y-1",children:s.map((g,p)=>{let w=g.id===e;return jsxs(Reorder.Item,{value:g,onDragEnd:h,className:`flex cursor-grab items-center gap-2 rounded-lg p-2 transition-colors active:cursor-grabbing ${w?"border border-blue-200 bg-blue-50":"border border-transparent hover:bg-gray-50"}`,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-4 w-4",weight:"bold"})}),jsxs("div",{onClick:()=>t(g.id,g.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${w?"text-blue-600":"text-gray-600"}`,children:f(g.type)}),jsx("span",{className:`text-sm ${w?"font-medium text-blue-900":"text-gray-700"}`,children:g.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:x=>{x.stopPropagation(),u(p);},disabled:p===0,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move up (forward)",children:jsx(ArrowUp,{className:"h-4 w-4"})}),jsx("button",{onClick:x=>{x.stopPropagation(),m(p);},disabled:p===s.length-1,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move down (backward)",children:jsx(ArrowDown,{className:"h-4 w-4"})})]})]},g.id)})})}),jsx("div",{className:"border-t border-gray-200 p-3 text-xs text-gray-500",children:jsx("p",{children:"Drag to reorder \u2022 Top layers appear above bottom layers"})})]})]})};var au=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>{let s=useSelector(z=>z.toolbar.selectedTool),c=s==="pen"||s==="eraser",[i,d]=useState(new Set),[f,u]=useState(false),[m,l]=useState(null),h=useRef(null);useEffect(()=>{let z=h.current;if(z)return a.current.set(e.id,z),()=>{a.current.delete(e.id);}},[e.id]);let g=new Set(e.data.responseOptions.correctIndex),p=g.size>1,w=z=>{f||d(p?O=>{let X=new Set(O);return X.has(z)?X.delete(z):X.add(z),X}:new Set([z]));},x=()=>{i.size>0&&u(true);},v=()=>{u(false),d(new Set);},L=i.size===g.size&&Array.from(i).every(z=>g.has(z)),I=Array.from(i).filter(z=>g.has(z)),k=p&&I.length>0&&!L,S=()=>L?"\u2713 Correct! Great job! \u{1F389}":k?`\u26A0 Partially correct (${I.length}/${g.size})`:"\u2717 Try again!",b=()=>L?{bg:"#dcfce7",text:"#166534"}:k?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},A=55,V=8,R=24,H=60,q=60,P=p&&!f?25:0,W=e.data.feedbackMode==="practice"?48:0,E=12,oe=H+P+(f?q:0),N=e.data.responseOptions.options.length*(A+V),fe=oe+N+E+W+R;return jsxs(Group,{ref:h,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:r,onClick:z=>t(e.id),onTap:z=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:fe,width:e.width,onTransformEnd:z=>o(e.id,z),onContextMenu:z=>{z.cancelBubble=true,n(z.evt,e.id,"mcq");}}),jsx(Text,{x:R+8,y:R,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-R*2,listening:false}),p&&!f&&e.data.feedbackMode==="practice"?jsx(Text,{x:R,y:R+35,text:`Select ${g.size} answers (${i.size}/${g.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-R*2,listening:false}):null,f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:R+24,y:H+P,width:e.width-R*2-40,height:q-20,fill:b().bg,cornerRadius:8}),jsx(Text,{x:R,y:H+P,width:e.width-R*2,height:q-20,text:S(),fontSize:16,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((z,O)=>{let X=g.has(O),U=i.has(O),K=oe+O*(A+V),Q="#e5e7eb",te="#ffffff",J="#111827";return f&&X?(Q="#22c55e",te="#dcfce7",J="#1B9D2C"):f&&U&&!X?(Q="#ef4444",te="#fee2e2",J="#ef4444"):U&&(Q="#096B76",te="#ECFFF8",J="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:R+12,y:K+(A-20)/2,width:20,height:20,fill:U?"#096B76":"white",stroke:U?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:p?4:10,onClick:de=>{de.cancelBubble=true,w(O);},onTap:de=>{de.cancelBubble=true,w(O);}}),U&&jsx(Text,{x:R+12,y:K+(A-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:R+44,y:K,width:e.width-R*2-60,height:A,fill:te,stroke:Q,strokeWidth:2,cornerRadius:8,onClick:de=>{de.cancelBubble=true,w(O);},onTap:de=>{de.cancelBubble=true,w(O);}}),jsx(Text,{x:R+60,y:K,width:e.width-R*2-80,height:A,text:z,fontSize:16,fill:J,verticalAlign:"middle",listening:false})]},O)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:oe+e.data.responseOptions.options.length*(A+V)+12,children:[jsxs(Group,{onMouseDown:z=>{z.cancelBubble=true,l("check");},onMouseUp:z=>{z.cancelBubble=true,l(null),x();},onMouseLeave:z=>{z.cancelBubble=true,l(null);},onTouchStart:z=>{z.cancelBubble=true,l("check");},onTouchEnd:z=>{z.cancelBubble=true,l(null),x();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:R+14,width:(e.width-R*2-24)/(f?2:1),height:48,fill:i.size===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:R+14,width:(e.width-R*2-24)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-R*2)/2+8,onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),v();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),v();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:R,width:(e.width-R*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:R,width:(e.width-R*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});au.displayName="MultipleChoice";var ou=au;var Li=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:r})=>{let n=useDispatch(),s=useSelector(U=>U.toolbar.selectedTool),c=s==="pen"||s==="eraser",[i,d]=useState(false),[f,u]=useState(new Set),[m,l]=useState(false),[h,g]=useState(false),[p,w]=useState(0),x=340,v=100,L=window.innerWidth*.4,I=window.innerHeight*.5,k=x+20,S=v+60,b=L-40,A=I-300,V=useRef(null);useEffect(()=>{let U=V.current;if(U)return r.current.set(e.id,U),()=>{r.current.delete(e.id);}},[e.id]);let R=U=>{n(ia({id:e.id,x:U.target.x(),y:U.target.y()}));},H=U=>{let K=U.target,Q=K.x(),te=K.y(),J=window.innerWidth*.2,Y=Q+J>k&&Q<k+b&&te+50>S&&te<S+A;d(Y);},q=(U,K)=>{let Q=K.target,te=Q.x(),J=Q.y(),de=window.innerWidth*.2,Me=te+de>k&&te<k+b&&J+50>S&&J<S+A;u(Me?De=>new Set(De).add(U):De=>{let Se=new Set(De);return Se.delete(U),Se}),d(false);},P=()=>{l(true);},W=()=>{l(false),u(new Set),w(U=>U+1);},E=new Set(e.data.responseOptions.correctIndex),oe=f.size===E.size&&Array.from(f).every(U=>E.has(U)),N=Array.from(f).filter(U=>E.has(U)),fe=N.length>0&&!oe,z=()=>oe?"\u2713 Correct! Great job!":fe?`\u26A0 Partially correct (${N.length}/${E.size})`:"\u2717 Try again!",O=()=>oe?{bg:"#dcfce7",text:"#166534"}:fe?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},X=()=>m?oe?"#4CAF50":fe?"#f59e0b":"#ef4444":i?"#4CAF50":"#075560";return jsxs(Group,{ref:V,name:"mcq-element",width:L,height:I,draggable:!c,listening:!c,...c?{}:{onClick:U=>a(e.id),onTap:U=>a(e.id),onContextMenu:U=>{U.evt.preventDefault(),o(U.evt,e.id,"mcq");}},children:[jsxs(Group,{x,y:v,rotation:e.rotation,onDragEnd:R,children:[jsx(Rect,{fill:"white",stroke:i?"#4CAF50":"#e5e7eb",strokeWidth:i?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?I-100:I-50,width:L,shadowColor:i?"#4CAF50":"transparent",shadowBlur:i?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:80,width:b,height:A,fill:"#EBF6F7",stroke:X(),strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:A+18,width:b-5,height:60,fill:O().bg,cornerRadius:8}),jsx(Text,{x:20,y:A+20,width:b,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:O().text,align:"center",verticalAlign:"middle"})]}),f.size===0&&!m&&jsx(Text,{x:20,y:60,width:b,height:A-60,text:E.size>1?`Drop ${E.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:m?I-200:I-160,children:[jsxs(Group,{onMouseDown:()=>{g(true),P();},onMouseUp:()=>g(false),onMouseLeave:()=>g(false),onTouchStart:()=>{g(true),P();},onTouchEnd:()=>g(false),scaleX:h?.95:1,scaleY:h?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:b}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:b,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:W,onTouchStart:W,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:b}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:b,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((U,K)=>{let Q=K%2,te=Math.floor(K/2),J=window.innerWidth*.2,de=50,Y=10,Me=f.has(K),De=E.has(K),Se=m&&Me,Rt="transparent";return Se?Rt=De?"#4CAF50":"#ef4444":Me&&(Rt="#4CAF50"),jsxs(Group,{x:340+Q*(J+Y),y:v+I-80+te*(de+Y),draggable:!m,onDragMove:H,onDragEnd:Ja=>q(K,Ja),opacity:m&&!Me?.5:1,children:[jsx(Rect,{width:J-20,height:de,fill:"white",stroke:Rt,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:J-20,height:de,text:U,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${K}-${p}`)})]})};Li.displayName="MultipleChoiceDragAndDrop";var ru=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(ou,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:c=>r(c,s.id),onContextMenu:n},s.id):jsx(Li,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:n},s.id))});var nu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(E=>E.toolbar.selectedTool),c=s==="pen"||s==="eraser",[i,d]=useState(null),[f,u]=useState(false),[m,l]=useState(null),h=useRef(null);useEffect(()=>{let E=h.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id]);let g=()=>{i!==null&&u(true);},p=()=>{u(false),d(null);},w=e.data.responseOptions.correctAnswer,x=i===w,v=E=>{f||d(E);},L=()=>x?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",I=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},k=70,S=12,b=24,A=60,V=60,R=e.data.feedbackMode==="practice"?48:0,H=12,q=A+(f?V:0),P=2*(k+S),W=q+P+H+R+b;return jsxs(Group,{ref:h,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:E=>n(E,e.id),onClick:E=>t(e.id),onTap:E=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:W-20,width:e.width,onTransformEnd:E=>o(e.id,E),onContextMenu:E=>{E.cancelBubble=true,r(E.evt,e.id,"trueFalse");}}),jsx(Text,{x:b,y:b,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:b,y:A,width:e.width-b*2,height:V-10,fill:I().bg,cornerRadius:8}),jsx(Text,{x:b,y:A,width:e.width-b*2,height:V-10,text:L(),fontSize:16,fontStyle:"bold",fill:I().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((E,oe)=>{let N=w===E.value,fe=i===E.value,z=(e.width-b*3)/2,O=b+oe*(z+b),X=q,U=E.value===true,K=U?"#10b981":"#ef4444",Q="#ffffff",te="#ffffff",J="#e5e7eb";return f&&(N?(te=U?"#f0fdf4":"#fef2f2",J=U?"#86efac":"#fecaca"):fe&&!N&&(te="#fee2e2",J="#ef4444")),fe&&!f&&(J="#096B76",te="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:O,y:X,width:z,height:k+50,fill:te,stroke:J,strokeWidth:2,cornerRadius:12,onClick:de=>{de.cancelBubble=true,v(E.value);},onTap:de=>{de.cancelBubble=true,v(E.value);}}),jsx(Circle,{x:O+z/2,y:X+40,radius:28,fill:K,listening:false}),U?jsx(Text,{x:O+z/2-14,y:X+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:Q,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:O+z/2-14,y:X+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:Q,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:O,y:X+85,width:z,height:30,text:E.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},E.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:q+2*(k+S),children:[jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,l("check");},onMouseUp:E=>{E.cancelBubble=true,l(null),g();},onMouseLeave:E=>{E.cancelBubble=true,l(null);},onTouchStart:E=>{E.cancelBubble=true,l("check");},onTouchEnd:E=>{E.cancelBubble=true,l(null),g();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,fill:i===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-b*2)/2+8,onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),p();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),p();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});nu.displayName="TrueFalse";var su=nu;var Eg="#FFFFFF",Ci=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),r=useSelector(K=>K.toolbar.selectedTool),n=r==="pen"||r==="eraser",[s,c]=useState(false),[i,d]=useState(null),[f,u]=useState(false),[m,l]=useState(false),[h,g]=useState(0),[p,w]=useState(false),x=340,v=100,L=window.innerWidth*.4,I=window.innerHeight*.5,k=L-40,S=I-300,b=20,A=60,V=k,R=S,H=L*.2-40,q=50,P=useRef(null),W=K=>{a(la({id:e.id,x:K.target.x(),y:K.target.y()}));},E=K=>{let Q=K.target,te=Q.x(),J=Q.y(),de=Math.max(0,Math.min(te+H,b+V)-Math.max(te,b)),Y=Math.max(0,Math.min(J+q,A+R)-Math.max(J,A)),Me=de*Y,De=H*q;c(Me/De>=.5);},oe=(K,Q)=>{let te=Q.target,J=te.x(),de=te.y(),Y=Math.max(0,Math.min(J+H,b+V)-Math.max(J,b)),Me=Math.max(0,Math.min(de+q,A+R)-Math.max(de,A)),De=Y*Me,Se=H*q;if(De/Se>=.5)d(K);else return;c(false);},N=()=>{u(true);},fe=()=>{u(false),d(null),g(K=>K+1);},z=e.data.responseOptions.correctAnswer,O=i===z,X=()=>O?"\u2713 Correct! Great job!":"\u2717 Try again!",U=()=>O?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:P,name:"trueFalse-element",width:L,height:I,draggable:!n,listening:!n,...n?{}:{onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:v,rotation:e.rotation,onDragEnd:W,children:[jsx(Rect,{fill:"white",stroke:s?"#4CAF50":"#e5e7eb",strokeWidth:s?4:2,cornerRadius:12,height:f?I:e.data.feedbackMode==="practice"?I-50:I-100,width:L,shadowColor:s?"#4CAF50":"transparent",shadowBlur:s?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:60,width:k,height:S,fill:"transparent",stroke:s?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:k,height:60,fill:U().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:k,height:60,text:X(),fontSize:18,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle"})]}),i===null&&!f&&jsx(Text,{x:20,y:60,width:k,height:S-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:I-100,children:[jsxs(Group,{onMouseDown:()=>{i!==null&&(l(true),N());},onMouseUp:()=>l(false),onMouseLeave:()=>l(false),onTouchStart:()=>{i!==null&&(l(true),N());},onTouchEnd:()=>l(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:i===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:fe,onTouchStart:fe,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((K,Q)=>{let te=window.innerWidth*.2,J=50,de=10,Y=i===K.value,Me=z===K.value,De=f&&Y,Se="transparent";return De?Se=Me?"#4CAF50":"#ef4444":Y&&(Se="#4CAF50"),jsxs(Group,{x:16+Q*(te+de),y:v+I-300,draggable:!f,onDragMove:E,onDragEnd:Rt=>oe(K.value,Rt),opacity:f&&!Y?.5:1,children:[jsx(Rect,{width:te-40,height:J,fill:"#075560",stroke:Se,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:te-40,height:J,text:K.label,fontSize:18,fontStyle:"bold",fill:Eg,align:"center",verticalAlign:"middle",listening:false})]},`${K.value}-${h}`)})]})})};Ci.displayName="TrueFalseDragAndDrop";var iu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(su,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r},s.id):jsx(Ci,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n},s.id))});var fa=new WeakMap,bo=new WeakMap,dr={current:[]},Mi=false,lr=0,ir=new Set,Pn=new Map;function lu(e){let o=Array.from(e).sort((t,a)=>t instanceof Vt&&t.options.deps.includes(a)?1:a instanceof Vt&&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=bo.get(t);if(a)for(let r of a){let n=fa.get(r);n&&lu(n);}}}function Og(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Ng(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Rn(e){if(lr>0&&!Pn.has(e)&&Pn.set(e,e.prevState),ir.add(e),!(lr>0)&&!Mi)try{for(Mi=!0;ir.size>0;){let o=Array.from(ir);ir.clear();for(let t of o){let a=Pn.get(t)??t.prevState;t.prevState=a,Og(t);}for(let t of o){let a=fa.get(t);a&&(dr.current.push(t),lu(a));}for(let t of o){let a=fa.get(t);if(a)for(let r of a)Ng(r);}}}finally{Mi=false,dr.current=[],Pn.clear();}}function ut(e){lr++;try{e();}finally{if(lr--,lr===0){let o=ir.values().next().value;o&&Rn(o);}}}function du(e){return typeof e=="function"}var _t=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,n;this.listeners.add(a);let s=(n=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:n.call(r,a,this);return ()=>{this.listeners.delete(a),s?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,r;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):du(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),Rn(this);}};var Vt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),r=new Array(t);for(let n=0;n<t;n++){let s=this.options.deps[n];a[n]=s.prevState,r[n]=s.state;}return this.lastSeenDepValues=r,{prevDepVals:a,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let n of this.options.deps)n instanceof e&&n.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let n=0;n<r.length;n++)if(r[n]!==a[n]){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,r;this.listeners.add(t);let n=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),n?.();}},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 _t){let a=fa.get(t);a||(a=new Set,fa.set(t,a)),a.add(this);let r=bo.get(this);r||(r=new Set,bo.set(this,r)),r.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 _t){let a=fa.get(t);a&&a.delete(this);let r=bo.get(this);r&&r.delete(t);}}};function Vg(e){return typeof e=="function"}function Ti(e,...o){return Vg(e)?e(...o):e}function uu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ma,tt,Je,ur,pa,Oa,Jt,vo,cr,Dn,fr,yo,Na=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Ae(this,ma,true);Ae(this,tt);Ae(this,Je);Ae(this,ur);Ae(this,pa);Ae(this,Oa);Ae(this,Jt);Ae(this,vo);Ae(this,cr,0);Ae(this,Dn,5);Ae(this,fr,()=>{this.debugLog("Connected to event bus"),Ce(this,Oa,true),this.debugLog("Emitting queued events",_(this,pa)),_(this,pa).forEach(o=>this.emitEventToBus(o)),Ce(this,pa,[]),this.stopConnectLoop(),_(this,Je).call(this).removeEventListener("tanstack-connect-success",_(this,fr));});Ae(this,yo,()=>{if(_(this,Je).call(this).addEventListener("tanstack-connect-success",_(this,fr)),_(this,cr)<_(this,Dn)){Wl(this,cr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}_(this,Je).call(this).removeEventListener("tanstack-connect",_(this,yo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Ce(this,tt,o),Ce(this,ma,a),Ce(this,Je,this.getGlobalTarget),Ce(this,ur,t),this.debugLog(" Initializing event subscription for plugin",_(this,tt)),Ce(this,pa,[]),Ce(this,Oa,false),Ce(this,Jt,null),Ce(this,vo,r);}startConnectLoop(){_(this,Jt)!==null||_(this,Oa)||(this.debugLog(`Starting connect loop (every ${_(this,vo)}ms)`),Ce(this,Jt,setInterval(_(this,yo),_(this,vo))));}stopConnectLoop(){_(this,Jt)!==null&&(clearInterval(_(this,Jt)),Ce(this,Jt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){_(this,ur)&&console.log(`\u{1F334} [tanstack-devtools:${_(this,tt)}-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,tt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});_(this,Je).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{_(this,Je).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,Oa)){this.debugLog("Bus not available, will be pushed as soon as connected"),_(this,pa).push({type:`${_(this,tt)}:${o}`,payload:t,pluginId:_(this,tt)}),typeof CustomEvent<"u"&&(_(this,yo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${_(this,tt)}:${o}`,payload:t,pluginId:_(this,tt)})}on(o,t){let a=`${_(this,tt)}:${o}`;if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=n=>{this.debugLog("Received event from bus",n.detail),t(n.detail);};return _(this,Je).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{_(this,Je).call(this).removeEventListener(a,r);}}onAll(o){if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).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 r=a.detail;_(this,tt)&&r.pluginId!==_(this,tt)||o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).call(this).removeEventListener("tanstack-devtools-global",t)}};ma=new WeakMap,tt=new WeakMap,Je=new WeakMap,ur=new WeakMap,pa=new WeakMap,Oa=new WeakMap,Jt=new WeakMap,vo=new WeakMap,cr=new WeakMap,Dn=new WeakMap,fr=new WeakMap,yo=new WeakMap;var Ai=class extends Na{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},cu=(e,o)=>{Pi.emit(e,o);},Pi=new Ai;function fu(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var qg={enabled:true,leading:true,trailing:true,wait:0},ha,ct,Va,qa,Ha,wo,En=class{constructor(o,t){Ae(this,ha);Ae(this,ct);Ae(this,Va);Ae(this,qa);Ae(this,Ha);Ae(this,wo);this.fn=o,this.store=new _t(fu()),this.setOptions=a=>{this.options={...this.options,...a},_(this,Va).call(this)||this.cancel();},Ce(this,ct,a=>{this.store.setState(r=>{let n={...r,...a},{isPending:s}=n;return {...n,status:_(this,Va).call(this)?s?"pending":"idle":"disabled"}}),cu("Throttler",this);}),Ce(this,Va,()=>!!Ti(this.options.enabled,this)),Ce(this,qa,()=>Ti(this.options.wait,this)),this.maybeExecute=(...a)=>{_(this,ct).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),n=r-this.store.state.lastExecutionTime,s=_(this,qa).call(this);if(this.options.leading&&n>=s)_(this,Ha).call(this,...a);else if(_(this,ct).call(this,{lastArgs:a}),!_(this,ha)&&this.options.trailing){let c=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,i=s-c;_(this,ct).call(this,{isPending:true}),Ce(this,ha,setTimeout(()=>{let{lastArgs:d}=this.store.state;d!==void 0&&_(this,Ha).call(this,...d);},i));}},Ce(this,Ha,(...a)=>{if(!_(this,Va).call(this))return;this.fn(...a);let r=Date.now(),n=r+_(this,qa).call(this);_(this,wo).call(this),_(this,ct).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:n,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||_(this,ct).call(this,{nextExecutionTime:void 0});},_(this,qa).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&_(this,Ha).call(this,...this.store.state.lastArgs);},Ce(this,wo,()=>{_(this,ha)&&(clearTimeout(_(this,ha)),Ce(this,ha,void 0));}),this.cancel=()=>{_(this,wo).call(this),_(this,ct).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{_(this,ct).call(this,fu());},this.key=uu(t.key),this.options={...qg,...t},_(this,ct).call(this,this.options.initialState??{}),Pi.on("d-Throttler",a=>{a.payload.key===this.key&&(_(this,ct).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};ha=new WeakMap,ct=new WeakMap,Va=new WeakMap,qa=new WeakMap,Ha=new WeakMap,wo=new WeakMap;function Ri(e,o){return new En(e,o).maybeExecute}function ga(e,o){return typeof e=="function"?e(o):e}function xa(e,o){return Nn(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function Lo(e,o,t){let a=Nn(o);function r(n){if(!a.length)return ga(t,n);let s=a.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(n))return typeof n=="object"?(n===null&&(n={}),{...n,[s]:r(n[s])}):{[s]:r()};if(Array.isArray(n)&&typeof s=="number"){let c=n.slice(0,s);return [...c.length?c:new Array(s),r(n[s]),...n.slice(s+1)]}return [...new Array(s),r()]}return r(e)}function Ei(e,o){let t=Nn(o);function a(r){if(!r)return;if(t.length===1){let s=t[0];if(Array.isArray(r)&&typeof s=="number")return r.filter((d,f)=>f!==s);let{[s]:c,...i}=r;return i}let n=t.shift();if(typeof n=="string"&&typeof r=="object")return {...r,[n]:a(r[n])};if(typeof n=="number"&&Array.isArray(r)){if(n>=r.length)return r;let s=r.slice(0,n);return [...s.length?s:new Array(n),a(r[n]),...r.slice(n+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var Hg=/^(\d+)$/gm,Ug=/\.(\d+)(?=\.)/gm,Wg=/^(\d+)\./gm,zg=/\.(\d+$)/gm,Gg=/\.{2,}/gm,Di="__int__",Fn=`${Di}$1`;function Nn(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(Hg,Fn).replace(Ug,`.${Fn}.`).replace(Wg,`${Fn}.`).replace(zg,`.${Fn}`).replace(Gg,".").split(".").map(o=>{if(o.startsWith(Di)){let t=o.substring(Di.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Fi(e){return !(Array.isArray(e)&&e.length===0)}function Io(e,o){let t=a=>a.validators.filter(Boolean).map(r=>({cause:r.cause,validate:r.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function So(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:n}=o.validators||{},s=t??0,c=i=>i.validators.filter(Boolean).map(d=>{let f=d?.cause||e,u=s;switch(f){case "change":u=r??s;break;case "blur":u=a??s;break;case "dynamic":u=n??s;break;case "submit":u=0;break}return e==="submit"&&(u=0),{cause:f,validate:d.fn,debounceMs:u}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:c})}var mr=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[r,n]of e)if(!o.has(r)||!Object.is(n,o.get(r)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let r of e)if(!o.has(r))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let r of t)if(!a.includes(r)||!ba(e[r],o[r]))return false;return true}var Vn=({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},qn=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Ge(e,o){return e==null?o:{...e,...o}}var Ua=256,On=[],Bn;for(;Ua--;)On[Ua]=(Ua+256).toString(16).substring(1);function Bi(){let e=0,o,t="";if(!Bn||Ua+16>256){for(Bn=new Array(256),e=256;e--;)Bn[e]=256*Math.random()|0;e=0,Ua=0;}for(;e<16;e++)o=Bn[Ua+e],e===6?t+=On[o&15|64]:e===8?t+=On[o&63|128]:t+=On[o],e&1&&e>1&&e<11&&(t+="-");return Ua++,t}var va=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"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},n={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,r,n,s],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,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 Kg(e,o){let t=new Map;for(let a of e){let r=a.path??[],n=o,s="";for(let c=0;c<r.length;c++){let i=r[c];if(i===void 0)continue;let d=typeof i=="object"?i.key:i,f=Number(d);Array.isArray(n)&&!Number.isNaN(f)?s+=`[${f}]`:s+=(c>0?".":"")+String(d),typeof n=="object"&&n!==null?n=n[d]:n=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var mu=(e,o)=>{let t=Kg(e,o);return {form:t,fields:t}},ya={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:mu(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:mu(a.issues,e)}},Hn=e=>!!e&&"~standard"in e;var Co={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function pr(e){function o(u,m,l,h){let g=a(u,m,l,h);({insert:()=>c(g,u,m),remove:()=>i(g),swap:()=>h!==void 0&&f(g,u,m,h),move:()=>h!==void 0&&d(g,u,m,h)})[l]();}function t(u,m){return `${u}[${m}]`}function a(u,m,l,h){let g=[t(u,m)];if(l==="swap")g.push(t(u,h));else if(l==="move"){let[p,w]=[Math.min(m,h),Math.max(m,h)];for(let x=p;x<=w;x++)g.push(t(u,x));}else {let p=e.getFieldValue(u),w=Array.isArray(p)?p.length:0;for(let x=m+1;x<w;x++)g.push(t(u,x));}return Object.keys(e.fieldInfo).filter(p=>g.some(w=>p.startsWith(w)))}function r(u,m){return u.replace(/\[(\d+)\]/,(l,h)=>{let g=parseInt(h,10);return `[${m==="up"?g+1:Math.max(0,g-1)}]`})}function n(u,m){(m==="up"?u:[...u].reverse()).forEach(h=>{let g=r(h.toString(),m),p=e.getFieldMeta(g);p?e.setFieldMeta(h,p):e.setFieldMeta(h,s());});}let s=()=>Co,c=(u,m,l)=>{n(u,"down"),u.forEach(h=>{h.toString().startsWith(t(m,l))&&e.setFieldMeta(h,s());});},i=u=>{n(u,"up");},d=(u,m,l,h)=>{let g=new Map(Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,l))).map(p=>[p,e.getFieldMeta(p)]));n(u,l<h?"up":"down"),Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,h))).forEach(p=>{let w=p.replace(t(m,h),t(m,l)),x=g.get(w);x&&e.setFieldMeta(p,x);});},f=(u,m,l,h)=>{u.forEach(g=>{if(!g.toString().startsWith(t(m,l)))return;let p=g.toString().replace(t(m,l),t(m,h)),[w,x]=[e.getFieldMeta(g),e.getFieldMeta(p)];w&&e.setFieldMeta(p,w),x&&e.setFieldMeta(g,x);});};return {handleArrayFieldMetaShift:o}}var Oi=class extends Na{constructor(){super({pluginId:"form-devtools"});}},ft=new Oi;function Ni(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 gr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),n=()=>{a(),r(),ft.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return ft.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),s&&this.validateSync("mount"),n},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let n=!!a.transform?.deps?.some((i,d)=>i!==this.prevTransformArray[d]),s=a.defaultValues&&!ba(a.defaultValues,r.defaultValues)&&!this.state.isTouched,c=!ba(a.defaultState,r.defaultState)&&!this.state.isTouched;!s&&!c&&!n||(ut(()=>{this.baseStore.setState(()=>Ni(Object.assign({},this.state,c?a.defaultState:{},s?{values:a.defaultValues}:{},n?{_force_re_eval:!this.state._force_re_eval}:{})));}),ft.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:n}=this.state,s=this.resetFieldMeta(n);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Ni({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let r=[];return ut(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;let c=s.instance;r.push(Promise.resolve().then(()=>c.validate(a,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,n)=>{let s=this.getFieldValue(a),c=Array.isArray(s)?Math.max(s.length-1,0):null,i=[`${a}[${r}]`];for(let m=r+1;m<=(c??0);m++)i.push(`${a}[${m}]`);let d=Object.keys(this.fieldInfo).filter(m=>i.some(l=>m.startsWith(l))),f=[];return ut(()=>{d.forEach(m=>{f.push(Promise.resolve().then(()=>this.validateField(m,n)));});}),(await Promise.all(f)).flat()},this.validateField=(a,r)=>{let n=this.fieldInfo[a]?.instance;return n?(n.state.meta.isTouched||n.setMeta(s=>({...s,isTouched:true})),n.validate(r)):[]},this.validateSync=a=>{let r=Io(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va}),n=false,s={};return ut(()=>{for(let d of r){if(!d.validate)continue;let f=this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:u,fieldErrors:m}=Un(f),l=hr(d.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let g=this.getFieldMeta(h);if(!g)continue;let{errorMap:p,errorSourceMap:w}=g,x=m?.[h],{newErrorValue:v,newSource:L}=Vn({newFormValidatorError:x,isPreviousErrorFromFormValidator:w?.[l]==="form",previousErrorValue:p?.[l]});L==="form"&&(s[h]={...s[h],[l]:x}),p?.[l]!==v&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[l]:v},errorSourceMap:{...I.errorSourceMap,[l]:L}}));}this.state.errorMap?.[l]!==u&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[l]:u}})),(u||m)&&(n=!0);}let c=hr("submit");this.state.errorMap?.[c]&&a!=="submit"&&!n&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[c]:void 0}}));let i=hr("server");this.state.errorMap?.[i]&&a!=="server"&&!n&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[i]:void 0}}));}),{hasErrored:n,fieldsErrorMap:s}},this.validateAsync=async a=>{let r=So(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va});this.state.isFormValidating||this.baseStore.setState(d=>({...d,isFormValidating:true}));let n=[],s;for(let d of r){if(!d.validate)continue;let f=hr(d.cause);this.state.validationMetaMap[f]?.lastAbortController.abort();let m=new AbortController;this.state.validationMetaMap[f]={lastAbortController:m},n.push(new Promise(async l=>{let h;try{h=await new Promise((x,v)=>{setTimeout(async()=>{if(m.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:m.signal},type:"validateAsync"}));}catch(L){v(L);}},d.debounceMs);});}catch(x){h=x;}let{formError:g,fieldErrors:p}=Un(h);p&&(s=s?{...s,...p}:p);let w=hr(d.cause);for(let x of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[x]===void 0)continue;let v=this.getFieldMeta(x);if(!v)continue;let{errorMap:L,errorSourceMap:I}=v,k=s?.[x],{newErrorValue:S,newSource:b}=Vn({newFormValidatorError:k,isPreviousErrorFromFormValidator:I?.[w]==="form",previousErrorValue:L?.[w]});L?.[w]!==S&&this.setFieldMeta(x,A=>({...A,errorMap:{...A.errorMap,[w]:S},errorSourceMap:{...A.errorSourceMap,[w]:b}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.errorMap,[w]:g}})),l(s?{fieldErrors:s,errorMapKey:w}:void 0);}));}let c=[],i={};if(n.length){c=await Promise.all(n);for(let d of c)if(d?.fieldErrors){let{errorMapKey:f}=d;for(let[u,m]of Object.entries(d.fieldErrors)){let h={...i[u]||{},[f]:m};i[u]=h;}}}return this.baseStore.setState(d=>({...d,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:n}=this.validateSync(a);return r&&!this.options.asyncAlways?n:this.validateAsync(a)},this.getFieldValue=a=>xa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var r;return (r=this.fieldInfo)[a]||(r[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,r)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:ga(r,n.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,n)=>{let s=n;return r[s]=Co,r},{}),this.setFieldValue=(a,r,n)=>{let s=n?.dontUpdateMeta??false,c=n?.dontRunListeners??false,i=n?.dontValidate??false;ut(()=>{s||this.setFieldMeta(a,d=>({...d,isTouched:!0,isDirty:!0,errorMap:{...d?.errorMap,onMount:void 0}})),this.baseStore.setState(d=>({...d,values:Lo(d.values,a,r)}));}),c||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let n=[...Object.keys(this.fieldInfo).filter(s=>{let c=a.toString();return s!==c&&s.startsWith(c)}),a];this.baseStore.setState(s=>{let c={...s};return n.forEach(i=>{c.values=Ei(c.values,i),delete this.fieldInfo[i],delete c.fieldMetaBase[i];}),c});},this.pushFieldValue=(a,r,n)=>{this.setFieldValue(a,s=>[...Array.isArray(s)?s:[],r],n);},this.insertFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,i=>[...i.slice(0,r),n,...i.slice(r)],Ge(s,{dontValidate:true}));let c=s?.dontValidate??false;c||await this.validateField(a,"change"),pr(this).handleArrayFieldMetaShift(a,r,"insert"),c||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,i=>i.map((d,f)=>f===r?n:d),Ge(s,{dontValidate:true})),(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,n)=>{let s=this.getFieldValue(a),c=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,d=>d.filter((f,u)=>u!==r),Ge(n,{dontValidate:true})),pr(this).handleArrayFieldMetaShift(a,r,"remove"),c!==null){let d=`${a}[${c}]`;this.deleteField(d);}(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,n,s)=>{this.setFieldValue(a,i=>{let d=i[r],f=i[n];return Lo(Lo(i,`${r}`,f),`${n}`,d)},Ge(s,{dontValidate:true})),pr(this).handleArrayFieldMetaShift(a,r,"swap",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.moveFieldValues=(a,r,n,s)=>{this.setFieldValue(a,i=>{let d=[...i];return d.splice(n,0,d.splice(r,1)[0]),d},Ge(s,{dontValidate:true})),pr(this).handleArrayFieldMetaShift(a,r,"move",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.clearFieldValues=(a,r)=>{let n=this.getFieldValue(a),s=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,[],Ge(r,{dontValidate:true})),s!==null)for(let i=0;i<=s;i++){let d=`${a}[${i}]`;this.deleteField(d);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Co},values:this.options.defaultValues?Lo(r.values,a,xa(this.options.defaultValues,a)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[r,n])=>(Object.keys(n).length&&n.errors.length&&(a[r]={errors:n.errors,errorMap:n.errorMap}),a),{})}),this.parseValuesWithSchema=a=>ya.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>ya.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Bi(),this._devtoolsSubmissionOverride=false,this.baseStore=new _t(Ni({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Vt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,c=a?.[0],i=r[0],d=0,f={};for(let u of Object.keys(i.fieldMetaBase)){let m=i.fieldMetaBase[u],l=c?.fieldMetaBase[u],h=s?.[u],g=xa(i.values,u),p=h?.errors;if(!l||m.errorMap!==l.errorMap){p=Object.values(m.errorMap??{}).filter(I=>I!==void 0);let L=this.getFieldInfo(u)?.instance;L&&!L.options.disableErrorFlat&&(p=p?.flat(1));}let w=!Fi(p??[]),x=!m.isDirty,v=ba(g,xa(this.options.defaultValues,u))||ba(g,this.getFieldInfo(u)?.instance?.options.defaultValue);if(h&&h.isPristine===x&&h.isValid===w&&h.isDefaultValue===v&&h.errors===p&&m===l){f[u]=h,d++;continue}f[u]={...m,errors:p,isPristine:x,isValid:w,isDefaultValue:v};}return Object.keys(i.fieldMetaBase).length&&s&&d===Object.keys(i.fieldMetaBase).length?s:f}}),this.store=new Vt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,c=a?.[0],i=r[0],d=r[1],f=Object.values(d).filter(Boolean),u=f.some(P=>P.isValidating),m=f.every(P=>P.isValid),l=f.some(P=>P.isTouched),h=f.some(P=>P.isBlurred),g=f.every(P=>P.isDefaultValue),p=l&&i.errorMap?.onMount,w=f.some(P=>P.isDirty),x=!w,v=!!(i.errorMap?.onMount||f.some(P=>P?.errorMap?.onMount)),L=!!u,I=s?.errors??[];(!c||i.errorMap!==c.errorMap)&&(I=Object.values(i.errorMap).reduce((P,W)=>W===void 0?P:W&&mr(W)?(P.push(W.form),P):(P.push(W),P),[]));let k=I.length===0,S=m&&k,b=this.options.canSubmitWhenInvalid??false,A=i.submissionAttempts===0&&!l&&!v||!L&&!i.isSubmitting&&S||b,V=i.errorMap;if(p&&(I=I.filter(P=>P!==i.errorMap.onMount),V=Object.assign(V,{onMount:void 0})),s&&c&&s.errorMap===V&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===I&&s.isFieldsValidating===u&&s.isFieldsValid===m&&s.isFormValid===k&&s.isValid===S&&s.canSubmit===A&&s.isTouched===l&&s.isBlurred===h&&s.isPristine===x&&s.isDefaultValue===g&&s.isDirty===w&&ba(c,i))return s;let R={...i,errorMap:V,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:u,isFieldsValid:m,isFormValid:k,isValid:S,canSubmit:A,isTouched:l,isBlurred:h,isPristine:x,isDefaultValue:g,isDirty:w},H=this.options.transform?.deps??[];if(H.length!==this.prevTransformArray.length||H.some((P,W)=>P!==this.prevTransformArray[W])){let P=Object.assign({},this,{state:R});this.options.transform?.fn(P),R=P.state,this.prevTransformArray=H;}return R}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Ri(a=>ft.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),ft.on("request-form-state",a=>{a.payload.id===this._formId&&ft.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),ft.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),ft.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 Hn(o.validate)?ya[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(r=>({...r,isSubmitted:false,submissionAttempts:r.submissionAttempts+1,isSubmitSuccessful:false})),ut(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(n=>({...n,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(r=>({...r,isSubmitting:true}));let a=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(r=>r.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}ut(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance?.options.listeners?.onSubmit?.({value:r.instance.state.value,fieldApi:r.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),ut(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(n=>({...n,isSubmitSuccessful:false})),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){ut(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(mr(a)){let{formError:n,fieldErrors:s}=Un(a);for(let c of Object.keys(this.fieldInfo))this.getFieldMeta(c)&&this.setFieldMeta(c,d=>({...d,errorMap:{...d.errorMap,[r]:s?.[c]},errorSourceMap:{...d.errorSourceMap,[r]:"form"}}));this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[r]:n}}));}else this.baseStore.setState(n=>({...n,errorMap:{...n.errorMap,[r]:a}}));});});}};function Un(e){if(e){if(mr(e)){let o=Un(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 xr=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:r}=this.options.validators||{};if(r){let n=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});n&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:n},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 r=xa(t.form.options.defaultValues,t.name),n=t.defaultValue??r;a?this.setValue(s=>s||n,{dontUpdateMeta:true}):n!==void 0&&this.setValue(n,{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,Ge(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,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Ge(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),r=[];for(let n of a){if(!n.instance)continue;let{onChangeListenTo:s,onBlurListenTo:c}=n.instance.options.validators||{};t==="change"&&s?.includes(this.name)&&r.push(n.instance),t==="blur"&&c?.includes(this.name)&&r.push(n.instance);}return r},this.validateSync=(t,a)=>{let r=Io(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),s=this.getLinkedFields(t).reduce((d,f)=>{let u=Io(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||va});return u.forEach(m=>{m.field=f;}),d.concat(u)},[]),c=false;ut(()=>{let d=(f,u)=>{let m=Wn(u.cause),l=u.validate?pu(f.runValidator({validate:u.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,h=a[m],{newErrorValue:g,newSource:p}=qn({formLevelError:h,fieldLevelError:l});f.state.meta.errorMap?.[m]!==g&&f.setMeta(w=>({...w,errorMap:{...w.errorMap,[m]:g},errorSourceMap:{...w.errorSourceMap,[m]:p}})),g&&(c=!0);};for(let f of r)d(this,f);for(let f of s)f.validate&&d(f.field,f);});let i=Wn("submit");return this.state.meta.errorMap?.[i]&&t!=="submit"&&!c&&this.setMeta(d=>({...d,errorMap:{...d.errorMap,[i]:void 0},errorSourceMap:{...d.errorSourceMap,[i]:void 0}})),{hasErrored:c}},this.validateAsync=async(t,a)=>{let r=So(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),n=await a,s=this.getLinkedFields(t),c=s.reduce((m,l)=>{let h=So(t,{...l.options,form:l.form,validationLogic:l.form.options.validationLogic||va});return h.forEach(g=>{g.field=l;}),m.concat(h)},[]);this.state.meta.isValidating||this.setMeta(m=>({...m,isValidating:true}));for(let m of s)m.setMeta(l=>({...l,isValidating:true}));let i=[],d=[],f=(m,l,h)=>{let g=Wn(l.cause);m.getInfo().validationMetaMap[g]?.lastAbortController.abort();let w=new AbortController;this.getInfo().validationMetaMap[g]={lastAbortController:w},h.push(new Promise(async x=>{let v;try{v=await new Promise((b,A)=>{this.timeoutIds.validations[l.cause]&&clearTimeout(this.timeoutIds.validations[l.cause]),this.timeoutIds.validations[l.cause]=setTimeout(async()=>{if(w.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:l.validate,value:{value:m.store.state.value,fieldApi:m,signal:w.signal,validationSource:"field"},type:"validateAsync"}));}catch(V){A(V);}},l.debounceMs);});}catch(b){v=b;}if(w.signal.aborted)return x(void 0);let L=pu(v),I=n[this.name]?.[g],{newErrorValue:k,newSource:S}=qn({formLevelError:I,fieldLevelError:L});m.setMeta(b=>({...b,errorMap:{...b?.errorMap,[g]:k},errorSourceMap:{...b.errorSourceMap,[g]:S}})),x(k);}));};for(let m of r)m.validate&&f(this,m,i);for(let m of c)m.validate&&f(m.field,m,d);let u=[];(i.length||d.length)&&(u=await Promise.all(i),await Promise.all(d)),this.setMeta(m=>({...m,isValidating:false}));for(let m of s)m.setMeta(l=>({...l,isValidating:false}));return u.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:n}=this.validateSync(t,r[this.name]??{});if(n&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Wn(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=>ya.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>ya.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Vt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Co,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Hn(o.validate)?ya[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 pu(e){if(e)return e}function Wn(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 zn(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,jg)}function jg(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,r]of e)if(!o.has(a)||!Object.is(r,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=hu(e);if(t.length!==hu(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 hu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var ko=typeof window<"u"?useLayoutEffect:useEffect;function ex(e){let[o]=useState(()=>{let a=new xr({...e,form:e.form,name:e.name});return a.Field=Vi,a});return ko(o.mount,[o]),ko(()=>{o.update(e);}),zn(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Vi=(({children:e,...o})=>{let t=ex(o),a=useMemo(()=>ga(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function ox({form:e,selector:o,children:t}){let a=zn(e.store,o);return ga(t,a)}function qi(e){let o=useId(),[t]=useState(()=>{let a=new gr({...e,formId:o}),r=a;return r.Field=function(s){return jsx(Vi,{...s,form:a})},r.Subscribe=function(s){return jsx(ox,{form:a,selector:s.selector,children:s.children})},r});return ko(t.mount,[]),ko(()=>{t.update(e);}),t}function Hi({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 mx=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[s,c]=useState(n),i=qi({defaultValues:{questionType:n,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:u})=>{if(u.questionType==="true-false"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctAnswer:u.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?la(m):Hs(m));}else if(u.questionType==="multiple-choice"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctIndex:u.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?ia(m):qs(m));}else if(u.questionType==="short-answer"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.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?Wo(m):Us(m));}else if(u.questionType==="fill-in-the-blank"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.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?Go(m):zs(m));}else if(u.questionType==="long-answer"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctLongAnswer:u.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?zo(m):Ws(m));}o(da(false));}}),d=()=>{o(da(false));},f=jsx("div",{className:"fixed inset-0 z-106 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-6 shadow-lg",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-240px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-100px)] w-full flex-col gap-1 rounded-lg bg-white p-4",onSubmit:u=>{u.preventDefault(),u.stopPropagation(),i.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-4",children:[jsxs("div",{className:"flex flex-col gap-1",children:[jsx("h2",{className:"text-2xl font-bold text-[#000000CC]",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"font-semibold text-[#00000099]",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-8 w-8 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600",onClick:()=>{d();},children:jsx("span",{className:"text-xl text-white",children:"\u2715"})})]}),jsxs("div",{className:"mb-4 flex justify-between gap-6",children:[jsx(i.Field,{name:"questionType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:m=>{u.handleChange(m.target.value),c(m.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-4 py-3 pr-10 font-semibold text-[#000000CC] ${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-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",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-xs text-gray-500 italic",children:"Question type cannot be changed when editing"}),jsx(Hi,{field:u})]})}),s&&!["short-answer","fill-in-the-blank","long-answer"].includes(s)&&jsx(i.Field,{name:"responseType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:m=>u.handleChange(m.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-4 py-3 pr-10 font-semibold text-[#000000CC]",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-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",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(Hi,{field:u})]})})]}),jsx(i.Field,{name:"feedbackMode",children:u=>jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-2 rounded-lg bg-gray-100 p-1.5 ${s==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:s==="long-answer",onClick:()=>u.handleChange("practice"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${u.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",size:16}),"Practice Mode"]}),jsxs("button",{type:"button",disabled:s==="long-answer",onClick:()=>u.handleChange("test"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${u.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",size:16}),"Assessment Mode"]})]}),s==="long-answer"&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Long answer questions are only available in Assessment Mode"}),jsx(Hi,{field:u})]})}),jsx(i.Field,{name:"question",validators:{onChange:({value:u})=>u?void 0:"A question is required"},children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",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-4 py-3 text-gray-900",value:u.state.value,onChange:m=>u.handleChange(m.target.value),onBlur:u.handleBlur,placeholder:"Enter Your Question"})}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),s==="true-false"&&jsx(i.Field,{name:"responseOptions.correctAnswer",children:u=>{let m=u.state.value;return jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{className:"text-base font-semibold text-[#00000066] uppercase",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-4",children:[jsxs("button",{type:"button",onClick:()=>u.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${m===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"True"}),m===true&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>u.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${m===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"False"}),m===false&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]})]}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Select the correct answer for this true/false question"})]})}}),s==="multiple-choice"&&jsx(i.Field,{name:"responseOptions",validators:{onChange:({value:u})=>{if(u.options.filter(l=>!l.trim()).length>0)return "All options must have text";if(!u.correctIndex||u.correctIndex.length===0)return "Please select at least one correct answer"}},children:u=>{let m=(p,w)=>{let x=[...u.state.value.options];x[p]=w,u.handleChange({...u.state.value,options:x});},l=()=>{if(u.state.value.options.length>=6){alert("Maximum 6 options allowed");return}u.handleChange({...u.state.value,options:[...u.state.value.options,""]});},h=p=>{if(u.state.value.options.length<=2){alert("Minimum 2 options required");return}let w=u.state.value.options.filter((v,L)=>L!==p),x=u.state.value.correctIndex?.filter(v=>v!==p).map(v=>v>p?v-1:v);u.handleChange({...u.state.value,options:w,correctIndex:x});},g=p=>{let w=u.state.value.correctIndex||[];if(w.includes(p))u.handleChange({...u.state.value,correctIndex:w.filter(v=>v!==p)});else {if(w.length>=6){alert("Maximum 6 correct answers allowed");return}u.handleChange({...u.state.value,correctIndex:[...w,p]});}};return jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:u.name,className:"mb-2 text-base font-semibold text-gray-900",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-4 flex flex-col gap-3",children:u.state.value.options.map((p,w)=>{let x=!p.trim(),v=u.state.value.correctIndex?.includes(w),L=u.state.meta.isTouched&&x;return jsxs("div",{className:"flex w-full items-center gap-3 px-1",children:[jsx("button",{type:"button",onClick:()=>g(w),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${v?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:v&&jsx("svg",{className:"h-3 w-3 text-white",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-4 py-3 transition-colors ${L?"border-red-500 bg-red-50":v?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${w+1}`,value:p,onChange:I=>m(w,I.target.value),onBlur:u.handleBlur,className:"w-full flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"})}),u.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>h(w),className:"text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",size:24})})]},w)})}),jsx("button",{type:"button",onClick:l,disabled:u.state.value.options.length>=6,className:"mx-2 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-3 text-lg font-semibold text-[#00000066] disabled:cursor-not-allowed",children:"+ Add Option"}),u.state.value.correctIndex.length===0||u.state.meta.errors.length>0?jsx("span",{className:"px-2 text-base font-semibold text-red-500",children:u.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"}),jsx("p",{className:"",children:"Correct answer selected"})]})]})}}),(s==="short-answer"||s==="fill-in-the-blank")&&jsx(i.Field,{name:"responseOptions.correctShortAnswer",children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:u.state.value,onChange:m=>{u.handleChange(m.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Learners must write this answer exactly (case-insensitive)."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),s==="long-answer"&&jsx(i.Field,{name:"responseOptions.correctLongAnswer",children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-gray-900",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:u.state.value,onChange:m=>{u.handleChange(m.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"This will be used as a reference answer for manual grading."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),jsx(i.Subscribe,{selector:u=>[u.canSubmit,u.isSubmitting],children:([u,m])=>jsx("button",{type:"submit",disabled:!u,className:"mt-2 mb-4 w-full rounded-lg bg-[#096B76] px-6 py-3 font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50",children:m?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,document.body)},bu=mx;var vu=({text:e,position:o})=>{let t=xe(),a=d=>{t(le()),t(wt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+d))}));},r=d=>{t(le()),t(wt({id:e.id,fill:d}));},n=()=>{t(le()),t(wt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},s=()=>{t(le()),t(wt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},c=()=>{t(le()),t(wt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},i=d=>{t(le()),t(wt({id:e.id,fontFamily:d}));};return jsxs("div",{className:"fixed z-1001 flex items-center gap-1 rounded-lg border border-gray-200 bg-white p-2 shadow-2xl",style:{left:`${o.x}px`,top:`${o.y-60}px`,transform:"translateX(-50%)"},onClick:d=>d.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:d=>i(d.target.value),className:"rounded border border-gray-300 bg-white px-2 py-1 text-xs hover:bg-gray-50",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:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-8 text-center text-xs font-medium",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:n,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:jsx(TextB,{size:16,weight:"bold"})}),jsx("button",{onClick:s,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:jsx(TextItalic,{size:16,weight:"bold"})}),jsx("button",{onClick:c,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:jsx(TextUnderline,{size:16,weight:"bold"})})]}),jsx("div",{className:"ml-1 border-l border-gray-200 pl-1",children:jsx("div",{className:"relative",children:jsx("input",{type:"color",value:e.fill,onChange:d=>r(d.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var wu=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:n,textareaRef:s})=>{let c=useRef(null),i=useMemo(()=>({fontSize:`${e.fontSize*n}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,n]),d=useCallback(f=>{f.style.height="auto",f.style.height=`${f.scrollHeight}px`;let u=document.createElement("span");u.style.font=window.getComputedStyle(f).font,u.style.fontSize=f.style.fontSize,u.style.fontFamily=f.style.fontFamily,u.style.fontWeight=f.style.fontWeight,u.style.fontStyle=f.style.fontStyle,u.style.visibility="hidden",u.style.position="absolute",u.style.whiteSpace="pre";let m=f.value.split(`
|
|
4
4
|
`),l=0;document.body.appendChild(u);for(let g of m){u.textContent=g||" ";let p=u.offsetWidth;p>l&&(l=p);}document.body.removeChild(u);let h=10;f.style.width=`${Math.max(200,l+h+20)}px`;},[]);return useEffect(()=>{let f=c.current;f&&(f.style.fontSize=`${e.fontSize*n}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,d(f));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,n,d]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:f=>{if(c.current=f,s.current=f,f){f.focus();let u=f.value.length;f.setSelectionRange(u,u),d(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 Lu=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(P=>P.toolbar.selectedTool),c=s==="pen"||s==="eraser",i=useRef(null),[d,f]=useState(""),[u,m]=useState(false),[l,h]=useState(null);useEffect(()=>{let P=i.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",p=u&&d.trim().toLowerCase()===g,w=()=>{m(false),f("");},x=()=>p?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",v=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,I=60,k=u?40:0,S=u?54:20,b=50,A=12,V=e.data.feedbackMode==="practice"?48:0,R=12,H=30,q=I+k+H+b+A+R+V+L;return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:q,name:"sa-element",...c?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:q,onTransformEnd:P=>t(e.id,P),onContextMenu:P=>{P.cancelBubble=true,r(P.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:I+k+H-S,width:e.width-L*2+4,height:b+6,fill:"#ffffff",stroke:p?"#22c55e":u?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:I+k+H-S},divProps:{style:{width:`${e.width-L*2-4}px`,height:`${b}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:P=>f(P.target.value),disabled:u,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:u?"none":"auto"}})}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:I+80,width:e.width/2+24,height:k,fill:v().bg,cornerRadius:8}),jsx(Text,{x:36,y:I+80,width:e.width-L*2,height:k,text:x(),fontSize:12,fontStyle:"bold",fill:v().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:I+k+H+b+A+R,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,h("check");},onMouseUp:P=>{P.cancelBubble=true,h(null),d.length>0&&m(true);},onMouseLeave:P=>{P.cancelBubble=true,h(null);},onTouchStart:P=>{P.cancelBubble=true,h("check");},onTouchEnd:P=>{P.cancelBubble=true,h(null),d.length>0&&m(true);},scaleX:l==="check"?.95:1,scaleY:l==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(u?2:1),height:48,fill:d.length===0||u?"#9ca3af":"#096B76",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(u?2:1),height:48,text:u?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),u&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),w();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),w();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Lu.displayName="ShortAnswer";var Iu=Lu;var Cu=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(Iu,{shortAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id)},s.id))});var ku=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],r=useRef(new Map),n=useCallback((s,c)=>{let i=s.target;o(Go({id:c,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:n}};var Ct=24,zi=51,Ir=64,Mu=15,jn=32,Tu=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:n})=>{let s=useSelector(b=>b.toolbar.selectedTool),c=s==="pen"||s==="eraser",i=useRef(null),[d,f]=useState(""),[u,m]=useState(false),[l,h]=useState(null);useEffect(()=>{let b=i.current;if(b)return n.current.set(e.id,b),()=>{n.current.delete(e.id);}},[e.id,n]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",p=u&&d.trim().toLowerCase()===g,w=()=>{m(false),f("");},x=()=>{d.length>0&&m(true);},v=e.width-Ct*2,L=(v-Mu)/2,I=e.data.feedbackMode==="practice",k=useMemo(()=>{let b=Ct,A=b;b+=60;let V=b;b+=35;let R=b;b+=zi+16;let H=b;u&&(b+=jn+16);let q=b;return I&&(b+=Ir),b+=Ct,{questionY:A,helperTextY:V,inputY:R,feedbackY:H,buttonsY:q,totalHeight:b}},[u,I]),S=()=>u?p?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...c?{}:{onDragEnd:b=>a(b,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:k.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:b=>t(e.id,b),onContextMenu:b=>{b.cancelBubble=true,r?.(b.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Ct,y:k.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:v,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Ct,y:k.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:v,listening:false}),jsx(Rect,{x:Ct,y:k.inputY,width:v,height:zi,fill:"#ffffff",stroke:S(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Ct,y:k.inputY},divProps:{style:{width:`${v}px`,height:`${zi}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:b=>f(b.target.value),disabled:u,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"}})}),u&&jsxs(Group,{y:k.feedbackY,children:[jsx(Rect,{x:Ct,width:p?206:140,height:jn,fill:p?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:p?"\u2713":"\u2717",x:Ct+10,y:0,width:16,height:jn,fontSize:14,fill:p?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:p?"Right Answer, Great Job!":"Wrong Answer",x:Ct+30,y:0,height:jn,fontSize:14,fontStyle:"600",fill:p?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),I&&jsxs(Group,{y:k.buttonsY,children:[jsxs(Group,{x:Ct,onMouseDown:b=>{b.cancelBubble=true,h("reset");},onMouseUp:b=>{b.cancelBubble=true,h(null),w();},onMouseLeave:b=>{b.cancelBubble=true,h(null);},onTouchStart:b=>{b.cancelBubble=true,h("reset");},onTouchEnd:b=>{b.cancelBubble=true,h(null),w();},scaleX:l==="reset"?.98:1,scaleY:l==="reset"?.98:1,children:[jsx(Rect,{width:L,height:Ir,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:L,height:Ir,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Ct+L+Mu,onMouseDown:b=>{b.cancelBubble=true,h("submit");},onMouseUp:b=>{b.cancelBubble=true,h(null),x();},onMouseLeave:b=>{b.cancelBubble=true,h(null);},onTouchStart:b=>{b.cancelBubble=true,h("submit");},onTouchEnd:b=>{b.cancelBubble=true,h(null),x();},scaleX:l==="submit"?.98:1,scaleY:l==="submit"?.98:1,children:[jsx(Rect,{width:L,height:Ir,fill:d.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:L,height:Ir,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Tu.displayName="FillInTheBlanks";var Au=Tu;var Ru=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n})=>jsx(Fragment,{children:e.map(s=>jsx(Au,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n},s.id))});var ji=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(q=>q.toolbar.selectedTool),c=s==="pen"||s==="eraser",i=useRef(null),[d,f]=useState(""),[u,m]=useState(false),[l,h]=useState(null);useEffect(()=>{let q=i.current;if(q)return a.current.set(e.id,q),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",p=u&&d.trim().toLowerCase()===g,w=()=>{m(false),f("");},x=()=>p?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",v=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,I=60,k=u?60:0,S=120,b=12,A=48,V=12,R=30,H=I+k+R+S+b+V+A+L;return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...c?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:q=>{let P=i.current?.getStage()?.getPointerPosition();if(!P||!r)return;let W={x:e.x,y:e.y,width:e.width,height:e.height};P.x>=W.x&&P.x<=W.x+W.width&&P.y>=W.y&&P.y<=W.y+W.height&&r(q.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:H,onTransformEnd:q=>t(e.id,q)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:I,width:e.width-L*2,height:k,fill:v().bg,cornerRadius:8}),jsx(Text,{x:L,y:I,width:e.width-L*2,height:k,text:x(),fontSize:14,fontStyle:"bold",fill:v().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:I+k+b,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:I+k+R,width:e.width-L*2,height:S,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:I+k+R},divProps:{style:{width:`${e.width-L*2}px`,height:`${S}px`,pointerEvents:u?"none":"auto"}},children:jsx("textarea",{value:d,onChange:q=>f(q.target.value),disabled:u,placeholder:`Type your extended answer here...\r
|
|
5
5
|
\r
|
|
6
|
-
This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:u?"none":"auto"}})}),jsx(Group,{y:I+k+R+S+b+V,children:u&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),w();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),w();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:q=>q.cancelBubble=true,onTap:q=>q.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});ji.displayName="LongAnswer";var Eu=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(ji,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id)},s.id))});var Wa=1920,za=1080,Nu=3840,Vu=2160,Yx=e=>{let o=0,t=0,a=Wa,r=za;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:Wa,height:za};let n=(i,d,f,u)=>{o=Math.min(o,i),t=Math.min(t,d),a=Math.max(a,i+f),r=Math.max(r,d+u);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let d=i.x||0,f=i.y||0,u=i.scaleX||1,m=i.scaleY||1;for(let l=0;l<i.points.length;l+=2){let h=d+i.points[l]*u,g=f+i.points[l+1]*m;o=Math.min(o,h),t=Math.min(t,g),a=Math.max(a,h),r=Math.max(r,g);}}}),e.images?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>n(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>n(i.x,i.y,i.width,i.height));let s=Math.min(a-o,Nu),c=Math.min(r-t,Vu);return o=Math.max(o,a-Nu),t=Math.max(t,r-Vu),{minX:o,minY:t,maxX:a,maxY:r,width:s,height:c}},Jx=(e,o,t={minX:0,minY:0,maxX:Wa,maxY:za,width:Wa,height:za})=>{let a=Math.max(t.width,Wa),r=Math.max(t.height,za),n=e/o,s=a/r,c,i,d,u=0;if(n>s){i=r,c=Math.round(i*n),d=o/i;}else {c=a,i=Math.round(c/n),d=e/c;let m=r*d;u=(o-m)/2;}return {scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:u,baseWidth:c,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},qu=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},Zx=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a}={})=>{let r=yt(),n=ee(y=>y.toolbar.selectedTool),s=ee(ge),c=ee($o),i=s?.editingActivity,d=s?.showMcqForm,f=s?.lines||[],u=useRef(null),m=useRef(null),[l,h]=useState(null),[g,p]=useState(""),w=useRef(null),[x,v]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Wa,stageHeight:za,offsetX:0,offsetY:0,baseWidth:Wa,baseHeight:za,contentOffsetX:0,contentOffsetY:0}),L=useMemo(()=>Yx(s||null),[c]),[I,k]=useState(null),[S,b]=useState(null),[A,V]=useState(null),[R,H]=useState(null),[q,P]=useState(null),[W,E]=useState(null),[oe,N]=useState(null),[fe,z]=useState(false),[O,X]=useState(null),[U,K]=useState(false),Q=useRef(null),te=useRef(null),J=useRef(null),{debouncedGenerateThumbnail:de}=vd(c,u);useEffect(()=>{let y=()=>{if(m.current){let T=m.current.getBoundingClientRect(),D=Jx(T.width,T.height,L);v(D);}};y();let C=new ResizeObserver(y);return m.current&&C.observe(m.current),window.addEventListener("resize",y),()=>{C.disconnect(),window.removeEventListener("resize",y);}},[L]),useEffect(()=>{if(u.current){let y=u.current.container();y&&(y.style.cursor="");}},[n]);let Y=useCallback(()=>{u.current&&requestAnimationFrame(()=>{if(!u.current)return;u.current.getLayers().forEach(D=>D.batchDraw());let C=1/6,T=u.current.toDataURL({pixelRatio:C});p(T),de();});},[de]),Me=useRef(c);useEffect(()=>{Me.current!==c&&(Me.current=c,Y());},[c,Y]);let De=useRef(null),Se=useRef(true);useEffect(()=>{if(!s)return;let y=(s.lines?.length||0)+(s.images?.length||0)+(s.videos?.length||0)+(s.shapes?.length||0)+(s.texts?.length||0)+(s.flashcards?.length||0)+(s.photoFrames?.length||0)+(s.multipleChoices?.length||0)+(s.trueFalses?.length||0)+(s.shortAnswers?.length||0)+(s.LongAnswer?.length||0)+(s.fillInTheBlanks?.length||0),C=De.current?.count!==y;!Se.current&&C&&setTimeout(()=>{Y();},100),De.current={slideId:c,count:y},Se.current=false;},[s,c,Y]),useEffect(()=>{u.current&&e&&e(u);},[e]),useEffect(()=>{J.current&&a&&a(J);},[a]);let{startDrawing:Rt,draw:Ja,stopDrawing:Er,setCanvasRef:Fr,tool:fs,color:ms,strokeWidth:ps,isSketchMode:hs}=_l(Y),Ma=useRef(new Map),{images:F,getLoadedImage:ne,imageRefs:ve,handleDragEnd:he,handleImageTransformEnd:se}=Ql(Y),{videos:re,videoRefs:Te,handleVideoClick:Dt,handleVideoDragEnd:Yt,handleVideoTransformEnd:st}=ad(Y),{multipleChoice:Ee,handleMcqTransform:qe,mcqRefs:ht,handleDragEnd:Ta}=ed(Y),{trueFalse:Za,handleTrueFalseTransform:Qa,trueFalseRefs:Aa,handleTrueFalseDragEnd:Et}=td(Y),{shortAnswers:ra,saRefs:Ft,handleShortAnswerDragEnd:Df}=ld(Y),{longAnswers:Ef,handleLongAnswerDragEnd:Ff}=dd(Y),{fillInTheBlanks:Bf,handleFillInTheBlanksDragEnd:Of,fibRefs:Br}=ku(Y),{transformerRef:ue,boundBoxFunc:gt}=hd(),{shapes:Nf,shapeRefs:Or,isDragging:Pl,handleShapeDragEnd:Vf,handleShapeResizeEnd:qf}=nd(Y),{texts:qo,textRefs:na,handleDragEnd:Hf,handleTransformEnd:Uf,handleDoubleClick:Wf,startEditing:Nr,editingTextId:me,editingValue:Rl,handleEditingChange:Dl,finishEditing:gs}=id(Y,Q);useEffect(()=>{t&&t(Nr);},[t,Nr]);let Vr=ee(y=>y.canvas.editingTextId);useEffect(()=>{Vr&&Vr!==me&&Nr(Vr);},[Vr,me,Nr]);let{flashcards:zf,flashcardRefs:qr,handleDragEnd:Gf,handleFlashcardTransformEnd:Kf,handleNext:_f,handlePrevious:jf}=cd(Y),{photoFrames:El,photoFrameRefs:Hr,handleDragEnd:$f,handlePhotoFrameTransformEnd:Xf,startCamera:Yf,capturePhoto:Jf,cameraStreams:Zf}=pd(Y);useEffect(()=>{if(ue.current){if(me){ue.current.nodes([]),ue.current.getLayer()?.batchDraw();return}if(l&&!re.find(T=>T.id===l)?.isPlaying){let T=Ma.current.get(l)||ve.current.get(l)||Te.current.get(l)||Or.current.get(l)||na.current.get(l)||ht.current.get(l)||qr.current.get(l)||Hr.current.get(l)||Ft.current.get(l)||Aa.current.get(l)||Br.current.get(l);if(T){let D=T.attrs?.locked;if(T.visible()&&D!==true){ue.current.nodes([T]),ue.current.getLayer()?.batchDraw();return}}}ue.current.nodes([]),ue.current.getLayer()?.batchDraw();}},[l,me,re,Ma,ve,Te,Or,na,qr,Hr,El,ht,Aa,Br,ue]);let Ue=useCallback(y=>{h(y),o?.(y);},[o]),eo=useCallback(()=>{h(null),o?.(null),ue.current&&(ue.current.nodes([]),ue.current.getLayer()?.batchDraw());},[ue,o]),Fl=useCallback(y=>s?s.lines?.some(C=>C.id===y)?"line":s.images?.some(C=>C.id===y)?"image":s.videos?.some(C=>C.id===y)?"video":s.shapes?.some(C=>C.id===y)?"shape":s.texts?.some(C=>C.id===y)?"text":s.flashcards?.some(C=>C.id===y)?"flashcard":s.photoFrames?.some(C=>C.id===y)?"photoFrame":s.multipleChoices?.some(C=>C.id===y)?"mcq":s.trueFalses?.some(C=>C.id===y)?"trueFalse":s.shortAnswers?.some(C=>C.id===y)?"shortAnswer":s.LongAnswer?.some(C=>C.id===y)?"longAnswer":s.fillInTheBlanks?.some(C=>C.id===y)?"fillInTheBlanks":null:null,[s]),Bl=useCallback((y,C)=>{switch(r(le()),C){case "line":r(xn(y));break;case "image":r(Wr(y));break;case "video":r(_r(y));break;case "shape":r(Xr(y));break;case "text":r(Yr(y));break;case "flashcard":r(Zr(y));break;case "photoFrame":r(en(y));break;case "mcq":r(an(y));break;case "trueFalse":r(rn(y));break;case "shortAnswer":r(sn(y));break;case "longAnswer":r(dn(y));break;case "fillInTheBlanks":r(cn(y));break}eo(),Y();},[r,eo,Y]);useEffect(()=>{let y=C=>{if(C.key!=="Delete"||!l||me)return;let T=document.activeElement;if(T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement||T?.getAttribute("contenteditable")==="true")return;C.preventDefault();let ke=Fl(l);ke&&Bl(l,ke);};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[l,me,Fl,Bl]),useEffect(()=>{let y=ue.current;return ()=>{y&&y.nodes([]);}},[c]),useEffect(()=>{let y=C=>{me&&C.target.tagName!=="TEXTAREA"&&gs();};return document.addEventListener("mousedown",y),()=>{document.removeEventListener("mousedown",y);}},[me,gs]),useEffect(()=>{let y=me||l;if(!y||l&&me){b(null);return}let C=na.current.get(y),T=u.current;if(!C||!T){b(null);return}let D=T.container().getBoundingClientRect(),ke=C.absolutePosition(),Le=T.scaleX();b({x:D.left+(ke.x+C.width()*Le/2)*Le,y:D.top+ke.y*Le});},[l,me,qo,na]),useEffect(()=>{if(!me){V(null);return}let y=na.current.get(me),C=u.current;if(!y||!C){V(null);return}let T=C.container().getBoundingClientRect(),D=y.absolutePosition(),ke=C.scaleX();V({top:T.top+D.y*ke,left:T.left+D.x*ke,scale:ke});},[me,qo,na]);let Ol=useCallback(y=>{let C=y.target.getClassName(),T=y.target===y.target.getStage(),D=C==="Transformer"||y.target.getParent()?.getClassName()==="Transformer",ke=C==="Image",Le=C==="Text",ae=C==="Group"||y.target.getParent()?.getClassName()==="Group",Bt=C==="Circle"||C==="Star"||C==="RegularPolygon"||C==="Ellipse"||C==="Ring"||C==="Wedge"||C==="Arrow"||C==="Line"||C==="Arc"||C==="Rect"&&y.target.attrs.id,bt=C==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:C,clickedOnImage:ke,clickedOnGroup:ae,tool:n,targetId:y.target.attrs?.id}),T&&!D&&!ke&&!Le&&!ae&&!Bt&&!bt&&eo(),!(n==="pen"||n==="eraser")&&(ke||Le||D||ae||Bt||bt))return;let _e=y.target.getStage()?.getPointerPosition();if(!_e)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let B=qu(_e,x);Rt(B);}},[n,Rt,eo,x]),Nl=useCallback(y=>{if(Pl)return;let C=y.target.getStage()?.getPointerPosition();if(!C)return;let T=qu(C,x);Ja(T);},[Ja,Pl,x]),Vl=useCallback(()=>{Er();},[Er]),Qf=useCallback(y=>{he(y,Y);},[he,Y]),em=useCallback(y=>{Dt(y),Ue(y);},[Dt,Ue]),xt=useCallback((y,C,T)=>{y.preventDefault();let D=y.clientX,ke=y.clientY,Le=w.current?.offsetHeight||450,ae=w.current?.offsetWidth||450,Bt=window.innerHeight,bt=window.innerWidth,Ze=D,_e=ke;ke+Le>Bt&&(_e=ke-Le),D+ae>bt&&(Ze=D-ae),k({x:Ze,y:_e,elementId:C,elementType:T}),Ue(C);},[Ue]),ql=useCallback(y=>{r(Ko(y)),r(da(true));},[r]),tm=useCallback(y=>{r(Uo(y)),r(Ra(true));},[r]),am=useCallback((y,C)=>{if(!I)return;let{elementId:T,elementType:D}=I;switch(y){case "order":if(C){let M=C.target.getBoundingClientRect();H({x:M.right+5,y:M.top,type:"order"});}break;case "lock":if(C){let M=C.target.getBoundingClientRect();H({x:M.right+5,y:M.top,type:"lock"});}break;case "link":if(k(null),D==="line")break;let ke=s?D==="image"?s.images.find(M=>M.id===T):s.videos.find(M=>M.id===T):null;P({type:"link",defaultValue:ke?.link||""});break;case "voice":if(k(null),D==="line")break;let Le=s?D==="image"?s.images.find(M=>M.id===T):D==="video"?s.videos.find(M=>M.id===T):D==="text"?s.texts.find(M=>M.id===T):D==="flashcard"?s.flashcards.find(M=>M.id===T):D==="photoFrame"?s.photoFrames.find(M=>M.id===T):D==="mcq"?s.multipleChoices.find(M=>M.id===T):D==="fillInTheBlanks"?s.fillInTheBlanks.find(M=>M.id===T):D==="longAnswer"?s.LongAnswer.find(M=>M.id===T):D==="shortAnswer"?s.shortAnswers.find(M=>M.id===T):D==="trueFalse"?s.trueFalses.find(M=>M.id===T):D==="shape"?s.shapes.find(M=>M.id===T):null:null;X({elementId:T,elementType:D,existingAudio:Le?.audioData});break;case "edit":k(null);let ae=null;D==="mcq"?ae=s?.multipleChoices.find(M=>M.id===T):D==="trueFalse"?ae=s?.trueFalses.find(M=>M.id===T):D==="shortAnswer"?ae=s?.shortAnswers.find(M=>M.id===T):D==="longAnswer"?ae=s?.LongAnswer.find(M=>M.id===T):D==="fillInTheBlanks"&&(ae=s?.fillInTheBlanks.find(M=>M.id===T)),ae&&ql(ae);break;case "editFlashcard":k(null);let Bt=s?.flashcards.find(M=>M.id===T);Bt&&tm(Bt);break;case "color":k(null);let bt=s?.shapes.find(M=>M.id===T);E({elementId:T,elementType:"shape",defaultColor:bt?.color||"#096B76"});break;case "crop":if(k(null),D==="image"){let M=s?.images.find(dm=>dm.id===T);M&&N({elementId:T,imageSrc:M.src});}break;case "draw":k(null),D==="image"?r(Bs(T)):D==="photoFrame"&&r(Ns(T));break;case "duplicate":r(le()),D==="line"?r(Xs(T)):D==="image"?r(zr(T)):D==="video"?r(jr(T)):D==="shape"?r($r(T)):D==="text"?r(Jr(T)):D==="flashcard"?r(Qr(T)):D==="photoFrame"?r(tn(T)):D==="mcq"?r(on(T)):D==="trueFalse"?r(nn(T)):D==="shortAnswer"?r(ln(T)):D==="fillInTheBlanks"?r(fn(T)):D==="longAnswer"&&r(un(T)),Y();break;case "infinite-clone":r(le());let Ze=5;for(let M=0;M<Ze;M++)D==="image"?r(zr(T)):D==="video"?r(jr(T)):D==="shape"?r($r(T)):D==="text"?r(Jr(T)):D==="flashcard"?r(Qr(T)):D==="photoFrame"?r(tn(T)):D==="mcq"?r(on(T)):D==="trueFalse"?r(nn(T)):D==="shortAnswer"?r(ln(T)):D==="fillInTheBlanks"?r(fn(T)):D==="longAnswer"&&r(un(T));Y();break;case "make-response":if(k(null),D==="line")break;let _e=`#response-${T}`;r(le()),r(mn({id:T,type:D,link:_e})),(s?D==="image"?s.images.find(M=>M.id===T):D==="video"?s.videos.find(M=>M.id===T):D==="shape"?s.shapes.find(M=>M.id===T):D==="flashcard"?s.flashcards.find(M=>M.id===T):D==="photoFrame"?s.photoFrames.find(M=>M.id===T):s.multipleChoices.find(M=>M.id===T):null)?.altText||r(pn({id:T,type:D,altText:"Interactive response area"})),Y(),console.log(`Element ${T} marked as interactive response area`);break;case "accessibility":if(k(null),D==="line")break;let B=s?D==="image"?s.images.find(M=>M.id===T):D==="video"?s.videos.find(M=>M.id===T):D==="shape"?s.shapes.find(M=>M.id===T):null:null;P({type:"altText",defaultValue:B?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),k(null),K(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(le()),D==="line"?r(xn(T)):D==="image"?r(Wr(T)):D==="video"?r(_r(T)):D==="shape"?r(Xr(T)):D==="text"?r(Yr(T)):D==="flashcard"?r(Zr(T)):D==="photoFrame"?r(en(T)):D==="mcq"?r(an(T)):D==="trueFalse"?r(rn(T)):D==="shortAnswer"?r(sn(T)):D==="longAnswer"?r(dn(T)):D==="fillInTheBlanks"&&r(cn(T)),eo(),Y();break}},[I,r,Y,eo,s,ql]),om=useCallback(()=>{k(null),H(null);},[]),xs=useCallback(y=>{if(!I)return;let{elementId:C,elementType:T}=I;switch(r(le()),y){case "bring-to-front":T!=="line"&&r(Ks({id:C,type:T}));break;case "send-to-back":T!=="line"&&r(_s({id:C,type:T}));break;case "lock":case "unlock":T!=="line"&&r(js({id:C,type:T}));break}Y(),k(null),H(null);},[I,r,Y]),rm=useCallback(y=>{if(!I||!q)return;let{elementId:C,elementType:T}=I;r(le()),q.type==="link"&&T!=="line"?r(mn({id:C,type:T,link:y})):q.type==="altText"&&T!=="line"&&r(pn({id:C,type:T,altText:y})),Y(),P(null);},[I,q,r,Y]),nm=useCallback(y=>{if(!O)return;let{elementId:C,elementType:T}=O;r(le()),r(hn({id:C,type:T,audioData:y})),Y(),X(null);},[O,r,Y]),sm=useCallback(()=>{if(!O)return;let{elementId:y,elementType:C}=O;r(le()),r(hn({id:y,type:C,audioData:""})),Y();},[O,r,Y]),im=useCallback(y=>{if(!W)return;let{elementId:C}=W;r(le()),r(oo({id:C,color:y})),Y(),E(null);},[W,r,Y]),lm=useCallback(y=>{if(!oe)return;let{elementId:C}=oe;r(le()),r(ao({id:C,src:y})),Y(),N(null);},[oe,r,Y]);return jsxs("div",{ref:m,className:"fixed inset-0",style:{cursor:n==="pen"?"crosshair":n==="eraser"?"":"default"},children:[n==="pen"&&jsx(Jl,{ref:y=>{if(te.current=y,Fr(y),y){let C=y.getCanvasElement();C&&(J.current=C,a&&a(J));}},width:x.baseWidth,height:x.baseHeight,tool:fs,color:ms,strokeWidth:ps/x.scale,isSketchMode:hs,xOffset:x.contentOffsetX,yOffset:x.contentOffsetY-x.offsetY/x.scale,style:{width:x.stageWidth,height:x.stageHeight}}),jsxs(Stage,{ref:u,width:x.stageWidth,height:x.stageHeight,scaleX:x.scaleX,scaleY:x.scaleY,x:x.offsetX,y:0,onMouseDown:Ol,onMouseMove:Nl,onMouseUp:Vl,onTouchStart:Ol,onTouchMove:Nl,onTouchEnd:Vl,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:x.baseWidth,height:x.stageHeight/x.scale,fill:s?.backgroundColor||"white"})}),jsx(Layer,{x:-x.contentOffsetX,y:x.offsetY/x.scale-x.contentOffsetY,children:(()=>{let y=[];return f.forEach((C,T)=>{y.push({type:"line",timestamp:C.timestamp||T,element:{...C,id:C.id??`line-${T}`},index:T});}),Nf.forEach(C=>{y.push({type:"shape",timestamp:C.timestamp||0,element:C});}),F.forEach(C=>{y.push({type:"image",timestamp:C.timestamp||0,element:C});}),re.forEach(C=>{y.push({type:"video",timestamp:C.timestamp||0,element:C});}),qo.forEach(C=>{y.push({type:"text",timestamp:C.timestamp||0,element:C});}),zf.forEach(C=>{y.push({type:"flashcard",timestamp:C.timestamp||0,element:C});}),El.forEach(C=>{y.push({type:"photoFrame",timestamp:C.timestamp||0,element:C});}),Ee.forEach(C=>{y.push({type:"mcq",timestamp:C.timestamp||0,element:C});}),Za.forEach(C=>{y.push({type:"trueFalse",timestamp:C.timestamp||0,element:C});}),ra.forEach(C=>{y.push({type:"shortAnswer",timestamp:C.timestamp||0,element:C});}),Ef.forEach(C=>{y.push({type:"longAnswer",timestamp:C.timestamp||0,element:C});}),Bf.forEach(C=>{y.push({type:"fillInTheBlanks",timestamp:C.timestamp||0,element:C});}),y.sort((C,T)=>C.timestamp-T.timestamp),y.map((C,T)=>{let D=`${C.type}-${"id"in C.element&&C.element.id||C.index||T}`,ke="id"in C.element?C.element.id:void 0,Le=ke&&l===ke;switch(C.type){case "line":let ae=C.element,Bt=C.index||0,bt=ae.tool==="eraser",Ze=ae.isSketch&&ae.tool==="pen",_e=ae.isSketch&&bt,vt=ae.id||`line-${Bt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),n==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:Ze||_e?void 0:ae.color,strokeWidth:Ze||_e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ze||_e?bt?"black":ae.color:void 0,closed:Ze||_e,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,onClick:()=>{r(le()),r(Ur(Bt));},onTap:()=>{r(le()),r(Ur(Bt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:B=>{let M=B.target.getStage();M&&(M.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:B=>{let M=B.target.getStage();M&&(M.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`);}})},D):jsxs(be__default.Fragment,{children:[jsx(Group,{id:vt,ref:B=>{B?Ma.current.set(vt,B):Ma.current.delete(vt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:n==="select",listening:n==="select",onClick:()=>{n==="select"&&(console.log("Line clicked:",vt),Ue(vt));},onTap:()=>{n==="select"&&(console.log("Line tapped:",vt),Ue(vt));},onDragEnd:B=>{r(le()),r(gn({id:vt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onTransformEnd:B=>{r(le()),r(gn({id:vt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onMouseEnter:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="move");}},onMouseLeave:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="default");}},onContextMenu:B=>{let M=B.evt;M.preventDefault(),xt(M,vt,"line");},children:jsx(Line,{points:ae.points||[],stroke:Ze||_e?void 0:ae.color,strokeWidth:Ze||_e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ze||_e?bt?"black":ae.color:void 0,closed:Ze||_e,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ma.current.get(l);console.log("Line Transformer - selectedId:",l,"node found:",!!M),M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:gt,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"]})]},D);case "shape":return jsxs(be__default.Fragment,{children:[jsx(ui,{onSelect:Ue,shapes:[C.element],shapeRefs:Or,handleShapeDragEnd:Vf,handleShapeResizeEnd:qf,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Or.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "image":return jsxs(be__default.Fragment,{children:[jsx(si,{images:[C.element],getLoadedImage:ne,imageRefs:ve,onDragEnd:Qf,onTransform:se,onSelect:Ue,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=ve.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "video":return jsxs(be__default.Fragment,{children:[jsx(di,{videos:[C.element],selectedId:l,videoRefs:Te,onVideoClick:em,onDragEnd:Yt,onTransformEnd:st,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Te.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "text":return jsxs(be__default.Fragment,{children:[jsx(Pd,{texts:[C.element],textRefs:na,onDragEnd:Hf,onTransformEnd:Uf,onSelect:Ue,onContextMenu:xt,onDoubleClick:Wf,editingTextId:me,editingValue:Rl,onEditingChange:Dl}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=na.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(mi,{flashcards:[C.element],flashcardRefs:qr,selectedId:l,onDragEnd:Gf,onTransform:Kf,onSelect:Ue,onNext:_f,onPrevious:jf,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=qr.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(bi,{photoFrames:[C.element],photoFrameRefs:Hr,selectedId:l,onDragEnd:$f,onTransform:Xf,onSelect:Ue,onStartCamera:Yf,onCapture:Jf,cameraStreams:Zf,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Hr.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(ru,{handleMcqTransform:qe,multipleChoice:[C.element],handleSelect:Ue,mcqRefs:ht,handleDragEnd:Ta,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=ht.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(iu,{trueFalses:[C.element],handleTrueFalseTransform:Qa,handleSelect:Ue,trueFalseRefs:Aa,onContextMenu:xt,handleDragEnd:Et}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Aa.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(Cu,{shortAnswers:[C.element],handleSelect:Ue,handleTransform:qe,saRefs:Ft,onContextMenu:xt,handleDragEnd:Df}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ft.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(Eu,{longAnswer:[C.element],handleSelect:Ue,handleTransform:qe,saRefs:Ft,onContextMenu:xt,handleDragEnd:Ff}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ft.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Ru,{fillInTheBlanks:[C.element],handleSelect:Ue,handleTransform:qe,onContextMenu:xt,handleDragEnd:Of,fibRefs:Br}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Br.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);default:return null}})})()})]}),I&&jsx(zd,{menuRef:w,x:I.x,y:I.y,type:I.elementType,onAction:am,onClose:om,isDrawingMode:I.elementType==="image"?s?.images.find(y=>y.id===I.elementId)?.isDrawingMode:I.elementType==="photoFrame"?s?.photoFrames.find(y=>y.id===I.elementId)?.isDrawingMode:false}),R&&I&&jsx(Gd,{x:R.x,y:R.y,items:R.type==="order"?[{label:"Bring to Front",onClick:()=>xs("bring-to-front")},{label:"Send to Back",onClick:()=>xs("send-to-back")}]:[{label:s&&(I.elementType==="image"?s.images.find(y=>y.id===I.elementId)?.locked:s.videos.find(y=>y.id===I.elementId)?.locked)?"Unlock":"Lock",onClick:()=>xs(s&&(I.elementType==="image"?s.images.find(y=>y.id===I.elementId)?.locked:s.videos.find(y=>y.id===I.elementId)?.locked)?"unlock":"lock")}],onClose:()=>H(null)}),q&&jsx(Kd,{title:q.type==="link"?"Add Link":"Add Alt Text",label:q.type==="link"?"URL":"Alternative Text",placeholder:q.type==="link"?"https://example.com":"Describe this image/video",defaultValue:q.defaultValue,onSave:rm,onClose:()=>P(null)}),W&&jsx(_d,{defaultColor:W.defaultColor,onConfirm:im,onCancel:()=>E(null)}),oe&&jsx(Yd,{imageSrc:oe.imageSrc,onConfirm:lm,onCancel:()=>N(null)}),fe&&jsx(or,{onClose:()=>z(false),stageRef:u}),O&&jsx(Zd,{elementId:O.elementId,elementType:O.elementType,existingAudio:O.existingAudio,onSave:nm,onDelete:sm,onClose:()=>X(null)}),U&&jsx(tu,{selectedElementId:l||void 0,onClose:()=>K(false),onSelectElement:y=>{Ue(y),K(false);}}),s?.images.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.videos.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.shapes?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.texts?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.flashcards?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.photoFrames?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.multipleChoices?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.trueFalses?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.shortAnswers?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.LongAnswer?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.fillInTheBlanks?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),d&&jsx(bu,{editElement:i}),S&&(()=>{let y=me||l;if(!y)return null;let C=qo.find(T=>T.id===y);return C?jsx(vu,{text:C,position:S}):null})(),A&&me&&(()=>{let y=qo.find(C=>C.id===me);return y?jsx(wu,{text:y,editingValue:Rl,onEditingChange:Dl,onFinish:gs,position:{top:A.top,left:A.left},scale:A.scale,textareaRef:Q},me):null})()]})},Qx=Zx;var eb="SchooplaVideoStorage";var $t="videos",Yn=()=>new Promise((e,o)=>{let t=indexedDB.open(eb,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains($t)||r.createObjectStore($t,{keyPath:"id"});};}),Ga=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Yn(),n=a.transaction([$t],"readwrite").objectStore($t),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((c,i)=>{let d=n.put(s);d.onsuccess=()=>c(!0),d.onerror=()=>i(d.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 Hu=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Yn(),t=e.transaction([$t],"readonly").objectStore($t);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result,c=new Map;s.forEach(i=>{c.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${c.size} video blobs from IndexedDB`),a(c);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},$i=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Yn(),a=o.transaction([$t],"readwrite").objectStore($t);await new Promise((r,n)=>{let s=a.delete(e);s.onsuccess=()=>r(!0),s.onerror=()=>n(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}},Uu=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Yn(),t=e.transaction([$t],"readwrite").objectStore($t);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Wu=e=>URL.createObjectURL(e);function wa(e,o=[]){let t=[];function a(n,s){let c=be.createContext(s),i=t.length;t=[...t,s];let d=u=>{let{scope:m,children:l,...h}=u,g=m?.[e]?.[i]||c,p=be.useMemo(()=>h,Object.values(h));return jsx(g.Provider,{value:p,children:l})};d.displayName=n+"Provider";function f(u,m){let l=m?.[e]?.[i]||c,h=be.useContext(l);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${n}\``)}return [d,f]}let r=()=>{let n=t.map(s=>be.createContext(s));return function(c){let i=c?.[e]||n;return be.useMemo(()=>({[`__scope${e}`]:{...c,[e]:i}}),[c,i])}};return r.scopeName=e,[a,ab(r,...o)]}function ab(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(n){let s=a.reduce((c,{useScope:i,scopeName:d})=>{let u=i(n)[`__scope${d}`];return {...c,...u}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function zu(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Cr(...e){return o=>{let t=false,a=e.map(r=>{let n=zu(r,o);return !t&&typeof n=="function"&&(t=true),n});if(t)return ()=>{for(let r=0;r<a.length;r++){let n=a[r];typeof n=="function"?n():zu(e[r],null);}}}}function Tt(...e){return be.useCallback(Cr(...e),e)}function _u(e){let o=ob(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,c=be.Children.toArray(n),i=c.find(nb);if(i){let d=i.props.children,f=c.map(u=>u===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function ob(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=ib(r),c=sb(n,r.props);return r.type!==be.Fragment&&(c.ref=a?Cr(a,s):s),be.cloneElement(r,c)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var rb=Symbol("radix.slottable");function nb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rb}function sb(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let i=n(...c);return r(...c),i}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function ib(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 ub=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rt=ub.reduce((e,o)=>{let t=_u(`Primitive.${o}`),a=be.forwardRef((r,n)=>{let{asChild:s,...c}=r,i=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...c,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function $e(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function Xi(e){let o=cb(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,c=be.Children.toArray(n),i=c.find(mb);if(i){let d=i.props.children,f=c.map(u=>u===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function cb(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=hb(r),c=pb(n,r.props);return r.type!==be.Fragment&&(c.ref=a?Cr(a,s):s),be.cloneElement(r,c)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var fb=Symbol("radix.slottable");function mb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===fb}function pb(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let i=n(...c);return r(...c),i}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function hb(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 Jn(e){let o=e+"CollectionProvider",[t,a]=wa(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=g=>{let{scope:p,children:w}=g,x=be__default.useRef(null),v=be__default.useRef(new Map).current;return jsx(r,{scope:p,itemMap:v,collectionRef:x,children:w})};s.displayName=o;let c=e+"CollectionSlot",i=Xi(c),d=be__default.forwardRef((g,p)=>{let{scope:w,children:x}=g,v=n(c,w),L=Tt(p,v.collectionRef);return jsx(i,{ref:L,children:x})});d.displayName=c;let f=e+"CollectionItemSlot",u="data-radix-collection-item",m=Xi(f),l=be__default.forwardRef((g,p)=>{let{scope:w,children:x,...v}=g,L=be__default.useRef(null),I=Tt(p,L),k=n(f,w);return be__default.useEffect(()=>(k.itemMap.set(L,{ref:L,...v}),()=>void k.itemMap.delete(L))),jsx(m,{[u]:"",ref:I,children:x})});l.displayName=f;function h(g){let p=n(e+"CollectionConsumer",g);return be__default.useCallback(()=>{let x=p.collectionRef.current;if(!x)return [];let v=Array.from(x.querySelectorAll(`[${u}]`));return Array.from(p.itemMap.values()).sort((k,S)=>v.indexOf(k.ref.current)-v.indexOf(S.ref.current))},[p.collectionRef,p.itemMap])}return [{Provider:s,Slot:d,ItemSlot:l},h,a]}var To=globalThis?.document?be.useLayoutEffect:()=>{};var gb=be[" useId ".trim().toString()]||(()=>{}),xb=0;function Yu(e){let[o,t]=be.useState(gb());return To(()=>{t(a=>a??String(xb++));},[e]),(o?`radix-${o}`:"")}function Ju(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var bb=be[" useInsertionEffect ".trim().toString()]||To;function Qt({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,s]=vb({defaultProp:o,onChange:t}),c=e!==void 0,i=c?e:r;{let f=be.useRef(e!==void 0);be.useEffect(()=>{let u=f.current;u!==c&&console.warn(`${a} is changing from ${u?"controlled":"uncontrolled"} to ${c?"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=c;},[c,a]);}let d=be.useCallback(f=>{if(c){let u=yb(f)?f(e):f;u!==e&&s.current?.(u);}else n(f);},[c,e,n,s]);return [i,d]}function vb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),n=be.useRef(o);return bb(()=>{n.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function yb(e){return typeof e=="function"}var wb=be.createContext(void 0);function Po(e){let o=be.useContext(wb);return e||o||"ltr"}var Zi="rovingFocusGroup.onEntryFocus",Lb={bubbles:false,cancelable:true},kr="RovingFocusGroup",[Qi,Zu,Ib]=Jn(kr),[Sb,el]=wa(kr,[Ib]),[Cb,kb]=Sb(kr),Qu=be.forwardRef((e,o)=>jsx(Qi.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Qi.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Mb,{...e,ref:o})})}));Qu.displayName=kr;var Mb=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:i,onEntryFocus:d,preventScrollOnEntryFocus:f=false,...u}=e,m=be.useRef(null),l=Tt(o,m),h=Po(n),[g,p]=Qt({prop:s,defaultProp:c??null,onChange:i,caller:kr}),[w,x]=be.useState(false),v=Ju(d),L=Zu(t),I=be.useRef(false),[k,S]=be.useState(0);return be.useEffect(()=>{let b=m.current;if(b)return b.addEventListener(Zi,v),()=>b.removeEventListener(Zi,v)},[v]),jsx(Cb,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:g,onItemFocus:be.useCallback(b=>p(b),[p]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>S(b=>b+1),[]),onFocusableItemRemove:be.useCallback(()=>S(b=>b-1),[]),children:jsx(rt.div,{tabIndex:w||k===0?-1:0,"data-orientation":a,...u,ref:l,style:{outline:"none",...e.style},onMouseDown:$e(e.onMouseDown,()=>{I.current=true;}),onFocus:$e(e.onFocus,b=>{let A=!I.current;if(b.target===b.currentTarget&&A&&!w){let V=new CustomEvent(Zi,Lb);if(b.currentTarget.dispatchEvent(V),!V.defaultPrevented){let R=L().filter(E=>E.focusable),H=R.find(E=>E.active),q=R.find(E=>E.id===g),W=[H,q,...R].filter(Boolean).map(E=>E.ref.current);ac(W,f);}}I.current=false;}),onBlur:$e(e.onBlur,()=>x(false))})})}),ec="RovingFocusGroupItem",tc=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:s,...c}=e,i=Yu(),d=n||i,f=kb(ec,t),u=f.currentTabStopId===d,m=Zu(t),{onFocusableItemAdd:l,onFocusableItemRemove:h,currentTabStopId:g}=f;return be.useEffect(()=>{if(a)return l(),()=>h()},[a,l,h]),jsx(Qi.ItemSlot,{scope:t,id:d,focusable:a,active:r,children:jsx(rt.span,{tabIndex:u?0:-1,"data-orientation":f.orientation,...c,ref:o,onMouseDown:$e(e.onMouseDown,p=>{a?f.onItemFocus(d):p.preventDefault();}),onFocus:$e(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:$e(e.onKeyDown,p=>{if(p.key==="Tab"&&p.shiftKey){f.onItemShiftTab();return}if(p.target!==p.currentTarget)return;let w=Pb(p,f.orientation,f.dir);if(w!==void 0){if(p.metaKey||p.ctrlKey||p.altKey||p.shiftKey)return;p.preventDefault();let v=m().filter(L=>L.focusable).map(L=>L.ref.current);if(w==="last")v.reverse();else if(w==="prev"||w==="next"){w==="prev"&&v.reverse();let L=v.indexOf(p.currentTarget);v=f.loop?Rb(v,L+1):v.slice(L+1);}setTimeout(()=>ac(v));}}),children:typeof s=="function"?s({isCurrentTabStop:u,hasTabStop:g!=null}):s})})});tc.displayName=ec;var Tb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Ab(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Pb(e,o,t){let a=Ab(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Tb[a]}function ac(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Rb(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var oc=Qu,rc=tc;var sc="Toggle",tl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[s,c]=Qt({prop:t,onChange:r,defaultProp:a??false,caller:sc});return jsx(rt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:$e(e.onClick,()=>{e.disabled||c(!s);})})});tl.displayName=sc;var La="ToggleGroup",[lc]=wa(La,[el]),dc=el(),al=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Fb,{...a,ref:o});if(t==="multiple")return jsx(Bb,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${La}\``)});al.displayName=La;var[uc,cc]=lc(La),Fb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=Qt({prop:t,defaultProp:a??"",onChange:r,caller:La});return jsx(uc,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:c,onItemDeactivate:be__default.useCallback(()=>c(""),[c]),children:jsx(fc,{...n,ref:o})})}),Bb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=Qt({prop:t,defaultProp:a??[],onChange:r,caller:La}),i=be__default.useCallback(f=>c((u=[])=>[...u,f]),[c]),d=be__default.useCallback(f=>c((u=[])=>u.filter(m=>m!==f)),[c]);return jsx(uc,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:d,children:jsx(fc,{...n,ref:o})})});al.displayName=La;var[Ob,Nb]=lc(La),fc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:s,loop:c=true,...i}=e,d=dc(t),f=Po(s),u={role:"group",dir:f,...i};return jsx(Ob,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(oc,{asChild:true,...d,orientation:n,dir:f,loop:c,children:jsx(rt.div,{...u,ref:o})}):jsx(rt.div,{...u,ref:o})})}),es="ToggleGroupItem",Vb=be__default.forwardRef((e,o)=>{let t=cc(es,e.__scopeToggleGroup),a=Nb(es,e.__scopeToggleGroup),r=dc(e.__scopeToggleGroup),n=t.value.includes(e.value),s=a.disabled||e.disabled,c={...e,pressed:n,disabled:s},i=be__default.useRef(null);return a.rovingFocus?jsx(rc,{asChild:true,...r,focusable:!s,active:n,ref:i,children:jsx(ic,{...c,ref:o})}):jsx(ic,{...c,ref:o})});Vb.displayName=es;var ic=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=cc(es,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=n.type==="single"?s:void 0;return jsx(tl,{...c,...r,ref:o,onPressedChange:i=>{i?n.onItemActivate(a):n.onItemDeactivate(a);}})}),mc=al;function pc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(o=0;o<r;o++)e[o]&&(t=pc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function ts(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=pc(e))&&(a&&(a+=" "),a+=o);return a}var Hb=(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},Ub=(e,o)=>({classGroupId:e,validator:o}),vc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var hc=[],Wb="arbitrary..",zb=e=>{let o=Kb(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return Gb(s);let c=s.split("-"),i=c[0]===""&&c.length>1?1:0;return yc(c,i,o)},getConflictingClassGroupIds:(s,c)=>{if(c){let i=a[s],d=t[s];return i?d?Hb(d,i):i:d||hc}return t[s]||hc}}},yc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let d=yc(e,o+1,n);if(d)return d}let s=t.validators;if(s===null)return;let c=o===0?e.join("-"):e.slice(o).join("-"),i=s.length;for(let d=0;d<i;d++){let f=s[d];if(f.validator(c))return f.classGroupId}},Gb=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?Wb+a:void 0})(),Kb=e=>{let{theme:o,classGroups:t}=e;return _b(t,o)},_b=(e,o)=>{let t=vc();for(let a in e){let r=e[a];nl(r,t,a,o);}return t},nl=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let s=e[n];jb(s,o,t,a);}},jb=(e,o,t,a)=>{if(typeof e=="string"){$b(e,o,t);return}if(typeof e=="function"){Xb(e,o,t,a);return}Yb(e,o,t,a);},$b=(e,o,t)=>{let a=e===""?o:wc(o,e);a.classGroupId=t;},Xb=(e,o,t,a)=>{if(Jb(e)){nl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Ub(t,e));},Yb=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let s=0;s<n;s++){let[c,i]=r[s];nl(i,wc(o,c),t,a);}},wc=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let n=0;n<r;n++){let s=a[n],c=t.nextPart.get(s);c||(c=vc(),t.nextPart.set(s,c)),t=c;}return t},Jb=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Zb=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(n,s)=>{t[n]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(n){let s=t[n];if(s!==void 0)return s;if((s=a[n])!==void 0)return r(n,s),s},set(n,s){n in t?t[n]=s:r(n,s);}}};var Qb=[],gc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),ev=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],s=0,c=0,i=0,d,f=r.length;for(let g=0;g<f;g++){let p=r[g];if(s===0&&c===0){if(p===":"){n.push(r.slice(i,g)),i=g+1;continue}if(p==="/"){d=g;continue}}p==="["?s++:p==="]"?s--:p==="("?c++:p===")"&&c--;}let u=n.length===0?r:r.slice(i),m=u,l=false;u.endsWith("!")?(m=u.slice(0,-1),l=true):u.startsWith("!")&&(m=u.slice(1),l=true);let h=d&&d>i?d-i:void 0;return gc(n,l,m,h)};if(o){let r=o+":",n=a;a=s=>s.startsWith(r)?n(s.slice(r.length)):gc(Qb,false,s,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},tv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let n=0;n<t.length;n++){let s=t[n],c=s[0]==="[",i=o.has(s);c||i?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(s)):r.push(s);}return r.length>0&&(r.sort(),a.push(...r)),a}},av=e=>({cache:Zb(e.cacheSize),parseClassName:ev(e),sortModifiers:tv(e),...zb(e)}),ov=/\s+/,rv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,s=[],c=e.trim().split(ov),i="";for(let d=c.length-1;d>=0;d-=1){let f=c[d],{isExternal:u,modifiers:m,hasImportantModifier:l,baseClassName:h,maybePostfixModifierPosition:g}=t(f);if(u){i=f+(i.length>0?" "+i:i);continue}let p=!!g,w=a(p?h.substring(0,g):h);if(!w){if(!p){i=f+(i.length>0?" "+i:i);continue}if(w=a(h),!w){i=f+(i.length>0?" "+i:i);continue}p=false;}let x=m.length===0?"":m.length===1?m[0]:n(m).join(":"),v=l?x+"!":x,L=v+w;if(s.indexOf(L)>-1)continue;s.push(L);let I=r(w,p);for(let k=0;k<I.length;++k){let S=I[k];s.push(v+S);}i=f+(i.length>0?" "+i:i);}return i},nv=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=Lc(t))&&(r&&(r+=" "),r+=a);return r},Lc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Lc(e[a]))&&(t&&(t+=" "),t+=o);return t},sv=(e,...o)=>{let t,a,r,n,s=i=>{let d=o.reduce((f,u)=>u(f),e());return t=av(d),a=t.cache.get,r=t.cache.set,n=c,c(i)},c=i=>{let d=a(i);if(d)return d;let f=rv(i,t);return r(i,f),f};return n=s,(...i)=>n(nv(...i))},iv=[],Ve=e=>{let o=t=>t[e]||iv;return o.isThemeGetter=true,o},Ic=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Sc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,lv=/^\d+\/\d+$/,dv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,uv=/\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$/,cv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,fv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,mv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ro=e=>lv.test(e),ie=e=>!!e&&!Number.isNaN(Number(e)),Ia=e=>!!e&&Number.isInteger(Number(e)),ol=e=>e.endsWith("%")&&ie(e.slice(0,-1)),ea=e=>dv.test(e),pv=()=>true,hv=e=>uv.test(e)&&!cv.test(e),Cc=()=>false,gv=e=>fv.test(e),xv=e=>mv.test(e),bv=e=>!j(e)&&!$(e),vv=e=>Do(e,Tc,Cc),j=e=>Ic.test(e),ja=e=>Do(e,Ac,hv),rl=e=>Do(e,Sv,ie),xc=e=>Do(e,kc,Cc),yv=e=>Do(e,Mc,xv),as=e=>Do(e,Pc,gv),$=e=>Sc.test(e),Mr=e=>Eo(e,Ac),wv=e=>Eo(e,Cv),bc=e=>Eo(e,kc),Lv=e=>Eo(e,Tc),Iv=e=>Eo(e,Mc),os=e=>Eo(e,Pc,true),Do=(e,o,t)=>{let a=Ic.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Eo=(e,o,t=false)=>{let a=Sc.exec(e);return a?a[1]?o(a[1]):t:false},kc=e=>e==="position"||e==="percentage",Mc=e=>e==="image"||e==="url",Tc=e=>e==="length"||e==="size"||e==="bg-size",Ac=e=>e==="length",Sv=e=>e==="number",Cv=e=>e==="family-name",Pc=e=>e==="shadow";var kv=()=>{let e=Ve("color"),o=Ve("font"),t=Ve("text"),a=Ve("font-weight"),r=Ve("tracking"),n=Ve("leading"),s=Ve("breakpoint"),c=Ve("container"),i=Ve("spacing"),d=Ve("radius"),f=Ve("shadow"),u=Ve("inset-shadow"),m=Ve("text-shadow"),l=Ve("drop-shadow"),h=Ve("blur"),g=Ve("perspective"),p=Ve("aspect"),w=Ve("ease"),x=Ve("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...L(),$,j],k=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],b=()=>[$,j,i],A=()=>[Ro,"full","auto",...b()],V=()=>[Ia,"none","subgrid",$,j],R=()=>["auto",{span:["full",Ia,$,j]},Ia,$,j],H=()=>[Ia,"auto",$,j],q=()=>["auto","min","max","fr",$,j],P=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],W=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...b()],oe=()=>[Ro,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],N=()=>[e,$,j],fe=()=>[...L(),bc,xc,{position:[$,j]}],z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],O=()=>["auto","cover","contain",Lv,vv,{size:[$,j]}],X=()=>[ol,Mr,ja],U=()=>["","none","full",d,$,j],K=()=>["",ie,Mr,ja],Q=()=>["solid","dashed","dotted","double"],te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[ie,ol,bc,xc],de=()=>["","none",h,$,j],Y=()=>["none",ie,$,j],Me=()=>["none",ie,$,j],De=()=>[ie,$,j],Se=()=>[Ro,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ea],breakpoint:[ea],color:[pv],container:[ea],"drop-shadow":[ea],ease:["in","out","in-out"],font:[bv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ea],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ea],shadow:[ea],spacing:["px",ie],text:[ea],"text-shadow":[ea],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ro,j,$,p]}],container:["container"],columns:[{columns:[ie,j,$,c]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"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:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:A()}],"inset-x":[{"inset-x":A()}],"inset-y":[{"inset-y":A()}],start:[{start:A()}],end:[{end:A()}],top:[{top:A()}],right:[{right:A()}],bottom:[{bottom:A()}],left:[{left:A()}],visibility:["visible","invisible","collapse"],z:[{z:[Ia,"auto",$,j]}],basis:[{basis:[Ro,"full","auto",c,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ie,Ro,"auto","initial","none",j]}],grow:[{grow:["",ie,$,j]}],shrink:[{shrink:["",ie,$,j]}],order:[{order:[Ia,"first","last","none",$,j]}],"grid-cols":[{"grid-cols":V()}],"col-start-end":[{col:R()}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":V()}],"row-start-end":[{row:R()}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":q()}],"auto-rows":[{"auto-rows":q()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...P(),"normal"]}],"justify-items":[{"justify-items":[...W(),"normal"]}],"justify-self":[{"justify-self":["auto",...W()]}],"align-content":[{content:["normal",...P()]}],"align-items":[{items:[...W(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...W(),{baseline:["","last"]}]}],"place-content":[{"place-content":P()}],"place-items":[{"place-items":[...W(),"baseline"]}],"place-self":[{"place-self":["auto",...W()]}],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:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:oe()}],w:[{w:[c,"screen",...oe()]}],"min-w":[{"min-w":[c,"screen","none",...oe()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[s]},...oe()]}],h:[{h:["screen","lh",...oe()]}],"min-h":[{"min-h":["screen","lh","none",...oe()]}],"max-h":[{"max-h":["screen","lh",...oe()]}],"font-size":[{text:["base",t,Mr,ja]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,rl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ol,j]}],"font-family":[{font:[wv,j,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,$,j]}],"line-clamp":[{"line-clamp":[ie,"none",$,rl]}],leading:[{leading:[n,...b()]}],"list-image":[{"list-image":["none",$,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Q(),"wavy"]}],"text-decoration-thickness":[{decoration:[ie,"from-font","auto",$,ja]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[ie,"auto",$,j]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,j]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:fe()}],"bg-repeat":[{bg:z()}],"bg-size":[{bg:O()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ia,$,j],radial:["",$,j],conic:[Ia,$,j]},Iv,yv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:X()}],"gradient-via-pos":[{via:X()}],"gradient-to-pos":[{to:X()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:U()}],"rounded-s":[{"rounded-s":U()}],"rounded-e":[{"rounded-e":U()}],"rounded-t":[{"rounded-t":U()}],"rounded-r":[{"rounded-r":U()}],"rounded-b":[{"rounded-b":U()}],"rounded-l":[{"rounded-l":U()}],"rounded-ss":[{"rounded-ss":U()}],"rounded-se":[{"rounded-se":U()}],"rounded-ee":[{"rounded-ee":U()}],"rounded-es":[{"rounded-es":U()}],"rounded-tl":[{"rounded-tl":U()}],"rounded-tr":[{"rounded-tr":U()}],"rounded-br":[{"rounded-br":U()}],"rounded-bl":[{"rounded-bl":U()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Q(),"hidden","none"]}],"divide-style":[{divide:[...Q(),"hidden","none"]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...Q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ie,$,j]}],"outline-w":[{outline:["",ie,Mr,ja]}],"outline-color":[{outline:N()}],shadow:[{shadow:["","none",f,os,as]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":["none",u,os,as]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[ie,ja]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":["none",m,os,as]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[ie,$,j]}],"mix-blend":[{"mix-blend":[...te(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":te()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ie]}],"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":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"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":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"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":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"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":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"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":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"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":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"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":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,j]}],"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":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[ie]}],"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":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:fe()}],"mask-repeat":[{mask:z()}],"mask-size":[{mask:O()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,j]}],filter:[{filter:["","none",$,j]}],blur:[{blur:de()}],brightness:[{brightness:[ie,$,j]}],contrast:[{contrast:[ie,$,j]}],"drop-shadow":[{"drop-shadow":["","none",l,os,as]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:["",ie,$,j]}],"hue-rotate":[{"hue-rotate":[ie,$,j]}],invert:[{invert:["",ie,$,j]}],saturate:[{saturate:[ie,$,j]}],sepia:[{sepia:["",ie,$,j]}],"backdrop-filter":[{"backdrop-filter":["","none",$,j]}],"backdrop-blur":[{"backdrop-blur":de()}],"backdrop-brightness":[{"backdrop-brightness":[ie,$,j]}],"backdrop-contrast":[{"backdrop-contrast":[ie,$,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ie,$,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ie,$,j]}],"backdrop-invert":[{"backdrop-invert":["",ie,$,j]}],"backdrop-opacity":[{"backdrop-opacity":[ie,$,j]}],"backdrop-saturate":[{"backdrop-saturate":[ie,$,j]}],"backdrop-sepia":[{"backdrop-sepia":["",ie,$,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ie,"initial",$,j]}],ease:[{ease:["linear","initial",w,$,j]}],delay:[{delay:[ie,$,j]}],animate:[{animate:["none",x,$,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,j]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:Y()}],"rotate-x":[{"rotate-x":Y()}],"rotate-y":[{"rotate-y":Y()}],"rotate-z":[{"rotate-z":Y()}],scale:[{scale:Me()}],"scale-x":[{"scale-x":Me()}],"scale-y":[{"scale-y":Me()}],"scale-z":[{"scale-z":Me()}],"scale-3d":["scale-3d"],skew:[{skew:De()}],"skew-x":[{"skew-x":De()}],"skew-y":[{"skew-y":De()}],transform:[{transform:[$,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Se()}],"translate-x":[{"translate-x":Se()}],"translate-y":[{"translate-y":Se()}],"translate-z":[{"translate-z":Se()}],"translate-none":["translate-none"],accent:[{accent:N()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,j]}],"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",$,j]}],fill:[{fill:["none",...N()]}],"stroke-w":[{stroke:[ie,Mr,ja,rl]}],stroke:[{stroke:["none",...N()]}],"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 Rc=sv(kv);function Sa(...e){return Rc(ts(e))}var Tv=be.createContext({size:"default",variant:"default",spacing:0});function Ca({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(mc,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Sa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(Tv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var Pv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Oc=createSlice({name:"toolbar",initialState:Pv,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:Wt,setPenColor:rs,setStrokeWidth:il,setFontSize:zA,setFontFamily:GA,setFontStyle:KA,setFontWeight:_A,setTextDecoration:jA,setTextColor:$A}=Oc.actions,Nc=Oc.reducer;var Vc=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,n]=useState(null),[s,c]=useState(0),[i,d]=useState(null),[f,u]=useState(false),m=useRef(null),l=useRef([]),h=useRef(null),g=useRef(null),p=useRef(null);useEffect(()=>((async()=>{try{let b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});d(b),u(!0),p.current&&(p.current.srcObject=b);}catch(b){console.error("Error accessing camera:",b),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{h.current&&clearInterval(h.current),i&&i.getTracks().forEach(b=>b.stop());}),[]);let w=()=>{i&&(i.getTracks().forEach(S=>S.stop()),d(null),u(false));},x=async()=>{try{let S=null,b=null;try{S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(q){console.error("Error accessing camera for recording:",q),alert("Failed to access camera for recording.");return}try{b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(q){console.warn("Microphone access denied:",q);}let A=[...S.getVideoTracks()];b&&A.push(...b.getAudioTracks());let V=new MediaStream(A),R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8");let H=new MediaRecorder(V,{mimeType:R,videoBitsPerSecond:25e5});m.current=H,l.current=[],H.ondataavailable=q=>{q.data.size>0&&l.current.push(q.data);},H.onstop=()=>{let q=new Blob(l.current,{type:R}),P=document.createElement("video");P.src=URL.createObjectURL(q),P.muted=!0,P.currentTime=.1,P.onseeked=()=>{let W=document.createElement("canvas");W.width=P.videoWidth,W.height=P.videoHeight;let E=W.getContext("2d");E&&(E.drawImage(P,0,0),g.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(P.src);},V.getTracks().forEach(W=>W.stop()),S&&S.getTracks().forEach(W=>W.stop()),b&&b.getTracks().forEach(W=>W.stop()),h.current&&clearInterval(h.current),n(q),w();},H.onerror=q=>{console.error("MediaRecorder error:",q);},H.start(1e3),a(!0),c(0),h.current=setInterval(()=>{c(q=>q+1);},1e3);}catch(S){console.error("Error starting camera recording:",S),alert("Failed to start recording. Please check permissions.");}},v=()=>{m.current&&t&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),a(false));},L=()=>{if(r){let S=URL.createObjectURL(r),b=document.createElement("a");b.href=S,b.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(S);}},I=S=>{let b=Math.floor(S/60),A=S%60;return `${b.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`},k=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50 p-6",onMouseDown:S=>{S.target===S.currentTarget&&e(),S.stopPropagation();},onMouseUp:S=>S.stopPropagation(),onMouseMove:S=>S.stopPropagation(),onTouchStart:S=>S.stopPropagation(),onTouchMove:S=>S.stopPropagation(),onTouchEnd:S=>S.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:S=>S.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:p,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!t&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:x,disabled:!f,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"})})}),!f&&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"})})]}),t&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:v,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:I(s)})]})]})]}),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: ",I(s)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),c(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&&g.current&&(o(r,g.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,document.body)};var ta=40,Hc=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,s]=useState(t?.order||"sequential"),[c,i]=useState(false),d=useRef(null),f=useRef(null);useEffect(()=>{let x=v=>{v.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let u=x=>{let v=x.target.files;if(!v||v.length===0)return;let L=ta-a.length;if(L<=0){alert(`You can only upload a maximum of ${ta} images`);return}let I=Array.from(v).slice(0,L);I.length<v.length&&alert(`Only ${L} more images can be added (max ${ta} total)`);let k=I.map(S=>new Promise((b,A)=>{let V=new FileReader;V.onload=R=>{R.target?.result?b(R.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(S);}));Promise.all(k).then(S=>{r(b=>[...b,...S]),f.current&&(f.current.value="");});},m=x=>{x.preventDefault(),i(false);let v=Array.from(x.dataTransfer.files).filter(S=>S.type.startsWith("image/"));if(v.length===0)return;let L=ta-a.length;if(L<=0){alert(`You can only upload a maximum of ${ta} images`);return}let I=v.slice(0,L);I.length<v.length&&alert(`Only ${L} more images can be added (max ${ta} total)`);let k=I.map(S=>new Promise((b,A)=>{let V=new FileReader;V.onload=R=>{R.target?.result?b(R.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(S);}));Promise.all(k).then(S=>{r(b=>[...b,...S]);});},l=x=>{x.preventDefault(),i(true);},h=()=>{i(false);},g=x=>{r(v=>v.filter((L,I)=>I!==x));},w=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 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:d,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:x=>{if(x.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,n,t?.id);},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>=ta?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ta," images"]}):jsxs("span",{children:[a.length,"/",ta," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:u,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:l,onDragLeave:h,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${c?"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$1,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:c?"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 ${n==="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 ${n==="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 ${n==="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 ${n==="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,v)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${v+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>g(v),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:v+1})]},v))})]}),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(w,document.body)};var ns={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},_v={enabled:true};function ul(e){return e?{tools:{...ns.tools,...e.tools},actions:{...ns.actions,...e.actions}}:ns}var jv={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},$v={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var wy=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:r}={})=>{let n=xe(),s=ee(F=>F.canvas.slides.find(ne=>ne.id===F.canvas.currentSlideId)),c=s?.videos||[],i=s?.editingFlashcard,d=ee(F=>F.toolbar.selectedTool),f=ee(F=>F.toolbar.penColor),u=s?.showMcqForm,m=s?.showFlashcardForm,l=useMemo(()=>ul(r),[r]),{tools:h,actions:g}=l,p=c.some(F=>F.isRecorded&&F.isPlaying),w=ee(F=>F.toolbar.fontSize),x=ee(F=>F.toolbar.fontFamily),v=ee(F=>F.toolbar.fontStyle),L=ee(F=>F.toolbar.fontWeight),I=ee(F=>F.toolbar.textDecoration),k=ee(F=>F.toolbar.textColor),[S,b]=useState(false),[A,V]=useState(false),[R,H]=useState(false),[q,P]=useState(false),[W,E]=useState(false),oe=useRef(null),N=useRef(null),fe=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),z=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"}],[]),O=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],[]),X=useMemo(()=>fe.filter(F=>{let ne=h[F.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[h,fe]),U=useMemo(()=>{let F=h.shapes;return F===false?[]:F===true?z:Array.isArray(F)?z.filter(ne=>F.includes(ne.name)):z},[h.shapes,z]),K=useMemo(()=>{let F=h.activities;return F===false?[]:F===true?O:Array.isArray(F)?O.filter(ne=>F.includes(ne.name)):O},[h.activities,O]),Q=useMemo(()=>{let F=h.media;return F===false?{photoFrame:false,image:false,video:false}:F===true?{photoFrame:true,image:true,video:true}:Array.isArray(F)?{photoFrame:F.includes("photo-frame"),image:F.includes("image"),video:F.includes("video")}:{photoFrame:true,image:true,video:true}},[h.media]),te=useMemo(()=>{let F=h.activities;return F===false?false:F===true?true:Array.isArray(F)?F.includes("flashcard"):true},[h.activities]),J=F=>{let ne=F.target.files;!ne||ne.length===0||(n(Wt("select")),n(it(false)),P(false),Array.from(ne).forEach(ve=>{let he=new FileReader;he.onload=se=>{let re=new window.Image;re.src=se.target?.result,re.onload=()=>{let Te=re.width/re.height,Dt=300,Yt=300,st=re.width,Ee=re.height;st>Dt&&(st=Dt,Ee=st/Te),Ee>Yt&&(Ee=Yt,st=Ee*Te),n(le());let qe=(window.innerWidth-st)/2,ht=(window.innerHeight-Ee)/2;n(Ts({id:v4(),src:re.src,x:qe,y:ht,width:st,height:Ee,draggable:true,rotation:0}));};},he.readAsDataURL(ve);}),F.target.value="");},de=async F=>{let ne=F.target.files;if(!(!ne||ne.length===0)){console.log("files",F),n(Wt("select")),n(it(false)),P(false);for(let ve of Array.from(ne))try{let he=URL.createObjectURL(ve),se=document.createElement("video");console.log("video",se),se.src=he,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((Et,ra)=>{let Ft=setTimeout(()=>ra(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ft),Et();},se.onerror=()=>{clearTimeout(Ft),ra(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Et,ra)=>{let Ft=setTimeout(()=>ra(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ft),Et()):se.onloadeddata=()=>{clearTimeout(Ft),Et();};});let re=Math.min(.8,se.duration/2);console.log("Seeking to:",re),se.currentTime=re,await new Promise(Et=>{let ra=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Et();},5e3);se.onseeked=()=>{clearTimeout(ra),console.log("Seek completed"),Et();};});let Te=document.createElement("canvas"),Dt=se.videoWidth/se.videoHeight,Yt=400,st=400,Ee=se.videoWidth,qe=se.videoHeight;Ee>Yt&&(Ee=Yt,qe=Ee/Dt),qe>st&&(qe=st,Ee=qe*Dt),Te.width=Ee,Te.height=qe;let ht=Te.getContext("2d",{willReadFrequently:!1});if(!ht)throw new Error("Failed to get canvas context");if(await new Promise(Et=>setTimeout(Et,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ee,height:qe}),ht.drawImage(se,0,0,Ee,qe);let Ta=Te.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Ta.length),n(le());let Za=(window.innerWidth-Ee)/2,Qa=(window.innerHeight-qe)/2,Aa=v4();await Ga(Aa,ve,Ta),n(Gr({id:Aa,objectUrl:he,thumbnailDataUrl:Ta,videoBlob:ve,x:Za,y:Qa,width:Ee,height:qe,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${ve.name}`);}catch(he){console.error("Error processing video:",he),alert(`Failed to process video: ${ve.name}`);}F.target.value="";}},Y=(F,ne,ve)=>{n(le()),n(Wt("select")),n(it(false));let he=300,se=300,re=(window.innerWidth-he)/2,Te=(window.innerHeight-se)/2;n(ve?ro({id:ve,images:F,order:ne,x:re,y:Te,width:he,height:se,rotation:0,draggable:true}):Rs({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:F,currentIndex:0,order:ne,x:re,y:Te,width:he,height:se,rotation:0,draggable:true})),n(Ra(false));},Me=()=>{n(le()),n(Wt("select")),n(it(false));let F=400,ne=300,ve=(window.innerWidth-F)/2,he=(window.innerHeight-ne)/2;n(Fs({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ve,y:he,width:F,height:ne,rotation:0,draggable:true,isCapturing:false})),E(false);},De=F=>{let he=(window.innerWidth-100)/2,se=(window.innerHeight-100)/2,re={};switch(F.name){case "circle":case "ring":case "wedge":case "arc":re.radius=50,(F.name==="ring"||F.name==="arc")&&(re.innerRadius=25,re.outerRadius=50),(F.name==="wedge"||F.name==="arc")&&(re.angle=F.name==="wedge"?60:90);break;case "ellipse":re.radiusX=60,re.radiusY=40;break;case "triangle":re.radius=50,re.sides=3;break;case "polygon":re.radius=50,re.sides=6;break;case "star":re.innerRadius=25,re.outerRadius=50,re.numPoints=5;break;case "arrow":case "line":re.points=[0,0,100,0],F.name==="arrow"&&(re.pointerLength=10,re.pointerWidth=10);break}let Te={id:`shape-${Date.now()}`,type:F.name,x:he,y:se,width:100,height:100,rotation:0,color:f,...re};n(le()),n(it(false)),n(Wt(F.name)),n(As(Te));},Se=F=>{if(n(Wt(F)),F==="select")n(it(false));else if(F==="text"){n(it(false)),n(le());let ne=200,ve=50,he=(window.innerWidth-ne)/2,se=(window.innerHeight-ve)/2,re=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;n(Ps({id:re,text:"",x:he,y:se,width:ne,height:ve,rotation:0,draggable:true,fontSize:w,fontFamily:x,fontStyle:v,fontWeight:L,textDecoration:I,fill:k,align:"left"})),setTimeout(()=>{n(jo(re));},100),a&&a(re);}else n(it(true));},Rt=()=>{n(Ys()),n(Wt("select")),n(it(false));},Ja=()=>{o?o():t?b(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Er=()=>{V(true);},Fr=async(F,ne)=>{try{n(Wt("select")),n(it(!1));let ve=URL.createObjectURL(F),he=document.createElement("video");he.src=ve,he.muted=!0,he.playsInline=!0,he.preload="auto",await new Promise((Ta,Za)=>{let Qa=setTimeout(()=>Za(new Error("Metadata load timeout")),1e4);he.onloadedmetadata=()=>{clearTimeout(Qa),Ta();},he.onerror=()=>{clearTimeout(Qa),Za(new Error("Failed to load video"));};});let se=640,re=he.videoWidth/he.videoHeight,Te=se,Dt=Te/re,Yt=window.innerWidth,st=window.innerHeight;n(le());let Ee=(Yt-Te)/2,qe=(st-Dt)/2,ht=v4();await Ga(ht,F,ne),n(Gr({id:ht,objectUrl:ve,thumbnailDataUrl:ne,videoBlob:F,x:Ee,y:qe,width:Te,height:Dt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),b(!1),V(!1);}catch(ve){console.error("Error adding recorded video to canvas:",ve),alert("Failed to add video to canvas. Please try again.");}},fs=F=>{n(Wt("select")),n(it(false)),n(Ko(null)),F&&n(Gs(F)),n(da(!u));},ms=()=>{n(Uo(null)),n(Ra(true)),E(false);},ps=()=>{H(!R);},hs=()=>{P(!q);},Ma=()=>{E(!W);};return p?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Ca,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:X.map((F,ne)=>jsx("div",{title:F.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 2xl:py-3 ${F.name===d?"bg-primary/10":""}`,onClick:()=>{if(F.name==="image"){hs(),H(false),E(false),Se(F.name);return}else if(F.name==="shapes"){ps(),P(false),E(false),Se(F.name);return}else if(F.name==="activities"){Se(F.name),Ma(),H(false),P(false);return}Se(F.name),H(false),P(false),E(false);},children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))}),R&&jsx(Ca,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:U.map((F,ne)=>jsx("div",{title:F.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",onClick:()=>De(F),children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))}),q&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Q.photoFrame&&jsx("div",{title:"Photo frame",onClick:Me,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),Q.image&&jsx("div",{title:"Image",onClick:()=>oe.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),Q.video&&jsx("div",{title:"Video",onClick:()=>N.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})})]}),W&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[te&&jsx("div",{title:"Flashcard",onClick:()=>ms(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),K.map((F,ne)=>jsx("div",{title:F.label,onClick:()=>fs(F.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))]})]}),(g.undo||g.redo||g.screenRecord||g.cameraRecord||g.clear)&&jsxs(Ca,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[g.undo&&jsx("button",{value:"undo",onClick:()=>n(Js()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.redo&&jsx("button",{value:"redo",onClick:()=>n(Zs()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.screenRecord&&jsx("button",{value:"screen-record",onClick:Ja,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6279F8]",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.cameraRecord&&jsx("button",{value:"camera-record",onClick:Er,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6BBB93]",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.clear&&jsx("button",{value:"clear",onClick:()=>Rt(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl 2xl:text-2xl"})})]})]}),jsx("input",{ref:oe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:J}),jsx("input",{ref:N,type:"file",accept:"video/*",className:"hidden",onChange:de}),!o&&S&&t&&jsx(or,{onClose:()=>b(false),stageRef:t,onRecordingComplete:Fr}),A&&jsx(Vc,{onClose:()=>V(false),onRecordingComplete:Fr}),m&&jsx(Hc,{editingFlashcard:i,onConfirm:Y,onCancel:()=>n(Ra(false))})]})},Ly=wy;var pl=({onPublish:e,label:o="Publish Slides",className:t})=>{let a=sa(Xo),s=(sa(h=>h.canvas.slides.find(g=>g.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),[c,i]=useState(false),[d,f]=useState(null),[u,m]=useState(null),l=async()=>{if(a.length===0){m({type:"error",message:"No slides to publish"});return}if(!e){m({type:"error",message:"No publish handler provided"});return}i(true),m(null);try{let h=await e(a,g=>{f(g);});h.success?m({type:"success",message:h.message}):m({type:"error",message:h.message});}catch(h){m({type:"error",message:h instanceof Error?h.message:"An unexpected error occurred"});}finally{i(false),setTimeout(()=>{f(null),m(null);},3e3);}};return s?null:jsxs("button",{onClick:l,disabled:c||a.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 Ty=({title:e="Untitled",autoSaveMessage:o="Auto-saved just now",onBack:t,onPublish:a,showPublishButton:r=true,showBackButton:n=true,className:s="",rightContent:c,leftContent:i})=>jsxs("div",{className:`fixed top-0 left-0 z-100 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${s}`,children:[i||jsxs("div",{className:"flex items-center gap-6",children:[n&&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 flex-col",children:[jsx("span",{className:"text-xl font-medium text-[#000000CC] md:text-2xl",children:e}),jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[jsx(CloudArrowUp,{weight:"fill",color:"#63748A",className:"text-sm md:text-xl"}),jsx("span",{className:"text-sm font-medium text-[#63748A] md:text-base",children:o})]})]})]}),c||r&&a&&jsx(pl,{onPublish:a})]});function hl(e,[o,t]){return Math.min(t,Math.max(o,e))}function zc(e){let o=be.useRef({value:e,previous:e});return be.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Kc(e){let[o,t]=be.useState(void 0);return To(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let n=r[0],s,c;if("borderBoxSize"in n){let i=n.borderBoxSize,d=Array.isArray(i)?i[0]:i;s=d.inlineSize,c=d.blockSize;}else s=e.offsetWidth,c=e.offsetHeight;t({width:s,height:c});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var _c=["PageUp","PageDown"],jc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],$c={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Oo="Slider",[gl,Py,Ry]=Jn(Oo),[Xc]=wa(Oo,[Ry]),[Dy,ls]=Xc(Oo),Yc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:s="horizontal",disabled:c=false,minStepsBetweenThumbs:i=0,defaultValue:d=[a],value:f,onValueChange:u=()=>{},onValueCommit:m=()=>{},inverted:l=false,form:h,...g}=e,p=be.useRef(new Set),w=be.useRef(0),v=s==="horizontal"?Ey:Fy,[L=[],I]=Qt({prop:f,defaultProp:d,onChange:R=>{[...p.current][w.current]?.focus(),u(R);}}),k=be.useRef(L);function S(R){let H=qy(L,R);V(R,H);}function b(R){V(R,w.current);}function A(){let R=k.current[w.current];L[w.current]!==R&&m(L);}function V(R,H,{commit:q}={commit:false}){let P=zy(n),W=Gy(Math.round((R-a)/n)*n+a,P),E=hl(W,[a,r]);I((oe=[])=>{let N=Ny(oe,E,H);if(Wy(N,i*n)){w.current=N.indexOf(E);let fe=String(N)!==String(oe);return fe&&q&&m(N),fe?N:oe}else return oe});}return jsx(Dy,{scope:e.__scopeSlider,name:t,disabled:c,min:a,max:r,valueIndexToChangeRef:w,thumbs:p.current,values:L,orientation:s,form:h,children:jsx(gl.Provider,{scope:e.__scopeSlider,children:jsx(gl.Slot,{scope:e.__scopeSlider,children:jsx(v,{"aria-disabled":c,"data-disabled":c?"":void 0,...g,ref:o,onPointerDown:$e(g.onPointerDown,()=>{c||(k.current=L);}),min:a,max:r,inverted:l,onSlideStart:c?void 0:S,onSlideMove:c?void 0:b,onSlideEnd:c?void 0:A,onHomeKeyDown:()=>!c&&V(a,0,{commit:true}),onEndKeyDown:()=>!c&&V(r,L.length-1,{commit:true}),onStepKeyDown:({event:R,direction:H})=>{if(!c){let W=_c.includes(R.key)||R.shiftKey&&jc.includes(R.key)?10:1,E=w.current,oe=L[E],N=n*W*H;V(oe+N,E,{commit:true});}}})})})})});Yc.displayName=Oo;var[Jc,Zc]=Xc(Oo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Ey=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:s,onSlideMove:c,onSlideEnd:i,onStepKeyDown:d,...f}=e,[u,m]=be.useState(null),l=Tt(o,v=>m(v)),h=be.useRef(void 0),g=Po(r),p=g==="ltr",w=p&&!n||!p&&n;function x(v){let L=h.current||u.getBoundingClientRect(),I=[0,L.width],S=vl(I,w?[t,a]:[a,t]);return h.current=L,S(v-L.left)}return jsx(Jc,{scope:e.__scopeSlider,startEdge:w?"left":"right",endEdge:w?"right":"left",direction:w?1:-1,size:"width",children:jsx(Qc,{dir:g,"data-orientation":"horizontal",...f,ref:l,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{let L=x(v.clientX);s?.(L);},onSlideMove:v=>{let L=x(v.clientX);c?.(L);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:v=>{let I=$c[w?"from-left":"from-right"].includes(v.key);d?.({event:v,direction:I?-1:1});}})})}),Fy=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:s,onSlideEnd:c,onStepKeyDown:i,...d}=e,f=be.useRef(null),u=Tt(o,f),m=be.useRef(void 0),l=!r;function h(g){let p=m.current||f.current.getBoundingClientRect(),w=[0,p.height],v=vl(w,l?[a,t]:[t,a]);return m.current=p,v(g-p.top)}return jsx(Jc,{scope:e.__scopeSlider,startEdge:l?"bottom":"top",endEdge:l?"top":"bottom",size:"height",direction:l?1:-1,children:jsx(Qc,{"data-orientation":"vertical",...d,ref:u,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{let p=h(g.clientY);n?.(p);},onSlideMove:g=>{let p=h(g.clientY);s?.(p);},onSlideEnd:()=>{m.current=void 0,c?.();},onStepKeyDown:g=>{let w=$c[l?"from-bottom":"from-top"].includes(g.key);i?.({event:g,direction:w?-1:1});}})})}),Qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:s,onEndKeyDown:c,onStepKeyDown:i,...d}=e,f=ls(Oo,t);return jsx(rt.span,{...d,ref:o,onKeyDown:$e(e.onKeyDown,u=>{u.key==="Home"?(s(u),u.preventDefault()):u.key==="End"?(c(u),u.preventDefault()):_c.concat(jc).includes(u.key)&&(i(u),u.preventDefault());}),onPointerDown:$e(e.onPointerDown,u=>{let m=u.target;m.setPointerCapture(u.pointerId),u.preventDefault(),f.thumbs.has(m)?m.focus():a(u);}),onPointerMove:$e(e.onPointerMove,u=>{u.target.hasPointerCapture(u.pointerId)&&r(u);}),onPointerUp:$e(e.onPointerUp,u=>{let m=u.target;m.hasPointerCapture(u.pointerId)&&(m.releasePointerCapture(u.pointerId),n(u));})})}),ef="SliderTrack",tf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ls(ef,t);return jsx(rt.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});tf.displayName=ef;var xl="SliderRange",af=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ls(xl,t),n=Zc(xl,t),s=be.useRef(null),c=Tt(o,s),i=r.values.length,d=r.values.map(m=>nf(m,r.min,r.max)),f=i>1?Math.min(...d):0,u=100-Math.max(...d);return jsx(rt.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:c,style:{...e.style,[n.startEdge]:f+"%",[n.endEdge]:u+"%"}})});af.displayName=xl;var bl="SliderThumb",of=be.forwardRef((e,o)=>{let t=Py(e.__scopeSlider),[a,r]=be.useState(null),n=Tt(o,c=>r(c)),s=be.useMemo(()=>a?t().findIndex(c=>c.ref.current===a):-1,[t,a]);return jsx(By,{...e,ref:n,index:s})}),By=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,s=ls(bl,t),c=Zc(bl,t),[i,d]=be.useState(null),f=Tt(o,x=>d(x)),u=i?s.form||!!i.closest("form"):true,m=Kc(i),l=s.values[a],h=l===void 0?0:nf(l,s.min,s.max),g=Vy(a,s.values.length),p=m?.[c.size],w=p?Hy(p,h,c.direction):0;return be.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",[c.startEdge]:`calc(${h}% + ${w}px)`},children:[jsx(gl.ItemSlot,{scope:e.__scopeSlider,children:jsx(rt.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":s.min,"aria-valuenow":l,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...n,ref:f,style:l===void 0?{display:"none"}:e.style,onFocus:$e(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),u&&jsx(rf,{name:r??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:l},a)]})});of.displayName=bl;var Oy="RadioBubbleInput",rf=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),n=Tt(r,a),s=zc(o);return be.useEffect(()=>{let c=r.current;if(!c)return;let i=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==o&&f){let u=new Event("input",{bubbles:true});f.call(c,o),c.dispatchEvent(u);}},[s,o]),jsx(rt.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});rf.displayName=Oy;function Ny(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function nf(e,o,t){let n=100/(t-o)*(e-o);return hl(n,[0,100])}function Vy(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function qy(e,o){if(e.length===1)return 0;let t=e.map(r=>Math.abs(r-o)),a=Math.min(...t);return t.indexOf(a)}function Hy(e,o,t){let a=e/2,n=vl([0,50],[0,a]);return (a-n(o)*t)*t}function Uy(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Wy(e,o){if(o>0){let t=Uy(e);return Math.min(...t)>=o}return true}function vl(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 zy(e){return (String(e).split(".")[1]||"").length}function Gy(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var sf=Yc,lf=tf,df=af,uf=of;function ff({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:s,thumbClassName:c,...i}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(sf,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Sa("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(lf,{"data-slot":"slider-track",className:Sa("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(df,{"data-slot":"slider-range",className:Sa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:d.length},(f,u)=>jsx(uf,{"data-slot":"slider-thumb",className:Sa("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",c)},u))]})}var $y=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Xy=({colors:e=$y,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let n=ee(c=>c.toolbar.penColor),s=xe();return jsxs("div",{className:`absolute bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:p-6 ${r}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(ff,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:c=>s(il(c[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(Ca,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(c=>jsx("button",{value:c.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${n===c.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:c.value},onClick:()=>s(rs(c.value))},c.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>s(rs(c.target.value))}),jsx(Plus,{color:"#00000099"})]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center px-2 2xl:px-4",children:jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033] lg:h-12 lg:w-12",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>s(ks(c.target.value))})})})]})};function Yy({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var pf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Zy=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),wl=e=>{let o=Zy(e);return o.charAt(0).toUpperCase()+o.slice(1)},ds=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),hf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var gf={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 bf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:s,...c},i)=>createElement("svg",{ref:i,...gf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:ds("lucide",r),...!n&&!hf(c)&&{"aria-hidden":"true"},...c},[...s.map(([d,f])=>createElement(d,f)),...Array.isArray(n)?n:[n]]));var us=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(bf,{ref:n,iconNode:o,className:ds(`lucide-${pf(wl(e))}`,`lucide-${e}`,a),...r}));return t.displayName=wl(e),t};var aw=[["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"}]],Rr=us("copy",aw);var ow=[["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"}]],Dr=us("trash-2",ow);var yf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:s})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"shadow-lg":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:r,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:c=>{c.stopPropagation(),n();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Rr,{size:14})}),!a&&jsx("button",{onClick:c=>{c.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(Dr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var iw=()=>{let e=yt(),o=sa(Xo),t=sa($o),a=sa(Qs),[r,n]=useState(true),i=(sa(l=>l.canvas.slides.find(h=>h.id===l.canvas.currentSlideId))?.videos||[]).some(l=>l.isRecorded&&l.isPlaying),d=()=>{a&&e(ws());},f=l=>{e(Ss(l));},u=l=>{e(Is(l));},m=l=>{o.length>1&&e(Ls(l));};return i?null:jsxs("div",{className:"pointer-events-none fixed top-22.5 right-0 bottom-0 z-100 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[o.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:o.map((l,h)=>jsx(yf,{slide:l,index:h,isSelected:l.id===t,isSingleSlide:o.length===1,onSelect:()=>f(l.id),onDuplicate:()=>u(l.id),onDelete:()=>m(l.id)},l.id))}),jsxs("button",{onClick:d,disabled:!a,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${a?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var lw="SchooplaEditorDB",dw=1,ka="slides",Ll="schoopla_current_slide_id",Il=()=>new Promise((e,o)=>{let t=indexedDB.open(lw,dw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(ka)||r.createObjectStore(ka,{keyPath:"id"});};}),Sl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Il(),a=o.transaction([ka],"readwrite").objectStore(ka);await new Promise((r,n)=>{let s=a.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);});for(let r of e)await new Promise((n,s)=>{let c=a.add(r);c.onsuccess=()=>n(!0),c.onerror=()=>s(c.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);}}},Cl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Il(),t=e.transaction([ka],"readonly").objectStore(ka);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.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(c=>({id:c.id,width:c.width,height:c.height,x:c.x,y:c.y}))),a(s.length>0?s:null);},n.onerror=()=>{e.close(),r(n.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}}},cs=async()=>{try{let e=await Il(),t=e.transaction([ka],"readwrite").objectStore(ka);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(Ll),await Uu();}catch(e){console.error("Error clearing local data:",e);}},kl=e=>{try{localStorage.setItem(Ll,e);}catch(o){console.error("Error saving current slide ID:",o);}},Ml=()=>{try{return localStorage.getItem(Ll)}catch(e){return console.error("Error loading current slide ID:",e),null}},If=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}};var uw=["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"],cw=["canvas/clearCanvas"],fw=If((e,o)=>{Sl(e),kl(o);},500),mw=(e,o)=>{Sl(e),kl(o);},Tl=false,Sf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;$i(r).catch(n=>{console.error("Error deleting video blob:",n);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,s=e.getState().canvas.slides.find(c=>c.id===r);s&&s.videos&&s.videos.length>0&&s.videos.forEach(c=>{$i(c.id).catch(i=>{console.error("Error deleting video blob:",i);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,n=e.getState(),c=n.canvas.slides.find(i=>i.id===n.canvas.currentSlideId)?.videos.find(i=>i.id===r);c&&c.videoBlob&&setTimeout(()=>{let i=e.getState(),f=i.canvas.slides.find(u=>u.id===i.canvas.currentSlideId)?.videos.find(u=>u.id!==r&&u.x===c.x+20&&u.y===c.y+20);f&&c.videoBlob&&Ga(f.id,c.videoBlob,f.thumbnailDataUrl).catch(u=>{console.error("Error saving duplicated video blob:",u);});},0);}let a=o(t);if(t.type&&cw.includes(t.type)){if(!Tl){Tl=true;try{let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;mw(n,s);}finally{setTimeout(()=>{Tl=false;},0);}}}else if(t.type&&uw.includes(t.type)){let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;fw(n,s);}return a});new QueryClient;var gw=configureStore({reducer:{toolbar:Nc,canvas:Gl},middleware:e=>e({serializableCheck:false}).concat(Sf)});var xw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:n=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",c=e.toDataURL({mimeType:s,quality:a,pixelRatio:r}),i=document.createElement("a");i.download=`${n}.${t}`,i.href=c,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")}},bw=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((n,s)=>{try{let c=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:c,quality:a,pixelRatio:r});fetch(i).then(d=>d.blob()).then(d=>n(d)).catch(d=>s(d));}catch(c){s(c);}})},vw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,n=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:n,quality:a,pixelRatio:r})};var yw=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let n=a*a+r*r,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/n)),c=o.x+s*a,i=o.y+s*r;return Math.sqrt(Math.pow(e.x-c,2)+Math.pow(e.y-i,2))},Al=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],n=e[e.length-1];for(let s=1;s<e.length-1;s++){let c=yw(e[s],r,n);c>t&&(t=c,a=s);}if(t>o){let s=Al(e.slice(0,a+1),o),c=Al(e.slice(a),o);return [...s.slice(0,-1),...c]}return [r,n]},ww=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},Lw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Cf=(e,o=1.5)=>{if(e.length<=4)return e;let t=ww(e),a=Al(t,o);return Lw(a)},kf=(e,o=1.5)=>({...e,points:Cf(e.points,o)}),Iw=(e,o=1.5)=>e.map(t=>kf(t,o)),Sw=(e,o)=>{let t=e.length/2,a=o.length/2,r=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${r}%`}};var Cw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Mf=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((n,s)=>{let c=new Image;c.onload=()=>{let{width:i,height:d}=c;if(i>t||d>a){let h=i/d;i>d?(i=Math.min(i,t),d=i/h):(d=Math.min(d,a),i=d*h);}let f=document.createElement("canvas");f.width=i,f.height=d;let u=f.getContext("2d");if(!u){s(new Error("Failed to get canvas context"));return}u.drawImage(c,0,0,i,d);let m=Cw(e),l=f.toDataURL(m,r);n(l);},c.onerror=s,c.src=e;})};var Ya=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return a.buffer},No=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Vo=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",kw=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,s=[],c=0;for(let i of e){let d=[],f=[],u=[];for(let m of i.images){let l=m.src;if(t&&l.startsWith("data:"))try{l=await Mf(l,{maxWidth:a,maxHeight:r,quality:n});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(l.startsWith("data:")){let h=Ya(l),g=No(l);c+=h.byteLength;let p={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,buffer:h,mimeType:g};if(m.audioData&&m.audioData.startsWith("data:")){let w=Ya(m.audioData),x=No(m.audioData);c+=w.byteLength,p.audioBuffer=w,p.audioMimeType=x;}d.push(p);}}for(let m of i.videos){let l,h;if(m.videoBlob)l=await m.videoBlob.arrayBuffer(),h=m.videoBlob.type;else if(m.videoData&&m.videoData.startsWith("data:"))l=Ya(m.videoData),h=No(m.videoData);else {console.warn(`Video ${m.id} has no blob or videoData, skipping`);continue}c+=l.byteLength;let g={id:m.id,thumbnailDataUrl:m.thumbnailDataUrl,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,isPlaying:m.isPlaying,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isRecorded:m.isRecorded,buffer:l,mimeType:h};if(m.audioData&&m.audioData.startsWith("data:")){let p=Ya(m.audioData),w=No(m.audioData);c+=p.byteLength,g.audioBuffer=p,g.audioMimeType=w;}f.push(g);}for(let m of i.photoFrames){let l={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:m.draggable,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isCapturing:m.isCapturing};if(m.capturedImageUrl&&m.capturedImageUrl.startsWith("data:")){let h=Ya(m.capturedImageUrl),g=No(m.capturedImageUrl);c+=h.byteLength,l.buffer=h,l.mimeType=g;}if(m.audioData&&m.audioData.startsWith("data:")){let h=Ya(m.audioData),g=No(m.audioData);c+=h.byteLength,l.audioBuffer=h,l.audioMimeType=g;}u.push(l);}s.push({...i,images:d,videos:f,photoFrames:u});}return {slides:s,totalSize:c}},Mw=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},Tw=e=>{let o=new FormData,t=e.slides.map((a,r)=>({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((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,mimeType:n.mimeType,fileKey:`slide_${r}_image_${s}`,audioFileKey:n.audioBuffer?`slide_${r}_image_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),videos:a.videos.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,isPlaying:n.isPlaying,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isRecorded:n.isRecorded,mimeType:n.mimeType,fileKey:`slide_${r}_video_${s}`,thumbnailFileKey:`slide_${r}_video_${s}_thumbnail`,audioFileKey:n.audioBuffer?`slide_${r}_video_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),photoFrames:a.photoFrames.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,draggable:n.draggable,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isCapturing:n.isCapturing,mimeType:n.mimeType,fileKey:n.buffer?`slide_${r}_photoframe_${s}`:void 0,audioFileKey:n.audioBuffer?`slide_${r}_photoframe_${s}_audio`:void 0,audioMimeType:n.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),i=`${n.id}.${Vo(n.mimeType)}`;if(o.append(`slide_${r}_image_${s}`,c,i),n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${Vo(n.audioMimeType)}`;o.append(`slide_${r}_image_${s}_audio`,d,f);}}),a.videos.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),i=`${n.id}.${Vo(n.mimeType)}`;if(o.append(`slide_${r}_video_${s}`,c,i),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let d=Ya(n.thumbnailDataUrl),f=new Blob([d],{type:"image/jpeg"}),u=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${s}_thumbnail`,f,u);}if(n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${Vo(n.audioMimeType)}`;o.append(`slide_${r}_video_${s}_audio`,d,f);}}),a.photoFrames.forEach((n,s)=>{if(n.buffer&&n.mimeType){let c=new Blob([n.buffer],{type:n.mimeType}),i=`${n.id}.${Vo(n.mimeType)}`;o.append(`slide_${r}_photoframe_${s}`,c,i);}if(n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),i=`${n.id}_audio.${Vo(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${s}_audio`,c,i);}});}),o};var Pw=()=>{let e=yt();useEffect(()=>{(async()=>{try{let t=await Cl(),a=Ml();if(t&&t.length>0){let r=await Hu(),n=t.map(c=>{if(c.videos&&c.videos.length>0){let i=c.videos.map(d=>{let f=r.get(d.id);if(f){let u=Wu(f.blob);return {...d,objectUrl:u,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return d});return {...c,videos:i}}return c}),s=a&&n.find(c=>c.id===a)?a:n[0].id;e(to({slides:n,currentSlideId:s}));}}catch(t){console.error("Error loading persisted slides:",t);}})();},[e]);};var Af=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||""})),Pf=new WeakSet,Rf=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 Ga(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},Rw=()=>{let e=yt(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Pf.has(a))return;Pf.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await cs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let c=n&&r.find(d=>d.id===n)?n:r[0].id,i=Af(r);e(to({slides:i,currentSlideId:c})),await Rf(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await cs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let c=n&&r.find(d=>d.id===n)?n:r[0].id,i=Af(r);e(to({slides:i,currentSlideId:c})),await Rf(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
|
|
6
|
+
This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:u?"none":"auto"}})}),jsx(Group,{y:I+k+R+S+b+V,children:u&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),w();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),w();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:q=>q.cancelBubble=true,onTap:q=>q.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});ji.displayName="LongAnswer";var Eu=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(ji,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id)},s.id))});var Wa=1920,za=1080,Nu=3840,Vu=2160,Yx=e=>{let o=0,t=0,a=Wa,r=za;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:Wa,height:za};let n=(i,d,f,u)=>{o=Math.min(o,i),t=Math.min(t,d),a=Math.max(a,i+f),r=Math.max(r,d+u);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let d=i.x||0,f=i.y||0,u=i.scaleX||1,m=i.scaleY||1;for(let l=0;l<i.points.length;l+=2){let h=d+i.points[l]*u,g=f+i.points[l+1]*m;o=Math.min(o,h),t=Math.min(t,g),a=Math.max(a,h),r=Math.max(r,g);}}}),e.images?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>n(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>n(i.x,i.y,i.width,i.height));let s=Math.min(a-o,Nu),c=Math.min(r-t,Vu);return o=Math.max(o,a-Nu),t=Math.max(t,r-Vu),{minX:o,minY:t,maxX:a,maxY:r,width:s,height:c}},Jx=(e,o,t={minX:0,minY:0,maxX:Wa,maxY:za,width:Wa,height:za})=>{let a=Math.max(t.width,Wa),r=Math.max(t.height,za),n=e/o,s=a/r,c,i,d,u=0;if(n>s){i=r,c=Math.round(i*n),d=o/i;}else {c=a,i=Math.round(c/n),d=e/c;let m=r*d;u=(o-m)/2;}return {scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:u,baseWidth:c,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},qu=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},Zx=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a}={})=>{let r=yt(),n=ee(y=>y.toolbar.selectedTool),s=ee(ge),c=ee($o),i=s?.editingActivity,d=s?.showMcqForm,f=s?.lines||[],u=useRef(null),m=useRef(null),[l,h]=useState(null),[g,p]=useState(""),w=useRef(null),[x,v]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Wa,stageHeight:za,offsetX:0,offsetY:0,baseWidth:Wa,baseHeight:za,contentOffsetX:0,contentOffsetY:0}),L=useMemo(()=>Yx(s||null),[c]),[I,k]=useState(null),[S,b]=useState(null),[A,V]=useState(null),[R,H]=useState(null),[q,P]=useState(null),[W,E]=useState(null),[oe,N]=useState(null),[fe,z]=useState(false),[O,X]=useState(null),[U,K]=useState(false),Q=useRef(null),te=useRef(null),J=useRef(null),{debouncedGenerateThumbnail:de}=vd(c,u);useEffect(()=>{let y=()=>{if(m.current){let T=m.current.getBoundingClientRect(),D=Jx(T.width,T.height,L);v(D);}};y();let C=new ResizeObserver(y);return m.current&&C.observe(m.current),window.addEventListener("resize",y),()=>{C.disconnect(),window.removeEventListener("resize",y);}},[L]),useEffect(()=>{if(u.current){let y=u.current.container();y&&(y.style.cursor="");}},[n]);let Y=useCallback(()=>{u.current&&requestAnimationFrame(()=>{if(!u.current)return;u.current.getLayers().forEach(D=>D.batchDraw());let C=1/6,T=u.current.toDataURL({pixelRatio:C});p(T),de();});},[de]),Me=useRef(c);useEffect(()=>{Me.current!==c&&(Me.current=c,Y());},[c,Y]);let De=useRef(null),Se=useRef(true);useEffect(()=>{if(!s)return;let y=(s.lines?.length||0)+(s.images?.length||0)+(s.videos?.length||0)+(s.shapes?.length||0)+(s.texts?.length||0)+(s.flashcards?.length||0)+(s.photoFrames?.length||0)+(s.multipleChoices?.length||0)+(s.trueFalses?.length||0)+(s.shortAnswers?.length||0)+(s.LongAnswer?.length||0)+(s.fillInTheBlanks?.length||0),C=De.current?.count!==y;!Se.current&&C&&setTimeout(()=>{Y();},100),De.current={slideId:c,count:y},Se.current=false;},[s,c,Y]),useEffect(()=>{u.current&&e&&e(u);},[e]),useEffect(()=>{J.current&&a&&a(J);},[a]);let{startDrawing:Rt,draw:Ja,stopDrawing:Er,setCanvasRef:Fr,tool:fs,color:ms,strokeWidth:ps,isSketchMode:hs}=_l(Y),Ma=useRef(new Map),{images:F,getLoadedImage:ne,imageRefs:ve,handleDragEnd:he,handleImageTransformEnd:se}=Ql(Y),{videos:re,videoRefs:Te,handleVideoClick:Dt,handleVideoDragEnd:Yt,handleVideoTransformEnd:st}=ad(Y),{multipleChoice:Ee,handleMcqTransform:qe,mcqRefs:ht,handleDragEnd:Ta}=ed(Y),{trueFalse:Za,handleTrueFalseTransform:Qa,trueFalseRefs:Aa,handleTrueFalseDragEnd:Et}=td(Y),{shortAnswers:ra,saRefs:Ft,handleShortAnswerDragEnd:Df}=ld(Y),{longAnswers:Ef,handleLongAnswerDragEnd:Ff}=dd(Y),{fillInTheBlanks:Bf,handleFillInTheBlanksDragEnd:Of,fibRefs:Br}=ku(Y),{transformerRef:ue,boundBoxFunc:gt}=hd(),{shapes:Nf,shapeRefs:Or,isDragging:Pl,handleShapeDragEnd:Vf,handleShapeResizeEnd:qf}=nd(Y),{texts:qo,textRefs:na,handleDragEnd:Hf,handleTransformEnd:Uf,handleDoubleClick:Wf,startEditing:Nr,editingTextId:me,editingValue:Rl,handleEditingChange:Dl,finishEditing:gs}=id(Y,Q);useEffect(()=>{t&&t(Nr);},[t,Nr]);let Vr=ee(y=>y.canvas.editingTextId);useEffect(()=>{Vr&&Vr!==me&&Nr(Vr);},[Vr,me,Nr]);let{flashcards:zf,flashcardRefs:qr,handleDragEnd:Gf,handleFlashcardTransformEnd:Kf,handleNext:_f,handlePrevious:jf}=cd(Y),{photoFrames:El,photoFrameRefs:Hr,handleDragEnd:$f,handlePhotoFrameTransformEnd:Xf,startCamera:Yf,capturePhoto:Jf,cameraStreams:Zf}=pd(Y);useEffect(()=>{if(ue.current){if(me){ue.current.nodes([]),ue.current.getLayer()?.batchDraw();return}if(l&&!re.find(T=>T.id===l)?.isPlaying){let T=Ma.current.get(l)||ve.current.get(l)||Te.current.get(l)||Or.current.get(l)||na.current.get(l)||ht.current.get(l)||qr.current.get(l)||Hr.current.get(l)||Ft.current.get(l)||Aa.current.get(l)||Br.current.get(l);if(T){let D=T.attrs?.locked;if(T.visible()&&D!==true){ue.current.nodes([T]),ue.current.getLayer()?.batchDraw();return}}}ue.current.nodes([]),ue.current.getLayer()?.batchDraw();}},[l,me,re,Ma,ve,Te,Or,na,qr,Hr,El,ht,Aa,Br,ue]);let Ue=useCallback(y=>{h(y),o?.(y);},[o]),eo=useCallback(()=>{h(null),o?.(null),ue.current&&(ue.current.nodes([]),ue.current.getLayer()?.batchDraw());},[ue,o]),Fl=useCallback(y=>s?s.lines?.some(C=>C.id===y)?"line":s.images?.some(C=>C.id===y)?"image":s.videos?.some(C=>C.id===y)?"video":s.shapes?.some(C=>C.id===y)?"shape":s.texts?.some(C=>C.id===y)?"text":s.flashcards?.some(C=>C.id===y)?"flashcard":s.photoFrames?.some(C=>C.id===y)?"photoFrame":s.multipleChoices?.some(C=>C.id===y)?"mcq":s.trueFalses?.some(C=>C.id===y)?"trueFalse":s.shortAnswers?.some(C=>C.id===y)?"shortAnswer":s.LongAnswer?.some(C=>C.id===y)?"longAnswer":s.fillInTheBlanks?.some(C=>C.id===y)?"fillInTheBlanks":null:null,[s]),Bl=useCallback((y,C)=>{switch(r(le()),C){case "line":r(xn(y));break;case "image":r(Wr(y));break;case "video":r(_r(y));break;case "shape":r(Xr(y));break;case "text":r(Yr(y));break;case "flashcard":r(Zr(y));break;case "photoFrame":r(en(y));break;case "mcq":r(an(y));break;case "trueFalse":r(rn(y));break;case "shortAnswer":r(sn(y));break;case "longAnswer":r(dn(y));break;case "fillInTheBlanks":r(cn(y));break}eo(),Y();},[r,eo,Y]);useEffect(()=>{let y=C=>{if(C.key!=="Delete"||!l||me)return;let T=document.activeElement;if(T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement||T?.getAttribute("contenteditable")==="true")return;C.preventDefault();let ke=Fl(l);ke&&Bl(l,ke);};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[l,me,Fl,Bl]),useEffect(()=>{let y=ue.current;return ()=>{y&&y.nodes([]);}},[c]),useEffect(()=>{let y=C=>{me&&C.target.tagName!=="TEXTAREA"&&gs();};return document.addEventListener("mousedown",y),()=>{document.removeEventListener("mousedown",y);}},[me,gs]),useEffect(()=>{let y=me||l;if(!y||l&&me){b(null);return}let C=na.current.get(y),T=u.current;if(!C||!T){b(null);return}let D=T.container().getBoundingClientRect(),ke=C.absolutePosition(),Le=T.scaleX();b({x:D.left+(ke.x+C.width()*Le/2)*Le,y:D.top+ke.y*Le});},[l,me,qo,na]),useEffect(()=>{if(!me){V(null);return}let y=na.current.get(me),C=u.current;if(!y||!C){V(null);return}let T=C.container().getBoundingClientRect(),D=y.absolutePosition(),ke=C.scaleX();V({top:T.top+D.y*ke,left:T.left+D.x*ke,scale:ke});},[me,qo,na]);let Ol=useCallback(y=>{let C=y.target.getClassName(),T=y.target===y.target.getStage(),D=C==="Transformer"||y.target.getParent()?.getClassName()==="Transformer",ke=C==="Image",Le=C==="Text",ae=C==="Group"||y.target.getParent()?.getClassName()==="Group",Bt=C==="Circle"||C==="Star"||C==="RegularPolygon"||C==="Ellipse"||C==="Ring"||C==="Wedge"||C==="Arrow"||C==="Line"||C==="Arc"||C==="Rect"&&y.target.attrs.id,bt=C==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:C,clickedOnImage:ke,clickedOnGroup:ae,tool:n,targetId:y.target.attrs?.id}),T&&!D&&!ke&&!Le&&!ae&&!Bt&&!bt&&eo(),!(n==="pen"||n==="eraser")&&(ke||Le||D||ae||Bt||bt))return;let _e=y.target.getStage()?.getPointerPosition();if(!_e)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let B=qu(_e,x);Rt(B);}},[n,Rt,eo,x]),Nl=useCallback(y=>{if(Pl)return;let C=y.target.getStage()?.getPointerPosition();if(!C)return;let T=qu(C,x);Ja(T);},[Ja,Pl,x]),Vl=useCallback(()=>{Er();},[Er]),Qf=useCallback(y=>{he(y,Y);},[he,Y]),em=useCallback(y=>{Dt(y),Ue(y);},[Dt,Ue]),xt=useCallback((y,C,T)=>{y.preventDefault();let D=y.clientX,ke=y.clientY,Le=w.current?.offsetHeight||450,ae=w.current?.offsetWidth||450,Bt=window.innerHeight,bt=window.innerWidth,Ze=D,_e=ke;ke+Le>Bt&&(_e=ke-Le),D+ae>bt&&(Ze=D-ae),k({x:Ze,y:_e,elementId:C,elementType:T}),Ue(C);},[Ue]),ql=useCallback(y=>{r(Ko(y)),r(da(true));},[r]),tm=useCallback(y=>{r(Uo(y)),r(Ra(true));},[r]),am=useCallback((y,C)=>{if(!I)return;let{elementId:T,elementType:D}=I;switch(y){case "order":if(C){let M=C.target.getBoundingClientRect();H({x:M.right+5,y:M.top,type:"order"});}break;case "lock":if(C){let M=C.target.getBoundingClientRect();H({x:M.right+5,y:M.top,type:"lock"});}break;case "link":if(k(null),D==="line")break;let ke=s?D==="image"?s.images.find(M=>M.id===T):s.videos.find(M=>M.id===T):null;P({type:"link",defaultValue:ke?.link||""});break;case "voice":if(k(null),D==="line")break;let Le=s?D==="image"?s.images.find(M=>M.id===T):D==="video"?s.videos.find(M=>M.id===T):D==="text"?s.texts.find(M=>M.id===T):D==="flashcard"?s.flashcards.find(M=>M.id===T):D==="photoFrame"?s.photoFrames.find(M=>M.id===T):D==="mcq"?s.multipleChoices.find(M=>M.id===T):D==="fillInTheBlanks"?s.fillInTheBlanks.find(M=>M.id===T):D==="longAnswer"?s.LongAnswer.find(M=>M.id===T):D==="shortAnswer"?s.shortAnswers.find(M=>M.id===T):D==="trueFalse"?s.trueFalses.find(M=>M.id===T):D==="shape"?s.shapes.find(M=>M.id===T):null:null;X({elementId:T,elementType:D,existingAudio:Le?.audioData});break;case "edit":k(null);let ae=null;D==="mcq"?ae=s?.multipleChoices.find(M=>M.id===T):D==="trueFalse"?ae=s?.trueFalses.find(M=>M.id===T):D==="shortAnswer"?ae=s?.shortAnswers.find(M=>M.id===T):D==="longAnswer"?ae=s?.LongAnswer.find(M=>M.id===T):D==="fillInTheBlanks"&&(ae=s?.fillInTheBlanks.find(M=>M.id===T)),ae&&ql(ae);break;case "editFlashcard":k(null);let Bt=s?.flashcards.find(M=>M.id===T);Bt&&tm(Bt);break;case "color":k(null);let bt=s?.shapes.find(M=>M.id===T);E({elementId:T,elementType:"shape",defaultColor:bt?.color||"#096B76"});break;case "crop":if(k(null),D==="image"){let M=s?.images.find(dm=>dm.id===T);M&&N({elementId:T,imageSrc:M.src});}break;case "draw":k(null),D==="image"?r(Bs(T)):D==="photoFrame"&&r(Ns(T));break;case "duplicate":r(le()),D==="line"?r(Xs(T)):D==="image"?r(zr(T)):D==="video"?r(jr(T)):D==="shape"?r($r(T)):D==="text"?r(Jr(T)):D==="flashcard"?r(Qr(T)):D==="photoFrame"?r(tn(T)):D==="mcq"?r(on(T)):D==="trueFalse"?r(nn(T)):D==="shortAnswer"?r(ln(T)):D==="fillInTheBlanks"?r(fn(T)):D==="longAnswer"&&r(un(T)),Y();break;case "infinite-clone":r(le());let Ze=5;for(let M=0;M<Ze;M++)D==="image"?r(zr(T)):D==="video"?r(jr(T)):D==="shape"?r($r(T)):D==="text"?r(Jr(T)):D==="flashcard"?r(Qr(T)):D==="photoFrame"?r(tn(T)):D==="mcq"?r(on(T)):D==="trueFalse"?r(nn(T)):D==="shortAnswer"?r(ln(T)):D==="fillInTheBlanks"?r(fn(T)):D==="longAnswer"&&r(un(T));Y();break;case "make-response":if(k(null),D==="line")break;let _e=`#response-${T}`;r(le()),r(mn({id:T,type:D,link:_e})),(s?D==="image"?s.images.find(M=>M.id===T):D==="video"?s.videos.find(M=>M.id===T):D==="shape"?s.shapes.find(M=>M.id===T):D==="flashcard"?s.flashcards.find(M=>M.id===T):D==="photoFrame"?s.photoFrames.find(M=>M.id===T):s.multipleChoices.find(M=>M.id===T):null)?.altText||r(pn({id:T,type:D,altText:"Interactive response area"})),Y(),console.log(`Element ${T} marked as interactive response area`);break;case "accessibility":if(k(null),D==="line")break;let B=s?D==="image"?s.images.find(M=>M.id===T):D==="video"?s.videos.find(M=>M.id===T):D==="shape"?s.shapes.find(M=>M.id===T):null:null;P({type:"altText",defaultValue:B?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),k(null),K(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(le()),D==="line"?r(xn(T)):D==="image"?r(Wr(T)):D==="video"?r(_r(T)):D==="shape"?r(Xr(T)):D==="text"?r(Yr(T)):D==="flashcard"?r(Zr(T)):D==="photoFrame"?r(en(T)):D==="mcq"?r(an(T)):D==="trueFalse"?r(rn(T)):D==="shortAnswer"?r(sn(T)):D==="longAnswer"?r(dn(T)):D==="fillInTheBlanks"&&r(cn(T)),eo(),Y();break}},[I,r,Y,eo,s,ql]),om=useCallback(()=>{k(null),H(null);},[]),xs=useCallback(y=>{if(!I)return;let{elementId:C,elementType:T}=I;switch(r(le()),y){case "bring-to-front":T!=="line"&&r(Ks({id:C,type:T}));break;case "send-to-back":T!=="line"&&r(_s({id:C,type:T}));break;case "lock":case "unlock":T!=="line"&&r(js({id:C,type:T}));break}Y(),k(null),H(null);},[I,r,Y]),rm=useCallback(y=>{if(!I||!q)return;let{elementId:C,elementType:T}=I;r(le()),q.type==="link"&&T!=="line"?r(mn({id:C,type:T,link:y})):q.type==="altText"&&T!=="line"&&r(pn({id:C,type:T,altText:y})),Y(),P(null);},[I,q,r,Y]),nm=useCallback(y=>{if(!O)return;let{elementId:C,elementType:T}=O;r(le()),r(hn({id:C,type:T,audioData:y})),Y(),X(null);},[O,r,Y]),sm=useCallback(()=>{if(!O)return;let{elementId:y,elementType:C}=O;r(le()),r(hn({id:y,type:C,audioData:""})),Y();},[O,r,Y]),im=useCallback(y=>{if(!W)return;let{elementId:C}=W;r(le()),r(oo({id:C,color:y})),Y(),E(null);},[W,r,Y]),lm=useCallback(y=>{if(!oe)return;let{elementId:C}=oe;r(le()),r(ao({id:C,src:y})),Y(),N(null);},[oe,r,Y]);return jsxs("div",{ref:m,className:"fixed inset-0",style:{cursor:n==="pen"?"crosshair":n==="eraser"?"":"default"},children:[n==="pen"&&jsx(Jl,{ref:y=>{if(te.current=y,Fr(y),y){let C=y.getCanvasElement();C&&(J.current=C,a&&a(J));}},width:x.baseWidth,height:x.baseHeight,tool:fs,color:ms,strokeWidth:ps/x.scale,isSketchMode:hs,xOffset:x.contentOffsetX,yOffset:x.contentOffsetY-x.offsetY/x.scale,style:{width:x.stageWidth,height:x.stageHeight}}),jsxs(Stage,{ref:u,width:x.stageWidth,height:x.stageHeight,scaleX:x.scaleX,scaleY:x.scaleY,x:x.offsetX,y:0,onMouseDown:Ol,onMouseMove:Nl,onMouseUp:Vl,onTouchStart:Ol,onTouchMove:Nl,onTouchEnd:Vl,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:x.baseWidth,height:x.stageHeight/x.scale,fill:s?.backgroundColor||"white"})}),jsx(Layer,{x:-x.contentOffsetX,y:x.offsetY/x.scale-x.contentOffsetY,children:(()=>{let y=[];return f.forEach((C,T)=>{y.push({type:"line",timestamp:C.timestamp||T,element:{...C,id:C.id??`line-${T}`},index:T});}),Nf.forEach(C=>{y.push({type:"shape",timestamp:C.timestamp||0,element:C});}),F.forEach(C=>{y.push({type:"image",timestamp:C.timestamp||0,element:C});}),re.forEach(C=>{y.push({type:"video",timestamp:C.timestamp||0,element:C});}),qo.forEach(C=>{y.push({type:"text",timestamp:C.timestamp||0,element:C});}),zf.forEach(C=>{y.push({type:"flashcard",timestamp:C.timestamp||0,element:C});}),El.forEach(C=>{y.push({type:"photoFrame",timestamp:C.timestamp||0,element:C});}),Ee.forEach(C=>{y.push({type:"mcq",timestamp:C.timestamp||0,element:C});}),Za.forEach(C=>{y.push({type:"trueFalse",timestamp:C.timestamp||0,element:C});}),ra.forEach(C=>{y.push({type:"shortAnswer",timestamp:C.timestamp||0,element:C});}),Ef.forEach(C=>{y.push({type:"longAnswer",timestamp:C.timestamp||0,element:C});}),Bf.forEach(C=>{y.push({type:"fillInTheBlanks",timestamp:C.timestamp||0,element:C});}),y.sort((C,T)=>C.timestamp-T.timestamp),y.map((C,T)=>{let D=`${C.type}-${"id"in C.element&&C.element.id||C.index||T}`,ke="id"in C.element?C.element.id:void 0,Le=ke&&l===ke;switch(C.type){case "line":let ae=C.element,Bt=C.index||0,bt=ae.tool==="eraser",Ze=ae.isSketch&&ae.tool==="pen",_e=ae.isSketch&&bt,vt=ae.id||`line-${Bt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),n==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:Ze||_e?void 0:ae.color,strokeWidth:Ze||_e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ze||_e?bt?"black":ae.color:void 0,closed:Ze||_e,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,onClick:()=>{r(le()),r(Ur(Bt));},onTap:()=>{r(le()),r(Ur(Bt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:B=>{let M=B.target.getStage();M&&(M.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:B=>{let M=B.target.getStage();M&&(M.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`);}})},D):jsxs(be__default.Fragment,{children:[jsx(Group,{id:vt,ref:B=>{B?Ma.current.set(vt,B):Ma.current.delete(vt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:n==="select",listening:n==="select",onClick:()=>{n==="select"&&(console.log("Line clicked:",vt),Ue(vt));},onTap:()=>{n==="select"&&(console.log("Line tapped:",vt),Ue(vt));},onDragEnd:B=>{r(le()),r(gn({id:vt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onTransformEnd:B=>{r(le()),r(gn({id:vt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onMouseEnter:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="move");}},onMouseLeave:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="default");}},onContextMenu:B=>{let M=B.evt;M.preventDefault(),xt(M,vt,"line");},children:jsx(Line,{points:ae.points||[],stroke:Ze||_e?void 0:ae.color,strokeWidth:Ze||_e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ze||_e?bt?"black":ae.color:void 0,closed:Ze||_e,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ma.current.get(l);console.log("Line Transformer - selectedId:",l,"node found:",!!M),M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:gt,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"]})]},D);case "shape":return jsxs(be__default.Fragment,{children:[jsx(ui,{onSelect:Ue,shapes:[C.element],shapeRefs:Or,handleShapeDragEnd:Vf,handleShapeResizeEnd:qf,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Or.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "image":return jsxs(be__default.Fragment,{children:[jsx(si,{images:[C.element],getLoadedImage:ne,imageRefs:ve,onDragEnd:Qf,onTransform:se,onSelect:Ue,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=ve.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "video":return jsxs(be__default.Fragment,{children:[jsx(di,{videos:[C.element],selectedId:l,videoRefs:Te,onVideoClick:em,onDragEnd:Yt,onTransformEnd:st,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Te.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "text":return jsxs(be__default.Fragment,{children:[jsx(Pd,{texts:[C.element],textRefs:na,onDragEnd:Hf,onTransformEnd:Uf,onSelect:Ue,onContextMenu:xt,onDoubleClick:Wf,editingTextId:me,editingValue:Rl,onEditingChange:Dl}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=na.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(mi,{flashcards:[C.element],flashcardRefs:qr,selectedId:l,onDragEnd:Gf,onTransform:Kf,onSelect:Ue,onNext:_f,onPrevious:jf,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=qr.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(bi,{photoFrames:[C.element],photoFrameRefs:Hr,selectedId:l,onDragEnd:$f,onTransform:Xf,onSelect:Ue,onStartCamera:Yf,onCapture:Jf,cameraStreams:Zf,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Hr.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(ru,{handleMcqTransform:qe,multipleChoice:[C.element],handleSelect:Ue,mcqRefs:ht,handleDragEnd:Ta,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=ht.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(iu,{trueFalses:[C.element],handleTrueFalseTransform:Qa,handleSelect:Ue,trueFalseRefs:Aa,onContextMenu:xt,handleDragEnd:Et}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Aa.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(Cu,{shortAnswers:[C.element],handleSelect:Ue,handleTransform:qe,saRefs:Ft,onContextMenu:xt,handleDragEnd:Df}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ft.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(Eu,{longAnswer:[C.element],handleSelect:Ue,handleTransform:qe,saRefs:Ft,onContextMenu:xt,handleDragEnd:Ff}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ft.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Ru,{fillInTheBlanks:[C.element],handleSelect:Ue,handleTransform:qe,onContextMenu:xt,handleDragEnd:Of,fibRefs:Br}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Br.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,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"]})]},D);default:return null}})})()})]}),I&&jsx(zd,{menuRef:w,x:I.x,y:I.y,type:I.elementType,onAction:am,onClose:om,isDrawingMode:I.elementType==="image"?s?.images.find(y=>y.id===I.elementId)?.isDrawingMode:I.elementType==="photoFrame"?s?.photoFrames.find(y=>y.id===I.elementId)?.isDrawingMode:false}),R&&I&&jsx(Gd,{x:R.x,y:R.y,items:R.type==="order"?[{label:"Bring to Front",onClick:()=>xs("bring-to-front")},{label:"Send to Back",onClick:()=>xs("send-to-back")}]:[{label:s&&(I.elementType==="image"?s.images.find(y=>y.id===I.elementId)?.locked:s.videos.find(y=>y.id===I.elementId)?.locked)?"Unlock":"Lock",onClick:()=>xs(s&&(I.elementType==="image"?s.images.find(y=>y.id===I.elementId)?.locked:s.videos.find(y=>y.id===I.elementId)?.locked)?"unlock":"lock")}],onClose:()=>H(null)}),q&&jsx(Kd,{title:q.type==="link"?"Add Link":"Add Alt Text",label:q.type==="link"?"URL":"Alternative Text",placeholder:q.type==="link"?"https://example.com":"Describe this image/video",defaultValue:q.defaultValue,onSave:rm,onClose:()=>P(null)}),W&&jsx(_d,{defaultColor:W.defaultColor,onConfirm:im,onCancel:()=>E(null)}),oe&&jsx(Yd,{imageSrc:oe.imageSrc,onConfirm:lm,onCancel:()=>N(null)}),fe&&jsx(or,{onClose:()=>z(false),stageRef:u}),O&&jsx(Zd,{elementId:O.elementId,elementType:O.elementType,existingAudio:O.existingAudio,onSave:nm,onDelete:sm,onClose:()=>X(null)}),U&&jsx(tu,{selectedElementId:l||void 0,onClose:()=>K(false),onSelectElement:y=>{Ue(y),K(false);}}),s?.images.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.videos.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.shapes?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.texts?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.flashcards?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.photoFrames?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.multipleChoices?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.trueFalses?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.shortAnswers?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.LongAnswer?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.fillInTheBlanks?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),d&&jsx(bu,{editElement:i}),S&&(()=>{let y=me||l;if(!y)return null;let C=qo.find(T=>T.id===y);return C?jsx(vu,{text:C,position:S}):null})(),A&&me&&(()=>{let y=qo.find(C=>C.id===me);return y?jsx(wu,{text:y,editingValue:Rl,onEditingChange:Dl,onFinish:gs,position:{top:A.top,left:A.left},scale:A.scale,textareaRef:Q},me):null})()]})},Qx=Zx;var eb="SchooplaVideoStorage";var $t="videos",Yn=()=>new Promise((e,o)=>{let t=indexedDB.open(eb,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains($t)||r.createObjectStore($t,{keyPath:"id"});};}),Ga=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Yn(),n=a.transaction([$t],"readwrite").objectStore($t),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((c,i)=>{let d=n.put(s);d.onsuccess=()=>c(!0),d.onerror=()=>i(d.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 Hu=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Yn(),t=e.transaction([$t],"readonly").objectStore($t);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result,c=new Map;s.forEach(i=>{c.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${c.size} video blobs from IndexedDB`),a(c);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},$i=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Yn(),a=o.transaction([$t],"readwrite").objectStore($t);await new Promise((r,n)=>{let s=a.delete(e);s.onsuccess=()=>r(!0),s.onerror=()=>n(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}},Uu=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Yn(),t=e.transaction([$t],"readwrite").objectStore($t);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Wu=e=>URL.createObjectURL(e);function wa(e,o=[]){let t=[];function a(n,s){let c=be.createContext(s),i=t.length;t=[...t,s];let d=u=>{let{scope:m,children:l,...h}=u,g=m?.[e]?.[i]||c,p=be.useMemo(()=>h,Object.values(h));return jsx(g.Provider,{value:p,children:l})};d.displayName=n+"Provider";function f(u,m){let l=m?.[e]?.[i]||c,h=be.useContext(l);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${n}\``)}return [d,f]}let r=()=>{let n=t.map(s=>be.createContext(s));return function(c){let i=c?.[e]||n;return be.useMemo(()=>({[`__scope${e}`]:{...c,[e]:i}}),[c,i])}};return r.scopeName=e,[a,ab(r,...o)]}function ab(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(n){let s=a.reduce((c,{useScope:i,scopeName:d})=>{let u=i(n)[`__scope${d}`];return {...c,...u}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function zu(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Cr(...e){return o=>{let t=false,a=e.map(r=>{let n=zu(r,o);return !t&&typeof n=="function"&&(t=true),n});if(t)return ()=>{for(let r=0;r<a.length;r++){let n=a[r];typeof n=="function"?n():zu(e[r],null);}}}}function Tt(...e){return be.useCallback(Cr(...e),e)}function _u(e){let o=ob(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,c=be.Children.toArray(n),i=c.find(nb);if(i){let d=i.props.children,f=c.map(u=>u===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function ob(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=ib(r),c=sb(n,r.props);return r.type!==be.Fragment&&(c.ref=a?Cr(a,s):s),be.cloneElement(r,c)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var rb=Symbol("radix.slottable");function nb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rb}function sb(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let i=n(...c);return r(...c),i}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function ib(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 ub=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rt=ub.reduce((e,o)=>{let t=_u(`Primitive.${o}`),a=be.forwardRef((r,n)=>{let{asChild:s,...c}=r,i=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...c,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function $e(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function Xi(e){let o=cb(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,c=be.Children.toArray(n),i=c.find(mb);if(i){let d=i.props.children,f=c.map(u=>u===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function cb(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=hb(r),c=pb(n,r.props);return r.type!==be.Fragment&&(c.ref=a?Cr(a,s):s),be.cloneElement(r,c)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var fb=Symbol("radix.slottable");function mb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===fb}function pb(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let i=n(...c);return r(...c),i}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function hb(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 Jn(e){let o=e+"CollectionProvider",[t,a]=wa(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=g=>{let{scope:p,children:w}=g,x=be__default.useRef(null),v=be__default.useRef(new Map).current;return jsx(r,{scope:p,itemMap:v,collectionRef:x,children:w})};s.displayName=o;let c=e+"CollectionSlot",i=Xi(c),d=be__default.forwardRef((g,p)=>{let{scope:w,children:x}=g,v=n(c,w),L=Tt(p,v.collectionRef);return jsx(i,{ref:L,children:x})});d.displayName=c;let f=e+"CollectionItemSlot",u="data-radix-collection-item",m=Xi(f),l=be__default.forwardRef((g,p)=>{let{scope:w,children:x,...v}=g,L=be__default.useRef(null),I=Tt(p,L),k=n(f,w);return be__default.useEffect(()=>(k.itemMap.set(L,{ref:L,...v}),()=>void k.itemMap.delete(L))),jsx(m,{[u]:"",ref:I,children:x})});l.displayName=f;function h(g){let p=n(e+"CollectionConsumer",g);return be__default.useCallback(()=>{let x=p.collectionRef.current;if(!x)return [];let v=Array.from(x.querySelectorAll(`[${u}]`));return Array.from(p.itemMap.values()).sort((k,S)=>v.indexOf(k.ref.current)-v.indexOf(S.ref.current))},[p.collectionRef,p.itemMap])}return [{Provider:s,Slot:d,ItemSlot:l},h,a]}var To=globalThis?.document?be.useLayoutEffect:()=>{};var gb=be[" useId ".trim().toString()]||(()=>{}),xb=0;function Yu(e){let[o,t]=be.useState(gb());return To(()=>{t(a=>a??String(xb++));},[e]),(o?`radix-${o}`:"")}function Ju(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var bb=be[" useInsertionEffect ".trim().toString()]||To;function Qt({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,s]=vb({defaultProp:o,onChange:t}),c=e!==void 0,i=c?e:r;{let f=be.useRef(e!==void 0);be.useEffect(()=>{let u=f.current;u!==c&&console.warn(`${a} is changing from ${u?"controlled":"uncontrolled"} to ${c?"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=c;},[c,a]);}let d=be.useCallback(f=>{if(c){let u=yb(f)?f(e):f;u!==e&&s.current?.(u);}else n(f);},[c,e,n,s]);return [i,d]}function vb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),n=be.useRef(o);return bb(()=>{n.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function yb(e){return typeof e=="function"}var wb=be.createContext(void 0);function Po(e){let o=be.useContext(wb);return e||o||"ltr"}var Zi="rovingFocusGroup.onEntryFocus",Lb={bubbles:false,cancelable:true},kr="RovingFocusGroup",[Qi,Zu,Ib]=Jn(kr),[Sb,el]=wa(kr,[Ib]),[Cb,kb]=Sb(kr),Qu=be.forwardRef((e,o)=>jsx(Qi.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Qi.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Mb,{...e,ref:o})})}));Qu.displayName=kr;var Mb=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:i,onEntryFocus:d,preventScrollOnEntryFocus:f=false,...u}=e,m=be.useRef(null),l=Tt(o,m),h=Po(n),[g,p]=Qt({prop:s,defaultProp:c??null,onChange:i,caller:kr}),[w,x]=be.useState(false),v=Ju(d),L=Zu(t),I=be.useRef(false),[k,S]=be.useState(0);return be.useEffect(()=>{let b=m.current;if(b)return b.addEventListener(Zi,v),()=>b.removeEventListener(Zi,v)},[v]),jsx(Cb,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:g,onItemFocus:be.useCallback(b=>p(b),[p]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>S(b=>b+1),[]),onFocusableItemRemove:be.useCallback(()=>S(b=>b-1),[]),children:jsx(rt.div,{tabIndex:w||k===0?-1:0,"data-orientation":a,...u,ref:l,style:{outline:"none",...e.style},onMouseDown:$e(e.onMouseDown,()=>{I.current=true;}),onFocus:$e(e.onFocus,b=>{let A=!I.current;if(b.target===b.currentTarget&&A&&!w){let V=new CustomEvent(Zi,Lb);if(b.currentTarget.dispatchEvent(V),!V.defaultPrevented){let R=L().filter(E=>E.focusable),H=R.find(E=>E.active),q=R.find(E=>E.id===g),W=[H,q,...R].filter(Boolean).map(E=>E.ref.current);ac(W,f);}}I.current=false;}),onBlur:$e(e.onBlur,()=>x(false))})})}),ec="RovingFocusGroupItem",tc=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:s,...c}=e,i=Yu(),d=n||i,f=kb(ec,t),u=f.currentTabStopId===d,m=Zu(t),{onFocusableItemAdd:l,onFocusableItemRemove:h,currentTabStopId:g}=f;return be.useEffect(()=>{if(a)return l(),()=>h()},[a,l,h]),jsx(Qi.ItemSlot,{scope:t,id:d,focusable:a,active:r,children:jsx(rt.span,{tabIndex:u?0:-1,"data-orientation":f.orientation,...c,ref:o,onMouseDown:$e(e.onMouseDown,p=>{a?f.onItemFocus(d):p.preventDefault();}),onFocus:$e(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:$e(e.onKeyDown,p=>{if(p.key==="Tab"&&p.shiftKey){f.onItemShiftTab();return}if(p.target!==p.currentTarget)return;let w=Pb(p,f.orientation,f.dir);if(w!==void 0){if(p.metaKey||p.ctrlKey||p.altKey||p.shiftKey)return;p.preventDefault();let v=m().filter(L=>L.focusable).map(L=>L.ref.current);if(w==="last")v.reverse();else if(w==="prev"||w==="next"){w==="prev"&&v.reverse();let L=v.indexOf(p.currentTarget);v=f.loop?Rb(v,L+1):v.slice(L+1);}setTimeout(()=>ac(v));}}),children:typeof s=="function"?s({isCurrentTabStop:u,hasTabStop:g!=null}):s})})});tc.displayName=ec;var Tb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Ab(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Pb(e,o,t){let a=Ab(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Tb[a]}function ac(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Rb(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var oc=Qu,rc=tc;var sc="Toggle",tl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[s,c]=Qt({prop:t,onChange:r,defaultProp:a??false,caller:sc});return jsx(rt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:$e(e.onClick,()=>{e.disabled||c(!s);})})});tl.displayName=sc;var La="ToggleGroup",[lc]=wa(La,[el]),dc=el(),al=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Fb,{...a,ref:o});if(t==="multiple")return jsx(Bb,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${La}\``)});al.displayName=La;var[uc,cc]=lc(La),Fb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=Qt({prop:t,defaultProp:a??"",onChange:r,caller:La});return jsx(uc,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:c,onItemDeactivate:be__default.useCallback(()=>c(""),[c]),children:jsx(fc,{...n,ref:o})})}),Bb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=Qt({prop:t,defaultProp:a??[],onChange:r,caller:La}),i=be__default.useCallback(f=>c((u=[])=>[...u,f]),[c]),d=be__default.useCallback(f=>c((u=[])=>u.filter(m=>m!==f)),[c]);return jsx(uc,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:d,children:jsx(fc,{...n,ref:o})})});al.displayName=La;var[Ob,Nb]=lc(La),fc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:s,loop:c=true,...i}=e,d=dc(t),f=Po(s),u={role:"group",dir:f,...i};return jsx(Ob,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(oc,{asChild:true,...d,orientation:n,dir:f,loop:c,children:jsx(rt.div,{...u,ref:o})}):jsx(rt.div,{...u,ref:o})})}),es="ToggleGroupItem",Vb=be__default.forwardRef((e,o)=>{let t=cc(es,e.__scopeToggleGroup),a=Nb(es,e.__scopeToggleGroup),r=dc(e.__scopeToggleGroup),n=t.value.includes(e.value),s=a.disabled||e.disabled,c={...e,pressed:n,disabled:s},i=be__default.useRef(null);return a.rovingFocus?jsx(rc,{asChild:true,...r,focusable:!s,active:n,ref:i,children:jsx(ic,{...c,ref:o})}):jsx(ic,{...c,ref:o})});Vb.displayName=es;var ic=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=cc(es,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=n.type==="single"?s:void 0;return jsx(tl,{...c,...r,ref:o,onPressedChange:i=>{i?n.onItemActivate(a):n.onItemDeactivate(a);}})}),mc=al;function pc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(o=0;o<r;o++)e[o]&&(t=pc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function ts(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=pc(e))&&(a&&(a+=" "),a+=o);return a}var Hb=(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},Ub=(e,o)=>({classGroupId:e,validator:o}),vc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var hc=[],Wb="arbitrary..",zb=e=>{let o=Kb(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return Gb(s);let c=s.split("-"),i=c[0]===""&&c.length>1?1:0;return yc(c,i,o)},getConflictingClassGroupIds:(s,c)=>{if(c){let i=a[s],d=t[s];return i?d?Hb(d,i):i:d||hc}return t[s]||hc}}},yc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let d=yc(e,o+1,n);if(d)return d}let s=t.validators;if(s===null)return;let c=o===0?e.join("-"):e.slice(o).join("-"),i=s.length;for(let d=0;d<i;d++){let f=s[d];if(f.validator(c))return f.classGroupId}},Gb=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?Wb+a:void 0})(),Kb=e=>{let{theme:o,classGroups:t}=e;return _b(t,o)},_b=(e,o)=>{let t=vc();for(let a in e){let r=e[a];nl(r,t,a,o);}return t},nl=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let s=e[n];jb(s,o,t,a);}},jb=(e,o,t,a)=>{if(typeof e=="string"){$b(e,o,t);return}if(typeof e=="function"){Xb(e,o,t,a);return}Yb(e,o,t,a);},$b=(e,o,t)=>{let a=e===""?o:wc(o,e);a.classGroupId=t;},Xb=(e,o,t,a)=>{if(Jb(e)){nl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Ub(t,e));},Yb=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let s=0;s<n;s++){let[c,i]=r[s];nl(i,wc(o,c),t,a);}},wc=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let n=0;n<r;n++){let s=a[n],c=t.nextPart.get(s);c||(c=vc(),t.nextPart.set(s,c)),t=c;}return t},Jb=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Zb=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(n,s)=>{t[n]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(n){let s=t[n];if(s!==void 0)return s;if((s=a[n])!==void 0)return r(n,s),s},set(n,s){n in t?t[n]=s:r(n,s);}}};var Qb=[],gc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),ev=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],s=0,c=0,i=0,d,f=r.length;for(let g=0;g<f;g++){let p=r[g];if(s===0&&c===0){if(p===":"){n.push(r.slice(i,g)),i=g+1;continue}if(p==="/"){d=g;continue}}p==="["?s++:p==="]"?s--:p==="("?c++:p===")"&&c--;}let u=n.length===0?r:r.slice(i),m=u,l=false;u.endsWith("!")?(m=u.slice(0,-1),l=true):u.startsWith("!")&&(m=u.slice(1),l=true);let h=d&&d>i?d-i:void 0;return gc(n,l,m,h)};if(o){let r=o+":",n=a;a=s=>s.startsWith(r)?n(s.slice(r.length)):gc(Qb,false,s,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},tv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let n=0;n<t.length;n++){let s=t[n],c=s[0]==="[",i=o.has(s);c||i?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(s)):r.push(s);}return r.length>0&&(r.sort(),a.push(...r)),a}},av=e=>({cache:Zb(e.cacheSize),parseClassName:ev(e),sortModifiers:tv(e),...zb(e)}),ov=/\s+/,rv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,s=[],c=e.trim().split(ov),i="";for(let d=c.length-1;d>=0;d-=1){let f=c[d],{isExternal:u,modifiers:m,hasImportantModifier:l,baseClassName:h,maybePostfixModifierPosition:g}=t(f);if(u){i=f+(i.length>0?" "+i:i);continue}let p=!!g,w=a(p?h.substring(0,g):h);if(!w){if(!p){i=f+(i.length>0?" "+i:i);continue}if(w=a(h),!w){i=f+(i.length>0?" "+i:i);continue}p=false;}let x=m.length===0?"":m.length===1?m[0]:n(m).join(":"),v=l?x+"!":x,L=v+w;if(s.indexOf(L)>-1)continue;s.push(L);let I=r(w,p);for(let k=0;k<I.length;++k){let S=I[k];s.push(v+S);}i=f+(i.length>0?" "+i:i);}return i},nv=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=Lc(t))&&(r&&(r+=" "),r+=a);return r},Lc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Lc(e[a]))&&(t&&(t+=" "),t+=o);return t},sv=(e,...o)=>{let t,a,r,n,s=i=>{let d=o.reduce((f,u)=>u(f),e());return t=av(d),a=t.cache.get,r=t.cache.set,n=c,c(i)},c=i=>{let d=a(i);if(d)return d;let f=rv(i,t);return r(i,f),f};return n=s,(...i)=>n(nv(...i))},iv=[],Ve=e=>{let o=t=>t[e]||iv;return o.isThemeGetter=true,o},Ic=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Sc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,lv=/^\d+\/\d+$/,dv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,uv=/\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$/,cv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,fv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,mv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ro=e=>lv.test(e),ie=e=>!!e&&!Number.isNaN(Number(e)),Ia=e=>!!e&&Number.isInteger(Number(e)),ol=e=>e.endsWith("%")&&ie(e.slice(0,-1)),ea=e=>dv.test(e),pv=()=>true,hv=e=>uv.test(e)&&!cv.test(e),Cc=()=>false,gv=e=>fv.test(e),xv=e=>mv.test(e),bv=e=>!j(e)&&!$(e),vv=e=>Do(e,Tc,Cc),j=e=>Ic.test(e),ja=e=>Do(e,Ac,hv),rl=e=>Do(e,Sv,ie),xc=e=>Do(e,kc,Cc),yv=e=>Do(e,Mc,xv),as=e=>Do(e,Pc,gv),$=e=>Sc.test(e),Mr=e=>Eo(e,Ac),wv=e=>Eo(e,Cv),bc=e=>Eo(e,kc),Lv=e=>Eo(e,Tc),Iv=e=>Eo(e,Mc),os=e=>Eo(e,Pc,true),Do=(e,o,t)=>{let a=Ic.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Eo=(e,o,t=false)=>{let a=Sc.exec(e);return a?a[1]?o(a[1]):t:false},kc=e=>e==="position"||e==="percentage",Mc=e=>e==="image"||e==="url",Tc=e=>e==="length"||e==="size"||e==="bg-size",Ac=e=>e==="length",Sv=e=>e==="number",Cv=e=>e==="family-name",Pc=e=>e==="shadow";var kv=()=>{let e=Ve("color"),o=Ve("font"),t=Ve("text"),a=Ve("font-weight"),r=Ve("tracking"),n=Ve("leading"),s=Ve("breakpoint"),c=Ve("container"),i=Ve("spacing"),d=Ve("radius"),f=Ve("shadow"),u=Ve("inset-shadow"),m=Ve("text-shadow"),l=Ve("drop-shadow"),h=Ve("blur"),g=Ve("perspective"),p=Ve("aspect"),w=Ve("ease"),x=Ve("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...L(),$,j],k=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],b=()=>[$,j,i],A=()=>[Ro,"full","auto",...b()],V=()=>[Ia,"none","subgrid",$,j],R=()=>["auto",{span:["full",Ia,$,j]},Ia,$,j],H=()=>[Ia,"auto",$,j],q=()=>["auto","min","max","fr",$,j],P=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],W=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...b()],oe=()=>[Ro,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],N=()=>[e,$,j],fe=()=>[...L(),bc,xc,{position:[$,j]}],z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],O=()=>["auto","cover","contain",Lv,vv,{size:[$,j]}],X=()=>[ol,Mr,ja],U=()=>["","none","full",d,$,j],K=()=>["",ie,Mr,ja],Q=()=>["solid","dashed","dotted","double"],te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[ie,ol,bc,xc],de=()=>["","none",h,$,j],Y=()=>["none",ie,$,j],Me=()=>["none",ie,$,j],De=()=>[ie,$,j],Se=()=>[Ro,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ea],breakpoint:[ea],color:[pv],container:[ea],"drop-shadow":[ea],ease:["in","out","in-out"],font:[bv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ea],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ea],shadow:[ea],spacing:["px",ie],text:[ea],"text-shadow":[ea],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ro,j,$,p]}],container:["container"],columns:[{columns:[ie,j,$,c]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"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:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:A()}],"inset-x":[{"inset-x":A()}],"inset-y":[{"inset-y":A()}],start:[{start:A()}],end:[{end:A()}],top:[{top:A()}],right:[{right:A()}],bottom:[{bottom:A()}],left:[{left:A()}],visibility:["visible","invisible","collapse"],z:[{z:[Ia,"auto",$,j]}],basis:[{basis:[Ro,"full","auto",c,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ie,Ro,"auto","initial","none",j]}],grow:[{grow:["",ie,$,j]}],shrink:[{shrink:["",ie,$,j]}],order:[{order:[Ia,"first","last","none",$,j]}],"grid-cols":[{"grid-cols":V()}],"col-start-end":[{col:R()}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":V()}],"row-start-end":[{row:R()}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":q()}],"auto-rows":[{"auto-rows":q()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...P(),"normal"]}],"justify-items":[{"justify-items":[...W(),"normal"]}],"justify-self":[{"justify-self":["auto",...W()]}],"align-content":[{content:["normal",...P()]}],"align-items":[{items:[...W(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...W(),{baseline:["","last"]}]}],"place-content":[{"place-content":P()}],"place-items":[{"place-items":[...W(),"baseline"]}],"place-self":[{"place-self":["auto",...W()]}],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:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:oe()}],w:[{w:[c,"screen",...oe()]}],"min-w":[{"min-w":[c,"screen","none",...oe()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[s]},...oe()]}],h:[{h:["screen","lh",...oe()]}],"min-h":[{"min-h":["screen","lh","none",...oe()]}],"max-h":[{"max-h":["screen","lh",...oe()]}],"font-size":[{text:["base",t,Mr,ja]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,rl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ol,j]}],"font-family":[{font:[wv,j,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,$,j]}],"line-clamp":[{"line-clamp":[ie,"none",$,rl]}],leading:[{leading:[n,...b()]}],"list-image":[{"list-image":["none",$,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Q(),"wavy"]}],"text-decoration-thickness":[{decoration:[ie,"from-font","auto",$,ja]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[ie,"auto",$,j]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,j]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:fe()}],"bg-repeat":[{bg:z()}],"bg-size":[{bg:O()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ia,$,j],radial:["",$,j],conic:[Ia,$,j]},Iv,yv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:X()}],"gradient-via-pos":[{via:X()}],"gradient-to-pos":[{to:X()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:U()}],"rounded-s":[{"rounded-s":U()}],"rounded-e":[{"rounded-e":U()}],"rounded-t":[{"rounded-t":U()}],"rounded-r":[{"rounded-r":U()}],"rounded-b":[{"rounded-b":U()}],"rounded-l":[{"rounded-l":U()}],"rounded-ss":[{"rounded-ss":U()}],"rounded-se":[{"rounded-se":U()}],"rounded-ee":[{"rounded-ee":U()}],"rounded-es":[{"rounded-es":U()}],"rounded-tl":[{"rounded-tl":U()}],"rounded-tr":[{"rounded-tr":U()}],"rounded-br":[{"rounded-br":U()}],"rounded-bl":[{"rounded-bl":U()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Q(),"hidden","none"]}],"divide-style":[{divide:[...Q(),"hidden","none"]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...Q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ie,$,j]}],"outline-w":[{outline:["",ie,Mr,ja]}],"outline-color":[{outline:N()}],shadow:[{shadow:["","none",f,os,as]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":["none",u,os,as]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[ie,ja]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":["none",m,os,as]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[ie,$,j]}],"mix-blend":[{"mix-blend":[...te(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":te()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ie]}],"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":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"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":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"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":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"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":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"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":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"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":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"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":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,j]}],"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":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[ie]}],"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":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:fe()}],"mask-repeat":[{mask:z()}],"mask-size":[{mask:O()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,j]}],filter:[{filter:["","none",$,j]}],blur:[{blur:de()}],brightness:[{brightness:[ie,$,j]}],contrast:[{contrast:[ie,$,j]}],"drop-shadow":[{"drop-shadow":["","none",l,os,as]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:["",ie,$,j]}],"hue-rotate":[{"hue-rotate":[ie,$,j]}],invert:[{invert:["",ie,$,j]}],saturate:[{saturate:[ie,$,j]}],sepia:[{sepia:["",ie,$,j]}],"backdrop-filter":[{"backdrop-filter":["","none",$,j]}],"backdrop-blur":[{"backdrop-blur":de()}],"backdrop-brightness":[{"backdrop-brightness":[ie,$,j]}],"backdrop-contrast":[{"backdrop-contrast":[ie,$,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ie,$,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ie,$,j]}],"backdrop-invert":[{"backdrop-invert":["",ie,$,j]}],"backdrop-opacity":[{"backdrop-opacity":[ie,$,j]}],"backdrop-saturate":[{"backdrop-saturate":[ie,$,j]}],"backdrop-sepia":[{"backdrop-sepia":["",ie,$,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ie,"initial",$,j]}],ease:[{ease:["linear","initial",w,$,j]}],delay:[{delay:[ie,$,j]}],animate:[{animate:["none",x,$,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,j]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:Y()}],"rotate-x":[{"rotate-x":Y()}],"rotate-y":[{"rotate-y":Y()}],"rotate-z":[{"rotate-z":Y()}],scale:[{scale:Me()}],"scale-x":[{"scale-x":Me()}],"scale-y":[{"scale-y":Me()}],"scale-z":[{"scale-z":Me()}],"scale-3d":["scale-3d"],skew:[{skew:De()}],"skew-x":[{"skew-x":De()}],"skew-y":[{"skew-y":De()}],transform:[{transform:[$,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Se()}],"translate-x":[{"translate-x":Se()}],"translate-y":[{"translate-y":Se()}],"translate-z":[{"translate-z":Se()}],"translate-none":["translate-none"],accent:[{accent:N()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,j]}],"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",$,j]}],fill:[{fill:["none",...N()]}],"stroke-w":[{stroke:[ie,Mr,ja,rl]}],stroke:[{stroke:["none",...N()]}],"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 Rc=sv(kv);function Sa(...e){return Rc(ts(e))}var Tv=be.createContext({size:"default",variant:"default",spacing:0});function Ca({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(mc,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Sa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(Tv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var Pv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Oc=createSlice({name:"toolbar",initialState:Pv,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:Wt,setPenColor:rs,setStrokeWidth:il,setFontSize:zA,setFontFamily:GA,setFontStyle:KA,setFontWeight:_A,setTextDecoration:jA,setTextColor:$A}=Oc.actions,Nc=Oc.reducer;var Vc=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,n]=useState(null),[s,c]=useState(0),[i,d]=useState(null),[f,u]=useState(false),m=useRef(null),l=useRef([]),h=useRef(null),g=useRef(null),p=useRef(null);useEffect(()=>((async()=>{try{let b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});d(b),u(!0),p.current&&(p.current.srcObject=b);}catch(b){console.error("Error accessing camera:",b),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{h.current&&clearInterval(h.current),i&&i.getTracks().forEach(b=>b.stop());}),[]);let w=()=>{i&&(i.getTracks().forEach(S=>S.stop()),d(null),u(false));},x=async()=>{try{let S=null,b=null;try{S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(q){console.error("Error accessing camera for recording:",q),alert("Failed to access camera for recording.");return}try{b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(q){console.warn("Microphone access denied:",q);}let A=[...S.getVideoTracks()];b&&A.push(...b.getAudioTracks());let V=new MediaStream(A),R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8");let H=new MediaRecorder(V,{mimeType:R,videoBitsPerSecond:25e5});m.current=H,l.current=[],H.ondataavailable=q=>{q.data.size>0&&l.current.push(q.data);},H.onstop=()=>{let q=new Blob(l.current,{type:R}),P=document.createElement("video");P.src=URL.createObjectURL(q),P.muted=!0,P.currentTime=.1,P.onseeked=()=>{let W=document.createElement("canvas");W.width=P.videoWidth,W.height=P.videoHeight;let E=W.getContext("2d");E&&(E.drawImage(P,0,0),g.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(P.src);},V.getTracks().forEach(W=>W.stop()),S&&S.getTracks().forEach(W=>W.stop()),b&&b.getTracks().forEach(W=>W.stop()),h.current&&clearInterval(h.current),n(q),w();},H.onerror=q=>{console.error("MediaRecorder error:",q);},H.start(1e3),a(!0),c(0),h.current=setInterval(()=>{c(q=>q+1);},1e3);}catch(S){console.error("Error starting camera recording:",S),alert("Failed to start recording. Please check permissions.");}},v=()=>{m.current&&t&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),a(false));},L=()=>{if(r){let S=URL.createObjectURL(r),b=document.createElement("a");b.href=S,b.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(S);}},I=S=>{let b=Math.floor(S/60),A=S%60;return `${b.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`},k=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50 p-6",onMouseDown:S=>{S.target===S.currentTarget&&e(),S.stopPropagation();},onMouseUp:S=>S.stopPropagation(),onMouseMove:S=>S.stopPropagation(),onTouchStart:S=>S.stopPropagation(),onTouchMove:S=>S.stopPropagation(),onTouchEnd:S=>S.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:S=>S.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:p,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!t&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:x,disabled:!f,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"})})}),!f&&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"})})]}),t&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:v,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:I(s)})]})]})]}),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: ",I(s)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),c(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&&g.current&&(o(r,g.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,document.body)};var ta=40,Hc=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,s]=useState(t?.order||"sequential"),[c,i]=useState(false),d=useRef(null),f=useRef(null);useEffect(()=>{let x=v=>{v.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let u=x=>{let v=x.target.files;if(!v||v.length===0)return;let L=ta-a.length;if(L<=0){alert(`You can only upload a maximum of ${ta} images`);return}let I=Array.from(v).slice(0,L);I.length<v.length&&alert(`Only ${L} more images can be added (max ${ta} total)`);let k=I.map(S=>new Promise((b,A)=>{let V=new FileReader;V.onload=R=>{R.target?.result?b(R.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(S);}));Promise.all(k).then(S=>{r(b=>[...b,...S]),f.current&&(f.current.value="");});},m=x=>{x.preventDefault(),i(false);let v=Array.from(x.dataTransfer.files).filter(S=>S.type.startsWith("image/"));if(v.length===0)return;let L=ta-a.length;if(L<=0){alert(`You can only upload a maximum of ${ta} images`);return}let I=v.slice(0,L);I.length<v.length&&alert(`Only ${L} more images can be added (max ${ta} total)`);let k=I.map(S=>new Promise((b,A)=>{let V=new FileReader;V.onload=R=>{R.target?.result?b(R.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(S);}));Promise.all(k).then(S=>{r(b=>[...b,...S]);});},l=x=>{x.preventDefault(),i(true);},h=()=>{i(false);},g=x=>{r(v=>v.filter((L,I)=>I!==x));},w=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 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:d,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:x=>{if(x.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,n,t?.id);},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>=ta?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ta," images"]}):jsxs("span",{children:[a.length,"/",ta," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:u,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:l,onDragLeave:h,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${c?"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$1,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:c?"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 ${n==="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 ${n==="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 ${n==="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 ${n==="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,v)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${v+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>g(v),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:v+1})]},v))})]}),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(w,document.body)};var ns={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},_v={enabled:true};function ul(e){return e?{tools:{...ns.tools,...e.tools},actions:{...ns.actions,...e.actions}}:ns}var jv={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},$v={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var wy=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:r}={})=>{let n=xe(),s=ee(F=>F.canvas.slides.find(ne=>ne.id===F.canvas.currentSlideId)),c=s?.videos||[],i=s?.editingFlashcard,d=ee(F=>F.toolbar.selectedTool),f=ee(F=>F.toolbar.penColor),u=s?.showMcqForm,m=s?.showFlashcardForm,l=useMemo(()=>ul(r),[r]),{tools:h,actions:g}=l,p=c.some(F=>F.isRecorded&&F.isPlaying),w=ee(F=>F.toolbar.fontSize),x=ee(F=>F.toolbar.fontFamily),v=ee(F=>F.toolbar.fontStyle),L=ee(F=>F.toolbar.fontWeight),I=ee(F=>F.toolbar.textDecoration),k=ee(F=>F.toolbar.textColor),[S,b]=useState(false),[A,V]=useState(false),[R,H]=useState(false),[q,P]=useState(false),[W,E]=useState(false),oe=useRef(null),N=useRef(null),fe=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),z=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"}],[]),O=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],[]),X=useMemo(()=>fe.filter(F=>{let ne=h[F.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[h,fe]),U=useMemo(()=>{let F=h.shapes;return F===false?[]:F===true?z:Array.isArray(F)?z.filter(ne=>F.includes(ne.name)):z},[h.shapes,z]),K=useMemo(()=>{let F=h.activities;return F===false?[]:F===true?O:Array.isArray(F)?O.filter(ne=>F.includes(ne.name)):O},[h.activities,O]),Q=useMemo(()=>{let F=h.media;return F===false?{photoFrame:false,image:false,video:false}:F===true?{photoFrame:true,image:true,video:true}:Array.isArray(F)?{photoFrame:F.includes("photo-frame"),image:F.includes("image"),video:F.includes("video")}:{photoFrame:true,image:true,video:true}},[h.media]),te=useMemo(()=>{let F=h.activities;return F===false?false:F===true?true:Array.isArray(F)?F.includes("flashcard"):true},[h.activities]),J=F=>{let ne=F.target.files;!ne||ne.length===0||(n(Wt("select")),n(it(false)),P(false),Array.from(ne).forEach(ve=>{let he=new FileReader;he.onload=se=>{let re=new window.Image;re.src=se.target?.result,re.onload=()=>{let Te=re.width/re.height,Dt=300,Yt=300,st=re.width,Ee=re.height;st>Dt&&(st=Dt,Ee=st/Te),Ee>Yt&&(Ee=Yt,st=Ee*Te),n(le());let qe=(window.innerWidth-st)/2,ht=(window.innerHeight-Ee)/2;n(Ts({id:v4(),src:re.src,x:qe,y:ht,width:st,height:Ee,draggable:true,rotation:0}));};},he.readAsDataURL(ve);}),F.target.value="");},de=async F=>{let ne=F.target.files;if(!(!ne||ne.length===0)){console.log("files",F),n(Wt("select")),n(it(false)),P(false);for(let ve of Array.from(ne))try{let he=URL.createObjectURL(ve),se=document.createElement("video");console.log("video",se),se.src=he,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((Et,ra)=>{let Ft=setTimeout(()=>ra(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ft),Et();},se.onerror=()=>{clearTimeout(Ft),ra(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Et,ra)=>{let Ft=setTimeout(()=>ra(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ft),Et()):se.onloadeddata=()=>{clearTimeout(Ft),Et();};});let re=Math.min(.8,se.duration/2);console.log("Seeking to:",re),se.currentTime=re,await new Promise(Et=>{let ra=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Et();},5e3);se.onseeked=()=>{clearTimeout(ra),console.log("Seek completed"),Et();};});let Te=document.createElement("canvas"),Dt=se.videoWidth/se.videoHeight,Yt=400,st=400,Ee=se.videoWidth,qe=se.videoHeight;Ee>Yt&&(Ee=Yt,qe=Ee/Dt),qe>st&&(qe=st,Ee=qe*Dt),Te.width=Ee,Te.height=qe;let ht=Te.getContext("2d",{willReadFrequently:!1});if(!ht)throw new Error("Failed to get canvas context");if(await new Promise(Et=>setTimeout(Et,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ee,height:qe}),ht.drawImage(se,0,0,Ee,qe);let Ta=Te.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Ta.length),n(le());let Za=(window.innerWidth-Ee)/2,Qa=(window.innerHeight-qe)/2,Aa=v4();await Ga(Aa,ve,Ta),n(Gr({id:Aa,objectUrl:he,thumbnailDataUrl:Ta,videoBlob:ve,x:Za,y:Qa,width:Ee,height:qe,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${ve.name}`);}catch(he){console.error("Error processing video:",he),alert(`Failed to process video: ${ve.name}`);}F.target.value="";}},Y=(F,ne,ve)=>{n(le()),n(Wt("select")),n(it(false));let he=300,se=300,re=(window.innerWidth-he)/2,Te=(window.innerHeight-se)/2;n(ve?ro({id:ve,images:F,order:ne,x:re,y:Te,width:he,height:se,rotation:0,draggable:true}):Rs({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:F,currentIndex:0,order:ne,x:re,y:Te,width:he,height:se,rotation:0,draggable:true})),n(Ra(false));},Me=()=>{n(le()),n(Wt("select")),n(it(false));let F=400,ne=300,ve=(window.innerWidth-F)/2,he=(window.innerHeight-ne)/2;n(Fs({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ve,y:he,width:F,height:ne,rotation:0,draggable:true,isCapturing:false})),E(false);},De=F=>{let he=(window.innerWidth-100)/2,se=(window.innerHeight-100)/2,re={};switch(F.name){case "circle":case "ring":case "wedge":case "arc":re.radius=50,(F.name==="ring"||F.name==="arc")&&(re.innerRadius=25,re.outerRadius=50),(F.name==="wedge"||F.name==="arc")&&(re.angle=F.name==="wedge"?60:90);break;case "ellipse":re.radiusX=60,re.radiusY=40;break;case "triangle":re.radius=50,re.sides=3;break;case "polygon":re.radius=50,re.sides=6;break;case "star":re.innerRadius=25,re.outerRadius=50,re.numPoints=5;break;case "arrow":case "line":re.points=[0,0,100,0],F.name==="arrow"&&(re.pointerLength=10,re.pointerWidth=10);break}let Te={id:`shape-${Date.now()}`,type:F.name,x:he,y:se,width:100,height:100,rotation:0,color:f,...re};n(le()),n(it(false)),n(Wt(F.name)),n(As(Te));},Se=F=>{if(n(Wt(F)),F==="select")n(it(false));else if(F==="text"){n(it(false)),n(le());let ne=200,ve=50,he=(window.innerWidth-ne)/2,se=(window.innerHeight-ve)/2,re=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;n(Ps({id:re,text:"",x:he,y:se,width:ne,height:ve,rotation:0,draggable:true,fontSize:w,fontFamily:x,fontStyle:v,fontWeight:L,textDecoration:I,fill:k,align:"left"})),setTimeout(()=>{n(jo(re));},100),a&&a(re);}else n(it(true));},Rt=()=>{n(Ys()),n(Wt("select")),n(it(false));},Ja=()=>{o?o():t?b(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Er=()=>{V(true);},Fr=async(F,ne)=>{try{n(Wt("select")),n(it(!1));let ve=URL.createObjectURL(F),he=document.createElement("video");he.src=ve,he.muted=!0,he.playsInline=!0,he.preload="auto",await new Promise((Ta,Za)=>{let Qa=setTimeout(()=>Za(new Error("Metadata load timeout")),1e4);he.onloadedmetadata=()=>{clearTimeout(Qa),Ta();},he.onerror=()=>{clearTimeout(Qa),Za(new Error("Failed to load video"));};});let se=640,re=he.videoWidth/he.videoHeight,Te=se,Dt=Te/re,Yt=window.innerWidth,st=window.innerHeight;n(le());let Ee=(Yt-Te)/2,qe=(st-Dt)/2,ht=v4();await Ga(ht,F,ne),n(Gr({id:ht,objectUrl:ve,thumbnailDataUrl:ne,videoBlob:F,x:Ee,y:qe,width:Te,height:Dt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),b(!1),V(!1);}catch(ve){console.error("Error adding recorded video to canvas:",ve),alert("Failed to add video to canvas. Please try again.");}},fs=F=>{n(Wt("select")),n(it(false)),n(Ko(null)),F&&n(Gs(F)),n(da(!u));},ms=()=>{n(Uo(null)),n(Ra(true)),E(false);},ps=()=>{H(!R);},hs=()=>{P(!q);},Ma=()=>{E(!W);};return p?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Ca,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:X.map((F,ne)=>jsx("div",{title:F.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 2xl:py-3 ${F.name===d?"bg-primary/10":""}`,onClick:()=>{if(F.name==="image"){hs(),H(false),E(false),Se(F.name);return}else if(F.name==="shapes"){ps(),P(false),E(false),Se(F.name);return}else if(F.name==="activities"){Se(F.name),Ma(),H(false),P(false);return}Se(F.name),H(false),P(false),E(false);},children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))}),R&&jsx(Ca,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:U.map((F,ne)=>jsx("div",{title:F.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",onClick:()=>De(F),children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))}),q&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Q.photoFrame&&jsx("div",{title:"Photo frame",onClick:Me,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),Q.image&&jsx("div",{title:"Image",onClick:()=>oe.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),Q.video&&jsx("div",{title:"Video",onClick:()=>N.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})})]}),W&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[te&&jsx("div",{title:"Flashcard",onClick:()=>ms(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),K.map((F,ne)=>jsx("div",{title:F.label,onClick:()=>fs(F.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))]})]}),(g.undo||g.redo||g.screenRecord||g.cameraRecord||g.clear)&&jsxs(Ca,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[g.undo&&jsx("button",{value:"undo",onClick:()=>n(Js()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.redo&&jsx("button",{value:"redo",onClick:()=>n(Zs()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.screenRecord&&jsx("button",{value:"screen-record",onClick:Ja,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6279F8]",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.cameraRecord&&jsx("button",{value:"camera-record",onClick:Er,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6BBB93]",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.clear&&jsx("button",{value:"clear",onClick:()=>Rt(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl 2xl:text-2xl"})})]})]}),jsx("input",{ref:oe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:J}),jsx("input",{ref:N,type:"file",accept:"video/*",className:"hidden",onChange:de}),!o&&S&&t&&jsx(or,{onClose:()=>b(false),stageRef:t,onRecordingComplete:Fr}),A&&jsx(Vc,{onClose:()=>V(false),onRecordingComplete:Fr}),m&&jsx(Hc,{editingFlashcard:i,onConfirm:Y,onCancel:()=>n(Ra(false))})]})},Ly=wy;var pl=({onPublish:e,label:o="Publish Slides",className:t})=>{let a=sa(Xo),s=(sa(h=>h.canvas.slides.find(g=>g.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),[c,i]=useState(false),[d,f]=useState(null),[u,m]=useState(null),l=async()=>{if(a.length===0){m({type:"error",message:"No slides to publish"});return}if(!e){m({type:"error",message:"No publish handler provided"});return}i(true),m(null);try{let h=await e(a,g=>{f(g);});h.success?m({type:"success",message:h.message}):m({type:"error",message:h.message});}catch(h){m({type:"error",message:h instanceof Error?h.message:"An unexpected error occurred"});}finally{i(false),setTimeout(()=>{f(null),m(null);},3e3);}};return s?null:jsxs("button",{onClick:l,disabled:c||a.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 Ty=({title:e="Untitled",autoSaveMessage:o="Auto-saved just now",onBack:t,onPublish:a,showPublishButton:r=true,showBackButton:n=true,className:s="",rightContent:c,leftContent:i})=>jsxs("div",{className:`fixed top-0 left-0 z-100 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${s}`,children:[i||jsxs("div",{className:"flex items-center gap-6",children:[n&&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 flex-col",children:[jsx("span",{className:"text-xl font-medium text-[#000000CC] md:text-2xl",children:e}),jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[jsx(CloudArrowUp,{weight:"fill",color:"#63748A",className:"text-sm md:text-xl"}),jsx("span",{className:"text-sm font-medium text-[#63748A] md:text-base",children:o})]})]})]}),c||r&&a&&jsx(pl,{onPublish:a})]});function hl(e,[o,t]){return Math.min(t,Math.max(o,e))}function zc(e){let o=be.useRef({value:e,previous:e});return be.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Kc(e){let[o,t]=be.useState(void 0);return To(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let n=r[0],s,c;if("borderBoxSize"in n){let i=n.borderBoxSize,d=Array.isArray(i)?i[0]:i;s=d.inlineSize,c=d.blockSize;}else s=e.offsetWidth,c=e.offsetHeight;t({width:s,height:c});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var _c=["PageUp","PageDown"],jc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],$c={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Oo="Slider",[gl,Py,Ry]=Jn(Oo),[Xc]=wa(Oo,[Ry]),[Dy,ls]=Xc(Oo),Yc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:s="horizontal",disabled:c=false,minStepsBetweenThumbs:i=0,defaultValue:d=[a],value:f,onValueChange:u=()=>{},onValueCommit:m=()=>{},inverted:l=false,form:h,...g}=e,p=be.useRef(new Set),w=be.useRef(0),v=s==="horizontal"?Ey:Fy,[L=[],I]=Qt({prop:f,defaultProp:d,onChange:R=>{[...p.current][w.current]?.focus(),u(R);}}),k=be.useRef(L);function S(R){let H=qy(L,R);V(R,H);}function b(R){V(R,w.current);}function A(){let R=k.current[w.current];L[w.current]!==R&&m(L);}function V(R,H,{commit:q}={commit:false}){let P=zy(n),W=Gy(Math.round((R-a)/n)*n+a,P),E=hl(W,[a,r]);I((oe=[])=>{let N=Ny(oe,E,H);if(Wy(N,i*n)){w.current=N.indexOf(E);let fe=String(N)!==String(oe);return fe&&q&&m(N),fe?N:oe}else return oe});}return jsx(Dy,{scope:e.__scopeSlider,name:t,disabled:c,min:a,max:r,valueIndexToChangeRef:w,thumbs:p.current,values:L,orientation:s,form:h,children:jsx(gl.Provider,{scope:e.__scopeSlider,children:jsx(gl.Slot,{scope:e.__scopeSlider,children:jsx(v,{"aria-disabled":c,"data-disabled":c?"":void 0,...g,ref:o,onPointerDown:$e(g.onPointerDown,()=>{c||(k.current=L);}),min:a,max:r,inverted:l,onSlideStart:c?void 0:S,onSlideMove:c?void 0:b,onSlideEnd:c?void 0:A,onHomeKeyDown:()=>!c&&V(a,0,{commit:true}),onEndKeyDown:()=>!c&&V(r,L.length-1,{commit:true}),onStepKeyDown:({event:R,direction:H})=>{if(!c){let W=_c.includes(R.key)||R.shiftKey&&jc.includes(R.key)?10:1,E=w.current,oe=L[E],N=n*W*H;V(oe+N,E,{commit:true});}}})})})})});Yc.displayName=Oo;var[Jc,Zc]=Xc(Oo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Ey=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:s,onSlideMove:c,onSlideEnd:i,onStepKeyDown:d,...f}=e,[u,m]=be.useState(null),l=Tt(o,v=>m(v)),h=be.useRef(void 0),g=Po(r),p=g==="ltr",w=p&&!n||!p&&n;function x(v){let L=h.current||u.getBoundingClientRect(),I=[0,L.width],S=vl(I,w?[t,a]:[a,t]);return h.current=L,S(v-L.left)}return jsx(Jc,{scope:e.__scopeSlider,startEdge:w?"left":"right",endEdge:w?"right":"left",direction:w?1:-1,size:"width",children:jsx(Qc,{dir:g,"data-orientation":"horizontal",...f,ref:l,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{let L=x(v.clientX);s?.(L);},onSlideMove:v=>{let L=x(v.clientX);c?.(L);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:v=>{let I=$c[w?"from-left":"from-right"].includes(v.key);d?.({event:v,direction:I?-1:1});}})})}),Fy=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:s,onSlideEnd:c,onStepKeyDown:i,...d}=e,f=be.useRef(null),u=Tt(o,f),m=be.useRef(void 0),l=!r;function h(g){let p=m.current||f.current.getBoundingClientRect(),w=[0,p.height],v=vl(w,l?[a,t]:[t,a]);return m.current=p,v(g-p.top)}return jsx(Jc,{scope:e.__scopeSlider,startEdge:l?"bottom":"top",endEdge:l?"top":"bottom",size:"height",direction:l?1:-1,children:jsx(Qc,{"data-orientation":"vertical",...d,ref:u,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{let p=h(g.clientY);n?.(p);},onSlideMove:g=>{let p=h(g.clientY);s?.(p);},onSlideEnd:()=>{m.current=void 0,c?.();},onStepKeyDown:g=>{let w=$c[l?"from-bottom":"from-top"].includes(g.key);i?.({event:g,direction:w?-1:1});}})})}),Qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:s,onEndKeyDown:c,onStepKeyDown:i,...d}=e,f=ls(Oo,t);return jsx(rt.span,{...d,ref:o,onKeyDown:$e(e.onKeyDown,u=>{u.key==="Home"?(s(u),u.preventDefault()):u.key==="End"?(c(u),u.preventDefault()):_c.concat(jc).includes(u.key)&&(i(u),u.preventDefault());}),onPointerDown:$e(e.onPointerDown,u=>{let m=u.target;m.setPointerCapture(u.pointerId),u.preventDefault(),f.thumbs.has(m)?m.focus():a(u);}),onPointerMove:$e(e.onPointerMove,u=>{u.target.hasPointerCapture(u.pointerId)&&r(u);}),onPointerUp:$e(e.onPointerUp,u=>{let m=u.target;m.hasPointerCapture(u.pointerId)&&(m.releasePointerCapture(u.pointerId),n(u));})})}),ef="SliderTrack",tf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ls(ef,t);return jsx(rt.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});tf.displayName=ef;var xl="SliderRange",af=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ls(xl,t),n=Zc(xl,t),s=be.useRef(null),c=Tt(o,s),i=r.values.length,d=r.values.map(m=>nf(m,r.min,r.max)),f=i>1?Math.min(...d):0,u=100-Math.max(...d);return jsx(rt.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:c,style:{...e.style,[n.startEdge]:f+"%",[n.endEdge]:u+"%"}})});af.displayName=xl;var bl="SliderThumb",of=be.forwardRef((e,o)=>{let t=Py(e.__scopeSlider),[a,r]=be.useState(null),n=Tt(o,c=>r(c)),s=be.useMemo(()=>a?t().findIndex(c=>c.ref.current===a):-1,[t,a]);return jsx(By,{...e,ref:n,index:s})}),By=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,s=ls(bl,t),c=Zc(bl,t),[i,d]=be.useState(null),f=Tt(o,x=>d(x)),u=i?s.form||!!i.closest("form"):true,m=Kc(i),l=s.values[a],h=l===void 0?0:nf(l,s.min,s.max),g=Vy(a,s.values.length),p=m?.[c.size],w=p?Hy(p,h,c.direction):0;return be.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",[c.startEdge]:`calc(${h}% + ${w}px)`},children:[jsx(gl.ItemSlot,{scope:e.__scopeSlider,children:jsx(rt.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":s.min,"aria-valuenow":l,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...n,ref:f,style:l===void 0?{display:"none"}:e.style,onFocus:$e(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),u&&jsx(rf,{name:r??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:l},a)]})});of.displayName=bl;var Oy="RadioBubbleInput",rf=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),n=Tt(r,a),s=zc(o);return be.useEffect(()=>{let c=r.current;if(!c)return;let i=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==o&&f){let u=new Event("input",{bubbles:true});f.call(c,o),c.dispatchEvent(u);}},[s,o]),jsx(rt.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});rf.displayName=Oy;function Ny(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function nf(e,o,t){let n=100/(t-o)*(e-o);return hl(n,[0,100])}function Vy(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function qy(e,o){if(e.length===1)return 0;let t=e.map(r=>Math.abs(r-o)),a=Math.min(...t);return t.indexOf(a)}function Hy(e,o,t){let a=e/2,n=vl([0,50],[0,a]);return (a-n(o)*t)*t}function Uy(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Wy(e,o){if(o>0){let t=Uy(e);return Math.min(...t)>=o}return true}function vl(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 zy(e){return (String(e).split(".")[1]||"").length}function Gy(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var sf=Yc,lf=tf,df=af,uf=of;function ff({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:s,thumbClassName:c,...i}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(sf,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Sa("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(lf,{"data-slot":"slider-track",className:Sa("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(df,{"data-slot":"slider-range",className:Sa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:d.length},(f,u)=>jsx(uf,{"data-slot":"slider-thumb",className:Sa("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",c)},u))]})}var $y=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Xy=({colors:e=$y,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let n=ee(c=>c.toolbar.penColor),s=xe();return jsxs("div",{className:`absolute bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:p-6 ${r}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(ff,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:c=>s(il(c[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(Ca,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(c=>jsx("button",{value:c.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${n===c.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:c.value},onClick:()=>s(rs(c.value))},c.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>s(rs(c.target.value))}),jsx(Plus,{color:"#00000099"})]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center px-2 2xl:px-4",children:jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033] lg:h-12 lg:w-12",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>s(ks(c.target.value))})})})]})};function Yy({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var pf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Zy=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),wl=e=>{let o=Zy(e);return o.charAt(0).toUpperCase()+o.slice(1)},ds=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),hf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var gf={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 bf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:s,...c},i)=>createElement("svg",{ref:i,...gf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:ds("lucide",r),...!n&&!hf(c)&&{"aria-hidden":"true"},...c},[...s.map(([d,f])=>createElement(d,f)),...Array.isArray(n)?n:[n]]));var us=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(bf,{ref:n,iconNode:o,className:ds(`lucide-${pf(wl(e))}`,`lucide-${e}`,a),...r}));return t.displayName=wl(e),t};var aw=[["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"}]],Rr=us("copy",aw);var ow=[["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"}]],Dr=us("trash-2",ow);var yf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:s})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"shadow-lg":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:r,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:c=>{c.stopPropagation(),n();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Rr,{size:14})}),!a&&jsx("button",{onClick:c=>{c.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(Dr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var iw=()=>{let e=yt(),o=sa(Xo),t=sa($o),a=sa(Qs),[r,n]=useState(true),i=(sa(l=>l.canvas.slides.find(h=>h.id===l.canvas.currentSlideId))?.videos||[]).some(l=>l.isRecorded&&l.isPlaying),d=()=>{a&&e(ws());},f=l=>{e(Ss(l));},u=l=>{e(Is(l));},m=l=>{o.length>1&&e(Ls(l));};return i?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-100 flex items-start",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[o.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:o.map((l,h)=>jsx(yf,{slide:l,index:h,isSelected:l.id===t,isSingleSlide:o.length===1,onSelect:()=>f(l.id),onDuplicate:()=>u(l.id),onDelete:()=>m(l.id)},l.id))}),jsxs("button",{onClick:d,disabled:!a,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${a?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var lw="SchooplaEditorDB",dw=1,ka="slides",Ll="schoopla_current_slide_id",Il=()=>new Promise((e,o)=>{let t=indexedDB.open(lw,dw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(ka)||r.createObjectStore(ka,{keyPath:"id"});};}),Sl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Il(),a=o.transaction([ka],"readwrite").objectStore(ka);await new Promise((r,n)=>{let s=a.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);});for(let r of e)await new Promise((n,s)=>{let c=a.add(r);c.onsuccess=()=>n(!0),c.onerror=()=>s(c.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);}}},Cl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Il(),t=e.transaction([ka],"readonly").objectStore(ka);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.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(c=>({id:c.id,width:c.width,height:c.height,x:c.x,y:c.y}))),a(s.length>0?s:null);},n.onerror=()=>{e.close(),r(n.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}}},cs=async()=>{try{let e=await Il(),t=e.transaction([ka],"readwrite").objectStore(ka);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(Ll),await Uu();}catch(e){console.error("Error clearing local data:",e);}},kl=e=>{try{localStorage.setItem(Ll,e);}catch(o){console.error("Error saving current slide ID:",o);}},Ml=()=>{try{return localStorage.getItem(Ll)}catch(e){return console.error("Error loading current slide ID:",e),null}},If=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}};var uw=["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"],cw=["canvas/clearCanvas"],fw=If((e,o)=>{Sl(e),kl(o);},500),mw=(e,o)=>{Sl(e),kl(o);},Tl=false,Sf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;$i(r).catch(n=>{console.error("Error deleting video blob:",n);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,s=e.getState().canvas.slides.find(c=>c.id===r);s&&s.videos&&s.videos.length>0&&s.videos.forEach(c=>{$i(c.id).catch(i=>{console.error("Error deleting video blob:",i);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,n=e.getState(),c=n.canvas.slides.find(i=>i.id===n.canvas.currentSlideId)?.videos.find(i=>i.id===r);c&&c.videoBlob&&setTimeout(()=>{let i=e.getState(),f=i.canvas.slides.find(u=>u.id===i.canvas.currentSlideId)?.videos.find(u=>u.id!==r&&u.x===c.x+20&&u.y===c.y+20);f&&c.videoBlob&&Ga(f.id,c.videoBlob,f.thumbnailDataUrl).catch(u=>{console.error("Error saving duplicated video blob:",u);});},0);}let a=o(t);if(t.type&&cw.includes(t.type)){if(!Tl){Tl=true;try{let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;mw(n,s);}finally{setTimeout(()=>{Tl=false;},0);}}}else if(t.type&&uw.includes(t.type)){let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;fw(n,s);}return a});new QueryClient;var gw=configureStore({reducer:{toolbar:Nc,canvas:Gl},middleware:e=>e({serializableCheck:false}).concat(Sf)});var xw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:n=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",c=e.toDataURL({mimeType:s,quality:a,pixelRatio:r}),i=document.createElement("a");i.download=`${n}.${t}`,i.href=c,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")}},bw=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((n,s)=>{try{let c=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:c,quality:a,pixelRatio:r});fetch(i).then(d=>d.blob()).then(d=>n(d)).catch(d=>s(d));}catch(c){s(c);}})},vw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,n=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:n,quality:a,pixelRatio:r})};var yw=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let n=a*a+r*r,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/n)),c=o.x+s*a,i=o.y+s*r;return Math.sqrt(Math.pow(e.x-c,2)+Math.pow(e.y-i,2))},Al=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],n=e[e.length-1];for(let s=1;s<e.length-1;s++){let c=yw(e[s],r,n);c>t&&(t=c,a=s);}if(t>o){let s=Al(e.slice(0,a+1),o),c=Al(e.slice(a),o);return [...s.slice(0,-1),...c]}return [r,n]},ww=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},Lw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Cf=(e,o=1.5)=>{if(e.length<=4)return e;let t=ww(e),a=Al(t,o);return Lw(a)},kf=(e,o=1.5)=>({...e,points:Cf(e.points,o)}),Iw=(e,o=1.5)=>e.map(t=>kf(t,o)),Sw=(e,o)=>{let t=e.length/2,a=o.length/2,r=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${r}%`}};var Cw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Mf=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((n,s)=>{let c=new Image;c.onload=()=>{let{width:i,height:d}=c;if(i>t||d>a){let h=i/d;i>d?(i=Math.min(i,t),d=i/h):(d=Math.min(d,a),i=d*h);}let f=document.createElement("canvas");f.width=i,f.height=d;let u=f.getContext("2d");if(!u){s(new Error("Failed to get canvas context"));return}u.drawImage(c,0,0,i,d);let m=Cw(e),l=f.toDataURL(m,r);n(l);},c.onerror=s,c.src=e;})};var Ya=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return a.buffer},No=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Vo=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",kw=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,s=[],c=0;for(let i of e){let d=[],f=[],u=[];for(let m of i.images){let l=m.src;if(t&&l.startsWith("data:"))try{l=await Mf(l,{maxWidth:a,maxHeight:r,quality:n});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(l.startsWith("data:")){let h=Ya(l),g=No(l);c+=h.byteLength;let p={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,buffer:h,mimeType:g};if(m.audioData&&m.audioData.startsWith("data:")){let w=Ya(m.audioData),x=No(m.audioData);c+=w.byteLength,p.audioBuffer=w,p.audioMimeType=x;}d.push(p);}}for(let m of i.videos){let l,h;if(m.videoBlob)l=await m.videoBlob.arrayBuffer(),h=m.videoBlob.type;else if(m.videoData&&m.videoData.startsWith("data:"))l=Ya(m.videoData),h=No(m.videoData);else {console.warn(`Video ${m.id} has no blob or videoData, skipping`);continue}c+=l.byteLength;let g={id:m.id,thumbnailDataUrl:m.thumbnailDataUrl,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,isPlaying:m.isPlaying,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isRecorded:m.isRecorded,buffer:l,mimeType:h};if(m.audioData&&m.audioData.startsWith("data:")){let p=Ya(m.audioData),w=No(m.audioData);c+=p.byteLength,g.audioBuffer=p,g.audioMimeType=w;}f.push(g);}for(let m of i.photoFrames){let l={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:m.draggable,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isCapturing:m.isCapturing};if(m.capturedImageUrl&&m.capturedImageUrl.startsWith("data:")){let h=Ya(m.capturedImageUrl),g=No(m.capturedImageUrl);c+=h.byteLength,l.buffer=h,l.mimeType=g;}if(m.audioData&&m.audioData.startsWith("data:")){let h=Ya(m.audioData),g=No(m.audioData);c+=h.byteLength,l.audioBuffer=h,l.audioMimeType=g;}u.push(l);}s.push({...i,images:d,videos:f,photoFrames:u});}return {slides:s,totalSize:c}},Mw=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},Tw=e=>{let o=new FormData,t=e.slides.map((a,r)=>({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((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,mimeType:n.mimeType,fileKey:`slide_${r}_image_${s}`,audioFileKey:n.audioBuffer?`slide_${r}_image_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),videos:a.videos.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,isPlaying:n.isPlaying,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isRecorded:n.isRecorded,mimeType:n.mimeType,fileKey:`slide_${r}_video_${s}`,thumbnailFileKey:`slide_${r}_video_${s}_thumbnail`,audioFileKey:n.audioBuffer?`slide_${r}_video_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),photoFrames:a.photoFrames.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,draggable:n.draggable,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isCapturing:n.isCapturing,mimeType:n.mimeType,fileKey:n.buffer?`slide_${r}_photoframe_${s}`:void 0,audioFileKey:n.audioBuffer?`slide_${r}_photoframe_${s}_audio`:void 0,audioMimeType:n.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),i=`${n.id}.${Vo(n.mimeType)}`;if(o.append(`slide_${r}_image_${s}`,c,i),n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${Vo(n.audioMimeType)}`;o.append(`slide_${r}_image_${s}_audio`,d,f);}}),a.videos.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),i=`${n.id}.${Vo(n.mimeType)}`;if(o.append(`slide_${r}_video_${s}`,c,i),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let d=Ya(n.thumbnailDataUrl),f=new Blob([d],{type:"image/jpeg"}),u=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${s}_thumbnail`,f,u);}if(n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${Vo(n.audioMimeType)}`;o.append(`slide_${r}_video_${s}_audio`,d,f);}}),a.photoFrames.forEach((n,s)=>{if(n.buffer&&n.mimeType){let c=new Blob([n.buffer],{type:n.mimeType}),i=`${n.id}.${Vo(n.mimeType)}`;o.append(`slide_${r}_photoframe_${s}`,c,i);}if(n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),i=`${n.id}_audio.${Vo(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${s}_audio`,c,i);}});}),o};var Pw=()=>{let e=yt();useEffect(()=>{(async()=>{try{let t=await Cl(),a=Ml();if(t&&t.length>0){let r=await Hu(),n=t.map(c=>{if(c.videos&&c.videos.length>0){let i=c.videos.map(d=>{let f=r.get(d.id);if(f){let u=Wu(f.blob);return {...d,objectUrl:u,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return d});return {...c,videos:i}}return c}),s=a&&n.find(c=>c.id===a)?a:n[0].id;e(to({slides:n,currentSlideId:s}));}}catch(t){console.error("Error loading persisted slides:",t);}})();},[e]);};var Af=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||""})),Pf=new WeakSet,Rf=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 Ga(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},Rw=()=>{let e=yt(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Pf.has(a))return;Pf.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await cs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let c=n&&r.find(d=>d.id===n)?n:r[0].id,i=Af(r);e(to({slides:i,currentSlideId:c})),await Rf(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await cs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let c=n&&r.find(d=>d.id===n)?n:r[0].id,i=Af(r);e(to({slides:i,currentSlideId:c})),await Rf(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
|
|
7
7
|
|
|
8
8
|
lucide-react/dist/esm/shared/src/utils.js:
|
|
9
9
|
lucide-react/dist/esm/defaultAttributes.js:
|