@turnix-co/konva-editor 2.0.56 → 2.0.57
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/package.json +1 -1
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,F=r.find(H=>H.id===n)?.fontSize||24,R=A*F*1.2+10;g.width=Math.max(200,L),g.height=Math.max(50,P,R);}else if(p&&u.trim()){let b=p.text(),y=p.width();p.text(u),p.width(void 0);let S=p.width(),I=p.height();p.text(b),p.width(y),g.width=Math.max(200,S+20),g.height=Math.max(50,I+20);}t(wt(g)),i(null),l(""),t(Ho(null)),e();}}}};var sd=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],r=useRef(new Map),s=useCallback((n,i)=>{let u=n.target;o(Oo({id:i,x:u.x(),y:u.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:s}};var nd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((s,n)=>{let i=s.target;o(No({id:n,x:i.x(),y:i.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var ld=e=>{let o=xe(),a=ee(ge)?.flashcards||[],r=useRef(new Map),s=useRef(new Map),n=useCallback((d,m)=>{if(s.current.has(m))return s.current.get(m);let f=new window.Image;return f.src=d,s.current.set(m,f),f},[]),i=useCallback((d,m)=>{let f=d.target,h=f.id();a.find(p=>p.id===h)&&(o(Za({id:h,x:f.x(),y:f.y()})),m?.());},[a,o]),u=useCallback((d,m)=>{let f=m.target,h=f.scaleX(),x=f.scaleY(),p=f.rotation(),v=Math.max(50,f.width()*h),g=Math.max(50,f.height()*x);f.scaleX(1),f.scaleY(1),f.width(v),f.height(g),o(Za({id:d,width:v,height:g,x:f.x(),y:f.y(),rotation:p})),f.getLayer()?.batchDraw(),e?.();},[o,e]),l=useCallback(d=>{o(In(d)),e?.();},[o,e]),c=useCallback(d=>{o(Cn(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:r,handleDragEnd:i,handleFlashcardTransformEnd:u,handleNext:l,handlePrevious:c}};var cd=e=>{let o=xe(),a=ee(ge)?.photoFrames||[],r=useRef(new Map),[s,n]=useState(new Map),i=useCallback((f,h)=>{console.log("handleDragEnd"),o(Aa({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),u=useCallback((f,h)=>{let x=h.target,p=x.scaleX(),v=x.scaleY(),g=x.rotation(),b=a.find(I=>I.id===f);if(!b)return;let y=Math.max(100,b.width*p),S=Math.max(100,b.height*v);x.scaleX(1),x.scaleY(1),o(Aa({id:f,width:y,height:S,x:x.x(),y:x.y(),rotation:g})),x.getLayer()?.batchDraw(),e?.();},[o,e,a]),l=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(x=>{let p=new Map(x);return p.set(f,h),p}),o(Aa({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),c=useCallback(f=>{let h=s.get(f);h&&(h.getTracks().forEach(x=>x.stop()),n(x=>{let p=new Map(x);return p.delete(f),p}),o(Aa({id:f,isCapturing:false})),e?.());},[s,o,e]),d=useCallback((f,h)=>{let x=document.createElement("canvas");x.width=h.videoWidth,x.height=h.videoHeight;let p=x.getContext("2d");if(p){p.drawImage(h,0,0,x.width,x.height);let v=x.toDataURL("image/jpeg",.8);return o(Aa({id:f,capturedImageUrl:v,isCapturing:false})),c(f),e?.(),v}return null},[o,c,e]),m=useRef(s);return useEffect(()=>{m.current=s;},[s]),useEffect(()=>()=>{m.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:i,handlePhotoFrameTransformEnd:u,startCamera:l,stopCamera:c,capturePhoto:d,cameraStreams:s}};var fd=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((s,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),a=useCallback((s,n,i,u,l,c,d=[])=>{if(e.current){if(s&&!d.find(h=>h.id===s)?.isPlaying){let h=n.get(s)||i.get(s)||u.get(s)||l.get(s)||c.get(s);if(h){e.current.boundBoxFunc(t),e.current.nodes([h]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var Wm=(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])},gd=(e,o)=>{let t=yt(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let n=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});n&&n.startsWith("data:")&&t(fn({id:a.current,thumbnail:n}));}catch(n){console.warn("Could not generate thumbnail (likely CORS issue with images):",n);}},[o,t]),s=Wm(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var Km=e=>e.flatMap(o=>[o[0],o[1]]),ss=(e,o)=>{let t=_l(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 Km(t)};var xd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[s,n]=useState(null),i=ee(b=>b.toolbar.selectedTool),u=ee(b=>b.toolbar.penColor),l=ee(b=>b.toolbar.strokeWidth),c=ee(b=>b.canvas.isSketchMode),d=ee(b=>b.canvas.slides.find(S=>S.id===b.canvas.currentSlideId)?.images.find(S=>S.id===e)),m=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,x=d?.height||1,p=useCallback(b=>{if(i!=="pen"&&i!=="eraser")return;t.current=true,a.current=false,r.current=[{x:b.x,y:b.y}];let y=b.x/h,S=b.y/x;n({tool:i,points:[y,S],color:u,strokeWidth:l/h,isSketch:c});},[i,u,l,c,h,x]),v=useCallback(b=>{if(!t.current||!s)return;a.current=true;let y=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-y.x,2)+Math.pow(b.y-y.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(c)I=ss(r.current,{size:l*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((L,P)=>P%2===0?L/h:L/x);else {let C=b.x/h,L=b.y/x;I=[...s.points,C,L];}n(C=>C?{...C,points:I}:null);},[c,l,s,h,x]),g=useCallback(()=>{t.current&&(s&&s.points.length>0&&o(An({imageId:e,line:s})),n(null),t.current=false,a.current=false,r.current=[]);},[o,e,s]);return {annotations:m,activeLine:s,isDrawingMode:f,startDrawing:p,draw:v,stopDrawing:g,tool:i}};var wd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:s,onContextMenu:n})=>{let{annotations:i,activeLine:u,stopDrawing:m,tool:f}=xd(e.id);useEffect(()=>{let g=t.current.get(e.id);g&&(g.width()!==e.width||g.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:g.width(),konvaHeight:g.height()}),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let h=false;useEffect(()=>{return;},[m,h]);let x=g=>{{s(e.id);return}},p=g=>{return;},v=g=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="eraser",children:[jsx(Image$1,{id:e.id,ref:g=>{if(g){t.current.set(e.id,g),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw();let b=g.getStage()?.container();if(b){let y=S=>{let I=g.getStage()?.getPointerPosition();if(I){let C={x:e.x,y:e.y,width:e.width,height:e.height};I.x>=C.x&&I.x<=C.x+C.width&&I.y>=C.y&&I.y<=C.y+C.height&&n(S,e.id,"image");}};b.addEventListener("contextmenu",y),g._contextMenuCleanup=()=>{b.removeEventListener("contextmenu",y);};}}else {let b=t.current.get(e.id);b?._contextMenuCleanup&&b._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:g=>r(e.id,g),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...f!=="pen"&&f!=="eraser"?{onClick:x,onTap:x,onMouseDown:x,onTouchStart:x,onMouseMove:p,onTouchMove:p,onMouseUp:v,onTouchEnd:v}:{}}),i?.map((g,b)=>{let y=g.points.map((I,C)=>C%2===0?I*e.width+e.x:I*e.height+e.y),S=g.strokeWidth*e.width;return jsx(Line,{points:y,stroke:g.tool==="eraser"?"white":g.color,strokeWidth:S,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:g.tool==="eraser"?"destination-out":"source-over",fill:g.isSketch?g.color:void 0,closed:g.isSketch,listening:false},b)}),u&&jsx(Line,{points:u.points.map((g,b)=>b%2===0?g*e.width+e.x:g*e.height+e.y),stroke:u.tool==="eraser"?"white":u.color,strokeWidth:u.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:u.tool==="eraser"?"destination-out":"source-over",fill:u.isSketch?u.color:void 0,closed:u.isSketch,listening:false},"active")]})});wd.displayName="ImageWithDrawing";var si=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:s,onContextMenu:n})=>jsx(Fragment,{children:e.map(i=>{let u=o(i);return u?jsx(wd,{img:i,loadedImage:u,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:s,onContextMenu:n},i.id):null})}));si.displayName="ImageLayer";var tp=({src:e,x:o,id:t,y:a,width:r,height:s,isSelected:n,rotation:i=0,onTransformEnd:u,onDragEnd:l})=>{let c=xe(),d=useRef(null),m=f=>{c(Eo(f));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:s,rotation:i,onDragEnd:l,onTransformEnd:u,children:[jsx(Rect,{width:r,height:s,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${s}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>m(t),onSeeking:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Ld=tp;var dp=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,nodeRef:n})=>{let[i,u]=useState(null),l=useSelector(x=>x.toolbar.selectedTool),c=l==="pen"||l==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let x=new window.Image;x.src=e.thumbnailDataUrl,x.onload=()=>{u(x);};}},[e.thumbnailDataUrl]),!i)return null;let d=e.width/2,m=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,80));return jsxs(Group,{draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:a,onTransformEnd:r},ref:x=>{if(n(x),x){let p=x.getStage()?.container();if(p){let v=g=>{let b=x.getStage()?.getPointerPosition();if(b){let y={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=y.x&&b.x<=y.x+y.width&&b.y>=y.y&&b.y<=y.y+y.height&&s(g);}};p.addEventListener("contextmenu",v),x._contextMenuCleanup=()=>{p.removeEventListener("contextmenu",v);};}}},children:[jsx(Image$1,{image:i,width:e.width,height:e.height,listening:!c,...c?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:d,y:m,radius:h,fill:"white",listening:!c,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...c?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:m,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!c,...c?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:m,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!c,...c?{}:{onClick:t,onTap:t}})]})},Id=dp;var li=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:s,onContextMenu:n})=>jsx(Fragment,{children:e.map(i=>jsxs(be__default.Fragment,{children:[jsx(Id,{video:i,isSelected:!i.isPlaying&&o===i.id,onClick:()=>a(i.id),onDragEnd:u=>r(i.id,u),onTransformEnd:u=>s(i.id,u),onContextMenu:u=>n(u,i.id,"video"),nodeRef:u=>{u?t.current.set(i.id,u):t.current.delete(i.id);}}),i.isPlaying&&(()=>{let u=i.x,l=i.y;if(i.isRecorded){let c=typeof window<"u"?window.innerWidth:i.width,d=typeof window<"u"?window.innerHeight:i.height;u=(c-i.width)/2,l=(d-i.height)/2;}return jsx(Ld,{id:i.id,src:i.objectUrl,x:u,y:l,width:i.width,height:i.height,isSelected:false,rotation:i.rotation,onTransformEnd:c=>s(i.id,c),onDragEnd:c=>r(i.id,c)})})()]},i.id))}));li.displayName="VideoLayer";var di=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:s,onContextMenu:n})=>{let i=useSelector(l=>l.toolbar.selectedTool),u=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map((l,c)=>{let d=l.id||c,m={id:l.id,x:l.x,y:l.y,rotation:l.rotation,draggable:!l.locked&&!u,listening:!u,fill:l.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(l.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},radius:l.radius||l.width/2,width:l.width,height:l.width},d);case "star":return jsx(Star,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},numPoints:5,innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},d);case "triangle":return jsx(RegularPolygon,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},sides:3,radius:l.radius||l.width/2},d);case "polygon":return jsx(RegularPolygon,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},sides:l.sides||6,radius:l.radius||l.width/2},d);case "ellipse":return jsx(Ellipse,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},radiusX:l.radiusX||l.width/2,radiusY:l.radiusY||l.height/2},d);case "ring":return jsx(Ring,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},d);case "wedge":return jsx(Wedge,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},radius:l.radius||l.width/2,angle:l.angle||60},d);case "arrow":return jsx(Arrow,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},points:l.points||[0,0,l.width,0],pointerLength:l.pointerLength||10,pointerWidth:l.pointerWidth||10,stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},d);case "line":return jsx(Line,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},points:l.points||[0,0,l.width,0],stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},d);case "arc":return jsx(Arc,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2,angle:l.angle||90},d);case "rectangle":default:return jsx(Rect,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},width:l.width,height:l.height,cornerRadius:l.type==="rounded-rectangle"?10:0},d)}})})});di.displayName="ShapeLayer";var Md=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:s,onDoubleClick:n,editingTextId:i})=>{let u=useSelector(c=>c.toolbar.selectedTool),l=u==="pen"||u==="eraser";return jsx(Fragment,{children:e.map(c=>{let d=c.id===i,m=c.fontWeight==="bold",f=m?Math.max(1,c.fontSize/25):0;return jsx(Text,{id:c.id,ref:h=>{h?o.current.set(c.id,h):o.current.delete(c.id);},text:c.text,x:c.x,y:c.y,width:c.width,height:c.height,rotation:c.rotation,draggable:!c.locked&&!d&&!l,listening:!l,fontSize:c.fontSize,fontFamily:c.fontFamily,fontStyle:c.fontStyle,fontWeight:c.fontWeight,textDecoration:c.textDecoration,fill:c.fill,stroke:m?c.fill:void 0,strokeWidth:f,align:c.align,wrap:"none",lineHeight:1.2,opacity:d?0:1,visible:!d,...l?{}:{onClick:()=>r(c.id),onTap:()=>r(c.id),onDblClick:()=>n(c.id),onDblTap:()=>n(c.id),onDragEnd:h=>t(h,c.id),onTransformEnd:()=>a(c.id),onContextMenu:h=>{h.evt.preventDefault();let x=h.evt;s(x,c.id,"text");}}},c.id)})})};var Ep=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,onNext:n,onPrevious:i,nodeRef:u})=>{let[l,c]=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=()=>{c(p);};}},[e.images,e.currentIndex]),!l||e.images.length===0)return null;let d=8,m=2,f=Math.min(e.width,e.height)*.08,h=Math.max(16,Math.min(f,32)),x=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(u(p),p){let v=p.getStage()?.container();if(v){let g=b=>{let y=p.getStage()?.getPointerPosition();if(y){let S={x:e.x,y:e.y,width:e.width,height:e.height};y.x>=S.x&&y.x<=S.x+S.width&&y.y>=S.y&&y.y<=S.y+S.height&&s(b);}};v.addEventListener("contextmenu",g),p._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",g);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:d,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:d,stroke:"#E5E7EB",strokeWidth:m,listening:false}),jsx(Image$1,{x:m+4,y:m+4,image:l,width:e.width-(m+4)*2,height:e.height-(m+4)*2,cornerRadius:d-m,onClick:t,onTap:t}),jsx(Rect,{x:m,y:e.height-50,width:e.width-m*2,height:50,cornerRadius:[0,0,d-m,d-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:x+h,y:e.height/2,onClick:p=>{p.cancelBubble=true,i();},onTap:p=>{p.cancelBubble=true,i();},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-x-h,y:e.height/2,onClick:p=>{p.cancelBubble=true,n();},onTap:p=>{p.cancelBubble=true,n();},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"})]})},Pd=Ep;var fi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:s,onNext:n,onPrevious:i,onContextMenu:u})=>jsx(Fragment,{children:e.map(l=>jsx(Pd,{flashcard:l,isSelected:t===l.id,onClick:()=>s(l.id),onDragEnd:a,onTransformEnd:c=>r(l.id,c),onContextMenu:c=>u(c,l.id,"flashcard"),onNext:()=>n(l.id),onPrevious:()=>i(l.id),nodeRef:c=>{c?o.current.set(l.id,c):o.current.delete(l.id);}},l.id))}));fi.displayName="FlashcardLayer";var Rd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[s,n]=useState(null);ee(b=>b.toolbar.selectedTool);let u=ee(b=>b.toolbar.penColor),l=ee(b=>b.toolbar.strokeWidth),c=ee(b=>b.canvas.isSketchMode),d=ee(b=>b.canvas.slides.find(S=>S.id===b.canvas.currentSlideId)?.photoFrames.find(S=>S.id===e)),m=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,x=d?.height||1,p=useCallback(b=>{if(!f)return;t.current=true,a.current=false,r.current=[{x:b.x,y:b.y}];let y=b.x/h,S=b.y/x;n({tool:"pen",points:[y,S],color:u,strokeWidth:l/h,isSketch:c});},[f,u,l,c,h,x]),v=useCallback(b=>{if(!t.current||!s)return;a.current=true;let y=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-y.x,2)+Math.pow(b.y-y.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(c)I=ss(r.current,{size:l*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((L,P)=>P%2===0?L/h:L/x);else {let C=b.x/h,L=b.y/x;I=[...s.points,C,L];}n(C=>C?{...C,points:I}:null);},[c,l,s,h,x]),g=useCallback(()=>{t.current&&(s&&s.points.length>0&&o(Dn({frameId:e,line:s})),n(null),t.current=false,a.current=false,r.current=[]);},[o,e,s]);return {annotations:m,activeLine:s,isDrawingMode:f,startDrawing:p,draw:v,stopDrawing:g}};var Wp=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,onStartCamera:n,onCapture:i,cameraStream:u,nodeRef:l})=>{let[c,d]=useState(null),[m,f]=useState(null),h=useRef(null),x=useRef(null),p=useRef(null),v=useRef(null),g=useRef(0),b=33,y=useSelector(D=>D.toolbar.selectedTool),S=y==="pen"||y==="eraser",{annotations:I,activeLine:C,isDrawingMode:L,startDrawing:P,draw:A,stopDrawing:U}=Rd(e.id);useEffect(()=>{if(!L)return;let D=()=>{U();},z=()=>{U();};return window.addEventListener("mouseup",D),window.addEventListener("touchend",z),()=>{window.removeEventListener("mouseup",D),window.removeEventListener("touchend",z);}},[U,L]),useEffect(()=>{if(e.capturedImageUrl){let D=new window.Image;D.src=e.capturedImageUrl,D.onload=()=>{d(D);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&u){h.current||(h.current=document.createElement("video"),h.current.autoplay=true,h.current.playsInline=true),x.current||(x.current=document.createElement("canvas"));let D=h.current,z=x.current;D.srcObject=u;let X=()=>{z.width=D.videoWidth||640,z.height=D.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",z.width,z.height);let _=Y=>{if(Y-g.current<b){p.current=requestAnimationFrame(_);return}g.current=Y;let Z=z.getContext("2d");if(Z&&D.readyState===D.HAVE_ENOUGH_DATA){Z.drawImage(D,0,0,z.width,z.height);let Q=z.toDataURL("image/jpeg",.6),pe=new window.Image;pe.onload=()=>{f(pe);},pe.src=Q;}p.current=requestAnimationFrame(_);};p.current=requestAnimationFrame(_);};return D.onloadedmetadata=X,D.readyState>=D.HAVE_METADATA&&X(),D.play().catch(_=>console.error("Error playing video:",_)),()=>{p.current&&(cancelAnimationFrame(p.current),p.current=null);}}return ()=>{f(null),v.current&&(v.current.src="");}},[e.isCapturing,u]);let F=()=>{h.current&&e.isCapturing&&i(h.current);},E=D=>{if(e.capturedImageUrl){if(!L){t();return}let z=D.currentTarget,X=z.getAbsoluteTransform().copy(),Y=z.getStage()?.getPointerPosition();if(Y){X.invert();let Z=X.point(Y);P(Z);}D.cancelBubble=true;}else t();},R=D=>{if(!L||!e.capturedImageUrl)return;let z=D.currentTarget,X=z.getAbsoluteTransform().copy(),Y=z.getStage()?.getPointerPosition();if(Y){X.invert();let Z=X.point(Y);A(Z);}},H=()=>{!L||!e.capturedImageUrl||U();},N=e.isCapturing?m:c,te=Math.min(e.width,e.height)*.12,q=Math.max(25,Math.min(te,50)),G=e.width/2,oe=e.height/2;return jsxs(Group,{id:e.id,draggable:!L&&!S,listening:true,x:e.x,y:e.y,...S?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:D=>{if(l(D),D){let z=D.getStage()?.container();if(z){let X=_=>{let Y=D.getStage()?.getPointerPosition();if(Y){let Z={x:e.x,y:e.y,width:e.width,height:e.height};Y.x>=Z.x&&Y.x<=Z.x+Z.width&&Y.y>=Z.y&&Y.y<=Z.y+Z.height&&s(_);}};z.addEventListener("contextmenu",X),D._contextMenuCleanup=()=>{z.removeEventListener("contextmenu",X);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:N?"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}}),N&&jsx(Image$1,{image:N,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:E,onTap:E,onMouseDown:E,onTouchStart:E,onMouseMove:R,onTouchMove:R,onMouseUp:H,onTouchEnd:H,...S?{}:{onDragEnd:a,onTransformEnd:r}}),I?.map((D,z)=>{let X=D.points.map((Y,Z)=>Z%2===0?Y*e.width:Y*e.height),_=D.strokeWidth*e.width;return jsx(Line,{points:X,stroke:D.tool==="eraser"?"white":D.color,strokeWidth:_,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:D.tool==="eraser"?"destination-out":"source-over",fill:D.isSketch?D.color:void 0,closed:D.isSketch,listening:false},z)}),C&&jsx(Line,{points:C.points.map((D,z)=>z%2===0?D*e.width:D*e.height),stroke:C.tool==="eraser"?"white":C.color,strokeWidth:C.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:C.tool==="eraser"?"destination-out":"source-over",fill:C.isSketch?C.color:void 0,closed:C.isSketch,listening:false},"active"),!N&&!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:oe-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:G-q+6,y:oe-60,width:q*1.6,height:q*1.6,radius:q,fill:"white",cornerRadius:8,listening:true,onClick:D=>{D.cancelBubble=true,e.isCapturing?F():n();},onTap:D=>{D.cancelBubble=true,e.isCapturing?F():n();}}),jsx(Html,{groupProps:{x:G-12,y:oe-40,width:q*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:D=>{D.stopPropagation(),e.isCapturing?F():n();}})})]}),jsx(Text,{x:0,y:oe,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:oe+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:G-24,y:oe+104,width:q*1.6,height:q*1.6,radius:q,fill:"#096B76",cornerRadius:q,listening:true,onClick:D=>{D.cancelBubble=true,e.isCapturing?F():n();},onTap:D=>{D.cancelBubble=true,e.isCapturing?F():n();}}),jsx(Html,{groupProps:{x:G-8,y:oe+120,width:q*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:D=>{D.stopPropagation(),e.isCapturing?F():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"})]})]})},Od=Wp;var xi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:s,onStartCamera:n,onCapture:i,cameraStreams:u,onContextMenu:l})=>jsx(Fragment,{children:e.map(c=>jsx(Od,{photoFrame:c,isSelected:t===c.id,onClick:()=>s(c.id),onDragEnd:d=>a(d,c.id),onTransformEnd:d=>r(c.id,d),onContextMenu:d=>l(d,c.id,"photoFrame"),onStartCamera:()=>n(c.id),onCapture:d=>i(c.id,d),cameraStream:u.get(c.id),nodeRef:d=>{d?o.current.set(c.id,d):o.current.delete(c.id);}},c.id))}));xi.displayName="PhotoFrameLayer";var Ud=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:s="",isDrawingMode:n,menuRef:i})=>{useEffect(()=>{let d=f=>{i?.current&&!i.current.contains(f.target)&&a();},m=f=>{f.key==="Escape"&&a();};return document.addEventListener("mousedown",d),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",m);}},[a]);let u=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:n?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(m=>!(m.showForTypes&&!m.showForTypes.includes(r)||m.hideForTypes&&m.hideForTypes.includes(r))),[r,n]),l=(d,m)=>{d==="order"||d==="lock"?t(d,m):(t(d),a());},c=jsx("div",{ref:i,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:u.map((d,m)=>jsxs("button",{onClick:f=>l(d.action,f),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${d.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[d.icon,jsx("span",{className:`font-medium ${d.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:d.label})]}),d.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},m))})});return createPortal(c,document.body)};var Hd=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let s=n=>{r.current&&!r.current.contains(n.target)&&a();};return document.addEventListener("mousedown",s),()=>{document.removeEventListener("mousedown",s);}},[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((s,n)=>jsx("button",{onClick:()=>{s.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:s.label})},n))})})};var zd=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:s})=>{let[n,i]=useState(a),u=useRef(null);useEffect(()=>{u.current?.focus();},[]);let l=()=>{r(n),s();};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:s,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:u,type:"text",value:n,onChange:d=>i(d.target.value),onKeyDown:d=>{d.key==="Enter"?l():d.key==="Escape"&&s();},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:s,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:l,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 Wd=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),s=useRef(null);useEffect(()=>{let c=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]);let n=c=>{c.preventDefault(),o(a);},i=(c,d,m)=>{m/=100;let f=d*Math.min(m,1-m)/100,h=x=>{let p=(x+c/30)%12,v=m-f*Math.max(Math.min(p-3,9-p,1),-1);return Math.round(255*v).toString(16).padStart(2,"0")};return `#${h(0)}${h(8)}${h(4)}`},l=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:c=>c.stopPropagation(),onMouseUp:c=>c.stopPropagation(),onMouseMove:c=>c.stopPropagation(),onTouchStart:c=>c.stopPropagation(),onTouchMove:c=>c.stopPropagation(),onTouchEnd:c=>c.stopPropagation(),children:jsxs("div",{ref:s,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:c=>c.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:n,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:c=>r(c.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:c=>r(c.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:c=>{let d=parseInt(c.target.value),m=i(d,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(c=>jsx("button",{type:"button",onClick:()=>r(c),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===c.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:c},title:c},c))})]})]}),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(l,document.body)};var kh=({imageSrc:e,onCrop:o})=>{let[t]=_d(e),a=useRef(null),r=useRef(null),s=useRef(null),n=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),i=useMemo(()=>{let m=n.width*.5,f=n.height*.5,h=(n.width-m)/2,x=(n.height-f)/2;return {x:h,y:x,width:m,height:f}},[n]),[u,l]=useState(i);useEffect(()=>{l(i);},[i]),useEffect(()=>{s.current&&r.current&&(s.current.nodes([r.current]),s.current.getLayer()?.batchDraw());},[u]),useEffect(()=>{o(u.x,u.y,u.width,u.height);},[u,o]);let c=()=>{let m=r.current;if(!m)return;let f=m.scaleX(),h=m.scaleY();m.scaleX(1),m.scaleY(1),l({x:m.x(),y:m.y(),width:Math.max(20,m.width()*f),height:Math.max(20,m.height()*h)});},d=()=>{let m=r.current;m&&l({x:m.x(),y:m.y(),width:m.width(),height:m.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:u.x,y:u.y,width:u.width,height:u.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:u.x,y:u.y,width:u.width,height:u.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:c,dragBoundFunc:m=>{let f=Math.max(0,Math.min(m.x,n.width-u.width)),h=Math.max(0,Math.min(m.y,n.height-u.height));return {x:f,y:h}}}),jsx(Transformer,{ref:s,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,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>n.width||f.y+f.height>n.height?m:f})]})})},jd=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,s]=useState({x:0,y:0,width:0,height:0}),[n]=_d(e);return useEffect(()=>{let c=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:c=>c.stopPropagation(),onMouseUp:c=>c.stopPropagation(),onMouseMove:c=>c.stopPropagation(),onTouchStart:c=>c.stopPropagation(),onTouchMove:c=>c.stopPropagation(),onTouchEnd:c=>c.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:c=>c.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(kh,{imageSrc:e,onCrop:(c,d,m,f)=>{s({x:c,y:d,width:m,height:f});}})}),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(!n)return;let m=Math.min(600/n.width,400/n.height),f=r.x/m,h=r.y/m,x=r.width/m,p=r.height/m,v=document.createElement("canvas");v.width=x,v.height=p;let g=v.getContext("2d");if(!g)return;g.drawImage(n,f,h,x,p,0,0,x,p);let b=v.toDataURL("image/png");o(b);},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 Jo=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[r,s]=useState(false),[n,i]=useState(null),[u,l]=useState(0),[c,d]=useState(true),m=useRef(null),f=useRef([]),h=useRef(null),x=useRef(null),p=useRef(null),v=useRef(null),g=useRef(null),b=useRef(null);useEffect(()=>()=>{p.current&&cancelAnimationFrame(p.current),h.current&&clearInterval(h.current),x.current&&x.current.getTracks().forEach(L=>L.stop());},[]);let y=async()=>{try{let L,P=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let R=o.current.getLayers();console.log("Konva layers:",R.length),R.forEach((z,X)=>{let _=z.getChildren();console.log(`Layer ${X} children count:`,_.length);});let H=document.createElement("canvas");H.width=o.current.width(),H.height=o.current.height();let N=H.getContext("2d",{willReadFrequently:!1});if(!N){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",H.width,"x",H.height),g.current=H;let te=()=>{if(N.clearRect(0,0,H.width,H.height),R.forEach(z=>{let X=z.getCanvas()._canvas;X&&N.drawImage(X,0,0);}),a?.current){let z=a.current;N.drawImage(z,0,0);}};b.current=te,o.current.draw(),te(),await new Promise(z=>setTimeout(z,100)),console.log("Creating captureStream..."),L=H.captureStream(30),console.log("Canvas stream created, tracks:",L.getTracks().length);let G=L.getVideoTracks()[0];G&&console.log("Video track:",G.label,"state:",G.readyState);let oe=0,D=()=>{te(),o?.current&&(o.current.getLayers().forEach(X=>{X.batchDraw();}),oe++,oe%60===0&&console.log("Drawing frame:",oe)),p.current=requestAnimationFrame(D);};D();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(c)try{P=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(R){console.warn("Microphone access denied:",R);}let A=[...L.getVideoTracks()];P&&A.push(...P.getAudioTracks());let U=new MediaStream(A);x.current=U;let F="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?F="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?F="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?F="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(F="video/webm;codecs=vp8"),console.log("Using mimeType:",F);let E=new MediaRecorder(U,{mimeType:F,videoBitsPerSecond:25e5});m.current=E,f.current=[],E.ondataavailable=R=>{console.log("Data available, size:",R.data.size),R.data.size>0&&f.current.push(R.data);},E.onstop=()=>{console.log("Recording stopped, chunks:",f.current.length);let R=new Blob(f.current,{type:F});console.log("Final blob size:",R.size),o?.current&&b.current&&g.current&&(o.current.draw(),o.current.getLayers().forEach(N=>{N.batchDraw();}),b.current(),v.current=g.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",v.current.length)),U.getTracks().forEach(H=>H.stop()),h.current&&clearInterval(h.current),p.current&&(cancelAnimationFrame(p.current),p.current=null),i(R);},E.onerror=R=>{console.error("MediaRecorder error:",R);},console.log("Starting recording..."),E.start(1e3),s(!0),l(0),h.current=setInterval(()=>{l(R=>R+1);},1e3);}catch(L){console.error("Error starting screen recording:",L),alert("Failed to start recording. Please ensure you granted permission.");}},S=()=>{m.current&&r&&(console.log("Stopping recording, state:",m.current.state),m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),s(false));},I=()=>{if(n){let L=URL.createObjectURL(n),P=document.createElement("a");P.href=L,P.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(L);}},C=L=>{let P=Math.floor(L/60),A=L%60;return `${P.toString().padStart(2,"0")}:${A.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:C(u)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:S,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:[!n&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>d(!c),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${c?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:c?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:y,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"]})]})]}),n&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(n),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",C(u)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&n&&v.current&&(t(n,v.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:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),l(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 Xd=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let[s,n]=useState(false),[i,u]=useState(null),[l,c]=useState(false),[d,m]=useState(0),f=useRef(null),h=useRef([]),x=useRef(null),p=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(L=>L.blob()).then(L=>u(L)).catch(L=>console.error("Error loading audio:",L));},[o,i]);let v=async()=>{try{let L=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),P=new MediaRecorder(L);f.current=P,h.current=[],P.ondataavailable=A=>{A.data.size>0&&h.current.push(A.data);},P.onstop=()=>{let A=new Blob(h.current,{type:"audio/webm"});u(A),L.getTracks().forEach(U=>U.stop()),x.current&&clearInterval(x.current);},P.start(),n(!0),m(0),x.current=setInterval(()=>{m(A=>A+1);},1e3);}catch(L){console.error("Error starting audio recording:",L),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{f.current&&s&&(f.current.stop(),n(false));},b=()=>{if(i){let L=URL.createObjectURL(i),P=new Audio(L);p.current=P,P.onended=()=>{c(false),URL.revokeObjectURL(L);},P.play(),c(true);}},y=()=>{p.current&&(p.current.pause(),p.current.currentTime=0,c(false));},S=async()=>{if(i){let L=new FileReader;L.onloadend=()=>{let P=L.result;t(P),r();},L.readAsDataURL(i);}},I=()=>{u(null),a();},C=L=>{let P=Math.floor(L/60),A=L%60;return `${P.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`};return s?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:C(d)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:g,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):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:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:v,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:l?y:b,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"}),l?"Playing...":"Play Audio"]}),jsx("button",{onClick:I,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:S,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 St=({audioData:e,x:o,y:t,width:a})=>{let[r,s]=useState(false),n=useRef(null);return jsx("button",{onClick:u=>{if(u.stopPropagation(),r&&n.current)n.current.pause(),n.current.currentTime=0,s(false);else {let l=new Audio(e);n.current=l,l.onended=()=>{s(false);},l.onerror=()=>{console.error("Error playing audio"),s(false);},l.play(),s(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 Zd=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=ee(ge),s=useMemo(()=>{if(!r)return [];let x=[];return r.images?.forEach(p=>{x.push({id:p.id,type:"image",name:"Image",timestamp:p.timestamp||0});}),r.videos?.forEach(p=>{x.push({id:p.id,type:"video",name:"Video",timestamp:p.timestamp||0});}),r.shapes?.forEach(p=>{x.push({id:p.id,type:"shape",name:`${p.type} Shape`,timestamp:p.timestamp||0});}),r.texts?.forEach(p=>{x.push({id:p.id,type:"text",name:p.text.substring(0,20)+(p.text.length>20?"...":""),timestamp:p.timestamp||0});}),r.flashcards?.forEach(p=>{x.push({id:p.id,type:"flashcard",name:`Flashcard (${p.images.length} images)`,timestamp:p.timestamp||0});}),r.photoFrames?.forEach(p=>{x.push({id:p.id,type:"photoFrame",name:"Photo Frame",timestamp:p.timestamp||0});}),r.multipleChoices?.forEach(p=>{x.push({id:p.id,type:"mcq",name:"Multiple Choice",timestamp:p.timestamp||0});}),r.trueFalses?.forEach(p=>{x.push({id:p.id,type:"trueFalse",name:"True/False",timestamp:p.timestamp||0});}),r.shortAnswers?.forEach(p=>{x.push({id:p.id,type:"shortAnswer",name:"Short Answer",timestamp:p.timestamp||0});}),r.LongAnswer?.forEach(p=>{x.push({id:p.id,type:"longAnswer",name:"Long Answer",timestamp:p.timestamp||0});}),r.fillInTheBlanks?.forEach(p=>{x.push({id:p.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:p.timestamp||0});}),r.lines?.forEach(p=>{p.id&&x.push({id:p.id,type:"line",name:"Drawn Line",timestamp:p.timestamp||0});}),x.sort((p,v)=>v.timestamp-p.timestamp)},[r]),[n,i]=useState(s),[u,l]=useState(false);useEffect(()=>{u||i(s);},[s]);let c=x=>{let p="h-5 w-5";switch(x){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})}},d=x=>{if(x===0)return;let p=n[x],v=n[x-1];a(Uo({id:p.id,type:p.type,newTimestamp:v.timestamp+1}));},m=x=>{if(x===n.length-1)return;let p=n[x],v=n[x+1];a(Uo({id:p.id,type:p.type,newTimestamp:v.timestamp-1}));},f=x=>{l(true),i(x);},h=()=>{l(false);let x=Date.now();n.forEach((p,v)=>{let g=x-v;a(Uo({id:p.id,type:p.type,newTimestamp:g}));});};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:n.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:n,onReorder:f,className:"space-y-1",children:n.map((x,p)=>{let v=x.id===e;return jsxs(Reorder.Item,{value:x,onDragEnd:h,className:`flex cursor-grab items-center gap-2 rounded-lg p-2 transition-colors active:cursor-grabbing ${v?"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(x.id,x.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${v?"text-blue-600":"text-gray-600"}`,children:c(x.type)}),jsx("span",{className:`text-sm ${v?"font-medium text-blue-900":"text-gray-700"}`,children:x.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:g=>{g.stopPropagation(),d(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:g=>{g.stopPropagation(),m(p);},disabled:p===n.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"})})]})]},x.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 Qd=memo(({multipleChoice:e,handleMcqTransform:o,mcqRefs:t,handleDragEnd:a,onContextMenu:r})=>{let s=useSelector(G=>G.toolbar.selectedTool),n=s==="pen"||s==="eraser",[i,u]=useState(new Set),[l,c]=useState(false),[d,m]=useState(null),f=useRef(null);useEffect(()=>{let G=f.current;if(G)return t.current.set(e.id,G),()=>{t.current.delete(e.id);}},[e.id]);let h=new Set(e.data.responseOptions.correctIndex),x=h.size>1,p=G=>{l||u(x?oe=>{let D=new Set(oe);return D.has(G)?D.delete(G):D.add(G),D}:new Set([G]));},v=()=>{i.size>0&&c(true);},g=()=>{c(false),u(new Set);},b=i.size===h.size&&Array.from(i).every(G=>h.has(G)),y=Array.from(i).filter(G=>h.has(G)),S=x&&y.length>0&&!b,I=()=>b?"\u2713 Correct! Great job! \u{1F389}":S?`\u26A0 Partially correct (${y.length}/${h.size})`:"\u2717 Try again!",C=()=>b?{bg:"#dcfce7",text:"#166534"}:S?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},L=55,P=8,A=24,U=60,F=60,E=x&&!l?25:0,R=e.data.feedbackMode==="practice"?48:0,H=12,N=U+E+(l?F:0),te=e.data.responseOptions.options.length*(L+P),q=N+te+H+R+A;return jsxs(Group,{ref:f,name:"mcq-element",draggable:!n,listening:!n,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...n?{}:{onDragEnd:a,onContextMenu:G=>{let oe=f.current?.getStage()?.getPointerPosition();if(oe){let D={x:e.x,y:e.y,width:e.width,height:e.height};if(oe.x>=D.x&&oe.x<=D.x+D.width&&oe.y>=D.y&&oe.y<=D.y+D.height){let z=G.evt;r(z,e.id,"mcq");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:q,width:e.width,onTransformEnd:G=>o(e.id,G)}),jsx(Text,{x:A+8,y:A,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-A*2,listening:false}),x&&!l&&e.data.feedbackMode==="practice"?jsx(Text,{x:A,y:A+35,text:`Select ${h.size} answers (${i.size}/${h.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-A*2,listening:false}):null,l&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:A+24,y:U+E,width:e.width-A*2-40,height:F-20,fill:C().bg,cornerRadius:8}),jsx(Text,{x:A,y:U+E,width:e.width-A*2,height:F-20,text:I(),fontSize:16,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((G,oe)=>{let D=h.has(oe),z=i.has(oe),X=N+oe*(L+P),_="#e5e7eb",Y="#ffffff",Z="#111827";return l&&D?(_="#22c55e",Y="#dcfce7",Z="#1B9D2C"):l&&z&&!D?(_="#ef4444",Y="#fee2e2",Z="#ef4444"):z&&(_="#096B76",Y="#ECFFF8",Z="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:A+12,y:X+(L-20)/2,width:20,height:20,fill:z?"#096B76":"white",stroke:z?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:x?4:10,listening:false}),z&&jsx(Text,{x:A+12,y:X+(L-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:A+44,y:X,width:e.width-A*2-60,height:L,fill:Y,stroke:_,strokeWidth:2,cornerRadius:8,onClick:Q=>{Q.cancelBubble=true,p(oe);},onTap:Q=>{Q.cancelBubble=true,p(oe);}}),jsx(Text,{x:A+60,y:X,width:e.width-A*2-80,height:L,text:G,fontSize:16,fill:Z,verticalAlign:"middle",listening:false})]},oe)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:N+e.data.responseOptions.options.length*(L+P)+12,children:[jsxs(Group,{onMouseDown:G=>{G.cancelBubble=true,m("check");},onMouseUp:G=>{G.cancelBubble=true,m(null),v();},onMouseLeave:G=>{G.cancelBubble=true,m(null);},onTouchStart:G=>{G.cancelBubble=true,m("check");},onTouchEnd:G=>{G.cancelBubble=true,m(null),v();},scaleX:d==="check"?.95:1,scaleY:d==="check"?.95:1,children:[jsx(Rect,{x:A+14,width:(e.width-A*2-24)/(l?2:1),height:48,fill:i.size===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:A+14,width:(e.width-A*2-24)/(l?2:1),height:48,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-A*2)/2+8,onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),g();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),g();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:A,width:(e.width-A*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:A,width:(e.width-A*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Qd.displayName="MultipleChoice";var eu=Qd;var wi=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t})=>{let a=useDispatch(),r=useSelector(D=>D.toolbar.selectedTool),s=r==="pen"||r==="eraser",[n,i]=useState(false),[u,l]=useState(new Set),[c,d]=useState(false),[m,f]=useState(false),[h,x]=useState(0),p=340,v=100,g=window.innerWidth*.4,b=window.innerHeight*.5,y=p+20,S=v+60,I=g-40,C=b-300,L=useRef(null),P=D=>{a(oa({id:e.id,x:D.target.x(),y:D.target.y()}));},A=D=>{let z=D.target,X=z.x(),_=z.y(),Y=window.innerWidth*.2,Q=X+Y>y&&X<y+I&&_+50>S&&_<S+C;i(Q);},U=(D,z)=>{let X=z.target,_=X.x(),Y=X.y(),Z=window.innerWidth*.2,pe=_+Z>y&&_<y+I&&Y+50>S&&Y<S+C;l(pe?we=>new Set(we).add(D):we=>{let De=new Set(we);return De.delete(D),De}),i(false);},F=()=>{d(true);},E=()=>{d(false),l(new Set),x(D=>D+1);},R=new Set(e.data.responseOptions.correctIndex),H=u.size===R.size&&Array.from(u).every(D=>R.has(D)),N=Array.from(u).filter(D=>R.has(D)),te=N.length>0&&!H,q=()=>H?"\u2713 Correct! Great job!":te?`\u26A0 Partially correct (${N.length}/${R.size})`:"\u2717 Try again!",G=()=>H?{bg:"#dcfce7",text:"#166534"}:te?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},oe=()=>c?H?"#4CAF50":te?"#f59e0b":"#ef4444":n?"#4CAF50":"#075560";return jsxs(Group,{ref:L,name:"mcq-element",width:g,height:b,draggable:!s,listening:!s,...s?{}:{onContextMenu:D=>{D.evt.preventDefault(),o(D.evt,e.id,"mcq");}},children:[jsxs(Group,{x:p,y:v,rotation:e.rotation,onDragEnd:P,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?b-100:b-50,width:g,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:g-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:I,height:C,fill:"#EBF6F7",stroke:oe(),strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:C+18,width:I-5,height:60,fill:G().bg,cornerRadius:8}),jsx(Text,{x:20,y:C+20,width:I,height:60,text:q(),fontSize:18,fontStyle:"bold",fill:G().text,align:"center",verticalAlign:"middle"})]}),u.size===0&&!c&&jsx(Text,{x:20,y:60,width:I,height:C-60,text:R.size>1?`Drop ${R.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:c?b-200:b-160,children:[jsxs(Group,{onMouseDown:()=>{f(true),F();},onMouseUp:()=>f(false),onMouseLeave:()=>f(false),onTouchStart:()=>{f(true),F();},onTouchEnd:()=>f(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{y:50,onMouseDown:E,onTouchStart:E,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((D,z)=>{let X=z%2,_=Math.floor(z/2),Y=window.innerWidth*.2,Z=50,Q=10,pe=u.has(z),we=R.has(z),De=c&&pe,Me="transparent";return De?Me=we?"#4CAF50":"#ef4444":pe&&(Me="#4CAF50"),jsxs(Group,{x:340+X*(Y+Q),y:v+b-80+_*(Z+Q),draggable:!c,onDragMove:A,onDragEnd:Ue=>U(z,Ue),opacity:c&&!pe?.5:1,children:[jsx(Rect,{width:Y-20,height:Z,fill:"white",stroke:Me,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:Y-20,height:Z,text:D,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${z}-${h}`)})]})};wi.displayName="MultipleChoiceDragAndDrop";var tu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(eu,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:i=>r(i,n.id),onContextMenu:s},n.id):jsx(wi,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:s},n.id))});var au=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s})=>{let n=useSelector(N=>N.toolbar.selectedTool),i=n==="pen"||n==="eraser",[u,l]=useState(null),[c,d]=useState(false),[m,f]=useState(null),h=useRef(null);useEffect(()=>{let N=h.current;if(N)return a.current.set(e.id,N),()=>{a.current.delete(e.id);}},[e.id]);let x=()=>{u!==null&&d(true);},p=()=>{d(false),l(null);},v=e.data.responseOptions.correctAnswer,g=u===v,b=N=>{c||l(N);},y=()=>g?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",S=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},I=70,C=12,L=24,P=60,A=60,U=e.data.feedbackMode==="practice"?48:0,F=12,E=P+(c?A:0),R=2*(I+C),H=E+R+F+U+L;return jsxs(Group,{ref:h,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:N=>s(N,e.id),onClick:N=>t(e.id),onTap:N=>t(e.id),onContextMenu:N=>{let te=h.current?.getStage()?.getPointerPosition();if(te){let q={x:e.x,y:e.y,width:e.width,height:e.height};if(te.x>=q.x&&te.x<=q.x+q.width&&te.y>=q.y&&te.y<=q.y+q.height){let G=N.evt;r(G,e.id,"trueFalse");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:H-20,width:e.width,onTransformEnd:N=>o(e.id,N)}),jsx(Text,{x:L,y:L,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),c&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:L,y:P,width:e.width-L*2,height:A-10,fill:S().bg,cornerRadius:8}),jsx(Text,{x:L,y:P,width:e.width-L*2,height:A-10,text:y(),fontSize:16,fontStyle:"bold",fill:S().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((N,te)=>{let q=v===N.value,G=u===N.value,oe=(e.width-L*3)/2,D=L+te*(oe+L),z=E,X=N.value===true,_=X?"#10b981":"#ef4444",Y="#ffffff",Z="#ffffff",Q="#e5e7eb";return c&&(q?(Z=X?"#f0fdf4":"#fef2f2",Q=X?"#86efac":"#fecaca"):G&&!q&&(Z="#fee2e2",Q="#ef4444")),G&&!c&&(Q="#096B76",Z="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:D,y:z,width:oe,height:I+50,fill:Z,stroke:Q,strokeWidth:2,cornerRadius:12,onClick:pe=>{pe.cancelBubble=true,b(N.value);},onTap:pe=>{pe.cancelBubble=true,b(N.value);}}),jsx(Circle,{x:D+oe/2,y:z+40,radius:28,fill:_,listening:false}),X?jsx(Text,{x:D+oe/2-14,y:z+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:D+oe/2-14,y:z+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:D,y:z+85,width:oe,height:30,text:N.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},N.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:E+2*(I+C),children:[jsxs(Group,{onMouseDown:N=>{N.cancelBubble=true,f("check");},onMouseUp:N=>{N.cancelBubble=true,f(null),x();},onMouseLeave:N=>{N.cancelBubble=true,f(null);},onTouchStart:N=>{N.cancelBubble=true,f("check");},onTouchEnd:N=>{N.cancelBubble=true,f(null),x();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(c?2:1),height:48,fill:u===null||c?"#9ca3af":"#096B76",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(c?2:1),height:48,text:c?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>f("reset"),onMouseUp:()=>{f(null),p();},onMouseLeave:()=>f(null),onTouchStart:()=>f("reset"),onTouchEnd:()=>{f(null),p();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.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})]})]})]})});au.displayName="TrueFalse";var ou=au;var Sg="#FFFFFF",Ii=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),r=useSelector(_=>_.toolbar.selectedTool),s=r==="pen"||r==="eraser",[n,i]=useState(false),[u,l]=useState(null),[c,d]=useState(false),[m,f]=useState(false),[h,x]=useState(0),[p,v]=useState(false),g=340,b=100,y=window.innerWidth*.4,S=window.innerHeight*.5,I=y-40,C=S-300,L=20,P=60,A=I,U=C,F=y*.2-40,E=50,R=useRef(null),H=_=>{a(ra({id:e.id,x:_.target.x(),y:_.target.y()}));},N=_=>{let Y=_.target,Z=Y.x(),Q=Y.y(),pe=Math.max(0,Math.min(Z+F,L+A)-Math.max(Z,L)),we=Math.max(0,Math.min(Q+E,P+U)-Math.max(Q,P)),De=pe*we,Me=F*E;i(De/Me>=.5);},te=(_,Y)=>{let Z=Y.target,Q=Z.x(),pe=Z.y(),we=Math.max(0,Math.min(Q+F,L+A)-Math.max(Q,L)),De=Math.max(0,Math.min(pe+E,P+U)-Math.max(pe,P)),Me=we*De,Ue=F*E;if(Me/Ue>=.5)l(_);else return;i(false);},q=()=>{d(true);},G=()=>{d(false),l(null),x(_=>_+1);},oe=e.data.responseOptions.correctAnswer,D=u===oe,z=()=>D?"\u2713 Correct! Great job!":"\u2717 Try again!",X=()=>D?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:R,name:"trueFalse-element",width:y,height:S,draggable:!s,listening:!s,...s?{}:{onContextMenu:_=>{_.evt.preventDefault(),o(_.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:g,y:b,rotation:e.rotation,onDragEnd:H,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:c?S:e.data.feedbackMode==="practice"?S-50:S-100,width:y,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:y-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:I,height:C,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:I,height:60,fill:X().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:I,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:X().text,align:"center",verticalAlign:"middle"})]}),u===null&&!c&&jsx(Text,{x:20,y:60,width:I,height:C-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:S-100,children:[jsxs(Group,{onMouseDown:()=>{u!==null&&(f(true),q());},onMouseUp:()=>f(false),onMouseLeave:()=>f(false),onTouchStart:()=>{u!==null&&(f(true),q());},onTouchEnd:()=>f(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:u===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{y:50,onMouseDown:G,onTouchStart:G,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((_,Y)=>{let Z=window.innerWidth*.2,Q=50,pe=10,we=u===_.value,De=oe===_.value,Me=c&&we,Ue="transparent";return Me?Ue=De?"#4CAF50":"#ef4444":we&&(Ue="#4CAF50"),jsxs(Group,{x:16+Y*(Z+pe),y:b+S-300,draggable:!c,onDragMove:N,onDragEnd:re=>te(_.value,re),opacity:c&&!we?.5:1,children:[jsx(Rect,{width:Z-40,height:Q,fill:"#075560",stroke:Ue,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z-40,height:Q,text:_.label,fontSize:18,fontStyle:"bold",fill:Sg,align:"center",verticalAlign:"middle",listening:false})]},`${_.value}-${h}`)})]})})};Ii.displayName="TrueFalseDragAndDrop";var ru=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(ou,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r},n.id):jsx(Ii,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s},n.id))});var da=new WeakMap,fo=new WeakMap,or={current:[]},ki=false,ar=0,tr=new Set,gs=new Map;function su(e){let o=Array.from(e).sort((t,a)=>t instanceof Ft&&t.options.deps.includes(a)?1:a instanceof Ft&&a.options.deps.includes(t)?-1:0);for(let t of o){if(or.current.includes(t))continue;or.current.push(t),t.recompute();let a=fo.get(t);if(a)for(let r of a){let s=da.get(r);s&&su(s);}}}function kg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Mg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function xs(e){if(ar>0&&!gs.has(e)&&gs.set(e,e.prevState),tr.add(e),!(ar>0)&&!ki)try{for(ki=!0;tr.size>0;){let o=Array.from(tr);tr.clear();for(let t of o){let a=gs.get(t)??t.prevState;t.prevState=a,kg(t);}for(let t of o){let a=da.get(t);a&&(or.current.push(t),su(a));}for(let t of o){let a=da.get(t);if(a)for(let r of a)Mg(r);}}}finally{ki=false,or.current=[],gs.clear();}}function ft(e){ar++;try{e();}finally{if(ar--,ar===0){let o=tr.values().next().value;o&&xs(o);}}}function nu(e){return typeof e=="function"}var zt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,s;this.listeners.add(a);let n=(s=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:s.call(r,a,this);return ()=>{this.listeners.delete(a),n?.();}},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):nu(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),xs(this);}};var Ft=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 s=0;s<t;s++){let n=this.options.deps[s];a[s]=n.prevState,r[s]=n.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 s of this.options.deps)s instanceof e&&s.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let s=0;s<r.length;s++)if(r[s]!==a[s]){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 s=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),s?.();}},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 zt){let a=da.get(t);a||(a=new Set,da.set(t,a)),a.add(this);let r=fo.get(this);r||(r=new Set,fo.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 zt){let a=da.get(t);a&&a.delete(this);let r=fo.get(this);r&&r.delete(t);}}};function Tg(e){return typeof e=="function"}function Mi(e,...o){return Tg(e)?e(...o):e}function iu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ua,rt,et,rr,ca,Ba,$t,mo,sr,bs,nr,po,Oa=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Te(this,ua,true);Te(this,rt);Te(this,et);Te(this,rr);Te(this,ca);Te(this,Ba);Te(this,$t);Te(this,mo);Te(this,sr,0);Te(this,bs,5);Te(this,nr,()=>{this.debugLog("Connected to event bus"),ke(this,Ba,true),this.debugLog("Emitting queued events",K(this,ca)),K(this,ca).forEach(o=>this.emitEventToBus(o)),ke(this,ca,[]),this.stopConnectLoop(),K(this,et).call(this).removeEventListener("tanstack-connect-success",K(this,nr));});Te(this,po,()=>{if(K(this,et).call(this).addEventListener("tanstack-connect-success",K(this,nr)),K(this,sr)<K(this,bs)){Vl(this,sr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}K(this,et).call(this).removeEventListener("tanstack-connect",K(this,po)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});ke(this,rt,o),ke(this,ua,a),ke(this,et,this.getGlobalTarget),ke(this,rr,t),this.debugLog(" Initializing event subscription for plugin",K(this,rt)),ke(this,ca,[]),ke(this,Ba,false),ke(this,$t,null),ke(this,mo,r);}startConnectLoop(){K(this,$t)!==null||K(this,Ba)||(this.debugLog(`Starting connect loop (every ${K(this,mo)}ms)`),ke(this,$t,setInterval(K(this,po),K(this,mo))));}stopConnectLoop(){K(this,$t)!==null&&(clearInterval(K(this,$t)),ke(this,$t,null),this.debugLog("Stopped connect loop"));}debugLog(...o){K(this,rr)&&console.log(`\u{1F334} [tanstack-devtools:${K(this,rt)}-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 K(this,rt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});K(this,et).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{K(this,et).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(!K(this,ua)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!K(this,Ba)){this.debugLog("Bus not available, will be pushed as soon as connected"),K(this,ca).push({type:`${K(this,rt)}:${o}`,payload:t,pluginId:K(this,rt)}),typeof CustomEvent<"u"&&(K(this,po).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${K(this,rt)}:${o}`,payload:t,pluginId:K(this,rt)})}on(o,t){let a=`${K(this,rt)}:${o}`;if(!K(this,ua))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=s=>{this.debugLog("Received event from bus",s.detail),t(s.detail);};return K(this,et).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{K(this,et).call(this).removeEventListener(a,r);}}onAll(o){if(!K(this,ua))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return K(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!K(this,ua))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;K(this,rt)&&r.pluginId!==K(this,rt)||o(r);};return K(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}};ua=new WeakMap,rt=new WeakMap,et=new WeakMap,rr=new WeakMap,ca=new WeakMap,Ba=new WeakMap,$t=new WeakMap,mo=new WeakMap,sr=new WeakMap,bs=new WeakMap,nr=new WeakMap,po=new WeakMap;var Ti=class extends Oa{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},lu=(e,o)=>{Ai.emit(e,o);},Ai=new Ti;function du(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Ag={enabled:true,leading:true,trailing:true,wait:0},fa,mt,Na,Va,qa,ho,vs=class{constructor(o,t){Te(this,fa);Te(this,mt);Te(this,Na);Te(this,Va);Te(this,qa);Te(this,ho);this.fn=o,this.store=new zt(du()),this.setOptions=a=>{this.options={...this.options,...a},K(this,Na).call(this)||this.cancel();},ke(this,mt,a=>{this.store.setState(r=>{let s={...r,...a},{isPending:n}=s;return {...s,status:K(this,Na).call(this)?n?"pending":"idle":"disabled"}}),lu("Throttler",this);}),ke(this,Na,()=>!!Mi(this.options.enabled,this)),ke(this,Va,()=>Mi(this.options.wait,this)),this.maybeExecute=(...a)=>{K(this,mt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),s=r-this.store.state.lastExecutionTime,n=K(this,Va).call(this);if(this.options.leading&&s>=n)K(this,qa).call(this,...a);else if(K(this,mt).call(this,{lastArgs:a}),!K(this,fa)&&this.options.trailing){let i=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,u=n-i;K(this,mt).call(this,{isPending:true}),ke(this,fa,setTimeout(()=>{let{lastArgs:l}=this.store.state;l!==void 0&&K(this,qa).call(this,...l);},u));}},ke(this,qa,(...a)=>{if(!K(this,Na).call(this))return;this.fn(...a);let r=Date.now(),s=r+K(this,Va).call(this);K(this,ho).call(this),K(this,mt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:s,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||K(this,mt).call(this,{nextExecutionTime:void 0});},K(this,Va).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&K(this,qa).call(this,...this.store.state.lastArgs);},ke(this,ho,()=>{K(this,fa)&&(clearTimeout(K(this,fa)),ke(this,fa,void 0));}),this.cancel=()=>{K(this,ho).call(this),K(this,mt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{K(this,mt).call(this,du());},this.key=iu(t.key),this.options={...Ag,...t},K(this,mt).call(this,this.options.initialState??{}),Ai.on("d-Throttler",a=>{a.payload.key===this.key&&(K(this,mt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};fa=new WeakMap,mt=new WeakMap,Na=new WeakMap,Va=new WeakMap,qa=new WeakMap,ho=new WeakMap;function Pi(e,o){return new vs(e,o).maybeExecute}function ma(e,o){return typeof e=="function"?e(o):e}function pa(e,o){return Ss(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function go(e,o,t){let a=Ss(o);function r(s){if(!a.length)return ma(t,s);let n=a.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(s))return typeof s=="object"?(s===null&&(s={}),{...s,[n]:r(s[n])}):{[n]:r()};if(Array.isArray(s)&&typeof n=="number"){let i=s.slice(0,n);return [...i.length?i:new Array(n),r(s[n]),...s.slice(n+1)]}return [...new Array(n),r()]}return r(e)}function Ri(e,o){let t=Ss(o);function a(r){if(!r)return;if(t.length===1){let n=t[0];if(Array.isArray(r)&&typeof n=="number")return r.filter((l,c)=>c!==n);let{[n]:i,...u}=r;return u}let s=t.shift();if(typeof s=="string"&&typeof r=="object")return {...r,[s]:a(r[s])};if(typeof s=="number"&&Array.isArray(r)){if(s>=r.length)return r;let n=r.slice(0,s);return [...n.length?n:new Array(s),a(r[s]),...r.slice(s+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var Pg=/^(\d+)$/gm,Dg=/\.(\d+)(?=\.)/gm,Rg=/^(\d+)\./gm,Fg=/\.(\d+$)/gm,Eg=/\.{2,}/gm,Di="__int__",ys=`${Di}$1`;function Ss(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(Pg,ys).replace(Dg,`.${ys}.`).replace(Rg,`${ys}.`).replace(Fg,`.${ys}`).replace(Eg,".").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 xo(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 bo(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:s}=o.validators||{},n=t??0,i=u=>u.validators.filter(Boolean).map(l=>{let c=l?.cause||e,d=n;switch(c){case "change":d=r??n;break;case "blur":d=a??n;break;case "dynamic":d=s??n;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:c,validate:l.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:i})}var ir=e=>!!e&&typeof e=="object"&&"fields"in e;function ha(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,s]of e)if(!o.has(r)||!Object.is(s,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)||!ha(e[r],o[r]))return false;return true}var Is=({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},Cs=({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,Ls=[],ws;for(;Ua--;)Ls[Ua]=(Ua+256).toString(16).substring(1);function Ei(){let e=0,o,t="";if(!ws||Ua+16>256){for(ws=new Array(256),e=256;e--;)ws[e]=256*Math.random()|0;e=0,Ua=0;}for(;e<16;e++)o=ws[Ua+e],e===6?t+=Ls[o&15|64]:e===8?t+=Ls[o&63|128]:t+=Ls[o],e&1&&e>1&&e<11&&(t+="-");return Ua++,t}var ga=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"},s={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,r,s,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,n],form:e.form});case "change":return e.runValidation({validators:[a,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Bg(e,o){let t=new Map;for(let a of e){let r=a.path??[],s=o,n="";for(let i=0;i<r.length;i++){let u=r[i];if(u===void 0)continue;let l=typeof u=="object"?u.key:u,c=Number(l);Array.isArray(s)&&!Number.isNaN(c)?n+=`[${c}]`:n+=(i>0?".":"")+String(l),typeof s=="object"&&s!==null?s=s[l]:s=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var uu=(e,o)=>{let t=Bg(e,o);return {form:t,fields:t}},xa={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:uu(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:uu(a.issues,e)}},ks=e=>!!e&&"~standard"in e;var vo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function lr(e){function o(d,m,f,h){let x=a(d,m,f,h);({insert:()=>i(x,d,m),remove:()=>u(x),swap:()=>h!==void 0&&c(x,d,m,h),move:()=>h!==void 0&&l(x,d,m,h)})[f]();}function t(d,m){return `${d}[${m}]`}function a(d,m,f,h){let x=[t(d,m)];if(f==="swap")x.push(t(d,h));else if(f==="move"){let[p,v]=[Math.min(m,h),Math.max(m,h)];for(let g=p;g<=v;g++)x.push(t(d,g));}else {let p=e.getFieldValue(d),v=Array.isArray(p)?p.length:0;for(let g=m+1;g<v;g++)x.push(t(d,g));}return Object.keys(e.fieldInfo).filter(p=>x.some(v=>p.startsWith(v)))}function r(d,m){return d.replace(/\[(\d+)\]/,(f,h)=>{let x=parseInt(h,10);return `[${m==="up"?x+1:Math.max(0,x-1)}]`})}function s(d,m){(m==="up"?d:[...d].reverse()).forEach(h=>{let x=r(h.toString(),m),p=e.getFieldMeta(x);p?e.setFieldMeta(h,p):e.setFieldMeta(h,n());});}let n=()=>vo,i=(d,m,f)=>{s(d,"down"),d.forEach(h=>{h.toString().startsWith(t(m,f))&&e.setFieldMeta(h,n());});},u=d=>{s(d,"up");},l=(d,m,f,h)=>{let x=new Map(Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,f))).map(p=>[p,e.getFieldMeta(p)]));s(d,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,h))).forEach(p=>{let v=p.replace(t(m,h),t(m,f)),g=x.get(v);g&&e.setFieldMeta(p,g);});},c=(d,m,f,h)=>{d.forEach(x=>{if(!x.toString().startsWith(t(m,f)))return;let p=x.toString().replace(t(m,f),t(m,h)),[v,g]=[e.getFieldMeta(x),e.getFieldMeta(p)];v&&e.setFieldMeta(p,v),g&&e.setFieldMeta(x,g);});};return {handleArrayFieldMetaShift:o}}var Bi=class extends Oa{constructor(){super({pluginId:"form-devtools"});}},pt=new Bi;function Oi(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 ur=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),s=()=>{a(),r(),pt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),s},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let s=!!a.transform?.deps?.some((u,l)=>u!==this.prevTransformArray[l]),n=a.defaultValues&&!ha(a.defaultValues,r.defaultValues)&&!this.state.isTouched,i=!ha(a.defaultState,r.defaultState)&&!this.state.isTouched;!n&&!i&&!s||(ft(()=>{this.baseStore.setState(()=>Oi(Object.assign({},this.state,i?a.defaultState:{},n?{values:a.defaultValues}:{},s?{_force_re_eval:!this.state._force_re_eval}:{})));}),pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:s}=this.state,n=this.resetFieldMeta(s);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Oi({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let r=[];return ft(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let i=n.instance;r.push(Promise.resolve().then(()=>i.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(u=>({...u,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,s)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null,u=[`${a}[${r}]`];for(let m=r+1;m<=(i??0);m++)u.push(`${a}[${m}]`);let l=Object.keys(this.fieldInfo).filter(m=>u.some(f=>m.startsWith(f))),c=[];return ft(()=>{l.forEach(m=>{c.push(Promise.resolve().then(()=>this.validateField(m,s)));});}),(await Promise.all(c)).flat()},this.validateField=(a,r)=>{let s=this.fieldInfo[a]?.instance;return s?(s.state.meta.isTouched||s.setMeta(n=>({...n,isTouched:true})),s.validate(r)):[]},this.validateSync=a=>{let r=xo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||ga}),s=false,n={};return ft(()=>{for(let l of r){if(!l.validate)continue;let c=this.runValidator({validate:l.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:m}=Ms(c),f=dr(l.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let x=this.getFieldMeta(h);if(!x)continue;let{errorMap:p,errorSourceMap:v}=x,g=m?.[h],{newErrorValue:b,newSource:y}=Is({newFormValidatorError:g,isPreviousErrorFromFormValidator:v?.[f]==="form",previousErrorValue:p?.[f]});y==="form"&&(n[h]={...n[h],[f]:g}),p?.[f]!==b&&this.setFieldMeta(h,S=>({...S,errorMap:{...S.errorMap,[f]:b},errorSourceMap:{...S.errorSourceMap,[f]:y}}));}this.state.errorMap?.[f]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:d}})),(d||m)&&(s=!0);}let i=dr("submit");this.state.errorMap?.[i]&&a!=="submit"&&!s&&this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[i]:void 0}}));let u=dr("server");this.state.errorMap?.[u]&&a!=="server"&&!s&&this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[u]:void 0}}));}),{hasErrored:s,fieldsErrorMap:n}},this.validateAsync=async a=>{let r=bo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||ga});this.state.isFormValidating||this.baseStore.setState(l=>({...l,isFormValidating:true}));let s=[],n;for(let l of r){if(!l.validate)continue;let c=dr(l.cause);this.state.validationMetaMap[c]?.lastAbortController.abort();let m=new AbortController;this.state.validationMetaMap[c]={lastAbortController:m},s.push(new Promise(async f=>{let h;try{h=await new Promise((g,b)=>{setTimeout(async()=>{if(m.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:l.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:m.signal},type:"validateAsync"}));}catch(y){b(y);}},l.debounceMs);});}catch(g){h=g;}let{formError:x,fieldErrors:p}=Ms(h);p&&(n=n?{...n,...p}:p);let v=dr(l.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let b=this.getFieldMeta(g);if(!b)continue;let{errorMap:y,errorSourceMap:S}=b,I=n?.[g],{newErrorValue:C,newSource:L}=Is({newFormValidatorError:I,isPreviousErrorFromFormValidator:S?.[v]==="form",previousErrorValue:y?.[v]});y?.[v]!==C&&this.setFieldMeta(g,P=>({...P,errorMap:{...P.errorMap,[v]:C},errorSourceMap:{...P.errorSourceMap,[v]:L}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[v]:x}})),f(n?{fieldErrors:n,errorMapKey:v}:void 0);}));}let i=[],u={};if(s.length){i=await Promise.all(s);for(let l of i)if(l?.fieldErrors){let{errorMapKey:c}=l;for(let[d,m]of Object.entries(l.fieldErrors)){let h={...u[d]||{},[c]:m};u[d]=h;}}}return this.baseStore.setState(l=>({...l,isFormValidating:false})),u},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:s}=this.validateSync(a);return r&&!this.options.asyncAlways?s:this.validateAsync(a)},this.getFieldValue=a=>pa(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(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:ma(r,s.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,s)=>{let n=s;return r[n]=vo,r},{}),this.setFieldValue=(a,r,s)=>{let n=s?.dontUpdateMeta??false,i=s?.dontRunListeners??false,u=s?.dontValidate??false;ft(()=>{n||this.setFieldMeta(a,l=>({...l,isTouched:!0,isDirty:!0,errorMap:{...l?.errorMap,onMount:void 0}})),this.baseStore.setState(l=>({...l,values:go(l.values,a,r)}));}),i||this.getFieldInfo(a).instance?.triggerOnChangeListener(),u||this.validateField(a,"change");},this.deleteField=a=>{let s=[...Object.keys(this.fieldInfo).filter(n=>{let i=a.toString();return n!==i&&n.startsWith(i)}),a];this.baseStore.setState(n=>{let i={...n};return s.forEach(u=>{i.values=Ri(i.values,u),delete this.fieldInfo[u],delete i.fieldMetaBase[u];}),i});},this.pushFieldValue=(a,r,s)=>{this.setFieldValue(a,n=>[...Array.isArray(n)?n:[],r],s);},this.insertFieldValue=async(a,r,s,n)=>{this.setFieldValue(a,u=>[...u.slice(0,r),s,...u.slice(r)],Ge(n,{dontValidate:true}));let i=n?.dontValidate??false;i||await this.validateField(a,"change"),lr(this).handleArrayFieldMetaShift(a,r,"insert"),i||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,s,n)=>{this.setFieldValue(a,u=>u.map((l,c)=>c===r?s:l),Ge(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,s)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,l=>l.filter((c,d)=>d!==r),Ge(s,{dontValidate:true})),lr(this).handleArrayFieldMetaShift(a,r,"remove"),i!==null){let l=`${a}[${i}]`;this.deleteField(l);}(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,s,n)=>{this.setFieldValue(a,u=>{let l=u[r],c=u[s];return go(go(u,`${r}`,c),`${s}`,l)},Ge(n,{dontValidate:true})),lr(this).handleArrayFieldMetaShift(a,r,"swap",s),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${s}]`,"change"));},this.moveFieldValues=(a,r,s,n)=>{this.setFieldValue(a,u=>{let l=[...u];return l.splice(s,0,l.splice(r,1)[0]),l},Ge(n,{dontValidate:true})),lr(this).handleArrayFieldMetaShift(a,r,"move",s),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${s}]`,"change"));},this.clearFieldValues=(a,r)=>{let s=this.getFieldValue(a),n=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,[],Ge(r,{dontValidate:true})),n!==null)for(let u=0;u<=n;u++){let l=`${a}[${u}]`;this.deleteField(l);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:vo},values:this.options.defaultValues?go(r.values,a,pa(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,s])=>(Object.keys(s).length&&s.errors.length&&(a[r]={errors:s.errors,errorMap:s.errorMap}),a),{})}),this.parseValuesWithSchema=a=>xa.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>xa.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Ei(),this._devtoolsSubmissionOverride=false,this.baseStore=new zt(Oi({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Ft({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:s})=>{let n=s,i=a?.[0],u=r[0],l=0,c={};for(let d of Object.keys(u.fieldMetaBase)){let m=u.fieldMetaBase[d],f=i?.fieldMetaBase[d],h=n?.[d],x=pa(u.values,d),p=h?.errors;if(!f||m.errorMap!==f.errorMap){p=Object.values(m.errorMap??{}).filter(S=>S!==void 0);let y=this.getFieldInfo(d)?.instance;y&&!y.options.disableErrorFlat&&(p=p?.flat(1));}let v=!Fi(p??[]),g=!m.isDirty,b=ha(x,pa(this.options.defaultValues,d))||ha(x,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===v&&h.isDefaultValue===b&&h.errors===p&&m===f){c[d]=h,l++;continue}c[d]={...m,errors:p,isPristine:g,isValid:v,isDefaultValue:b};}return Object.keys(u.fieldMetaBase).length&&n&&l===Object.keys(u.fieldMetaBase).length?n:c}}),this.store=new Ft({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:s})=>{let n=s,i=a?.[0],u=r[0],l=r[1],c=Object.values(l).filter(Boolean),d=c.some(R=>R.isValidating),m=c.every(R=>R.isValid),f=c.some(R=>R.isTouched),h=c.some(R=>R.isBlurred),x=c.every(R=>R.isDefaultValue),p=f&&u.errorMap?.onMount,v=c.some(R=>R.isDirty),g=!v,b=!!(u.errorMap?.onMount||c.some(R=>R?.errorMap?.onMount)),y=!!d,S=n?.errors??[];(!i||u.errorMap!==i.errorMap)&&(S=Object.values(u.errorMap).reduce((R,H)=>H===void 0?R:H&&ir(H)?(R.push(H.form),R):(R.push(H),R),[]));let I=S.length===0,C=m&&I,L=this.options.canSubmitWhenInvalid??false,P=u.submissionAttempts===0&&!f&&!b||!y&&!u.isSubmitting&&C||L,A=u.errorMap;if(p&&(S=S.filter(R=>R!==u.errorMap.onMount),A=Object.assign(A,{onMount:void 0})),n&&i&&n.errorMap===A&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===S&&n.isFieldsValidating===d&&n.isFieldsValid===m&&n.isFormValid===I&&n.isValid===C&&n.canSubmit===P&&n.isTouched===f&&n.isBlurred===h&&n.isPristine===g&&n.isDefaultValue===x&&n.isDirty===v&&ha(i,u))return n;let U={...u,errorMap:A,fieldMeta:this.fieldMetaDerived.state,errors:S,isFieldsValidating:d,isFieldsValid:m,isFormValid:I,isValid:C,canSubmit:P,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:x,isDirty:v},F=this.options.transform?.deps??[];if(F.length!==this.prevTransformArray.length||F.some((R,H)=>R!==this.prevTransformArray[H])){let R=Object.assign({},this,{state:U});this.options.transform?.fn(R),U=R.state,this.prevTransformArray=F;}return U}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Pi(a=>pt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),pt.on("request-form-state",a=>{a.payload.id===this._formId&&pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),pt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),pt.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return ks(o.validate)?xa[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})),ft(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(s=>({...s,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}),pt.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}),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}ft(()=>{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}),ft(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(s=>({...s,isSubmitSuccessful:false})),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){ft(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(ir(a)){let{formError:s,fieldErrors:n}=Ms(a);for(let i of Object.keys(this.fieldInfo))this.getFieldMeta(i)&&this.setFieldMeta(i,l=>({...l,errorMap:{...l.errorMap,[r]:n?.[i]},errorSourceMap:{...l.errorSourceMap,[r]:"form"}}));this.baseStore.setState(i=>({...i,errorMap:{...i.errorMap,[r]:s}}));}else this.baseStore.setState(s=>({...s,errorMap:{...s.errorMap,[r]:a}}));});});}};function Ms(e){if(e){if(ir(e)){let o=Ms(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function dr(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 cr=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 s=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});s&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:s},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let r=pa(t.form.options.defaultValues,t.name),s=t.defaultValue??r;a?this.setValue(n=>n||s,{dontUpdateMeta:true}):s!==void 0&&this.setValue(s,{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 s of a){if(!s.instance)continue;let{onChangeListenTo:n,onBlurListenTo:i}=s.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&r.push(s.instance),t==="blur"&&i?.includes(this.name)&&r.push(s.instance);}return r},this.validateSync=(t,a)=>{let r=xo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ga}),n=this.getLinkedFields(t).reduce((l,c)=>{let d=xo(t,{...c.options,form:c.form,validationLogic:c.form.options.validationLogic||ga});return d.forEach(m=>{m.field=c;}),l.concat(d)},[]),i=false;ft(()=>{let l=(c,d)=>{let m=Ts(d.cause),f=d.validate?cu(c.runValidator({validate:d.validate,value:{value:c.store.state.value,validationSource:"field",fieldApi:c},type:"validate"})):void 0,h=a[m],{newErrorValue:x,newSource:p}=Cs({formLevelError:h,fieldLevelError:f});c.state.meta.errorMap?.[m]!==x&&c.setMeta(v=>({...v,errorMap:{...v.errorMap,[m]:x},errorSourceMap:{...v.errorSourceMap,[m]:p}})),x&&(i=!0);};for(let c of r)l(this,c);for(let c of n)c.validate&&l(c.field,c);});let u=Ts("submit");return this.state.meta.errorMap?.[u]&&t!=="submit"&&!i&&this.setMeta(l=>({...l,errorMap:{...l.errorMap,[u]:void 0},errorSourceMap:{...l.errorSourceMap,[u]:void 0}})),{hasErrored:i}},this.validateAsync=async(t,a)=>{let r=bo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ga}),s=await a,n=this.getLinkedFields(t),i=n.reduce((m,f)=>{let h=bo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||ga});return h.forEach(x=>{x.field=f;}),m.concat(h)},[]);this.state.meta.isValidating||this.setMeta(m=>({...m,isValidating:true}));for(let m of n)m.setMeta(f=>({...f,isValidating:true}));let u=[],l=[],c=(m,f,h)=>{let x=Ts(f.cause);m.getInfo().validationMetaMap[x]?.lastAbortController.abort();let v=new AbortController;this.getInfo().validationMetaMap[x]={lastAbortController:v},h.push(new Promise(async g=>{let b;try{b=await new Promise((L,P)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(v.signal.aborted)return L(void 0);try{L(await this.runValidator({validate:f.validate,value:{value:m.store.state.value,fieldApi:m,signal:v.signal,validationSource:"field"},type:"validateAsync"}));}catch(A){P(A);}},f.debounceMs);});}catch(L){b=L;}if(v.signal.aborted)return g(void 0);let y=cu(b),S=s[this.name]?.[x],{newErrorValue:I,newSource:C}=Cs({formLevelError:S,fieldLevelError:y});m.setMeta(L=>({...L,errorMap:{...L?.errorMap,[x]:I},errorSourceMap:{...L.errorSourceMap,[x]:C}})),g(I);}));};for(let m of r)m.validate&&c(this,m,u);for(let m of i)m.validate&&c(m.field,m,l);let d=[];(u.length||l.length)&&(d=await Promise.all(u),await Promise.all(l)),this.setMeta(m=>({...m,isValidating:false}));for(let m of n)m.setMeta(f=>({...f,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:s}=this.validateSync(t,r[this.name]??{});if(s&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Ts(t)]?.lastAbortController.abort(),this.state.meta.errors;let n=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,n)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>xa.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>xa.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Ft({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...vo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return ks(o.validate)?xa[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 cu(e){if(e)return e}function Ts(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 As(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Ng)}function Ng(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=fu(e);if(t.length!==fu(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 fu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var yo=typeof window<"u"?useLayoutEffect:useEffect;function Gg(e){let[o]=useState(()=>{let a=new cr({...e,form:e.form,name:e.name});return a.Field=Ni,a});return yo(o.mount,[o]),yo(()=>{o.update(e);}),As(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Ni=(({children:e,...o})=>{let t=Gg(o),a=useMemo(()=>ma(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function jg({form:e,selector:o,children:t}){let a=As(e.store,o);return ma(t,a)}function Vi(e){let o=useId(),[t]=useState(()=>{let a=new ur({...e,formId:o}),r=a;return r.Field=function(n){return jsx(Ni,{...n,form:a})},r.Subscribe=function(n){return jsx(jg,{form:a,selector:n.selector,children:n.children})},r});return yo(t.mount,[]),yo(()=>{t.update(e);}),t}function qi({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 ox=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),r=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[n,i]=useState(s),u=Vi({defaultValues:{questionType:s,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:d})=>{if(d.questionType==="true-false"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctAnswer:d.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?ra(m):En(m));}else if(d.questionType==="multiple-choice"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctIndex:d.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?oa(m):Rn(m));}else if(d.questionType==="short-answer"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Oo(m):On(m));}else if(d.questionType==="fill-in-the-blank"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Vo(m):Un(m));}else if(d.questionType==="long-answer"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctLongAnswer:d.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?No(m):Vn(m));}o(sa(false));}}),l=()=>{o(sa(false));},c=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:d=>{d.preventDefault(),d.stopPropagation(),u.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:()=>{l();},children:jsx("span",{className:"text-xl text-white",children:"\u2715"})})]}),jsxs("div",{className:"mb-4 flex justify-between gap-6",children:[jsx(u.Field,{name:"questionType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:m=>{d.handleChange(m.target.value),i(m.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-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(qi,{field:d})]})}),n&&!["short-answer","fill-in-the-blank","long-answer"].includes(n)&&jsx(u.Field,{name:"responseType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:m=>d.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(qi,{field:d})]})})]}),jsx(u.Field,{name:"feedbackMode",children:d=>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 ${n==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:n==="long-answer",onClick:()=>d.handleChange("practice"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${d.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",size:16}),"Practice Mode"]}),jsxs("button",{type:"button",disabled:n==="long-answer",onClick:()=>d.handleChange("test"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${d.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",size:16}),"Assessment Mode"]})]}),n==="long-answer"&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Long answer questions are only available in Assessment Mode"}),jsx(qi,{field:d})]})}),jsx(u.Field,{name:"question",validators:{onChange:({value:d})=>d?void 0:"A question is required"},children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.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:d.state.value,onChange:m=>d.handleChange(m.target.value),onBlur:d.handleBlur,placeholder:"Enter Your Question"})}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),n==="true-false"&&jsx(u.Field,{name:"responseOptions.correctAnswer",children:d=>{let m=d.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:()=>d.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:()=>d.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"})]})}}),n==="multiple-choice"&&jsx(u.Field,{name:"responseOptions",validators:{onChange:({value:d})=>{if(d.options.filter(f=>!f.trim()).length>0)return "All options must have text";if(!d.correctIndex||d.correctIndex.length===0)return "Please select at least one correct answer"}},children:d=>{let m=(p,v)=>{let g=[...d.state.value.options];g[p]=v,d.handleChange({...d.state.value,options:g});},f=()=>{if(d.state.value.options.length>=6){alert("Maximum 6 options allowed");return}d.handleChange({...d.state.value,options:[...d.state.value.options,""]});},h=p=>{if(d.state.value.options.length<=2){alert("Minimum 2 options required");return}let v=d.state.value.options.filter((b,y)=>y!==p),g=d.state.value.correctIndex?.filter(b=>b!==p).map(b=>b>p?b-1:b);d.handleChange({...d.state.value,options:v,correctIndex:g});},x=p=>{let v=d.state.value.correctIndex||[];if(v.includes(p))d.handleChange({...d.state.value,correctIndex:v.filter(b=>b!==p)});else {if(v.length>=6){alert("Maximum 6 correct answers allowed");return}d.handleChange({...d.state.value,correctIndex:[...v,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:d.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:d.state.value.options.map((p,v)=>{let g=!p.trim(),b=d.state.value.correctIndex?.includes(v),y=d.state.meta.isTouched&&g;return jsxs("div",{className:"flex w-full items-center gap-3 px-1",children:[jsx("button",{type:"button",onClick:()=>x(v),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${b?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:b&&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 ${y?"border-red-500 bg-red-50":b?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${v+1}`,value:p,onChange:S=>m(v,S.target.value),onBlur:d.handleBlur,className:"w-full flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"})}),d.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>h(v),className:"text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",size:24})})]},v)})}),jsx("button",{type:"button",onClick:f,disabled:d.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"}),d.state.value.correctIndex.length===0||d.state.meta.errors.length>0?jsx("span",{className:"px-2 text-base font-semibold text-red-500",children:d.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill"}),jsx("p",{className:"",children:"Correct answer selected"})]})]})}}),(n==="short-answer"||n==="fill-in-the-blank")&&jsx(u.Field,{name:"responseOptions.correctShortAnswer",children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:d.state.value,onChange:m=>{d.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)."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),n==="long-answer"&&jsx(u.Field,{name:"responseOptions.correctLongAnswer",children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.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:d.state.value,onChange:m=>{d.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."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),jsx(u.Subscribe,{selector:d=>[d.canSubmit,d.isSubmitting],children:([d,m])=>jsx("button",{type:"submit",disabled:!d,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(c,document.body)},hu=ox;var gu=({text:e,position:o})=>{let t=xe(),a=l=>{t(ue()),t(wt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+l))}));},r=l=>{t(ue()),t(wt({id:e.id,fill:l}));},s=()=>{t(ue()),t(wt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ue()),t(wt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},i=()=>{t(ue()),t(wt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},u=l=>{t(ue()),t(wt({id:e.id,fontFamily:l}));};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:l=>l.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:l=>u(l.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:s,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:n,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:i,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:l=>r(l.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var bu=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:s,textareaRef:n})=>{let i=useRef(null),u=useMemo(()=>({fontSize:`${e.fontSize*s}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,s]),l=useCallback(c=>{c.style.height="auto",c.style.height=`${c.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(c).font,d.style.fontSize=c.style.fontSize,d.style.fontFamily=c.style.fontFamily,d.style.fontWeight=c.style.fontWeight,d.style.fontStyle=c.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let m=c.value.split(`
|
|
4
4
|
`),f=0;document.body.appendChild(d);for(let x of m){d.textContent=x||" ";let p=d.offsetWidth;p>f&&(f=p);}document.body.removeChild(d);let h=10;c.style.width=`${Math.max(200,f+h+20)}px`;},[]);return useEffect(()=>{let c=i.current;c&&(c.style.fontSize=`${e.fontSize*s}px`,c.style.fontFamily=e.fontFamily,c.style.fontStyle=e.fontStyle,c.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",c.style.textDecoration=e.textDecoration,c.style.color=e.fill,l(c));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,s,l]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:c=>{if(i.current=c,n.current=c,c){c.focus();let d=c.value.length;c.setSelectionRange(d,d),l(c);}},value:o,onChange:c=>{t(c.target.value);},onKeyDown:c=>{c.key==="Escape"&&a();},style:u},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var vu=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>{let n=useSelector(E=>E.toolbar.selectedTool),i=n==="pen"||n==="eraser",u=useRef(null),[l,c]=useState(""),[d,m]=useState(false),[f,h]=useState(null);useEffect(()=>{let E=u.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id,a]);let x=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",p=d&&l.trim().toLowerCase()===x,v=()=>{m(false),c("");},g=()=>p?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",b=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},y=24,S=60,I=d?50:0,C=50,L=12,P=e.data.feedbackMode==="practice"?48:0,A=12,U=30,F=S+I+U+C+L+A+P+y;return jsxs(Group,{ref:u,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"sa-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let R=u.current?.getStage()?.getPointerPosition();if(!R)return;let H={x:e.x,y:e.y,width:e.width,height:e.height};R.x>=H.x&&R.x<=H.x+H.width&&R.y>=H.y&&R.y<=H.y+H.height&&r(E.evt,e.id,"shortAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:F,onTransformEnd:E=>t(e.id,E)}),jsx(Text,{text:e.data.question,x:y,y,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:y,y:S,width:e.width-y*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:y,y:S,width:e.width-y*2,height:I,text:g(),fontSize:16,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer:",x:y,y:S+I+L,fontSize:14,fill:"#6b7280",width:e.width-y*2,listening:false}),jsx(Rect,{x:y,y:S+I+U,width:e.width-y*2,height:C,fill:"#ffffff",stroke:p?"#22c55e":d?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${S+I+U}px`,left:`${y}px`,width:`${e.width-y*2}px`,height:`${C}px`,pointerEvents:d?"none":"auto"}},children:jsx("input",{type:"text",value:l,onChange:E=>c(E.target.value),disabled:d,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:d?"none":"auto"}})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:S+I+U+C+L+A,children:[!d&&jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,h("check");},onMouseUp:E=>{E.cancelBubble=true,h(null),l.length>0&&m(true);},onMouseLeave:E=>{E.cancelBubble=true,h(null);},onTouchStart:E=>{E.cancelBubble=true,h("check");},onTouchEnd:E=>{E.cancelBubble=true,h(null),l.length>0&&m(true);},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:l.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),v();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),v();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});vu.displayName="ShortAnswer";var yu=vu;var Lu=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>jsx(Fragment,{children:e.map(n=>jsx(yu,{shortAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>s(i,n.id)},n.id))});var Su=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],r=useRef(new Map),s=useCallback((n,i)=>{let u=n.target;o(Vo({id:i,x:u.x(),y:u.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:s}};var Iu=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r})=>{let s=useSelector(F=>F.toolbar.selectedTool),n=s==="pen"||s==="eraser",i=useRef(null),[u,l]=useState(""),[c,d]=useState(false),[m,f]=useState(null);useEffect(()=>{if(i.current)return ()=>{}},[e.id]);let h=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",x=c&&u.trim().toLowerCase()===h,p=()=>{d(false),l("");},v=()=>x?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",g=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},b=24,y=80,S=c?50:0,I=45,C=8,L=20,P=e.data.feedbackMode==="practice"?48:0,A=12,U=y+S+C+L+C+A+P+b;return jsxs(Group,{ref:i,draggable:!n,listening:!n,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...n?{}:{onDragEnd:F=>a(F,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:F=>{let E=i.current?.getStage()?.getPointerPosition();if(!E||!r)return;let R={x:e.x,y:e.y,width:e.width,height:e.height};E.x>=R.x&&E.x<=R.x+R.width&&E.y>=R.y&&E.y<=R.y+R.height&&r(F.evt,e.id,"fillInTheBlanks");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:U,onTransformEnd:F=>t(e.id,F)}),jsx(Text,{text:e.data.question,x:b,y:b,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2-200,listening:false}),jsx(Rect,{x:e.width-b-180,y:b+10,width:180,height:I,fill:"#ffffff",stroke:x?"#22c55e":c?"#ef4444":"#096B76",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${b+10}px`,left:`${e.width-b-180}px`,width:"180px",height:`${I}px`,pointerEvents:c?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:F=>l(F.target.value),disabled:c,placeholder:"__________",className:"h-full w-full border-0 bg-white px-2 text-center text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:c?"none":"auto"}})}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:b,y,width:e.width-b*2,height:S,fill:g().bg,cornerRadius:8}),jsx(Text,{x:b,y,width:e.width-b*2,height:S,text:v(),fontSize:16,fontStyle:"bold",fill:g().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"\u26A0\uFE0F Answer is case sensitive",x:b,y:y+S+C,fontSize:10,fontStyle:"italic",fill:"#6b7280",width:e.width-b*2,listening:false}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:y+S+C+L+C+A,children:[!c&&jsxs(Group,{onMouseDown:F=>{F.cancelBubble=true,f("check");},onMouseUp:F=>{F.cancelBubble=true,f(null),u.length>0&&d(true);},onMouseLeave:F=>{F.cancelBubble=true,f(null);},onTouchStart:F=>{F.cancelBubble=true,f("check");},onTouchEnd:F=>{F.cancelBubble=true,f(null),u.length>0&&d(true);},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:u.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{onMouseDown:()=>f("reset"),onMouseUp:()=>{f(null),p();},onMouseLeave:()=>f(null),onTouchStart:()=>f("reset"),onTouchEnd:()=>{f(null),p();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Iu.displayName="FillInTheBlanks";var Cu=Iu;var Mu=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r})=>jsx(Fragment,{children:e.map(s=>jsx(Cu,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r},s.id))});var Ki=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>{let n=useSelector(E=>E.toolbar.selectedTool),i=n==="pen"||n==="eraser",u=useRef(null),[l,c]=useState(""),[d,m]=useState(false),[f,h]=useState(null);useEffect(()=>{let E=u.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id,a]);let x=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",p=d&&l.trim().toLowerCase()===x,v=()=>{m(false),c("");},g=()=>p?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",b=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},y=24,S=60,I=d?60:0,C=120,L=12,P=48,A=12,U=30,F=S+I+U+C+L+A+P+y;return jsxs(Group,{ref:u,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let R=u.current?.getStage()?.getPointerPosition();if(!R||!r)return;let H={x:e.x,y:e.y,width:e.width,height:e.height};R.x>=H.x&&R.x<=H.x+H.width&&R.y>=H.y&&R.y<=H.y+H.height&&r(E.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:F,onTransformEnd:E=>t(e.id,E)}),jsx(Text,{text:e.data.question,x:y,y,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:y,y:S,width:e.width-y*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:y,y:S,width:e.width-y*2,height:I,text:g(),fontSize:14,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:y,y:S+I+L,fontSize:14,fill:"#6b7280",width:e.width-y*2,listening:false}),jsx(Rect,{x:y,y:S+I+U,width:e.width-y*2,height:C,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${S+I+U}px`,left:`${y}px`,width:`${e.width-y*2}px`,height:`${C}px`,pointerEvents:d?"none":"auto"}},children:jsx("textarea",{value:l,onChange:E=>c(E.target.value),disabled:d,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:d?"none":"auto"}})}),jsx(Group,{y:S+I+U+C+L+A,children:d&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),v();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),v();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Ki.displayName="LongAnswer";var Au=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>jsx(Fragment,{children:e.map(n=>jsx(Ki,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>s(i,n.id)},n.id))});var qx=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r,className:s,style:n}={})=>{let i=yt(),u=ee(w=>w.toolbar.selectedTool),l=ee(ge),c=ee(zo),d=l?.editingActivity,m=l?.showMcqForm,f=l?.lines||[],h=useRef(null),x=useRef(null),[p,v]=useState(null),[g,b]=useState(""),[y,S]=useState({width:1280,height:1200}),[I,C]=useState("bottom"),L=useRef(null),[P,A]=useState(null),[U,F]=useState(null),[E,R]=useState(null),[H,N]=useState(null),[te,q]=useState(null),[G,oe]=useState(null),[D,z]=useState(null),[X,_]=useState(false),[Y,Z]=useState(null),[Q,pe]=useState(false),we=useRef(null),De=useRef(null),Me=useRef(null),{debouncedGenerateThumbnail:Ue}=gd(c,h);useEffect(()=>{let w=()=>{if(x.current){let T=x.current.getBoundingClientRect();S({width:T.width,height:T.height});}};w();let M=new ResizeObserver(w);return x.current&&M.observe(x.current),window.addEventListener("resize",w),()=>{M.disconnect(),window.removeEventListener("resize",w);}},[]),useEffect(()=>{if(h.current){let w=h.current.container();w&&(w.style.cursor="");}},[u]);let re=useCallback(()=>{h.current&&requestAnimationFrame(()=>{if(!h.current)return;h.current.getLayers().forEach(O=>O.batchDraw());let M=1/6,T=h.current.toDataURL({pixelRatio:M});b(T),Ue();});},[Ue]),Mr=useRef(c);useEffect(()=>{Mr.current!==c&&(Mr.current=c,re());},[c,re]);let Tr=useRef(null),Ar=useRef(true);useEffect(()=>{if(!l)return;let w=(l.lines?.length||0)+(l.images?.length||0)+(l.videos?.length||0)+(l.shapes?.length||0)+(l.texts?.length||0)+(l.flashcards?.length||0)+(l.photoFrames?.length||0)+(l.multipleChoices?.length||0)+(l.trueFalses?.length||0)+(l.shortAnswers?.length||0)+(l.LongAnswer?.length||0)+(l.fillInTheBlanks?.length||0),M=Tr.current?.count!==w;!Ar.current&&M&&setTimeout(()=>{re();},100),Tr.current={slideId:c,count:w},Ar.current=false;},[l,c,re]),useEffect(()=>{h.current&&e&&e(h);},[e]),useEffect(()=>{Me.current&&a&&a(Me);},[a]);let{startDrawing:Pr,draw:Ia,stopDrawing:Dr,setCanvasRef:Js,tool:Zs,color:Rr,strokeWidth:Qs,isSketchMode:en}=Wl(re),Ca=useRef(new Map),{images:tn,getLoadedImage:an,imageRefs:B,handleDragEnd:ne,handleImageTransformEnd:Ie}=Yl(re),{videos:me,videoRefs:se,handleVideoClick:ie,handleVideoDragEnd:Ve,handleVideoTransformEnd:qt}=Ql(re),{multipleChoice:_t,handleMcqTransform:_e,mcqRefs:Ce,handleDragEnd:Je}=Jl(re),{trueFalse:jt,handleTrueFalseTransform:ka,trueFalseRefs:Ma,handleTrueFalseDragEnd:$a}=Zl(re),{shortAnswers:Fr,saRefs:Ze,handleShortAnswerDragEnd:ea}=sd(re),{longAnswers:Ta,handleLongAnswerDragEnd:Cf}=nd(re),{fillInTheBlanks:kf,handleFillInTheBlanksDragEnd:Mf}=Su(re),{transformerRef:de,boundBoxFunc:gt}=fd(),{shapes:Tf,shapeRefs:Er,isDragging:Tl,handleShapeDragEnd:Af,handleShapeResizeEnd:Pf}=ad(re),{texts:Fo,textRefs:ta,handleDragEnd:Df,handleTransformEnd:Rf,handleDoubleClick:Ff,startEditing:Br,editingTextId:he,editingValue:Al,handleEditingChange:Pl,finishEditing:on}=rd(re,we);useEffect(()=>{t&&t(Br);},[t,Br]);let Or=ee(w=>w.canvas.editingTextId);useEffect(()=>{Or&&Or!==he&&Br(Or);},[Or,he,Br]);let{flashcards:Ef,flashcardRefs:Nr,handleDragEnd:Bf,handleFlashcardTransformEnd:Of,handleNext:Nf,handlePrevious:Vf}=ld(re),{photoFrames:Dl,photoFrameRefs:Vr,handleDragEnd:qf,handlePhotoFrameTransformEnd:Uf,startCamera:Hf,capturePhoto:zf,cameraStreams:Wf}=cd(re);useEffect(()=>{if(de.current){if(he){de.current.nodes([]),de.current.getLayer()?.batchDraw();return}if(p&&!me.find(T=>T.id===p)?.isPlaying){let T=Ca.current.get(p)||B.current.get(p)||se.current.get(p)||Er.current.get(p)||ta.current.get(p)||Ce.current.get(p)||Nr.current.get(p)||Vr.current.get(p);if(T){let O=T.attrs?.locked;if(T.visible()&&O!==true){de.current.nodes([T]),de.current.getLayer()?.batchDraw();return}}}de.current.nodes([]),de.current.getLayer()?.batchDraw();}},[p,he,me,Ca,B,se,Er,ta,Nr,Vr,Dl,Ce,de]);let He=useCallback(w=>{v(w),o?.(w);},[o]),qr=useCallback(()=>{v(null),o?.(null),de.current&&(de.current.nodes([]),de.current.getLayer()?.batchDraw());},[de,o]);useEffect(()=>{let w=de.current;return ()=>{w&&w.nodes([]);}},[c]),useEffect(()=>{let w=M=>{he&&M.target.tagName!=="TEXTAREA"&&on();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[he,on]),useEffect(()=>{let w=he||p;if(!w||p&&he){F(null);return}let M=ta.current.get(w),T=h.current;if(!M||!T){F(null);return}let O=T.container().getBoundingClientRect(),Re=M.absolutePosition(),Le=T.scaleX();F({x:O.left+(Re.x+M.width()*Le/2)*Le,y:O.top+Re.y*Le});},[p,he,Fo,ta]),useEffect(()=>{if(!he){R(null);return}let w=ta.current.get(he),M=h.current;if(!w||!M){R(null);return}let T=M.container().getBoundingClientRect(),O=w.absolutePosition(),Re=M.scaleX();R({top:T.top+O.y*Re,left:T.left+O.x*Re,scale:Re});},[he,Fo,ta]);let Rl=useCallback(w=>{let M=w.target.getClassName(),T=w.target===w.target.getStage(),O=M==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",Re=M==="Image",Le=M==="Text",ae=M==="Group"||w.target.getParent()?.getClassName()==="Group",Dt=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&w.target.attrs.id,bt=M==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:M,clickedOnImage:Re,clickedOnGroup:ae,tool:u,targetId:w.target.attrs?.id}),T&&!O&&!Re&&!Le&&!ae&&!Dt&&!bt&&qr(),!(u==="pen"||u==="eraser")&&(Re||Le||O||ae||Dt||bt))return;let je=w.target.getStage()?.getPointerPosition();if(!je)return;["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)||Pr(je);},[u,Pr,qr]),Fl=useCallback(w=>{if(Tl)return;let M=w.target.getStage()?.getPointerPosition();M&&Ia(M);},[Ia,Tl]),El=useCallback(()=>{Dr();},[Dr]),Gf=useCallback(w=>{ne(w,re);},[ne,re]),Kf=useCallback(w=>{ie(w),He(w);},[ie,He]),xt=useCallback((w,M,T)=>{w.preventDefault();let O=w.clientX,Re=w.clientY,Le=L.current?.offsetHeight||450,ae=L.current?.offsetWidth||450,Dt=window.innerHeight,bt=window.innerWidth,tt=O,je=Re;Re+Le>Dt&&(je=Re-Le),O+ae>bt&&(tt=O-ae),A({x:tt,y:je,elementId:M,elementType:T}),He(M);},[He]),Bl=useCallback(w=>{i(qo(w)),i(sa(true));},[i]),_f=useCallback(w=>{i(Bo(w)),i(Pa(true));},[i]),jf=useCallback((w,M)=>{if(!P)return;let{elementId:T,elementType:O}=P;switch(w){case "order":if(M){let k=M.target.getBoundingClientRect();N({x:k.right+5,y:k.top,type:"order"});}break;case "lock":if(M){let k=M.target.getBoundingClientRect();N({x:k.right+5,y:k.top,type:"lock"});}break;case "link":if(A(null),O==="line")break;let Re=l?O==="image"?l.images.find(k=>k.id===T):l.videos.find(k=>k.id===T):null;q({type:"link",defaultValue:Re?.link||""});break;case "voice":if(A(null),O==="line")break;let Le=l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="text"?l.texts.find(k=>k.id===T):O==="flashcard"?l.flashcards.find(k=>k.id===T):O==="photoFrame"?l.photoFrames.find(k=>k.id===T):O==="mcq"?l.multipleChoices.find(k=>k.id===T):O==="fillInTheBlanks"?l.fillInTheBlanks.find(k=>k.id===T):O==="longAnswer"?l.LongAnswer.find(k=>k.id===T):O==="shortAnswer"?l.shortAnswers.find(k=>k.id===T):O==="trueFalse"?l.trueFalses.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):null:null;Z({elementId:T,elementType:O,existingAudio:Le?.audioData});break;case "edit":A(null);let ae=null;O==="mcq"?ae=l?.multipleChoices.find(k=>k.id===T):O==="trueFalse"?ae=l?.trueFalses.find(k=>k.id===T):O==="shortAnswer"?ae=l?.shortAnswers.find(k=>k.id===T):O==="longAnswer"?ae=l?.LongAnswer.find(k=>k.id===T):O==="fillInTheBlanks"&&(ae=l?.fillInTheBlanks.find(k=>k.id===T)),ae&&Bl(ae);break;case "editFlashcard":A(null);let Dt=l?.flashcards.find(k=>k.id===T);Dt&&_f(Dt);break;case "color":A(null);let bt=l?.shapes.find(k=>k.id===T);oe({elementId:T,elementType:"shape",defaultColor:bt?.color||"#096B76"});break;case "crop":if(A(null),O==="image"){let k=l?.images.find(em=>em.id===T);k&&z({elementId:T,imageSrc:k.src});}break;case "draw":A(null),O==="image"?i(Tn(T)):O==="photoFrame"&&i(Pn(T));break;case "duplicate":i(ue()),O==="line"?i($n(T)):O==="image"?i(Hr(T)):O==="video"?i(Gr(T)):O==="shape"?i(Kr(T)):O==="text"?i(_r(T)):O==="flashcard"?i(jr(T)):O==="photoFrame"?i($r(T)):O==="mcq"?i(Xr(T)):O==="trueFalse"?i(Yr(T)):O==="shortAnswer"?i(Jr(T)):O==="fillInTheBlanks"?i(Qr(T)):O==="longAnswer"&&i(Zr(T)),re();break;case "infinite-clone":i(ue());let tt=5;for(let k=0;k<tt;k++)O==="image"?i(Hr(T)):O==="video"?i(Gr(T)):O==="shape"?i(Kr(T)):O==="text"?i(_r(T)):O==="flashcard"?i(jr(T)):O==="photoFrame"?i($r(T)):O==="mcq"?i(Xr(T)):O==="trueFalse"?i(Yr(T)):O==="shortAnswer"?i(Jr(T)):O==="fillInTheBlanks"?i(Qr(T)):O==="longAnswer"&&i(Zr(T));re();break;case "make-response":if(A(null),O==="line")break;let je=`#response-${T}`;i(ue()),i(es({id:T,type:O,link:je})),(l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):O==="flashcard"?l.flashcards.find(k=>k.id===T):O==="photoFrame"?l.photoFrames.find(k=>k.id===T):l.multipleChoices.find(k=>k.id===T):null)?.altText||i(ts({id:T,type:O,altText:"Interactive response area"})),re(),console.log(`Element ${T} marked as interactive response area`);break;case "accessibility":if(A(null),O==="line")break;let V=l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):null:null;q({type:"altText",defaultValue:V?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),A(null),pe(true),console.log("showLayersPanel state set to:",true);break;case "delete":i(ue()),O==="line"?i(jn(T)):O==="image"?i(gn(T)):O==="video"?i(xn(T)):O==="shape"?i(vn(T)):O==="text"?i(wn(T)):O==="flashcard"?i(Sn(T)):O==="photoFrame"?i(Mn(T)):O==="mcq"?i(Fn(T)):O==="trueFalse"?i(Bn(T)):O==="shortAnswer"?i(Nn(T)):O==="longAnswer"?i(qn(T)):O==="fillInTheBlanks"&&i(Hn(T)),qr(),re();break}},[P,i,re,qr,l,Bl]),$f=useCallback(()=>{A(null),N(null);},[]),rn=useCallback(w=>{if(!P)return;let{elementId:M,elementType:T}=P;switch(i(ue()),w){case "bring-to-front":T!=="line"&&i(Wn({id:M,type:T}));break;case "send-to-back":T!=="line"&&i(Gn({id:M,type:T}));break;case "lock":case "unlock":T!=="line"&&i(Kn({id:M,type:T}));break}re(),A(null),N(null);},[P,i,re]),Xf=useCallback(w=>{if(!P||!te)return;let{elementId:M,elementType:T}=P;i(ue()),te.type==="link"&&T!=="line"?i(es({id:M,type:T,link:w})):te.type==="altText"&&T!=="line"&&i(ts({id:M,type:T,altText:w})),re(),q(null);},[P,te,i,re]),Yf=useCallback(w=>{if(!Y)return;let{elementId:M,elementType:T}=Y;i(ue()),i(as({id:M,type:T,audioData:w})),re(),Z(null);},[Y,i,re]),Jf=useCallback(()=>{if(!Y)return;let{elementId:w,elementType:M}=Y;i(ue()),i(as({id:w,type:M,audioData:""})),re();},[Y,i,re]),Zf=useCallback(w=>{if(!G)return;let{elementId:M}=G;i(ue()),i(Ja({id:M,color:w})),re(),oe(null);},[G,i,re]),Qf=useCallback(w=>{if(!D)return;let{elementId:M}=D;i(ue()),i(Ya({id:M,src:w})),re(),z(null);},[D,i,re]);return jsxs("div",{ref:x,className:s||"fixed top-[90px] right-80 bottom-0 left-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default",...n},children:[u==="pen"&&jsx($l,{ref:w=>{if(De.current=w,Js(w),w){let M=w.getCanvasElement();M&&(Me.current=M,a&&a(Me));}},width:y.width,height:y.height,tool:Zs,color:Rr,strokeWidth:Qs,isSketchMode:en}),jsxs(Stage,{ref:h,width:y.width,height:y.height,onMouseDown:Rl,onMouseMove:Fl,onMouseUp:El,onTouchStart:Rl,onTouchMove:Fl,onTouchEnd:El,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:y.width,height:y.height,fill:l?.backgroundColor||"white"})}),jsx(Layer,{children:(()=>{let w=[];return f.forEach((M,T)=>{w.push({type:"line",timestamp:M.timestamp||T,element:{...M,id:M.id??`line-${T}`},index:T});}),Tf.forEach(M=>{w.push({type:"shape",timestamp:M.timestamp||0,element:M});}),tn.forEach(M=>{w.push({type:"image",timestamp:M.timestamp||0,element:M});}),me.forEach(M=>{w.push({type:"video",timestamp:M.timestamp||0,element:M});}),Fo.forEach(M=>{w.push({type:"text",timestamp:M.timestamp||0,element:M});}),Ef.forEach(M=>{w.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Dl.forEach(M=>{w.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),_t.forEach(M=>{w.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),jt.forEach(M=>{w.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),Fr.forEach(M=>{w.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),Ta.forEach(M=>{w.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),kf.forEach(M=>{w.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),w.sort((M,T)=>M.timestamp-T.timestamp),w.map((M,T)=>{let O=`${M.type}-${"id"in M.element&&M.element.id||M.index||T}`,Re="id"in M.element?M.element.id:void 0,Le=Re&&p===Re;switch(M.type){case "line":let ae=M.element,Dt=M.index||0,bt=ae.tool==="eraser",tt=ae.isSketch&&ae.tool==="pen",je=ae.isSketch&&bt,vt=ae.id||`line-${Dt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),u==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:tt||je?void 0:ae.color,strokeWidth:tt||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||je?bt?"black":ae.color:void 0,closed:tt||je,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,onClick:()=>{i(ue()),i(Ur(Dt));},onTap:()=>{i(ue()),i(Ur(Dt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:V=>{let k=V.target.getStage();k&&(k.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:V=>{let k=V.target.getStage();k&&(k.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},O):jsxs(be__default.Fragment,{children:[jsx(Group,{id:vt,ref:V=>{V?Ca.current.set(vt,V):Ca.current.delete(vt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",vt),He(vt));},onTap:()=>{u==="select"&&(console.log("Line tapped:",vt),He(vt));},onDragEnd:V=>{i(ue()),i(os({id:vt,x:V.target.x(),y:V.target.y(),scaleX:V.target.scaleX(),scaleY:V.target.scaleY(),rotation:V.target.rotation()})),re();},onTransformEnd:V=>{i(ue()),i(os({id:vt,x:V.target.x(),y:V.target.y(),scaleX:V.target.scaleX(),scaleY:V.target.scaleY(),rotation:V.target.rotation()})),re();},onMouseEnter:V=>{if(u==="select"){let k=V.target.getStage();k&&(k.container().style.cursor="move");}},onMouseLeave:V=>{if(u==="select"){let k=V.target.getStage();k&&(k.container().style.cursor="default");}},onContextMenu:V=>{let k=V.evt;k.preventDefault(),xt(k,vt,"line");},children:jsx(Line,{points:ae.points||[],stroke:tt||je?void 0:ae.color,strokeWidth:tt||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||je?bt?"black":ae.color:void 0,closed:tt||je,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ca.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!k),k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "shape":return jsxs(be__default.Fragment,{children:[jsx(di,{onSelect:He,shapes:[M.element],shapeRefs:Er,handleShapeDragEnd:Af,handleShapeResizeEnd:Pf,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Er.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "image":return jsxs(be__default.Fragment,{children:[jsx(si,{images:[M.element],getLoadedImage:an,imageRefs:B,onDragEnd:Gf,onTransform:Ie,onSelect:He,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=B.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "video":return jsxs(be__default.Fragment,{children:[jsx(li,{videos:[M.element],selectedId:p,videoRefs:se,onVideoClick:Kf,onDragEnd:Ve,onTransformEnd:qt,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=se.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "text":return jsxs(be__default.Fragment,{children:[jsx(Md,{texts:[M.element],textRefs:ta,onDragEnd:Df,onTransformEnd:Rf,onSelect:He,onContextMenu:xt,onDoubleClick:Ff,editingTextId:he,editingValue:Al,onEditingChange:Pl}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=ta.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(fi,{flashcards:[M.element],flashcardRefs:Nr,selectedId:p,onDragEnd:Bf,onTransform:Of,onSelect:He,onNext:Nf,onPrevious:Vf,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Nr.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(xi,{photoFrames:[M.element],photoFrameRefs:Vr,selectedId:p,onDragEnd:qf,onTransform:Uf,onSelect:He,onStartCamera:Hf,onCapture:zf,cameraStreams:Wf,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Vr.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(tu,{handleMcqTransform:_e,multipleChoice:[M.element],handleSelect:He,mcqRefs:Ce,handleDragEnd:Je,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ce.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(ru,{trueFalses:[M.element],handleTrueFalseTransform:ka,handleSelect:He,trueFalseRefs:Ma,onContextMenu:xt,handleDragEnd:$a}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ma.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(Lu,{shortAnswers:[M.element],handleSelect:He,handleTransform:_e,saRefs:Ze,onContextMenu:xt,handleDragEnd:ea}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(Au,{longAnswer:[M.element],handleSelect:He,handleTransform:_e,saRefs:Ze,onContextMenu:xt,handleDragEnd:Cf}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Mu,{fillInTheBlanks:[M.element],handleSelect:He,handleTransform:_e,onContextMenu:xt,handleDragEnd:Mf}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);default:return null}})})()})]}),P&&r?.enabled!==false&&jsx(Ud,{menuRef:L,x:P.x,y:P.y,type:P.elementType,elementId:P.elementId,onAction:jf,onClose:$f,isDrawingMode:P.elementType==="image"?l?.images.find(w=>w.id===P.elementId)?.isDrawingMode:P.elementType==="photoFrame"?l?.photoFrames.find(w=>w.id===P.elementId)?.isDrawingMode:false}),H&&P&&jsx(Hd,{x:H.x,y:H.y,items:H.type==="order"?[{label:"Bring to Front",onClick:()=>rn("bring-to-front")},{label:"Send to Back",onClick:()=>rn("send-to-back")}]:[{label:l&&(P.elementType==="image"?l.images.find(w=>w.id===P.elementId)?.locked:l.videos.find(w=>w.id===P.elementId)?.locked)?"Unlock":"Lock",onClick:()=>rn(l&&(P.elementType==="image"?l.images.find(w=>w.id===P.elementId)?.locked:l.videos.find(w=>w.id===P.elementId)?.locked)?"unlock":"lock")}],onClose:()=>N(null)}),te&&jsx(zd,{title:te.type==="link"?"Add Link":"Add Alt Text",label:te.type==="link"?"URL":"Alternative Text",placeholder:te.type==="link"?"https://example.com":"Describe this image/video",defaultValue:te.defaultValue,onSave:Xf,onClose:()=>q(null)}),G&&jsx(Wd,{defaultColor:G.defaultColor,onConfirm:Zf,onCancel:()=>oe(null)}),D&&jsx(jd,{imageSrc:D.imageSrc,onConfirm:Qf,onCancel:()=>z(null)}),X&&jsx(Jo,{onClose:()=>_(false),stageRef:h}),Y&&jsx(Xd,{elementId:Y.elementId,elementType:Y.elementType,existingAudio:Y.existingAudio,onSave:Yf,onDelete:Jf,onClose:()=>Z(null)}),Q&&jsx(Zd,{selectedElementId:p||void 0,onClose:()=>pe(false),onSelectElement:w=>{He(w),pe(false);}}),l?.images.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.videos.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.shapes?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.texts?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.flashcards?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),m&&jsx(hu,{editElement:d}),U&&(()=>{let w=he||p;if(!w)return null;let M=Fo.find(T=>T.id===w);return M?jsx(gu,{text:M,position:U}):null})(),E&&he&&(()=>{let w=Fo.find(M=>M.id===he);return w?jsx(bu,{text:w,editingValue:Al,onEditingChange:Pl,onFinish:on,position:{top:E.top,left:E.left},scale:E.scale,textareaRef:we},he):null})()]})},Ux=qx;var Hx="SchooplaVideoStorage";var Gt="videos",Bs=()=>new Promise((e,o)=>{let t=indexedDB.open(Hx,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Gt)||r.createObjectStore(Gt,{keyPath:"id"});};}),Ha=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Bs(),s=a.transaction([Gt],"readwrite").objectStore(Gt),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((i,u)=>{let l=s.put(n);l.onsuccess=()=>i(!0),l.onerror=()=>u(l.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 Fu=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Bs(),t=e.transaction([Gt],"readonly").objectStore(Gt);return new Promise((a,r)=>{let s=t.getAll();s.onsuccess=()=>{e.close();let n=s.result,i=new Map;n.forEach(u=>{i.set(u.id,{blob:u.blob,thumbnailDataUrl:u.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${i.size} video blobs from IndexedDB`),a(i);},s.onerror=()=>{e.close(),r(s.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 Bs(),a=o.transaction([Gt],"readwrite").objectStore(Gt);await new Promise((r,s)=>{let n=a.delete(e);n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Eu=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Bs(),t=e.transaction([Gt],"readwrite").objectStore(Gt);await new Promise((a,r)=>{let s=t.clear();s.onsuccess=()=>a(!0),s.onerror=()=>r(s.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Bu=e=>URL.createObjectURL(e);function ba(e,o=[]){let t=[];function a(s,n){let i=be.createContext(n),u=t.length;t=[...t,n];let l=d=>{let{scope:m,children:f,...h}=d,x=m?.[e]?.[u]||i,p=be.useMemo(()=>h,Object.values(h));return jsx(x.Provider,{value:p,children:f})};l.displayName=s+"Provider";function c(d,m){let f=m?.[e]?.[u]||i,h=be.useContext(f);if(h)return h;if(n!==void 0)return n;throw new Error(`\`${d}\` must be used within \`${s}\``)}return [l,c]}let r=()=>{let s=t.map(n=>be.createContext(n));return function(i){let u=i?.[e]||s;return be.useMemo(()=>({[`__scope${e}`]:{...i,[e]:u}}),[i,u])}};return r.scopeName=e,[a,Wx(r,...o)]}function Wx(...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(s){let n=a.reduce((i,{useScope:u,scopeName:l})=>{let d=u(s)[`__scope${l}`];return {...i,...d}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}function Ou(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function vr(...e){return o=>{let t=false,a=e.map(r=>{let s=Ou(r,o);return !t&&typeof s=="function"&&(t=true),s});if(t)return ()=>{for(let r=0;r<a.length;r++){let s=a[r];typeof s=="function"?s():Ou(e[r],null);}}}}function At(...e){return be.useCallback(vr(...e),e)}function qu(e){let o=Gx(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),u=i.find(_x);if(u){let l=u.props.children,c=i.map(d=>d===u?be.Children.count(l)>1?be.Children.only(null):be.isValidElement(l)?l.props.children:null:d);return jsx(o,{...n,ref:r,children:be.isValidElement(l)?be.cloneElement(l,void 0,c):null})}return jsx(o,{...n,ref:r,children:s})});return t.displayName=`${e}.Slot`,t}function Gx(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=$x(r),i=jx(s,r.props);return r.type!==be.Fragment&&(i.ref=a?vr(a,n):n),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Kx=Symbol("radix.slottable");function _x(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Kx}function jx(e,o){let t={...o};for(let a in o){let r=e[a],s=o[a];/^on[A-Z]/.test(a)?r&&s?t[a]=(...i)=>{let u=s(...i);return r(...i),u}:r&&(t[a]=r):a==="style"?t[a]={...r,...s}:a==="className"&&(t[a]=[r,s].filter(Boolean).join(" "));}return {...e,...t}}function $x(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 Jx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],it=Jx.reduce((e,o)=>{let t=qu(`Primitive.${o}`),a=be.forwardRef((r,s)=>{let{asChild:n,...i}=r,u=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(u,{...i,ref:s})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function Xe(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function ji(e){let o=Zx(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),u=i.find(eb);if(u){let l=u.props.children,c=i.map(d=>d===u?be.Children.count(l)>1?be.Children.only(null):be.isValidElement(l)?l.props.children:null:d);return jsx(o,{...n,ref:r,children:be.isValidElement(l)?be.cloneElement(l,void 0,c):null})}return jsx(o,{...n,ref:r,children:s})});return t.displayName=`${e}.Slot`,t}function Zx(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=ab(r),i=tb(s,r.props);return r.type!==be.Fragment&&(i.ref=a?vr(a,n):n),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Qx=Symbol("radix.slottable");function eb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Qx}function tb(e,o){let t={...o};for(let a in o){let r=e[a],s=o[a];/^on[A-Z]/.test(a)?r&&s?t[a]=(...i)=>{let u=s(...i);return r(...i),u}:r&&(t[a]=r):a==="style"?t[a]={...r,...s}:a==="className"&&(t[a]=[r,s].filter(Boolean).join(" "));}return {...e,...t}}function ab(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 Os(e){let o=e+"CollectionProvider",[t,a]=ba(o),[r,s]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=x=>{let{scope:p,children:v}=x,g=be__default.useRef(null),b=be__default.useRef(new Map).current;return jsx(r,{scope:p,itemMap:b,collectionRef:g,children:v})};n.displayName=o;let i=e+"CollectionSlot",u=ji(i),l=be__default.forwardRef((x,p)=>{let{scope:v,children:g}=x,b=s(i,v),y=At(p,b.collectionRef);return jsx(u,{ref:y,children:g})});l.displayName=i;let c=e+"CollectionItemSlot",d="data-radix-collection-item",m=ji(c),f=be__default.forwardRef((x,p)=>{let{scope:v,children:g,...b}=x,y=be__default.useRef(null),S=At(p,y),I=s(c,v);return be__default.useEffect(()=>(I.itemMap.set(y,{ref:y,...b}),()=>void I.itemMap.delete(y))),jsx(m,{[d]:"",ref:S,children:g})});f.displayName=c;function h(x){let p=s(e+"CollectionConsumer",x);return be__default.useCallback(()=>{let g=p.collectionRef.current;if(!g)return [];let b=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(p.itemMap.values()).sort((I,C)=>b.indexOf(I.ref.current)-b.indexOf(C.ref.current))},[p.collectionRef,p.itemMap])}return [{Provider:n,Slot:l,ItemSlot:f},h,a]}var wo=globalThis?.document?be.useLayoutEffect:()=>{};var ob=be[" useId ".trim().toString()]||(()=>{}),rb=0;function Wu(e){let[o,t]=be.useState(ob());return wo(()=>{t(a=>a??String(rb++));},[e]),(o?`radix-${o}`:"")}function Gu(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var sb=be[" useInsertionEffect ".trim().toString()]||wo;function Yt({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,s,n]=nb({defaultProp:o,onChange:t}),i=e!==void 0,u=i?e:r;{let c=be.useRef(e!==void 0);be.useEffect(()=>{let d=c.current;d!==i&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${i?"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.`),c.current=i;},[i,a]);}let l=be.useCallback(c=>{if(i){let d=ib(c)?c(e):c;d!==e&&n.current?.(d);}else s(c);},[i,e,s,n]);return [u,l]}function nb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),s=be.useRef(o);return sb(()=>{s.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(s.current?.(t),r.current=t);},[t,r]),[t,a,s]}function ib(e){return typeof e=="function"}var lb=be.createContext(void 0);function So(e){let o=be.useContext(lb);return e||o||"ltr"}var Yi="rovingFocusGroup.onEntryFocus",db={bubbles:false,cancelable:true},yr="RovingFocusGroup",[Ji,Ku,ub]=Os(yr),[cb,Zi]=ba(yr,[ub]),[fb,mb]=cb(yr),_u=be.forwardRef((e,o)=>jsx(Ji.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Ji.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(pb,{...e,ref:o})})}));_u.displayName=yr;var pb=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:s,currentTabStopId:n,defaultCurrentTabStopId:i,onCurrentTabStopIdChange:u,onEntryFocus:l,preventScrollOnEntryFocus:c=false,...d}=e,m=be.useRef(null),f=At(o,m),h=So(s),[x,p]=Yt({prop:n,defaultProp:i??null,onChange:u,caller:yr}),[v,g]=be.useState(false),b=Gu(l),y=Ku(t),S=be.useRef(false),[I,C]=be.useState(0);return be.useEffect(()=>{let L=m.current;if(L)return L.addEventListener(Yi,b),()=>L.removeEventListener(Yi,b)},[b]),jsx(fb,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:x,onItemFocus:be.useCallback(L=>p(L),[p]),onItemShiftTab:be.useCallback(()=>g(true),[]),onFocusableItemAdd:be.useCallback(()=>C(L=>L+1),[]),onFocusableItemRemove:be.useCallback(()=>C(L=>L-1),[]),children:jsx(it.div,{tabIndex:v||I===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:Xe(e.onMouseDown,()=>{S.current=true;}),onFocus:Xe(e.onFocus,L=>{let P=!S.current;if(L.target===L.currentTarget&&P&&!v){let A=new CustomEvent(Yi,db);if(L.currentTarget.dispatchEvent(A),!A.defaultPrevented){let U=y().filter(N=>N.focusable),F=U.find(N=>N.active),E=U.find(N=>N.id===x),H=[F,E,...U].filter(Boolean).map(N=>N.ref.current);Xu(H,c);}}S.current=false;}),onBlur:Xe(e.onBlur,()=>g(false))})})}),ju="RovingFocusGroupItem",$u=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:s,children:n,...i}=e,u=Wu(),l=s||u,c=mb(ju,t),d=c.currentTabStopId===l,m=Ku(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:x}=c;return be.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(Ji.ItemSlot,{scope:t,id:l,focusable:a,active:r,children:jsx(it.span,{tabIndex:d?0:-1,"data-orientation":c.orientation,...i,ref:o,onMouseDown:Xe(e.onMouseDown,p=>{a?c.onItemFocus(l):p.preventDefault();}),onFocus:Xe(e.onFocus,()=>c.onItemFocus(l)),onKeyDown:Xe(e.onKeyDown,p=>{if(p.key==="Tab"&&p.shiftKey){c.onItemShiftTab();return}if(p.target!==p.currentTarget)return;let v=xb(p,c.orientation,c.dir);if(v!==void 0){if(p.metaKey||p.ctrlKey||p.altKey||p.shiftKey)return;p.preventDefault();let b=m().filter(y=>y.focusable).map(y=>y.ref.current);if(v==="last")b.reverse();else if(v==="prev"||v==="next"){v==="prev"&&b.reverse();let y=b.indexOf(p.currentTarget);b=c.loop?bb(b,y+1):b.slice(y+1);}setTimeout(()=>Xu(b));}}),children:typeof n=="function"?n({isCurrentTabStop:d,hasTabStop:x!=null}):n})})});$u.displayName=ju;var hb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function gb(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function xb(e,o,t){let a=gb(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return hb[a]}function Xu(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function bb(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Yu=_u,Ju=$u;var Qu="Toggle",Qi=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...s}=e,[n,i]=Yt({prop:t,onChange:r,defaultProp:a??false,caller:Qu});return jsx(it.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...s,ref:o,onClick:Xe(e.onClick,()=>{e.disabled||i(!n);})})});Qi.displayName=Qu;var va="ToggleGroup",[tc]=ba(va,[Zi]),ac=Zi(),el=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(wb,{...a,ref:o});if(t==="multiple")return jsx(Lb,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${va}\``)});el.displayName=va;var[oc,rc]=tc(va),wb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Yt({prop:t,defaultProp:a??"",onChange:r,caller:va});return jsx(oc,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:i,onItemDeactivate:be__default.useCallback(()=>i(""),[i]),children:jsx(sc,{...s,ref:o})})}),Lb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Yt({prop:t,defaultProp:a??[],onChange:r,caller:va}),u=be__default.useCallback(c=>i((d=[])=>[...d,c]),[i]),l=be__default.useCallback(c=>i((d=[])=>d.filter(m=>m!==c)),[i]);return jsx(oc,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:u,onItemDeactivate:l,children:jsx(sc,{...s,ref:o})})});el.displayName=va;var[Sb,Ib]=tc(va),sc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:s,dir:n,loop:i=true,...u}=e,l=ac(t),c=So(n),d={role:"group",dir:c,...u};return jsx(Sb,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(Yu,{asChild:true,...l,orientation:s,dir:c,loop:i,children:jsx(it.div,{...d,ref:o})}):jsx(it.div,{...d,ref:o})})}),qs="ToggleGroupItem",Cb=be__default.forwardRef((e,o)=>{let t=rc(qs,e.__scopeToggleGroup),a=Ib(qs,e.__scopeToggleGroup),r=ac(e.__scopeToggleGroup),s=t.value.includes(e.value),n=a.disabled||e.disabled,i={...e,pressed:s,disabled:n},u=be__default.useRef(null);return a.rovingFocus?jsx(Ju,{asChild:true,...r,focusable:!n,active:s,ref:u,children:jsx(ec,{...i,ref:o})}):jsx(ec,{...i,ref:o})});Cb.displayName=qs;var ec=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,s=rc(qs,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=s.type==="single"?n:void 0;return jsx(Qi,{...i,...r,ref:o,onPressedChange:u=>{u?s.onItemActivate(a):s.onItemDeactivate(a);}})}),nc=el;function ic(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=ic(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Us(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=ic(e))&&(a&&(a+=" "),a+=o);return a}var Mb=(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},Tb=(e,o)=>({classGroupId:e,validator:o}),fc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var lc=[],Ab="arbitrary..",Pb=e=>{let o=Rb(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return Db(n);let i=n.split("-"),u=i[0]===""&&i.length>1?1:0;return mc(i,u,o)},getConflictingClassGroupIds:(n,i)=>{if(i){let u=a[n],l=t[n];return u?l?Mb(l,u):u:l||lc}return t[n]||lc}}},mc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],s=t.nextPart.get(r);if(s){let l=mc(e,o+1,s);if(l)return l}let n=t.validators;if(n===null)return;let i=o===0?e.join("-"):e.slice(o).join("-"),u=n.length;for(let l=0;l<u;l++){let c=n[l];if(c.validator(i))return c.classGroupId}},Db=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?Ab+a:void 0})(),Rb=e=>{let{theme:o,classGroups:t}=e;return Fb(t,o)},Fb=(e,o)=>{let t=fc();for(let a in e){let r=e[a];ol(r,t,a,o);}return t},ol=(e,o,t,a)=>{let r=e.length;for(let s=0;s<r;s++){let n=e[s];Eb(n,o,t,a);}},Eb=(e,o,t,a)=>{if(typeof e=="string"){Bb(e,o,t);return}if(typeof e=="function"){Ob(e,o,t,a);return}Nb(e,o,t,a);},Bb=(e,o,t)=>{let a=e===""?o:pc(o,e);a.classGroupId=t;},Ob=(e,o,t,a)=>{if(Vb(e)){ol(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Tb(t,e));},Nb=(e,o,t,a)=>{let r=Object.entries(e),s=r.length;for(let n=0;n<s;n++){let[i,u]=r[n];ol(u,pc(o,i),t,a);}},pc=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let s=0;s<r;s++){let n=a[s],i=t.nextPart.get(n);i||(i=fc(),t.nextPart.set(n,i)),t=i;}return t},Vb=e=>"isThemeGetter"in e&&e.isThemeGetter===true,qb=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(s,n)=>{t[s]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(s){let n=t[s];if(n!==void 0)return n;if((n=a[s])!==void 0)return r(s,n),n},set(s,n){s in t?t[s]=n:r(s,n);}}};var Ub=[],dc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),Hb=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let s=[],n=0,i=0,u=0,l,c=r.length;for(let x=0;x<c;x++){let p=r[x];if(n===0&&i===0){if(p===":"){s.push(r.slice(u,x)),u=x+1;continue}if(p==="/"){l=x;continue}}p==="["?n++:p==="]"?n--:p==="("?i++:p===")"&&i--;}let d=s.length===0?r:r.slice(u),m=d,f=false;d.endsWith("!")?(m=d.slice(0,-1),f=true):d.startsWith("!")&&(m=d.slice(1),f=true);let h=l&&l>u?l-u:void 0;return dc(s,f,m,h)};if(o){let r=o+":",s=a;a=n=>n.startsWith(r)?s(n.slice(r.length)):dc(Ub,false,n,void 0,true);}if(t){let r=a;a=s=>t({className:s,parseClassName:r});}return a},zb=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],i=n[0]==="[",u=o.has(n);i||u?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(n)):r.push(n);}return r.length>0&&(r.sort(),a.push(...r)),a}},Wb=e=>({cache:qb(e.cacheSize),parseClassName:Hb(e),sortModifiers:zb(e),...Pb(e)}),Gb=/\s+/,Kb=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:s}=o,n=[],i=e.trim().split(Gb),u="";for(let l=i.length-1;l>=0;l-=1){let c=i[l],{isExternal:d,modifiers:m,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:x}=t(c);if(d){u=c+(u.length>0?" "+u:u);continue}let p=!!x,v=a(p?h.substring(0,x):h);if(!v){if(!p){u=c+(u.length>0?" "+u:u);continue}if(v=a(h),!v){u=c+(u.length>0?" "+u:u);continue}p=false;}let g=m.length===0?"":m.length===1?m[0]:s(m).join(":"),b=f?g+"!":g,y=b+v;if(n.indexOf(y)>-1)continue;n.push(y);let S=r(v,p);for(let I=0;I<S.length;++I){let C=S[I];n.push(b+C);}u=c+(u.length>0?" "+u:u);}return u},_b=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=hc(t))&&(r&&(r+=" "),r+=a);return r},hc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=hc(e[a]))&&(t&&(t+=" "),t+=o);return t},jb=(e,...o)=>{let t,a,r,s,n=u=>{let l=o.reduce((c,d)=>d(c),e());return t=Wb(l),a=t.cache.get,r=t.cache.set,s=i,i(u)},i=u=>{let l=a(u);if(l)return l;let c=Kb(u,t);return r(u,c),c};return s=n,(...u)=>s(_b(...u))},$b=[],Ne=e=>{let o=t=>t[e]||$b;return o.isThemeGetter=true,o},gc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,xc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Xb=/^\d+\/\d+$/,Yb=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Jb=/\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$/,Zb=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Qb=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ev=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Io=e=>Xb.test(e),le=e=>!!e&&!Number.isNaN(Number(e)),ya=e=>!!e&&Number.isInteger(Number(e)),tl=e=>e.endsWith("%")&&le(e.slice(0,-1)),Jt=e=>Yb.test(e),tv=()=>true,av=e=>Jb.test(e)&&!Zb.test(e),bc=()=>false,ov=e=>Qb.test(e),rv=e=>ev.test(e),sv=e=>!j(e)&&!$(e),nv=e=>Co(e,wc,bc),j=e=>gc.test(e),Ga=e=>Co(e,Lc,av),al=e=>Co(e,cv,le),uc=e=>Co(e,vc,bc),iv=e=>Co(e,yc,rv),Hs=e=>Co(e,Sc,ov),$=e=>xc.test(e),wr=e=>ko(e,Lc),lv=e=>ko(e,fv),cc=e=>ko(e,vc),dv=e=>ko(e,wc),uv=e=>ko(e,yc),zs=e=>ko(e,Sc,true),Co=(e,o,t)=>{let a=gc.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},ko=(e,o,t=false)=>{let a=xc.exec(e);return a?a[1]?o(a[1]):t:false},vc=e=>e==="position"||e==="percentage",yc=e=>e==="image"||e==="url",wc=e=>e==="length"||e==="size"||e==="bg-size",Lc=e=>e==="length",cv=e=>e==="number",fv=e=>e==="family-name",Sc=e=>e==="shadow";var mv=()=>{let e=Ne("color"),o=Ne("font"),t=Ne("text"),a=Ne("font-weight"),r=Ne("tracking"),s=Ne("leading"),n=Ne("breakpoint"),i=Ne("container"),u=Ne("spacing"),l=Ne("radius"),c=Ne("shadow"),d=Ne("inset-shadow"),m=Ne("text-shadow"),f=Ne("drop-shadow"),h=Ne("blur"),x=Ne("perspective"),p=Ne("aspect"),v=Ne("ease"),g=Ne("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],y=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],S=()=>[...y(),$,j],I=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],L=()=>[$,j,u],P=()=>[Io,"full","auto",...L()],A=()=>[ya,"none","subgrid",$,j],U=()=>["auto",{span:["full",ya,$,j]},ya,$,j],F=()=>[ya,"auto",$,j],E=()=>["auto","min","max","fr",$,j],R=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],H=()=>["start","end","center","stretch","center-safe","end-safe"],N=()=>["auto",...L()],te=()=>[Io,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...L()],q=()=>[e,$,j],G=()=>[...y(),cc,uc,{position:[$,j]}],oe=()=>["no-repeat",{repeat:["","x","y","space","round"]}],D=()=>["auto","cover","contain",dv,nv,{size:[$,j]}],z=()=>[tl,wr,Ga],X=()=>["","none","full",l,$,j],_=()=>["",le,wr,Ga],Y=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Q=()=>[le,tl,cc,uc],pe=()=>["","none",h,$,j],we=()=>["none",le,$,j],De=()=>["none",le,$,j],Me=()=>[le,$,j],Ue=()=>[Io,"full",...L()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Jt],breakpoint:[Jt],color:[tv],container:[Jt],"drop-shadow":[Jt],ease:["in","out","in-out"],font:[sv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Jt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Jt],shadow:[Jt],spacing:["px",le],text:[Jt],"text-shadow":[Jt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Io,j,$,p]}],container:["container"],columns:[{columns:[le,j,$,i]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:S()}],overflow:[{overflow:I()}],"overflow-x":[{"overflow-x":I()}],"overflow-y":[{"overflow-y":I()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:P()}],"inset-x":[{"inset-x":P()}],"inset-y":[{"inset-y":P()}],start:[{start:P()}],end:[{end:P()}],top:[{top:P()}],right:[{right:P()}],bottom:[{bottom:P()}],left:[{left:P()}],visibility:["visible","invisible","collapse"],z:[{z:[ya,"auto",$,j]}],basis:[{basis:[Io,"full","auto",i,...L()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[le,Io,"auto","initial","none",j]}],grow:[{grow:["",le,$,j]}],shrink:[{shrink:["",le,$,j]}],order:[{order:[ya,"first","last","none",$,j]}],"grid-cols":[{"grid-cols":A()}],"col-start-end":[{col:U()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":A()}],"row-start-end":[{row:U()}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":E()}],"auto-rows":[{"auto-rows":E()}],gap:[{gap:L()}],"gap-x":[{"gap-x":L()}],"gap-y":[{"gap-y":L()}],"justify-content":[{justify:[...R(),"normal"]}],"justify-items":[{"justify-items":[...H(),"normal"]}],"justify-self":[{"justify-self":["auto",...H()]}],"align-content":[{content:["normal",...R()]}],"align-items":[{items:[...H(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...H(),{baseline:["","last"]}]}],"place-content":[{"place-content":R()}],"place-items":[{"place-items":[...H(),"baseline"]}],"place-self":[{"place-self":["auto",...H()]}],p:[{p:L()}],px:[{px:L()}],py:[{py:L()}],ps:[{ps:L()}],pe:[{pe:L()}],pt:[{pt:L()}],pr:[{pr:L()}],pb:[{pb:L()}],pl:[{pl:L()}],m:[{m:N()}],mx:[{mx:N()}],my:[{my:N()}],ms:[{ms:N()}],me:[{me:N()}],mt:[{mt:N()}],mr:[{mr:N()}],mb:[{mb:N()}],ml:[{ml:N()}],"space-x":[{"space-x":L()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":L()}],"space-y-reverse":["space-y-reverse"],size:[{size:te()}],w:[{w:[i,"screen",...te()]}],"min-w":[{"min-w":[i,"screen","none",...te()]}],"max-w":[{"max-w":[i,"screen","none","prose",{screen:[n]},...te()]}],h:[{h:["screen","lh",...te()]}],"min-h":[{"min-h":["screen","lh","none",...te()]}],"max-h":[{"max-h":["screen","lh",...te()]}],"font-size":[{text:["base",t,wr,Ga]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,al]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",tl,j]}],"font-family":[{font:[lv,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":[le,"none",$,al]}],leading:[{leading:[s,...L()]}],"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:q()}],"text-color":[{text:q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:[le,"from-font","auto",$,Ga]}],"text-decoration-color":[{decoration:q()}],"underline-offset":[{"underline-offset":[le,"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:L()}],"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:G()}],"bg-repeat":[{bg:oe()}],"bg-size":[{bg:D()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ya,$,j],radial:["",$,j],conic:[ya,$,j]},uv,iv]}],"bg-color":[{bg:q()}],"gradient-from-pos":[{from:z()}],"gradient-via-pos":[{via:z()}],"gradient-to-pos":[{to:z()}],"gradient-from":[{from:q()}],"gradient-via":[{via:q()}],"gradient-to":[{to:q()}],rounded:[{rounded:X()}],"rounded-s":[{"rounded-s":X()}],"rounded-e":[{"rounded-e":X()}],"rounded-t":[{"rounded-t":X()}],"rounded-r":[{"rounded-r":X()}],"rounded-b":[{"rounded-b":X()}],"rounded-l":[{"rounded-l":X()}],"rounded-ss":[{"rounded-ss":X()}],"rounded-se":[{"rounded-se":X()}],"rounded-ee":[{"rounded-ee":X()}],"rounded-es":[{"rounded-es":X()}],"rounded-tl":[{"rounded-tl":X()}],"rounded-tr":[{"rounded-tr":X()}],"rounded-br":[{"rounded-br":X()}],"rounded-bl":[{"rounded-bl":X()}],"border-w":[{border:_()}],"border-w-x":[{"border-x":_()}],"border-w-y":[{"border-y":_()}],"border-w-s":[{"border-s":_()}],"border-w-e":[{"border-e":_()}],"border-w-t":[{"border-t":_()}],"border-w-r":[{"border-r":_()}],"border-w-b":[{"border-b":_()}],"border-w-l":[{"border-l":_()}],"divide-x":[{"divide-x":_()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":_()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Y(),"hidden","none"]}],"divide-style":[{divide:[...Y(),"hidden","none"]}],"border-color":[{border:q()}],"border-color-x":[{"border-x":q()}],"border-color-y":[{"border-y":q()}],"border-color-s":[{"border-s":q()}],"border-color-e":[{"border-e":q()}],"border-color-t":[{"border-t":q()}],"border-color-r":[{"border-r":q()}],"border-color-b":[{"border-b":q()}],"border-color-l":[{"border-l":q()}],"divide-color":[{divide:q()}],"outline-style":[{outline:[...Y(),"none","hidden"]}],"outline-offset":[{"outline-offset":[le,$,j]}],"outline-w":[{outline:["",le,wr,Ga]}],"outline-color":[{outline:q()}],shadow:[{shadow:["","none",c,zs,Hs]}],"shadow-color":[{shadow:q()}],"inset-shadow":[{"inset-shadow":["none",d,zs,Hs]}],"inset-shadow-color":[{"inset-shadow":q()}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:q()}],"ring-offset-w":[{"ring-offset":[le,Ga]}],"ring-offset-color":[{"ring-offset":q()}],"inset-ring-w":[{"inset-ring":_()}],"inset-ring-color":[{"inset-ring":q()}],"text-shadow":[{"text-shadow":["none",m,zs,Hs]}],"text-shadow-color":[{"text-shadow":q()}],opacity:[{opacity:[le,$,j]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"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":[le]}],"mask-image-linear-from-pos":[{"mask-linear-from":Q()}],"mask-image-linear-to-pos":[{"mask-linear-to":Q()}],"mask-image-linear-from-color":[{"mask-linear-from":q()}],"mask-image-linear-to-color":[{"mask-linear-to":q()}],"mask-image-t-from-pos":[{"mask-t-from":Q()}],"mask-image-t-to-pos":[{"mask-t-to":Q()}],"mask-image-t-from-color":[{"mask-t-from":q()}],"mask-image-t-to-color":[{"mask-t-to":q()}],"mask-image-r-from-pos":[{"mask-r-from":Q()}],"mask-image-r-to-pos":[{"mask-r-to":Q()}],"mask-image-r-from-color":[{"mask-r-from":q()}],"mask-image-r-to-color":[{"mask-r-to":q()}],"mask-image-b-from-pos":[{"mask-b-from":Q()}],"mask-image-b-to-pos":[{"mask-b-to":Q()}],"mask-image-b-from-color":[{"mask-b-from":q()}],"mask-image-b-to-color":[{"mask-b-to":q()}],"mask-image-l-from-pos":[{"mask-l-from":Q()}],"mask-image-l-to-pos":[{"mask-l-to":Q()}],"mask-image-l-from-color":[{"mask-l-from":q()}],"mask-image-l-to-color":[{"mask-l-to":q()}],"mask-image-x-from-pos":[{"mask-x-from":Q()}],"mask-image-x-to-pos":[{"mask-x-to":Q()}],"mask-image-x-from-color":[{"mask-x-from":q()}],"mask-image-x-to-color":[{"mask-x-to":q()}],"mask-image-y-from-pos":[{"mask-y-from":Q()}],"mask-image-y-to-pos":[{"mask-y-to":Q()}],"mask-image-y-from-color":[{"mask-y-from":q()}],"mask-image-y-to-color":[{"mask-y-to":q()}],"mask-image-radial":[{"mask-radial":[$,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":Q()}],"mask-image-radial-to-pos":[{"mask-radial-to":Q()}],"mask-image-radial-from-color":[{"mask-radial-from":q()}],"mask-image-radial-to-color":[{"mask-radial-to":q()}],"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":y()}],"mask-image-conic-pos":[{"mask-conic":[le]}],"mask-image-conic-from-pos":[{"mask-conic-from":Q()}],"mask-image-conic-to-pos":[{"mask-conic-to":Q()}],"mask-image-conic-from-color":[{"mask-conic-from":q()}],"mask-image-conic-to-color":[{"mask-conic-to":q()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:G()}],"mask-repeat":[{mask:oe()}],"mask-size":[{mask:D()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,j]}],filter:[{filter:["","none",$,j]}],blur:[{blur:pe()}],brightness:[{brightness:[le,$,j]}],contrast:[{contrast:[le,$,j]}],"drop-shadow":[{"drop-shadow":["","none",f,zs,Hs]}],"drop-shadow-color":[{"drop-shadow":q()}],grayscale:[{grayscale:["",le,$,j]}],"hue-rotate":[{"hue-rotate":[le,$,j]}],invert:[{invert:["",le,$,j]}],saturate:[{saturate:[le,$,j]}],sepia:[{sepia:["",le,$,j]}],"backdrop-filter":[{"backdrop-filter":["","none",$,j]}],"backdrop-blur":[{"backdrop-blur":pe()}],"backdrop-brightness":[{"backdrop-brightness":[le,$,j]}],"backdrop-contrast":[{"backdrop-contrast":[le,$,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",le,$,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[le,$,j]}],"backdrop-invert":[{"backdrop-invert":["",le,$,j]}],"backdrop-opacity":[{"backdrop-opacity":[le,$,j]}],"backdrop-saturate":[{"backdrop-saturate":[le,$,j]}],"backdrop-sepia":[{"backdrop-sepia":["",le,$,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":L()}],"border-spacing-x":[{"border-spacing-x":L()}],"border-spacing-y":[{"border-spacing-y":L()}],"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:[le,"initial",$,j]}],ease:[{ease:["linear","initial",v,$,j]}],delay:[{delay:[le,$,j]}],animate:[{animate:["none",g,$,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[x,$,j]}],"perspective-origin":[{"perspective-origin":S()}],rotate:[{rotate:we()}],"rotate-x":[{"rotate-x":we()}],"rotate-y":[{"rotate-y":we()}],"rotate-z":[{"rotate-z":we()}],scale:[{scale:De()}],"scale-x":[{"scale-x":De()}],"scale-y":[{"scale-y":De()}],"scale-z":[{"scale-z":De()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[$,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:S()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ue()}],"translate-x":[{"translate-x":Ue()}],"translate-y":[{"translate-y":Ue()}],"translate-z":[{"translate-z":Ue()}],"translate-none":["translate-none"],accent:[{accent:q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:q()}],"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":L()}],"scroll-mx":[{"scroll-mx":L()}],"scroll-my":[{"scroll-my":L()}],"scroll-ms":[{"scroll-ms":L()}],"scroll-me":[{"scroll-me":L()}],"scroll-mt":[{"scroll-mt":L()}],"scroll-mr":[{"scroll-mr":L()}],"scroll-mb":[{"scroll-mb":L()}],"scroll-ml":[{"scroll-ml":L()}],"scroll-p":[{"scroll-p":L()}],"scroll-px":[{"scroll-px":L()}],"scroll-py":[{"scroll-py":L()}],"scroll-ps":[{"scroll-ps":L()}],"scroll-pe":[{"scroll-pe":L()}],"scroll-pt":[{"scroll-pt":L()}],"scroll-pr":[{"scroll-pr":L()}],"scroll-pb":[{"scroll-pb":L()}],"scroll-pl":[{"scroll-pl":L()}],"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",...q()]}],"stroke-w":[{stroke:[le,wr,Ga,al]}],stroke:[{stroke:["none",...q()]}],"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 Ic=jb(mv);function wa(...e){return Ic(Us(e))}var hv=be.createContext({size:"default",variant:"default",spacing:0});function La({className:e,variant:o,size:t,spacing:a=2,children:r,...s}){return jsx(nc,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:wa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...s,children:jsx(hv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var xv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Ac=createSlice({name:"toolbar",initialState:xv,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:Ot,setPenColor:Ws,setStrokeWidth:sl,setFontSize:TA,setFontFamily:AA,setFontStyle:PA,setFontWeight:DA,setTextDecoration:RA,setTextColor:FA}=Ac.actions,Pc=Ac.reducer;var Dc=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,s]=useState(null),[n,i]=useState(0),[u,l]=useState(null),[c,d]=useState(false),m=useRef(null),f=useRef([]),h=useRef(null),x=useRef(null),p=useRef(null);useEffect(()=>((async()=>{try{let C=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});l(C),d(!0),p.current&&(p.current.srcObject=C);}catch(C){console.error("Error accessing camera:",C),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{h.current&&clearInterval(h.current),u&&u.getTracks().forEach(C=>C.stop());}),[]);let v=()=>{u&&(u.getTracks().forEach(I=>I.stop()),l(null),d(false));},g=async()=>{try{let I=null,C=null;try{I=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(F){console.error("Error accessing camera for recording:",F),alert("Failed to access camera for recording.");return}try{C=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(F){console.warn("Microphone access denied:",F);}let L=[...I.getVideoTracks()];C&&L.push(...C.getAudioTracks());let P=new MediaStream(L),A="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?A="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?A="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?A="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(A="video/webm;codecs=vp8");let U=new MediaRecorder(P,{mimeType:A,videoBitsPerSecond:25e5});m.current=U,f.current=[],U.ondataavailable=F=>{F.data.size>0&&f.current.push(F.data);},U.onstop=()=>{let F=new Blob(f.current,{type:A}),E=document.createElement("video");E.src=URL.createObjectURL(F),E.muted=!0,E.currentTime=.1,E.onseeked=()=>{let R=document.createElement("canvas");R.width=E.videoWidth,R.height=E.videoHeight;let H=R.getContext("2d");H&&(H.drawImage(E,0,0),x.current=R.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(E.src);},P.getTracks().forEach(R=>R.stop()),I&&I.getTracks().forEach(R=>R.stop()),C&&C.getTracks().forEach(R=>R.stop()),h.current&&clearInterval(h.current),s(F),v();},U.onerror=F=>{console.error("MediaRecorder error:",F);},U.start(1e3),a(!0),i(0),h.current=setInterval(()=>{i(F=>F+1);},1e3);}catch(I){console.error("Error starting camera recording:",I),alert("Failed to start recording. Please check permissions.");}},b=()=>{m.current&&t&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),a(false));},y=()=>{if(r){let I=URL.createObjectURL(r),C=document.createElement("a");C.href=I,C.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(I);}},S=I=>{let C=Math.floor(I/60),L=I%60;return `${C.toString().padStart(2,"0")}:${L.toString().padStart(2,"0")}`};return jsx("div",{className:"fixed inset-0 flex items-center justify-center",children:jsxs("div",{className:"relative w-full max-w-2xl overflow-hidden rounded-2xl shadow-2xl",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:g,disabled:!c,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"})})}),!c&&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:b,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:S(n)})]})]})]}),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: ",S(n)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{s(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:y,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&&x.current&&(o(r,x.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"})]})]})]})]})]})})};var Zt=40,Fc=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[s,n]=useState(t?.order||"sequential"),[i,u]=useState(false),l=useRef(null),c=useRef(null);useEffect(()=>{let g=b=>{b.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let d=g=>{let b=g.target.files;if(!b||b.length===0)return;let y=Zt-a.length;if(y<=0){alert(`You can only upload a maximum of ${Zt} images`);return}let S=Array.from(b).slice(0,y);S.length<b.length&&alert(`Only ${y} more images can be added (max ${Zt} total)`);let I=S.map(C=>new Promise((L,P)=>{let A=new FileReader;A.onload=U=>{U.target?.result?L(U.target.result):P(new Error("Failed to read file"));},A.onerror=P,A.readAsDataURL(C);}));Promise.all(I).then(C=>{r(L=>[...L,...C]),c.current&&(c.current.value="");});},m=g=>{g.preventDefault(),u(false);let b=Array.from(g.dataTransfer.files).filter(C=>C.type.startsWith("image/"));if(b.length===0)return;let y=Zt-a.length;if(y<=0){alert(`You can only upload a maximum of ${Zt} images`);return}let S=b.slice(0,y);S.length<b.length&&alert(`Only ${y} more images can be added (max ${Zt} total)`);let I=S.map(C=>new Promise((L,P)=>{let A=new FileReader;A.onload=U=>{U.target?.result?L(U.target.result):P(new Error("Failed to read file"));},A.onerror=P,A.readAsDataURL(C);}));Promise.all(I).then(C=>{r(L=>[...L,...C]);});},f=g=>{g.preventDefault(),u(true);},h=()=>{u(false);},x=g=>{r(b=>b.filter((y,S)=>S!==g));},v=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:l,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:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,s,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>=Zt?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",Zt," images"]}):jsxs("span",{children:[a.length,"/",Zt," images"]})})]}),jsx("input",{ref:c,type:"file",accept:"image/*",multiple:true,onChange:d,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:f,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 ${i?"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:i?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${s==="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 ${s==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${s==="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 ${s==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,b)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${b+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>x(b),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:b+1})]},b))})]}),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(v,document.body)};var Gs={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}},Rv={enabled:true};function ll(e){return e?{tools:{...Gs.tools,...e.tools},actions:{...Gs.actions,...e.actions}}:Gs}var Fv={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}},Ev={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 iy=({isOpen:e,onClose:o,onScreenRecord:t,stageRef:a,onTextAdded:r,showToggleButton:s=true,config:n}={})=>{let i=xe(),u=ee(B=>B.canvas.slides.find(ne=>ne.id===B.canvas.currentSlideId)),l=u?.videos||[],c=u?.editingFlashcard,d=ee(B=>B.toolbar.selectedTool),m=ee(B=>B.toolbar.penColor),f=u?.showMcqForm,h=u?.showFlashcardForm,x=useMemo(()=>ll(n),[n]),{tools:p,actions:v}=x,g=l.some(B=>B.isRecorded&&B.isPlaying),b=ee(B=>B.toolbar.fontSize),y=ee(B=>B.toolbar.fontFamily),S=ee(B=>B.toolbar.fontStyle),I=ee(B=>B.toolbar.fontWeight),C=ee(B=>B.toolbar.textDecoration),L=ee(B=>B.toolbar.textColor),[P,A]=useState(false),[U,F]=useState(false),[E,R]=useState(false),[H,N]=useState(false),[te,q]=useState(false),[G,oe]=useState(true),z=useRef(null),X=useRef(null),Y=[{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(()=>Y.filter(B=>{let ne=p[B.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[p]),Q=[{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"}],pe=useMemo(()=>{let B=p.shapes;return B===false?[]:B===true?Q:Array.isArray(B)?Q.filter(ne=>B.includes(ne.name)):Q},[p.shapes]),we=[{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"}],De=useMemo(()=>{let B=p.activities;return B===false?[]:B===true?we:Array.isArray(B)?we.filter(ne=>B.includes(ne.name)):we},[p.activities]),Me=useMemo(()=>{let B=p.media;return B===false?{photoFrame:false,image:false,video:false}:B===true?{photoFrame:true,image:true,video:true}:Array.isArray(B)?{photoFrame:B.includes("photo-frame"),image:B.includes("image"),video:B.includes("video")}:{photoFrame:true,image:true,video:true}},[p.media]),Ue=useMemo(()=>{let B=p.activities;return B===false?false:B===true?true:Array.isArray(B)?B.includes("flashcard"):true},[p.activities]),re=B=>{let ne=B.target.files;!ne||ne.length===0||(i(Ot("select")),i(dt(false)),N(false),Array.from(ne).forEach(Ie=>{let me=new FileReader;me.onload=se=>{let ie=new window.Image;ie.src=se.target?.result,ie.onload=()=>{let Ve=ie.width/ie.height,qt=300,_t=300,_e=ie.width,Ce=ie.height;_e>qt&&(_e=qt,Ce=_e/Ve),Ce>_t&&(Ce=_t,_e=Ce*Ve),i(ue());let Je=(window.innerWidth-_e)/2,jt=(window.innerHeight-Ce)/2;i(hn({id:v4(),src:ie.src,x:Je,y:jt,width:_e,height:Ce,draggable:true,rotation:0}));};},me.readAsDataURL(Ie);}),B.target.value="");},Mr=async B=>{let ne=B.target.files;if(!(!ne||ne.length===0)){console.log("files",B),i(Ot("select")),i(dt(false)),N(false);for(let Ie of Array.from(ne))try{let me=URL.createObjectURL(Ie),se=document.createElement("video");console.log("video",se),se.src=me,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((Ze,ea)=>{let Ta=setTimeout(()=>ea(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ta),Ze();},se.onerror=()=>{clearTimeout(Ta),ea(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Ze,ea)=>{let Ta=setTimeout(()=>ea(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ta),Ze()):se.onloadeddata=()=>{clearTimeout(Ta),Ze();};});let ie=Math.min(.8,se.duration/2);console.log("Seeking to:",ie),se.currentTime=ie,await new Promise(Ze=>{let ea=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ze();},5e3);se.onseeked=()=>{clearTimeout(ea),console.log("Seek completed"),Ze();};});let Ve=document.createElement("canvas"),qt=se.videoWidth/se.videoHeight,_t=400,_e=400,Ce=se.videoWidth,Je=se.videoHeight;Ce>_t&&(Ce=_t,Je=Ce/qt),Je>_e&&(Je=_e,Ce=Je*qt),Ve.width=Ce,Ve.height=Je;let jt=Ve.getContext("2d",{willReadFrequently:!1});if(!jt)throw new Error("Failed to get canvas context");if(await new Promise(Ze=>setTimeout(Ze,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ce,height:Je}),jt.drawImage(se,0,0,Ce,Je);let ka=Ve.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",ka.length),i(ue());let Ma=(window.innerWidth-Ce)/2,$a=(window.innerHeight-Je)/2,Fr=v4();await Ha(Fr,Ie,ka),i(zr({id:Fr,objectUrl:me,thumbnailDataUrl:ka,videoBlob:Ie,x:Ma,y:$a,width:Ce,height:Je,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${Ie.name}`);}catch(me){console.error("Error processing video:",me),alert(`Failed to process video: ${Ie.name}`);}B.target.value="";}},Tr=(B,ne,Ie)=>{i(ue()),i(Ot("select")),i(dt(false));let me=300,se=300,ie=(window.innerWidth-me)/2,Ve=(window.innerHeight-se)/2;i(Ie?Za({id:Ie,images:B,order:ne,x:ie,y:Ve,width:me,height:se,rotation:0,draggable:true}):Ln({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:B,currentIndex:0,order:ne,x:ie,y:Ve,width:me,height:se,rotation:0,draggable:true})),i(Pa(false));},Ar=()=>{i(ue()),i(Ot("select")),i(dt(false));let B=400,ne=300,Ie=(window.innerWidth-B)/2,me=(window.innerHeight-ne)/2;i(kn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ie,y:me,width:B,height:ne,rotation:0,draggable:true,isCapturing:false})),q(false);},Pr=B=>{let me=(window.innerWidth-100)/2,se=(window.innerHeight-100)/2,ie={};switch(B.name){case "circle":case "ring":case "wedge":case "arc":ie.radius=50,(B.name==="ring"||B.name==="arc")&&(ie.innerRadius=25,ie.outerRadius=50),(B.name==="wedge"||B.name==="arc")&&(ie.angle=B.name==="wedge"?60:90);break;case "ellipse":ie.radiusX=60,ie.radiusY=40;break;case "triangle":ie.radius=50,ie.sides=3;break;case "polygon":ie.radius=50,ie.sides=6;break;case "star":ie.innerRadius=25,ie.outerRadius=50,ie.numPoints=5;break;case "arrow":case "line":ie.points=[0,0,100,0],B.name==="arrow"&&(ie.pointerLength=10,ie.pointerWidth=10);break}let Ve={id:`shape-${Date.now()}`,type:B.name,x:me,y:se,width:100,height:100,rotation:0,color:m,...ie};i(ue()),i(dt(false)),i(Ot(B.name)),i(bn(Ve));},Ia=B=>{if(i(Ot(B)),B==="select")i(dt(false));else if(B==="text"){i(dt(false)),i(ue());let ne=200,Ie=50,me=(window.innerWidth-ne)/2,se=(window.innerHeight-Ie)/2,ie=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;i(yn({id:ie,text:"",x:me,y:se,width:ne,height:Ie,rotation:0,draggable:true,fontSize:b,fontFamily:y,fontStyle:S,fontWeight:I,textDecoration:C,fill:L,align:"left"})),setTimeout(()=>{i(Ho(ie));},100),r&&r(ie);}else i(dt(true));},Dr=()=>{i(Xn()),i(Ot("select")),i(dt(false));},Js=()=>{t?t():a?A(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Zs=()=>{F(true);},Rr=async(B,ne)=>{try{i(Ot("select")),i(dt(!1));let Ie=URL.createObjectURL(B),me=document.createElement("video");me.src=Ie,me.muted=!0,me.playsInline=!0,me.preload="auto",await new Promise((ka,Ma)=>{let $a=setTimeout(()=>Ma(new Error("Metadata load timeout")),1e4);me.onloadedmetadata=()=>{clearTimeout($a),ka();},me.onerror=()=>{clearTimeout($a),Ma(new Error("Failed to load video"));};});let se=640,ie=me.videoWidth/me.videoHeight,Ve=se,qt=Ve/ie,_t=window.innerWidth,_e=window.innerHeight;i(ue());let Ce=(_t-Ve)/2,Je=(_e-qt)/2,jt=v4();await Ha(jt,B,ne),i(zr({id:jt,objectUrl:Ie,thumbnailDataUrl:ne,videoBlob:B,x:Ce,y:Je,width:Ve,height:qt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),A(!1),F(!1);}catch(Ie){console.error("Error adding recorded video to canvas:",Ie),alert("Failed to add video to canvas. Please try again.");}},Qs=B=>{i(Ot("select")),i(dt(false)),i(qo(null)),B&&i(zn(B)),i(sa(!f));},en=()=>{i(Bo(null)),i(Pa(true)),q(false);},Ca=()=>{R(!E);},tn=()=>{N(!H);},an=()=>{q(!te);};return g?null:jsx("div",{className:"konva-editor-root",children:jsxs("div",{className:"fixed top-1/2 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(La,{type:"single",className:"flex flex-col gap-1 border bg-white p-1 shadow-xl",children:Z.map((B,ne)=>jsx("div",{title:B.label,className:`hover:bg-primary/10 mb-1 cursor-pointer rounded-md px-4 py-3 ${B.name===d?"bg-primary/10":""}`,onClick:()=>{if(B.name==="image"){tn(),R(false),q(false),Ia(B.name);return}else if(B.name==="shapes"){Ca(),N(false),q(false),Ia(B.name);return}else if(B.name==="activities"){Ia(B.name),an(),R(false),N(false);return}Ia(B.name),R(false),N(false),q(false);},children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},ne))}),E&&jsx(La,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:pe.map((B,ne)=>jsx("div",{title:B.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",onClick:()=>Pr(B),children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},ne))}),H&&jsxs(La,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Me.photoFrame&&jsx("div",{title:"Photo frame",onClick:Ar,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),Me.image&&jsx("div",{onClick:()=>z.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(Image$2,{weight:"fill",size:24,className:"text-primary"})}),Me.video&&jsx("div",{onClick:()=>X.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(MonitorPlay,{weight:"fill",size:24,className:"text-primary"})})]}),te&&jsxs(La,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Ue&&jsx("div",{title:"Flashcard",onClick:()=>en(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(Cards,{weight:"fill",size:24,className:"text-primary"})}),De.map((B,ne)=>jsx("div",{title:B.label,onClick:()=>Qs(B.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},ne))]})]}),jsx("input",{ref:z,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:re}),jsx("input",{ref:X,type:"file",accept:"video/*",className:"hidden",onChange:Mr}),!t&&P&&a&&jsx(Jo,{onClose:()=>A(false),stageRef:a,onRecordingComplete:Rr}),U&&jsx(Dc,{onClose:()=>F(false),onRecordingComplete:Rr}),h&&jsx(Fc,{editingFlashcard:c,onConfirm:Tr,onCancel:()=>i(Pa(false))}),(v.undo||v.redo||v.screenRecord||v.cameraRecord||v.clear)&&jsxs(La,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[v.undo&&jsx("button",{value:"undo",onClick:()=>i(Yn()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{size:24,weight:"bold"})}),v.redo&&jsx("button",{value:"redo",onClick:()=>i(Jn()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{size:24,weight:"bold"})}),v.screenRecord&&jsx("button",{value:"screen-record",onClick:Js,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#2260DD]",title:"Screen Record",children:jsx(Record,{size:24,weight:"bold"})}),v.cameraRecord&&jsx("button",{value:"camera-record",onClick:Zs,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#804FF2]",title:"Camera Record",children:jsx(Camera,{size:24,weight:"fill"})}),v.clear&&jsx("button",{value:"clear",onClick:()=>Dr(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{size:24,weight:"bold"})})]})]})})},ly=iy;var fl=({onPublish:e,label:o="Publish Slides",className:t})=>{let a=aa(Wo),n=(aa(h=>h.canvas.slides.find(x=>x.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),[i,u]=useState(false),[l,c]=useState(null),[d,m]=useState(null),f=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}u(true),m(null);try{let h=await e(a,x=>{c(x);});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{u(false),setTimeout(()=>{c(null),m(null);},3e3);}};return n?null:jsxs("button",{onClick:f,disabled:i||a.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-3 px-4 py-3 font-medium text-white transition-colors",children:[jsx(Export,{size:24,color:"#fff"})," Publish"]})};var py=({title:e="Untitled",autoSaveMessage:o="Auto-saved just now",onBack:t,onPublish:a,showPublishButton:r=true,showBackButton:s=true,className:n="",rightContent:i,leftContent:u})=>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-6 shadow-sm ${n}`,children:[u||jsxs("div",{className:"flex items-center gap-6 px-2",children:[s&&jsx("button",{onClick:t,className:"h-10 w-10 rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A]",children:jsx(CaretLeft,{size:24,color:"#64758B",weight:"bold"})}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{className:"text-2xl font-medium text-[#000000CC]",children:e}),jsxs("div",{className:"flex items-center gap-2",children:[jsx(CloudArrowUp,{weight:"fill",color:"#63748A",size:20}),jsx("span",{className:"text-base font-medium text-[#63748A]",children:o})]})]})]}),i||r&&a&&jsx(fl,{onPublish:a})]});function ml(e,[o,t]){return Math.min(t,Math.max(o,e))}function Oc(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 Vc(e){let[o,t]=be.useState(void 0);return wo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let s=r[0],n,i;if("borderBoxSize"in s){let u=s.borderBoxSize,l=Array.isArray(u)?u[0]:u;n=l.inlineSize,i=l.blockSize;}else n=e.offsetWidth,i=e.offsetHeight;t({width:n,height:i});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var qc=["PageUp","PageDown"],Uc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Hc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Po="Slider",[pl,gy,xy]=Os(Po),[zc]=ba(Po,[xy]),[by,js]=zc(Po),Wc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:s=1,orientation:n="horizontal",disabled:i=false,minStepsBetweenThumbs:u=0,defaultValue:l=[a],value:c,onValueChange:d=()=>{},onValueCommit:m=()=>{},inverted:f=false,form:h,...x}=e,p=be.useRef(new Set),v=be.useRef(0),b=n==="horizontal"?vy:yy,[y=[],S]=Yt({prop:c,defaultProp:l,onChange:U=>{[...p.current][v.current]?.focus(),d(U);}}),I=be.useRef(y);function C(U){let F=Cy(y,U);A(U,F);}function L(U){A(U,v.current);}function P(){let U=I.current[v.current];y[v.current]!==U&&m(y);}function A(U,F,{commit:E}={commit:false}){let R=Ay(s),H=Py(Math.round((U-a)/s)*s+a,R),N=ml(H,[a,r]);S((te=[])=>{let q=Sy(te,N,F);if(Ty(q,u*s)){v.current=q.indexOf(N);let G=String(q)!==String(te);return G&&E&&m(q),G?q:te}else return te});}return jsx(by,{scope:e.__scopeSlider,name:t,disabled:i,min:a,max:r,valueIndexToChangeRef:v,thumbs:p.current,values:y,orientation:n,form:h,children:jsx(pl.Provider,{scope:e.__scopeSlider,children:jsx(pl.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":i,"data-disabled":i?"":void 0,...x,ref:o,onPointerDown:Xe(x.onPointerDown,()=>{i||(I.current=y);}),min:a,max:r,inverted:f,onSlideStart:i?void 0:C,onSlideMove:i?void 0:L,onSlideEnd:i?void 0:P,onHomeKeyDown:()=>!i&&A(a,0,{commit:true}),onEndKeyDown:()=>!i&&A(r,y.length-1,{commit:true}),onStepKeyDown:({event:U,direction:F})=>{if(!i){let H=qc.includes(U.key)||U.shiftKey&&Uc.includes(U.key)?10:1,N=v.current,te=y[N],q=s*H*F;A(te+q,N,{commit:true});}}})})})})});Wc.displayName=Po;var[Gc,Kc]=zc(Po,{startEdge:"left",endEdge:"right",size:"width",direction:1}),vy=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:s,onSlideStart:n,onSlideMove:i,onSlideEnd:u,onStepKeyDown:l,...c}=e,[d,m]=be.useState(null),f=At(o,b=>m(b)),h=be.useRef(void 0),x=So(r),p=x==="ltr",v=p&&!s||!p&&s;function g(b){let y=h.current||d.getBoundingClientRect(),S=[0,y.width],C=xl(S,v?[t,a]:[a,t]);return h.current=y,C(b-y.left)}return jsx(Gc,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:jsx(_c,{dir:x,"data-orientation":"horizontal",...c,ref:f,style:{...c.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let y=g(b.clientX);n?.(y);},onSlideMove:b=>{let y=g(b.clientX);i?.(y);},onSlideEnd:()=>{h.current=void 0,u?.();},onStepKeyDown:b=>{let S=Hc[v?"from-left":"from-right"].includes(b.key);l?.({event:b,direction:S?-1:1});}})})}),yy=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:s,onSlideMove:n,onSlideEnd:i,onStepKeyDown:u,...l}=e,c=be.useRef(null),d=At(o,c),m=be.useRef(void 0),f=!r;function h(x){let p=m.current||c.current.getBoundingClientRect(),v=[0,p.height],b=xl(v,f?[a,t]:[t,a]);return m.current=p,b(x-p.top)}return jsx(Gc,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(_c,{"data-orientation":"vertical",...l,ref:d,style:{...l.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:x=>{let p=h(x.clientY);s?.(p);},onSlideMove:x=>{let p=h(x.clientY);n?.(p);},onSlideEnd:()=>{m.current=void 0,i?.();},onStepKeyDown:x=>{let v=Hc[f?"from-bottom":"from-top"].includes(x.key);u?.({event:x,direction:v?-1:1});}})})}),_c=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:s,onHomeKeyDown:n,onEndKeyDown:i,onStepKeyDown:u,...l}=e,c=js(Po,t);return jsx(it.span,{...l,ref:o,onKeyDown:Xe(e.onKeyDown,d=>{d.key==="Home"?(n(d),d.preventDefault()):d.key==="End"?(i(d),d.preventDefault()):qc.concat(Uc).includes(d.key)&&(u(d),d.preventDefault());}),onPointerDown:Xe(e.onPointerDown,d=>{let m=d.target;m.setPointerCapture(d.pointerId),d.preventDefault(),c.thumbs.has(m)?m.focus():a(d);}),onPointerMove:Xe(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d);}),onPointerUp:Xe(e.onPointerUp,d=>{let m=d.target;m.hasPointerCapture(d.pointerId)&&(m.releasePointerCapture(d.pointerId),s(d));})})}),jc="SliderTrack",$c=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=js(jc,t);return jsx(it.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});$c.displayName=jc;var hl="SliderRange",Xc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=js(hl,t),s=Kc(hl,t),n=be.useRef(null),i=At(o,n),u=r.values.length,l=r.values.map(m=>Zc(m,r.min,r.max)),c=u>1?Math.min(...l):0,d=100-Math.max(...l);return jsx(it.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:i,style:{...e.style,[s.startEdge]:c+"%",[s.endEdge]:d+"%"}})});Xc.displayName=hl;var gl="SliderThumb",Yc=be.forwardRef((e,o)=>{let t=gy(e.__scopeSlider),[a,r]=be.useState(null),s=At(o,i=>r(i)),n=be.useMemo(()=>a?t().findIndex(i=>i.ref.current===a):-1,[t,a]);return jsx(wy,{...e,ref:s,index:n})}),wy=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...s}=e,n=js(gl,t),i=Kc(gl,t),[u,l]=be.useState(null),c=At(o,g=>l(g)),d=u?n.form||!!u.closest("form"):true,m=Vc(u),f=n.values[a],h=f===void 0?0:Zc(f,n.min,n.max),x=Iy(a,n.values.length),p=m?.[i.size],v=p?ky(p,h,i.direction):0;return be.useEffect(()=>{if(u)return n.thumbs.add(u),()=>{n.thumbs.delete(u);}},[u,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[i.startEdge]:`calc(${h}% + ${v}px)`},children:[jsx(pl.ItemSlot,{scope:e.__scopeSlider,children:jsx(it.span,{role:"slider","aria-label":e["aria-label"]||x,"aria-valuemin":n.min,"aria-valuenow":f,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...s,ref:c,style:f===void 0?{display:"none"}:e.style,onFocus:Xe(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),d&&jsx(Jc,{name:r??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:f},a)]})});Yc.displayName=gl;var Ly="RadioBubbleInput",Jc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),s=At(r,a),n=Oc(o);return be.useEffect(()=>{let i=r.current;if(!i)return;let u=window.HTMLInputElement.prototype,c=Object.getOwnPropertyDescriptor(u,"value").set;if(n!==o&&c){let d=new Event("input",{bubbles:true});c.call(i,o),i.dispatchEvent(d);}},[n,o]),jsx(it.input,{style:{display:"none"},...t,ref:s,defaultValue:o})});Jc.displayName=Ly;function Sy(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,s)=>r-s)}function Zc(e,o,t){let s=100/(t-o)*(e-o);return ml(s,[0,100])}function Iy(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Cy(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 ky(e,o,t){let a=e/2,s=xl([0,50],[0,a]);return (a-s(o)*t)*t}function My(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Ty(e,o){if(o>0){let t=My(e);return Math.min(...t)>=o}return true}function xl(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 Ay(e){return (String(e).split(".")[1]||"").length}function Py(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Qc=Wc,ef=$c,tf=Xc,af=Yc;function rf({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:s,trackClassName:n,thumbClassName:i,...u}){let l=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(Qc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:wa("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),...u,children:[jsx(ef,{"data-slot":"slider-track",className:wa("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(tf,{"data-slot":"slider-range",className:wa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",s)})}),Array.from({length:l.length},(c,d)=>jsx(af,{"data-slot":"slider-thumb",className:wa("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",i)},d))]})}var Fy=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Ey=({colors:e=Fy,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let s=ee(i=>i.toolbar.penColor),n=xe();return jsxs("div",{className:`fixed bottom-6 left-1/2 z-50 flex h-fit w-full max-w-3xl -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-6 shadow-2xl xl:max-w-4xl ${r}`,style:{marginLeft:"-160px"},children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex w-full flex-col px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex w-full items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(rf,{defaultValue:[12],max:28,min:6,step:1,className:"w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:i=>n(sl(i[0]))}),jsx("div",{className:"h-8 w-8 rounded-full bg-black"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(La,{type:"single",className:"flex w-full px-6",children:[e.map(i=>jsx("button",{value:i.value,className:`h-12 w-12 rounded-full border hover:cursor-pointer ${s===i.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:i.value},onClick:()=>n(Ws(i.value))},i.value)),jsxs("label",{className:"relative flex h-12 w-12 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033]",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>n(Ws(i.target.value))}),"+"]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center",children:jsx("label",{className:"relative flex h-12 w-12 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033]",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>n(mn(i.target.value))})})})]})};function By({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var nf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ny=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),vl=e=>{let o=Ny(e);return o.charAt(0).toUpperCase()+o.slice(1)},$s=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),lf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var df={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 cf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:s,iconNode:n,...i},u)=>createElement("svg",{ref:u,...df,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:$s("lucide",r),...!s&&!lf(i)&&{"aria-hidden":"true"},...i},[...n.map(([l,c])=>createElement(l,c)),...Array.isArray(s)?s:[s]]));var Xs=(e,o)=>{let t=forwardRef(({className:a,...r},s)=>createElement(cf,{ref:s,iconNode:o,className:$s(`lucide-${nf(vl(e))}`,`lucide-${e}`,a),...r}));return t.displayName=vl(e),t};var Hy=[["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"}]],Cr=Xs("copy",Hy);var zy=[["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"}]],kr=Xs("trash-2",zy);var mf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:s,onDelete:n})=>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:i=>{i.stopPropagation(),s();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Cr,{size:14})}),!a&&jsx("button",{onClick:i=>{i.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(kr,{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:`Slide ${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 _y=()=>{let e=yt(),o=aa(Wo),t=aa(zo),a=aa(Zn),[r,s]=useState(true),u=(aa(f=>f.canvas.slides.find(h=>h.id===f.canvas.currentSlideId))?.videos||[]).some(f=>f.isRecorded&&f.isPlaying),l=()=>{a&&e(ln());},c=f=>{e(cn(f));},d=f=>{e(un(f));},m=f=>{o.length>1&&e(dn(f));};return u?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:()=>s(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Slides"})]}),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((f,h)=>jsx(mf,{slide:f,index:h,isSelected:f.id===t,isSingleSlide:o.length===1,onSelect:()=>c(f.id),onDuplicate:()=>d(f.id),onDelete:()=>m(f.id)},f.id))}),jsxs("button",{onClick:l,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 Slide"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>s(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var jy="SchooplaEditorDB",$y=1,Sa="slides",yl="schoopla_current_slide_id",wl=()=>new Promise((e,o)=>{let t=indexedDB.open(jy,$y);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Sa)||r.createObjectStore(Sa,{keyPath:"id"});};}),Ll=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await wl(),a=o.transaction([Sa],"readwrite").objectStore(Sa);await new Promise((r,s)=>{let n=a.clear();n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);});for(let r of e)await new Promise((s,n)=>{let i=a.add(r);i.onsuccess=()=>s(!0),i.onerror=()=>n(i.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);}}},Sl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await wl(),t=e.transaction([Sa],"readonly").objectStore(Sa);return new Promise((a,r)=>{let s=t.getAll();s.onsuccess=()=>{e.close();let n=s.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(i=>({id:i.id,width:i.width,height:i.height,x:i.x,y:i.y}))),a(n.length>0?n:null);},s.onerror=()=>{e.close(),r(s.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}}},Ys=async()=>{try{let e=await wl(),t=e.transaction([Sa],"readwrite").objectStore(Sa);await new Promise((a,r)=>{let s=t.clear();s.onsuccess=()=>a(!0),s.onerror=()=>r(s.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(yl),await Eu();}catch(e){console.error("Error clearing local data:",e);}},Il=e=>{try{localStorage.setItem(yl,e);}catch(o){console.error("Error saving current slide ID:",o);}},Cl=()=>{try{return localStorage.getItem(yl)}catch(e){return console.error("Error loading current slide ID:",e),null}},gf=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}};var Xy=["canvas/loadSlides","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/setCurrentSlide","canvas/updateSlideThumbnail","canvas/reorderSlides"],Yy=["canvas/clearCanvas"],Jy=gf((e,o)=>{Ll(e),Il(o);},500),Zy=(e,o)=>{Ll(e),Il(o);},kl=false,xf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;_i(r).catch(s=>{console.error("Error deleting video blob:",s);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,n=e.getState().canvas.slides.find(i=>i.id===r);n&&n.videos&&n.videos.length>0&&n.videos.forEach(i=>{_i(i.id).catch(u=>{console.error("Error deleting video blob:",u);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,s=e.getState(),i=s.canvas.slides.find(u=>u.id===s.canvas.currentSlideId)?.videos.find(u=>u.id===r);i&&i.videoBlob&&setTimeout(()=>{let u=e.getState(),c=u.canvas.slides.find(d=>d.id===u.canvas.currentSlideId)?.videos.find(d=>d.id!==r&&d.x===i.x+20&&d.y===i.y+20);c&&i.videoBlob&&Ha(c.id,i.videoBlob,c.thumbnailDataUrl).catch(d=>{console.error("Error saving duplicated video blob:",d);});},0);}let a=o(t);if(t.type&&Yy.includes(t.type)){if(!kl){kl=true;try{let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;Zy(s,n);}finally{setTimeout(()=>{kl=false;},0);}}}else if(t.type&&Xy.includes(t.type)){let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;Jy(s,n);}return a});new QueryClient;var tw=configureStore({reducer:{toolbar:Pc,canvas:Hl},middleware:e=>e({serializableCheck:false}).concat(xf)});var aw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:s=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:n,quality:a,pixelRatio:r}),u=document.createElement("a");u.download=`${s}.${t}`,u.href=i,document.body.appendChild(u),u.click(),document.body.removeChild(u);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},ow=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((s,n)=>{try{let i=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:i,quality:a,pixelRatio:r});fetch(u).then(l=>l.blob()).then(l=>s(l)).catch(l=>n(l));}catch(i){n(i);}})},rw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,s=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:s,quality:a,pixelRatio:r})};var sw=(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 s=a*a+r*r,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/s)),i=o.x+n*a,u=o.y+n*r;return Math.sqrt(Math.pow(e.x-i,2)+Math.pow(e.y-u,2))},Ml=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],s=e[e.length-1];for(let n=1;n<e.length-1;n++){let i=sw(e[n],r,s);i>t&&(t=i,a=n);}if(t>o){let n=Ml(e.slice(0,a+1),o),i=Ml(e.slice(a),o);return [...n.slice(0,-1),...i]}return [r,s]},nw=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},iw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},bf=(e,o=1.5)=>{if(e.length<=4)return e;let t=nw(e),a=Ml(t,o);return iw(a)},vf=(e,o=1.5)=>({...e,points:bf(e.points,o)}),lw=(e,o=1.5)=>e.map(t=>vf(t,o)),dw=(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 uw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var yf=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((s,n)=>{let i=new Image;i.onload=()=>{let{width:u,height:l}=i;if(u>t||l>a){let h=u/l;u>l?(u=Math.min(u,t),l=u/h):(l=Math.min(l,a),u=l*h);}let c=document.createElement("canvas");c.width=u,c.height=l;let d=c.getContext("2d");if(!d){n(new Error("Failed to get canvas context"));return}d.drawImage(i,0,0,u,l);let m=uw(e),f=c.toDataURL(m,r);s(f);},i.onerror=n,i.src=e;})};var ja=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},Do=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Ro=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",cw=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:s=.85}=o,n=[],i=0;for(let u of e){let l=[],c=[],d=[];for(let m of u.images){let f=m.src;if(t&&f.startsWith("data:"))try{f=await yf(f,{maxWidth:a,maxHeight:r,quality:s});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=ja(f),x=Do(f);i+=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:x};if(m.audioData&&m.audioData.startsWith("data:")){let v=ja(m.audioData),g=Do(m.audioData);i+=v.byteLength,p.audioBuffer=v,p.audioMimeType=g;}l.push(p);}}for(let m of u.videos){let f,h;if(m.videoBlob)f=await m.videoBlob.arrayBuffer(),h=m.videoBlob.type;else if(m.videoData&&m.videoData.startsWith("data:"))f=ja(m.videoData),h=Do(m.videoData);else {console.warn(`Video ${m.id} has no blob or videoData, skipping`);continue}i+=f.byteLength;let x={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:f,mimeType:h};if(m.audioData&&m.audioData.startsWith("data:")){let p=ja(m.audioData),v=Do(m.audioData);i+=p.byteLength,x.audioBuffer=p,x.audioMimeType=v;}c.push(x);}for(let m of u.photoFrames){let f={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=ja(m.capturedImageUrl),x=Do(m.capturedImageUrl);i+=h.byteLength,f.buffer=h,f.mimeType=x;}if(m.audioData&&m.audioData.startsWith("data:")){let h=ja(m.audioData),x=Do(m.audioData);i+=h.byteLength,f.audioBuffer=h,f.audioMimeType=x;}d.push(f);}n.push({...u,images:l,videos:c,photoFrames:d});}return {slides:n,totalSize:i}},fw=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},mw=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((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,draggable:s.draggable,rotation:s.rotation,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,mimeType:s.mimeType,fileKey:`slide_${r}_image_${n}`,audioFileKey:s.audioBuffer?`slide_${r}_image_${n}_audio`:void 0,audioMimeType:s.audioMimeType})),videos:a.videos.map((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,draggable:s.draggable,isPlaying:s.isPlaying,rotation:s.rotation,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,isRecorded:s.isRecorded,mimeType:s.mimeType,fileKey:`slide_${r}_video_${n}`,thumbnailFileKey:`slide_${r}_video_${n}_thumbnail`,audioFileKey:s.audioBuffer?`slide_${r}_video_${n}_audio`:void 0,audioMimeType:s.audioMimeType})),photoFrames:a.photoFrames.map((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,rotation:s.rotation,draggable:s.draggable,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,isCapturing:s.isCapturing,mimeType:s.mimeType,fileKey:s.buffer?`slide_${r}_photoframe_${n}`:void 0,audioFileKey:s.audioBuffer?`slide_${r}_photoframe_${n}_audio`:void 0,audioMimeType:s.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((s,n)=>{let i=new Blob([s.buffer],{type:s.mimeType}),u=`${s.id}.${Ro(s.mimeType)}`;if(o.append(`slide_${r}_image_${n}`,i,u),s.audioBuffer&&s.audioMimeType){let l=new Blob([s.audioBuffer],{type:s.audioMimeType}),c=`${s.id}_audio.${Ro(s.audioMimeType)}`;o.append(`slide_${r}_image_${n}_audio`,l,c);}}),a.videos.forEach((s,n)=>{let i=new Blob([s.buffer],{type:s.mimeType}),u=`${s.id}.${Ro(s.mimeType)}`;if(o.append(`slide_${r}_video_${n}`,i,u),s.thumbnailDataUrl&&s.thumbnailDataUrl.startsWith("data:")){let l=ja(s.thumbnailDataUrl),c=new Blob([l],{type:"image/jpeg"}),d=`${s.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${n}_thumbnail`,c,d);}if(s.audioBuffer&&s.audioMimeType){let l=new Blob([s.audioBuffer],{type:s.audioMimeType}),c=`${s.id}_audio.${Ro(s.audioMimeType)}`;o.append(`slide_${r}_video_${n}_audio`,l,c);}}),a.photoFrames.forEach((s,n)=>{if(s.buffer&&s.mimeType){let i=new Blob([s.buffer],{type:s.mimeType}),u=`${s.id}.${Ro(s.mimeType)}`;o.append(`slide_${r}_photoframe_${n}`,i,u);}if(s.audioBuffer&&s.audioMimeType){let i=new Blob([s.audioBuffer],{type:s.audioMimeType}),u=`${s.id}_audio.${Ro(s.audioMimeType)}`;o.append(`slide_${r}_photoframe_${n}_audio`,i,u);}});}),o};var hw=()=>{let e=yt();useEffect(()=>{(async()=>{try{let t=await Sl(),a=Cl();if(t&&t.length>0){let r=await Fu(),s=t.map(i=>{if(i.videos&&i.videos.length>0){let u=i.videos.map(l=>{let c=r.get(l.id);if(c){let d=Bu(c.blob);return {...l,objectUrl:d,thumbnailDataUrl:c.thumbnailDataUrl,videoBlob:c.blob}}else return l});return {...i,videos:u}}return i}),n=a&&s.find(i=>i.id===a)?a:s[0].id;e(Xa({slides:s,currentSlideId:n}));}}catch(t){console.error("Error loading persisted slides:",t);}})();},[e]);};var Lf=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||""})),Sf=new WeakSet,If=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 Ha(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},gw=()=>{let e=yt(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Sf.has(a))return;Sf.add(a);let{slides:r,currentSlideId:s,skipLocalPersistence:n=true}=a;if(n)try{await Ys(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(l){console.error("Error clearing local data:",l);}let i=s&&r.find(l=>l.id===s)?s:r[0].id,u=Lf(r);e(Xa({slides:u,currentSlideId:i})),await If(u);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:s,skipLocalPersistence:n=true}=a;if(n)try{await Ys(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(l){console.error("Error clearing local data:",l);}let i=s&&r.find(l=>l.id===s)?s:r[0].id,u=Lf(r);e(Xa({slides:u,currentSlideId:i})),await If(u);},[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:d?"none":"auto"}})}),jsx(Group,{y:S+I+U+C+L+A,children:d&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),v();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),v();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Ki.displayName="LongAnswer";var Au=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>jsx(Fragment,{children:e.map(n=>jsx(Ki,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>s(i,n.id)},n.id))});var qx=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r,className:s,style:n}={})=>{let i=yt(),u=ee(w=>w.toolbar.selectedTool),l=ee(ge),c=ee(zo),d=l?.editingActivity,m=l?.showMcqForm,f=l?.lines||[],h=useRef(null),x=useRef(null),[p,v]=useState(null),[g,b]=useState(""),[y,S]=useState({width:1280,height:1200}),[I,C]=useState("bottom"),L=useRef(null),[P,A]=useState(null),[U,F]=useState(null),[E,R]=useState(null),[H,N]=useState(null),[te,q]=useState(null),[G,oe]=useState(null),[D,z]=useState(null),[X,_]=useState(false),[Y,Z]=useState(null),[Q,pe]=useState(false),we=useRef(null),De=useRef(null),Me=useRef(null),{debouncedGenerateThumbnail:Ue}=gd(c,h);useEffect(()=>{let w=()=>{if(x.current){let T=x.current.getBoundingClientRect();S({width:T.width,height:T.height});}};w();let M=new ResizeObserver(w);return x.current&&M.observe(x.current),window.addEventListener("resize",w),()=>{M.disconnect(),window.removeEventListener("resize",w);}},[]),useEffect(()=>{if(h.current){let w=h.current.container();w&&(w.style.cursor="");}},[u]);let re=useCallback(()=>{h.current&&requestAnimationFrame(()=>{if(!h.current)return;h.current.getLayers().forEach(O=>O.batchDraw());let M=1/6,T=h.current.toDataURL({pixelRatio:M});b(T),Ue();});},[Ue]),Mr=useRef(c);useEffect(()=>{Mr.current!==c&&(Mr.current=c,re());},[c,re]);let Tr=useRef(null),Ar=useRef(true);useEffect(()=>{if(!l)return;let w=(l.lines?.length||0)+(l.images?.length||0)+(l.videos?.length||0)+(l.shapes?.length||0)+(l.texts?.length||0)+(l.flashcards?.length||0)+(l.photoFrames?.length||0)+(l.multipleChoices?.length||0)+(l.trueFalses?.length||0)+(l.shortAnswers?.length||0)+(l.LongAnswer?.length||0)+(l.fillInTheBlanks?.length||0),M=Tr.current?.count!==w;!Ar.current&&M&&setTimeout(()=>{re();},100),Tr.current={slideId:c,count:w},Ar.current=false;},[l,c,re]),useEffect(()=>{h.current&&e&&e(h);},[e]),useEffect(()=>{Me.current&&a&&a(Me);},[a]);let{startDrawing:Pr,draw:Ia,stopDrawing:Dr,setCanvasRef:Js,tool:Zs,color:Rr,strokeWidth:Qs,isSketchMode:en}=Wl(re),Ca=useRef(new Map),{images:tn,getLoadedImage:an,imageRefs:B,handleDragEnd:ne,handleImageTransformEnd:Ie}=Yl(re),{videos:me,videoRefs:se,handleVideoClick:ie,handleVideoDragEnd:Ve,handleVideoTransformEnd:qt}=Ql(re),{multipleChoice:_t,handleMcqTransform:_e,mcqRefs:Ce,handleDragEnd:Je}=Jl(re),{trueFalse:jt,handleTrueFalseTransform:ka,trueFalseRefs:Ma,handleTrueFalseDragEnd:$a}=Zl(re),{shortAnswers:Fr,saRefs:Ze,handleShortAnswerDragEnd:ea}=sd(re),{longAnswers:Ta,handleLongAnswerDragEnd:Cf}=nd(re),{fillInTheBlanks:kf,handleFillInTheBlanksDragEnd:Mf}=Su(re),{transformerRef:de,boundBoxFunc:gt}=fd(),{shapes:Tf,shapeRefs:Er,isDragging:Tl,handleShapeDragEnd:Af,handleShapeResizeEnd:Pf}=ad(re),{texts:Fo,textRefs:ta,handleDragEnd:Df,handleTransformEnd:Rf,handleDoubleClick:Ff,startEditing:Br,editingTextId:he,editingValue:Al,handleEditingChange:Pl,finishEditing:on}=rd(re,we);useEffect(()=>{t&&t(Br);},[t,Br]);let Or=ee(w=>w.canvas.editingTextId);useEffect(()=>{Or&&Or!==he&&Br(Or);},[Or,he,Br]);let{flashcards:Ef,flashcardRefs:Nr,handleDragEnd:Bf,handleFlashcardTransformEnd:Of,handleNext:Nf,handlePrevious:Vf}=ld(re),{photoFrames:Dl,photoFrameRefs:Vr,handleDragEnd:qf,handlePhotoFrameTransformEnd:Uf,startCamera:Hf,capturePhoto:zf,cameraStreams:Wf}=cd(re);useEffect(()=>{if(de.current){if(he){de.current.nodes([]),de.current.getLayer()?.batchDraw();return}if(p&&!me.find(T=>T.id===p)?.isPlaying){let T=Ca.current.get(p)||B.current.get(p)||se.current.get(p)||Er.current.get(p)||ta.current.get(p)||Ce.current.get(p)||Nr.current.get(p)||Vr.current.get(p);if(T){let O=T.attrs?.locked;if(T.visible()&&O!==true){de.current.nodes([T]),de.current.getLayer()?.batchDraw();return}}}de.current.nodes([]),de.current.getLayer()?.batchDraw();}},[p,he,me,Ca,B,se,Er,ta,Nr,Vr,Dl,Ce,de]);let He=useCallback(w=>{v(w),o?.(w);},[o]),qr=useCallback(()=>{v(null),o?.(null),de.current&&(de.current.nodes([]),de.current.getLayer()?.batchDraw());},[de,o]);useEffect(()=>{let w=de.current;return ()=>{w&&w.nodes([]);}},[c]),useEffect(()=>{let w=M=>{he&&M.target.tagName!=="TEXTAREA"&&on();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[he,on]),useEffect(()=>{let w=he||p;if(!w||p&&he){F(null);return}let M=ta.current.get(w),T=h.current;if(!M||!T){F(null);return}let O=T.container().getBoundingClientRect(),Re=M.absolutePosition(),Le=T.scaleX();F({x:O.left+(Re.x+M.width()*Le/2)*Le,y:O.top+Re.y*Le});},[p,he,Fo,ta]),useEffect(()=>{if(!he){R(null);return}let w=ta.current.get(he),M=h.current;if(!w||!M){R(null);return}let T=M.container().getBoundingClientRect(),O=w.absolutePosition(),Re=M.scaleX();R({top:T.top+O.y*Re,left:T.left+O.x*Re,scale:Re});},[he,Fo,ta]);let Rl=useCallback(w=>{let M=w.target.getClassName(),T=w.target===w.target.getStage(),O=M==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",Re=M==="Image",Le=M==="Text",ae=M==="Group"||w.target.getParent()?.getClassName()==="Group",Dt=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&w.target.attrs.id,bt=M==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:M,clickedOnImage:Re,clickedOnGroup:ae,tool:u,targetId:w.target.attrs?.id}),T&&!O&&!Re&&!Le&&!ae&&!Dt&&!bt&&qr(),!(u==="pen"||u==="eraser")&&(Re||Le||O||ae||Dt||bt))return;let je=w.target.getStage()?.getPointerPosition();if(!je)return;["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)||Pr(je);},[u,Pr,qr]),Fl=useCallback(w=>{if(Tl)return;let M=w.target.getStage()?.getPointerPosition();M&&Ia(M);},[Ia,Tl]),El=useCallback(()=>{Dr();},[Dr]),Gf=useCallback(w=>{ne(w,re);},[ne,re]),Kf=useCallback(w=>{ie(w),He(w);},[ie,He]),xt=useCallback((w,M,T)=>{w.preventDefault();let O=w.clientX,Re=w.clientY,Le=L.current?.offsetHeight||450,ae=L.current?.offsetWidth||450,Dt=window.innerHeight,bt=window.innerWidth,tt=O,je=Re;Re+Le>Dt&&(je=Re-Le),O+ae>bt&&(tt=O-ae),A({x:tt,y:je,elementId:M,elementType:T}),He(M);},[He]),Bl=useCallback(w=>{i(qo(w)),i(sa(true));},[i]),_f=useCallback(w=>{i(Bo(w)),i(Pa(true));},[i]),jf=useCallback((w,M)=>{if(!P)return;let{elementId:T,elementType:O}=P;switch(w){case "order":if(M){let k=M.target.getBoundingClientRect();N({x:k.right+5,y:k.top,type:"order"});}break;case "lock":if(M){let k=M.target.getBoundingClientRect();N({x:k.right+5,y:k.top,type:"lock"});}break;case "link":if(A(null),O==="line")break;let Re=l?O==="image"?l.images.find(k=>k.id===T):l.videos.find(k=>k.id===T):null;q({type:"link",defaultValue:Re?.link||""});break;case "voice":if(A(null),O==="line")break;let Le=l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="text"?l.texts.find(k=>k.id===T):O==="flashcard"?l.flashcards.find(k=>k.id===T):O==="photoFrame"?l.photoFrames.find(k=>k.id===T):O==="mcq"?l.multipleChoices.find(k=>k.id===T):O==="fillInTheBlanks"?l.fillInTheBlanks.find(k=>k.id===T):O==="longAnswer"?l.LongAnswer.find(k=>k.id===T):O==="shortAnswer"?l.shortAnswers.find(k=>k.id===T):O==="trueFalse"?l.trueFalses.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):null:null;Z({elementId:T,elementType:O,existingAudio:Le?.audioData});break;case "edit":A(null);let ae=null;O==="mcq"?ae=l?.multipleChoices.find(k=>k.id===T):O==="trueFalse"?ae=l?.trueFalses.find(k=>k.id===T):O==="shortAnswer"?ae=l?.shortAnswers.find(k=>k.id===T):O==="longAnswer"?ae=l?.LongAnswer.find(k=>k.id===T):O==="fillInTheBlanks"&&(ae=l?.fillInTheBlanks.find(k=>k.id===T)),ae&&Bl(ae);break;case "editFlashcard":A(null);let Dt=l?.flashcards.find(k=>k.id===T);Dt&&_f(Dt);break;case "color":A(null);let bt=l?.shapes.find(k=>k.id===T);oe({elementId:T,elementType:"shape",defaultColor:bt?.color||"#096B76"});break;case "crop":if(A(null),O==="image"){let k=l?.images.find(em=>em.id===T);k&&z({elementId:T,imageSrc:k.src});}break;case "draw":A(null),O==="image"?i(Tn(T)):O==="photoFrame"&&i(Pn(T));break;case "duplicate":i(ue()),O==="line"?i($n(T)):O==="image"?i(Hr(T)):O==="video"?i(Gr(T)):O==="shape"?i(Kr(T)):O==="text"?i(_r(T)):O==="flashcard"?i(jr(T)):O==="photoFrame"?i($r(T)):O==="mcq"?i(Xr(T)):O==="trueFalse"?i(Yr(T)):O==="shortAnswer"?i(Jr(T)):O==="fillInTheBlanks"?i(Qr(T)):O==="longAnswer"&&i(Zr(T)),re();break;case "infinite-clone":i(ue());let tt=5;for(let k=0;k<tt;k++)O==="image"?i(Hr(T)):O==="video"?i(Gr(T)):O==="shape"?i(Kr(T)):O==="text"?i(_r(T)):O==="flashcard"?i(jr(T)):O==="photoFrame"?i($r(T)):O==="mcq"?i(Xr(T)):O==="trueFalse"?i(Yr(T)):O==="shortAnswer"?i(Jr(T)):O==="fillInTheBlanks"?i(Qr(T)):O==="longAnswer"&&i(Zr(T));re();break;case "make-response":if(A(null),O==="line")break;let je=`#response-${T}`;i(ue()),i(es({id:T,type:O,link:je})),(l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):O==="flashcard"?l.flashcards.find(k=>k.id===T):O==="photoFrame"?l.photoFrames.find(k=>k.id===T):l.multipleChoices.find(k=>k.id===T):null)?.altText||i(ts({id:T,type:O,altText:"Interactive response area"})),re(),console.log(`Element ${T} marked as interactive response area`);break;case "accessibility":if(A(null),O==="line")break;let V=l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):null:null;q({type:"altText",defaultValue:V?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),A(null),pe(true),console.log("showLayersPanel state set to:",true);break;case "delete":i(ue()),O==="line"?i(jn(T)):O==="image"?i(gn(T)):O==="video"?i(xn(T)):O==="shape"?i(vn(T)):O==="text"?i(wn(T)):O==="flashcard"?i(Sn(T)):O==="photoFrame"?i(Mn(T)):O==="mcq"?i(Fn(T)):O==="trueFalse"?i(Bn(T)):O==="shortAnswer"?i(Nn(T)):O==="longAnswer"?i(qn(T)):O==="fillInTheBlanks"&&i(Hn(T)),qr(),re();break}},[P,i,re,qr,l,Bl]),$f=useCallback(()=>{A(null),N(null);},[]),rn=useCallback(w=>{if(!P)return;let{elementId:M,elementType:T}=P;switch(i(ue()),w){case "bring-to-front":T!=="line"&&i(Wn({id:M,type:T}));break;case "send-to-back":T!=="line"&&i(Gn({id:M,type:T}));break;case "lock":case "unlock":T!=="line"&&i(Kn({id:M,type:T}));break}re(),A(null),N(null);},[P,i,re]),Xf=useCallback(w=>{if(!P||!te)return;let{elementId:M,elementType:T}=P;i(ue()),te.type==="link"&&T!=="line"?i(es({id:M,type:T,link:w})):te.type==="altText"&&T!=="line"&&i(ts({id:M,type:T,altText:w})),re(),q(null);},[P,te,i,re]),Yf=useCallback(w=>{if(!Y)return;let{elementId:M,elementType:T}=Y;i(ue()),i(as({id:M,type:T,audioData:w})),re(),Z(null);},[Y,i,re]),Jf=useCallback(()=>{if(!Y)return;let{elementId:w,elementType:M}=Y;i(ue()),i(as({id:w,type:M,audioData:""})),re();},[Y,i,re]),Zf=useCallback(w=>{if(!G)return;let{elementId:M}=G;i(ue()),i(Ja({id:M,color:w})),re(),oe(null);},[G,i,re]),Qf=useCallback(w=>{if(!D)return;let{elementId:M}=D;i(ue()),i(Ya({id:M,src:w})),re(),z(null);},[D,i,re]);return jsxs("div",{ref:x,className:s||"fixed top-[90px] right-80 bottom-0 left-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default",...n},children:[u==="pen"&&jsx($l,{ref:w=>{if(De.current=w,Js(w),w){let M=w.getCanvasElement();M&&(Me.current=M,a&&a(Me));}},width:y.width,height:y.height,tool:Zs,color:Rr,strokeWidth:Qs,isSketchMode:en}),jsxs(Stage,{ref:h,width:y.width,height:y.height,onMouseDown:Rl,onMouseMove:Fl,onMouseUp:El,onTouchStart:Rl,onTouchMove:Fl,onTouchEnd:El,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:y.width,height:y.height,fill:l?.backgroundColor||"white"})}),jsx(Layer,{children:(()=>{let w=[];return f.forEach((M,T)=>{w.push({type:"line",timestamp:M.timestamp||T,element:{...M,id:M.id??`line-${T}`},index:T});}),Tf.forEach(M=>{w.push({type:"shape",timestamp:M.timestamp||0,element:M});}),tn.forEach(M=>{w.push({type:"image",timestamp:M.timestamp||0,element:M});}),me.forEach(M=>{w.push({type:"video",timestamp:M.timestamp||0,element:M});}),Fo.forEach(M=>{w.push({type:"text",timestamp:M.timestamp||0,element:M});}),Ef.forEach(M=>{w.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Dl.forEach(M=>{w.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),_t.forEach(M=>{w.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),jt.forEach(M=>{w.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),Fr.forEach(M=>{w.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),Ta.forEach(M=>{w.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),kf.forEach(M=>{w.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),w.sort((M,T)=>M.timestamp-T.timestamp),w.map((M,T)=>{let O=`${M.type}-${"id"in M.element&&M.element.id||M.index||T}`,Re="id"in M.element?M.element.id:void 0,Le=Re&&p===Re;switch(M.type){case "line":let ae=M.element,Dt=M.index||0,bt=ae.tool==="eraser",tt=ae.isSketch&&ae.tool==="pen",je=ae.isSketch&&bt,vt=ae.id||`line-${Dt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),u==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:tt||je?void 0:ae.color,strokeWidth:tt||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||je?bt?"black":ae.color:void 0,closed:tt||je,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,onClick:()=>{i(ue()),i(Ur(Dt));},onTap:()=>{i(ue()),i(Ur(Dt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:V=>{let k=V.target.getStage();k&&(k.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:V=>{let k=V.target.getStage();k&&(k.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},O):jsxs(be__default.Fragment,{children:[jsx(Group,{id:vt,ref:V=>{V?Ca.current.set(vt,V):Ca.current.delete(vt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",vt),He(vt));},onTap:()=>{u==="select"&&(console.log("Line tapped:",vt),He(vt));},onDragEnd:V=>{i(ue()),i(os({id:vt,x:V.target.x(),y:V.target.y(),scaleX:V.target.scaleX(),scaleY:V.target.scaleY(),rotation:V.target.rotation()})),re();},onTransformEnd:V=>{i(ue()),i(os({id:vt,x:V.target.x(),y:V.target.y(),scaleX:V.target.scaleX(),scaleY:V.target.scaleY(),rotation:V.target.rotation()})),re();},onMouseEnter:V=>{if(u==="select"){let k=V.target.getStage();k&&(k.container().style.cursor="move");}},onMouseLeave:V=>{if(u==="select"){let k=V.target.getStage();k&&(k.container().style.cursor="default");}},onContextMenu:V=>{let k=V.evt;k.preventDefault(),xt(k,vt,"line");},children:jsx(Line,{points:ae.points||[],stroke:tt||je?void 0:ae.color,strokeWidth:tt||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||je?bt?"black":ae.color:void 0,closed:tt||je,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ca.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!k),k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "shape":return jsxs(be__default.Fragment,{children:[jsx(di,{onSelect:He,shapes:[M.element],shapeRefs:Er,handleShapeDragEnd:Af,handleShapeResizeEnd:Pf,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Er.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "image":return jsxs(be__default.Fragment,{children:[jsx(si,{images:[M.element],getLoadedImage:an,imageRefs:B,onDragEnd:Gf,onTransform:Ie,onSelect:He,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=B.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "video":return jsxs(be__default.Fragment,{children:[jsx(li,{videos:[M.element],selectedId:p,videoRefs:se,onVideoClick:Kf,onDragEnd:Ve,onTransformEnd:qt,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=se.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "text":return jsxs(be__default.Fragment,{children:[jsx(Md,{texts:[M.element],textRefs:ta,onDragEnd:Df,onTransformEnd:Rf,onSelect:He,onContextMenu:xt,onDoubleClick:Ff,editingTextId:he,editingValue:Al,onEditingChange:Pl}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=ta.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(fi,{flashcards:[M.element],flashcardRefs:Nr,selectedId:p,onDragEnd:Bf,onTransform:Of,onSelect:He,onNext:Nf,onPrevious:Vf,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Nr.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(xi,{photoFrames:[M.element],photoFrameRefs:Vr,selectedId:p,onDragEnd:qf,onTransform:Uf,onSelect:He,onStartCamera:Hf,onCapture:zf,cameraStreams:Wf,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Vr.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(tu,{handleMcqTransform:_e,multipleChoice:[M.element],handleSelect:He,mcqRefs:Ce,handleDragEnd:Je,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ce.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(ru,{trueFalses:[M.element],handleTrueFalseTransform:ka,handleSelect:He,trueFalseRefs:Ma,onContextMenu:xt,handleDragEnd:$a}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ma.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(Lu,{shortAnswers:[M.element],handleSelect:He,handleTransform:_e,saRefs:Ze,onContextMenu:xt,handleDragEnd:ea}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(Au,{longAnswer:[M.element],handleSelect:He,handleTransform:_e,saRefs:Ze,onContextMenu:xt,handleDragEnd:Cf}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Mu,{fillInTheBlanks:[M.element],handleSelect:He,handleTransform:_e,onContextMenu:xt,handleDragEnd:Mf}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(p);k&&k.visible()&&(V.nodes([k]),V.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"]})]},O);default:return null}})})()})]}),P&&r?.enabled!==false&&jsx(Ud,{menuRef:L,x:P.x,y:P.y,type:P.elementType,elementId:P.elementId,onAction:jf,onClose:$f,isDrawingMode:P.elementType==="image"?l?.images.find(w=>w.id===P.elementId)?.isDrawingMode:P.elementType==="photoFrame"?l?.photoFrames.find(w=>w.id===P.elementId)?.isDrawingMode:false}),H&&P&&jsx(Hd,{x:H.x,y:H.y,items:H.type==="order"?[{label:"Bring to Front",onClick:()=>rn("bring-to-front")},{label:"Send to Back",onClick:()=>rn("send-to-back")}]:[{label:l&&(P.elementType==="image"?l.images.find(w=>w.id===P.elementId)?.locked:l.videos.find(w=>w.id===P.elementId)?.locked)?"Unlock":"Lock",onClick:()=>rn(l&&(P.elementType==="image"?l.images.find(w=>w.id===P.elementId)?.locked:l.videos.find(w=>w.id===P.elementId)?.locked)?"unlock":"lock")}],onClose:()=>N(null)}),te&&jsx(zd,{title:te.type==="link"?"Add Link":"Add Alt Text",label:te.type==="link"?"URL":"Alternative Text",placeholder:te.type==="link"?"https://example.com":"Describe this image/video",defaultValue:te.defaultValue,onSave:Xf,onClose:()=>q(null)}),G&&jsx(Wd,{defaultColor:G.defaultColor,onConfirm:Zf,onCancel:()=>oe(null)}),D&&jsx(jd,{imageSrc:D.imageSrc,onConfirm:Qf,onCancel:()=>z(null)}),X&&jsx(Jo,{onClose:()=>_(false),stageRef:h}),Y&&jsx(Xd,{elementId:Y.elementId,elementType:Y.elementType,existingAudio:Y.existingAudio,onSave:Yf,onDelete:Jf,onClose:()=>Z(null)}),Q&&jsx(Zd,{selectedElementId:p||void 0,onClose:()=>pe(false),onSelectElement:w=>{He(w),pe(false);}}),l?.images.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.videos.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.shapes?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.texts?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.flashcards?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),m&&jsx(hu,{editElement:d}),U&&(()=>{let w=he||p;if(!w)return null;let M=Fo.find(T=>T.id===w);return M?jsx(gu,{text:M,position:U}):null})(),E&&he&&(()=>{let w=Fo.find(M=>M.id===he);return w?jsx(bu,{text:w,editingValue:Al,onEditingChange:Pl,onFinish:on,position:{top:E.top,left:E.left},scale:E.scale,textareaRef:we},he):null})()]})},Ux=qx;var Hx="SchooplaVideoStorage";var Gt="videos",Bs=()=>new Promise((e,o)=>{let t=indexedDB.open(Hx,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Gt)||r.createObjectStore(Gt,{keyPath:"id"});};}),Ha=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Bs(),s=a.transaction([Gt],"readwrite").objectStore(Gt),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((i,u)=>{let l=s.put(n);l.onsuccess=()=>i(!0),l.onerror=()=>u(l.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 Fu=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Bs(),t=e.transaction([Gt],"readonly").objectStore(Gt);return new Promise((a,r)=>{let s=t.getAll();s.onsuccess=()=>{e.close();let n=s.result,i=new Map;n.forEach(u=>{i.set(u.id,{blob:u.blob,thumbnailDataUrl:u.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${i.size} video blobs from IndexedDB`),a(i);},s.onerror=()=>{e.close(),r(s.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 Bs(),a=o.transaction([Gt],"readwrite").objectStore(Gt);await new Promise((r,s)=>{let n=a.delete(e);n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Eu=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Bs(),t=e.transaction([Gt],"readwrite").objectStore(Gt);await new Promise((a,r)=>{let s=t.clear();s.onsuccess=()=>a(!0),s.onerror=()=>r(s.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Bu=e=>URL.createObjectURL(e);function ba(e,o=[]){let t=[];function a(s,n){let i=be.createContext(n),u=t.length;t=[...t,n];let l=d=>{let{scope:m,children:f,...h}=d,x=m?.[e]?.[u]||i,p=be.useMemo(()=>h,Object.values(h));return jsx(x.Provider,{value:p,children:f})};l.displayName=s+"Provider";function c(d,m){let f=m?.[e]?.[u]||i,h=be.useContext(f);if(h)return h;if(n!==void 0)return n;throw new Error(`\`${d}\` must be used within \`${s}\``)}return [l,c]}let r=()=>{let s=t.map(n=>be.createContext(n));return function(i){let u=i?.[e]||s;return be.useMemo(()=>({[`__scope${e}`]:{...i,[e]:u}}),[i,u])}};return r.scopeName=e,[a,Wx(r,...o)]}function Wx(...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(s){let n=a.reduce((i,{useScope:u,scopeName:l})=>{let d=u(s)[`__scope${l}`];return {...i,...d}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}function Ou(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function vr(...e){return o=>{let t=false,a=e.map(r=>{let s=Ou(r,o);return !t&&typeof s=="function"&&(t=true),s});if(t)return ()=>{for(let r=0;r<a.length;r++){let s=a[r];typeof s=="function"?s():Ou(e[r],null);}}}}function At(...e){return be.useCallback(vr(...e),e)}function qu(e){let o=Gx(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),u=i.find(_x);if(u){let l=u.props.children,c=i.map(d=>d===u?be.Children.count(l)>1?be.Children.only(null):be.isValidElement(l)?l.props.children:null:d);return jsx(o,{...n,ref:r,children:be.isValidElement(l)?be.cloneElement(l,void 0,c):null})}return jsx(o,{...n,ref:r,children:s})});return t.displayName=`${e}.Slot`,t}function Gx(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=$x(r),i=jx(s,r.props);return r.type!==be.Fragment&&(i.ref=a?vr(a,n):n),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Kx=Symbol("radix.slottable");function _x(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Kx}function jx(e,o){let t={...o};for(let a in o){let r=e[a],s=o[a];/^on[A-Z]/.test(a)?r&&s?t[a]=(...i)=>{let u=s(...i);return r(...i),u}:r&&(t[a]=r):a==="style"?t[a]={...r,...s}:a==="className"&&(t[a]=[r,s].filter(Boolean).join(" "));}return {...e,...t}}function $x(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 Jx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],it=Jx.reduce((e,o)=>{let t=qu(`Primitive.${o}`),a=be.forwardRef((r,s)=>{let{asChild:n,...i}=r,u=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(u,{...i,ref:s})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function Xe(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function ji(e){let o=Zx(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),u=i.find(eb);if(u){let l=u.props.children,c=i.map(d=>d===u?be.Children.count(l)>1?be.Children.only(null):be.isValidElement(l)?l.props.children:null:d);return jsx(o,{...n,ref:r,children:be.isValidElement(l)?be.cloneElement(l,void 0,c):null})}return jsx(o,{...n,ref:r,children:s})});return t.displayName=`${e}.Slot`,t}function Zx(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=ab(r),i=tb(s,r.props);return r.type!==be.Fragment&&(i.ref=a?vr(a,n):n),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Qx=Symbol("radix.slottable");function eb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Qx}function tb(e,o){let t={...o};for(let a in o){let r=e[a],s=o[a];/^on[A-Z]/.test(a)?r&&s?t[a]=(...i)=>{let u=s(...i);return r(...i),u}:r&&(t[a]=r):a==="style"?t[a]={...r,...s}:a==="className"&&(t[a]=[r,s].filter(Boolean).join(" "));}return {...e,...t}}function ab(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 Os(e){let o=e+"CollectionProvider",[t,a]=ba(o),[r,s]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=x=>{let{scope:p,children:v}=x,g=be__default.useRef(null),b=be__default.useRef(new Map).current;return jsx(r,{scope:p,itemMap:b,collectionRef:g,children:v})};n.displayName=o;let i=e+"CollectionSlot",u=ji(i),l=be__default.forwardRef((x,p)=>{let{scope:v,children:g}=x,b=s(i,v),y=At(p,b.collectionRef);return jsx(u,{ref:y,children:g})});l.displayName=i;let c=e+"CollectionItemSlot",d="data-radix-collection-item",m=ji(c),f=be__default.forwardRef((x,p)=>{let{scope:v,children:g,...b}=x,y=be__default.useRef(null),S=At(p,y),I=s(c,v);return be__default.useEffect(()=>(I.itemMap.set(y,{ref:y,...b}),()=>void I.itemMap.delete(y))),jsx(m,{[d]:"",ref:S,children:g})});f.displayName=c;function h(x){let p=s(e+"CollectionConsumer",x);return be__default.useCallback(()=>{let g=p.collectionRef.current;if(!g)return [];let b=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(p.itemMap.values()).sort((I,C)=>b.indexOf(I.ref.current)-b.indexOf(C.ref.current))},[p.collectionRef,p.itemMap])}return [{Provider:n,Slot:l,ItemSlot:f},h,a]}var wo=globalThis?.document?be.useLayoutEffect:()=>{};var ob=be[" useId ".trim().toString()]||(()=>{}),rb=0;function Wu(e){let[o,t]=be.useState(ob());return wo(()=>{t(a=>a??String(rb++));},[e]),(o?`radix-${o}`:"")}function Gu(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var sb=be[" useInsertionEffect ".trim().toString()]||wo;function Yt({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,s,n]=nb({defaultProp:o,onChange:t}),i=e!==void 0,u=i?e:r;{let c=be.useRef(e!==void 0);be.useEffect(()=>{let d=c.current;d!==i&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${i?"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.`),c.current=i;},[i,a]);}let l=be.useCallback(c=>{if(i){let d=ib(c)?c(e):c;d!==e&&n.current?.(d);}else s(c);},[i,e,s,n]);return [u,l]}function nb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),s=be.useRef(o);return sb(()=>{s.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(s.current?.(t),r.current=t);},[t,r]),[t,a,s]}function ib(e){return typeof e=="function"}var lb=be.createContext(void 0);function So(e){let o=be.useContext(lb);return e||o||"ltr"}var Yi="rovingFocusGroup.onEntryFocus",db={bubbles:false,cancelable:true},yr="RovingFocusGroup",[Ji,Ku,ub]=Os(yr),[cb,Zi]=ba(yr,[ub]),[fb,mb]=cb(yr),_u=be.forwardRef((e,o)=>jsx(Ji.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Ji.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(pb,{...e,ref:o})})}));_u.displayName=yr;var pb=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:s,currentTabStopId:n,defaultCurrentTabStopId:i,onCurrentTabStopIdChange:u,onEntryFocus:l,preventScrollOnEntryFocus:c=false,...d}=e,m=be.useRef(null),f=At(o,m),h=So(s),[x,p]=Yt({prop:n,defaultProp:i??null,onChange:u,caller:yr}),[v,g]=be.useState(false),b=Gu(l),y=Ku(t),S=be.useRef(false),[I,C]=be.useState(0);return be.useEffect(()=>{let L=m.current;if(L)return L.addEventListener(Yi,b),()=>L.removeEventListener(Yi,b)},[b]),jsx(fb,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:x,onItemFocus:be.useCallback(L=>p(L),[p]),onItemShiftTab:be.useCallback(()=>g(true),[]),onFocusableItemAdd:be.useCallback(()=>C(L=>L+1),[]),onFocusableItemRemove:be.useCallback(()=>C(L=>L-1),[]),children:jsx(it.div,{tabIndex:v||I===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:Xe(e.onMouseDown,()=>{S.current=true;}),onFocus:Xe(e.onFocus,L=>{let P=!S.current;if(L.target===L.currentTarget&&P&&!v){let A=new CustomEvent(Yi,db);if(L.currentTarget.dispatchEvent(A),!A.defaultPrevented){let U=y().filter(N=>N.focusable),F=U.find(N=>N.active),E=U.find(N=>N.id===x),H=[F,E,...U].filter(Boolean).map(N=>N.ref.current);Xu(H,c);}}S.current=false;}),onBlur:Xe(e.onBlur,()=>g(false))})})}),ju="RovingFocusGroupItem",$u=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:s,children:n,...i}=e,u=Wu(),l=s||u,c=mb(ju,t),d=c.currentTabStopId===l,m=Ku(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:x}=c;return be.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(Ji.ItemSlot,{scope:t,id:l,focusable:a,active:r,children:jsx(it.span,{tabIndex:d?0:-1,"data-orientation":c.orientation,...i,ref:o,onMouseDown:Xe(e.onMouseDown,p=>{a?c.onItemFocus(l):p.preventDefault();}),onFocus:Xe(e.onFocus,()=>c.onItemFocus(l)),onKeyDown:Xe(e.onKeyDown,p=>{if(p.key==="Tab"&&p.shiftKey){c.onItemShiftTab();return}if(p.target!==p.currentTarget)return;let v=xb(p,c.orientation,c.dir);if(v!==void 0){if(p.metaKey||p.ctrlKey||p.altKey||p.shiftKey)return;p.preventDefault();let b=m().filter(y=>y.focusable).map(y=>y.ref.current);if(v==="last")b.reverse();else if(v==="prev"||v==="next"){v==="prev"&&b.reverse();let y=b.indexOf(p.currentTarget);b=c.loop?bb(b,y+1):b.slice(y+1);}setTimeout(()=>Xu(b));}}),children:typeof n=="function"?n({isCurrentTabStop:d,hasTabStop:x!=null}):n})})});$u.displayName=ju;var hb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function gb(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function xb(e,o,t){let a=gb(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return hb[a]}function Xu(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function bb(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Yu=_u,Ju=$u;var Qu="Toggle",Qi=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...s}=e,[n,i]=Yt({prop:t,onChange:r,defaultProp:a??false,caller:Qu});return jsx(it.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...s,ref:o,onClick:Xe(e.onClick,()=>{e.disabled||i(!n);})})});Qi.displayName=Qu;var va="ToggleGroup",[tc]=ba(va,[Zi]),ac=Zi(),el=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(wb,{...a,ref:o});if(t==="multiple")return jsx(Lb,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${va}\``)});el.displayName=va;var[oc,rc]=tc(va),wb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Yt({prop:t,defaultProp:a??"",onChange:r,caller:va});return jsx(oc,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:i,onItemDeactivate:be__default.useCallback(()=>i(""),[i]),children:jsx(sc,{...s,ref:o})})}),Lb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Yt({prop:t,defaultProp:a??[],onChange:r,caller:va}),u=be__default.useCallback(c=>i((d=[])=>[...d,c]),[i]),l=be__default.useCallback(c=>i((d=[])=>d.filter(m=>m!==c)),[i]);return jsx(oc,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:u,onItemDeactivate:l,children:jsx(sc,{...s,ref:o})})});el.displayName=va;var[Sb,Ib]=tc(va),sc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:s,dir:n,loop:i=true,...u}=e,l=ac(t),c=So(n),d={role:"group",dir:c,...u};return jsx(Sb,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(Yu,{asChild:true,...l,orientation:s,dir:c,loop:i,children:jsx(it.div,{...d,ref:o})}):jsx(it.div,{...d,ref:o})})}),qs="ToggleGroupItem",Cb=be__default.forwardRef((e,o)=>{let t=rc(qs,e.__scopeToggleGroup),a=Ib(qs,e.__scopeToggleGroup),r=ac(e.__scopeToggleGroup),s=t.value.includes(e.value),n=a.disabled||e.disabled,i={...e,pressed:s,disabled:n},u=be__default.useRef(null);return a.rovingFocus?jsx(Ju,{asChild:true,...r,focusable:!n,active:s,ref:u,children:jsx(ec,{...i,ref:o})}):jsx(ec,{...i,ref:o})});Cb.displayName=qs;var ec=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,s=rc(qs,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=s.type==="single"?n:void 0;return jsx(Qi,{...i,...r,ref:o,onPressedChange:u=>{u?s.onItemActivate(a):s.onItemDeactivate(a);}})}),nc=el;function ic(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=ic(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Us(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=ic(e))&&(a&&(a+=" "),a+=o);return a}var Mb=(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},Tb=(e,o)=>({classGroupId:e,validator:o}),fc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var lc=[],Ab="arbitrary..",Pb=e=>{let o=Rb(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return Db(n);let i=n.split("-"),u=i[0]===""&&i.length>1?1:0;return mc(i,u,o)},getConflictingClassGroupIds:(n,i)=>{if(i){let u=a[n],l=t[n];return u?l?Mb(l,u):u:l||lc}return t[n]||lc}}},mc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],s=t.nextPart.get(r);if(s){let l=mc(e,o+1,s);if(l)return l}let n=t.validators;if(n===null)return;let i=o===0?e.join("-"):e.slice(o).join("-"),u=n.length;for(let l=0;l<u;l++){let c=n[l];if(c.validator(i))return c.classGroupId}},Db=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?Ab+a:void 0})(),Rb=e=>{let{theme:o,classGroups:t}=e;return Fb(t,o)},Fb=(e,o)=>{let t=fc();for(let a in e){let r=e[a];ol(r,t,a,o);}return t},ol=(e,o,t,a)=>{let r=e.length;for(let s=0;s<r;s++){let n=e[s];Eb(n,o,t,a);}},Eb=(e,o,t,a)=>{if(typeof e=="string"){Bb(e,o,t);return}if(typeof e=="function"){Ob(e,o,t,a);return}Nb(e,o,t,a);},Bb=(e,o,t)=>{let a=e===""?o:pc(o,e);a.classGroupId=t;},Ob=(e,o,t,a)=>{if(Vb(e)){ol(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Tb(t,e));},Nb=(e,o,t,a)=>{let r=Object.entries(e),s=r.length;for(let n=0;n<s;n++){let[i,u]=r[n];ol(u,pc(o,i),t,a);}},pc=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let s=0;s<r;s++){let n=a[s],i=t.nextPart.get(n);i||(i=fc(),t.nextPart.set(n,i)),t=i;}return t},Vb=e=>"isThemeGetter"in e&&e.isThemeGetter===true,qb=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(s,n)=>{t[s]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(s){let n=t[s];if(n!==void 0)return n;if((n=a[s])!==void 0)return r(s,n),n},set(s,n){s in t?t[s]=n:r(s,n);}}};var Ub=[],dc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),Hb=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let s=[],n=0,i=0,u=0,l,c=r.length;for(let x=0;x<c;x++){let p=r[x];if(n===0&&i===0){if(p===":"){s.push(r.slice(u,x)),u=x+1;continue}if(p==="/"){l=x;continue}}p==="["?n++:p==="]"?n--:p==="("?i++:p===")"&&i--;}let d=s.length===0?r:r.slice(u),m=d,f=false;d.endsWith("!")?(m=d.slice(0,-1),f=true):d.startsWith("!")&&(m=d.slice(1),f=true);let h=l&&l>u?l-u:void 0;return dc(s,f,m,h)};if(o){let r=o+":",s=a;a=n=>n.startsWith(r)?s(n.slice(r.length)):dc(Ub,false,n,void 0,true);}if(t){let r=a;a=s=>t({className:s,parseClassName:r});}return a},zb=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],i=n[0]==="[",u=o.has(n);i||u?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(n)):r.push(n);}return r.length>0&&(r.sort(),a.push(...r)),a}},Wb=e=>({cache:qb(e.cacheSize),parseClassName:Hb(e),sortModifiers:zb(e),...Pb(e)}),Gb=/\s+/,Kb=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:s}=o,n=[],i=e.trim().split(Gb),u="";for(let l=i.length-1;l>=0;l-=1){let c=i[l],{isExternal:d,modifiers:m,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:x}=t(c);if(d){u=c+(u.length>0?" "+u:u);continue}let p=!!x,v=a(p?h.substring(0,x):h);if(!v){if(!p){u=c+(u.length>0?" "+u:u);continue}if(v=a(h),!v){u=c+(u.length>0?" "+u:u);continue}p=false;}let g=m.length===0?"":m.length===1?m[0]:s(m).join(":"),b=f?g+"!":g,y=b+v;if(n.indexOf(y)>-1)continue;n.push(y);let S=r(v,p);for(let I=0;I<S.length;++I){let C=S[I];n.push(b+C);}u=c+(u.length>0?" "+u:u);}return u},_b=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=hc(t))&&(r&&(r+=" "),r+=a);return r},hc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=hc(e[a]))&&(t&&(t+=" "),t+=o);return t},jb=(e,...o)=>{let t,a,r,s,n=u=>{let l=o.reduce((c,d)=>d(c),e());return t=Wb(l),a=t.cache.get,r=t.cache.set,s=i,i(u)},i=u=>{let l=a(u);if(l)return l;let c=Kb(u,t);return r(u,c),c};return s=n,(...u)=>s(_b(...u))},$b=[],Ne=e=>{let o=t=>t[e]||$b;return o.isThemeGetter=true,o},gc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,xc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Xb=/^\d+\/\d+$/,Yb=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Jb=/\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$/,Zb=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Qb=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ev=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Io=e=>Xb.test(e),le=e=>!!e&&!Number.isNaN(Number(e)),ya=e=>!!e&&Number.isInteger(Number(e)),tl=e=>e.endsWith("%")&&le(e.slice(0,-1)),Jt=e=>Yb.test(e),tv=()=>true,av=e=>Jb.test(e)&&!Zb.test(e),bc=()=>false,ov=e=>Qb.test(e),rv=e=>ev.test(e),sv=e=>!j(e)&&!$(e),nv=e=>Co(e,wc,bc),j=e=>gc.test(e),Ga=e=>Co(e,Lc,av),al=e=>Co(e,cv,le),uc=e=>Co(e,vc,bc),iv=e=>Co(e,yc,rv),Hs=e=>Co(e,Sc,ov),$=e=>xc.test(e),wr=e=>ko(e,Lc),lv=e=>ko(e,fv),cc=e=>ko(e,vc),dv=e=>ko(e,wc),uv=e=>ko(e,yc),zs=e=>ko(e,Sc,true),Co=(e,o,t)=>{let a=gc.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},ko=(e,o,t=false)=>{let a=xc.exec(e);return a?a[1]?o(a[1]):t:false},vc=e=>e==="position"||e==="percentage",yc=e=>e==="image"||e==="url",wc=e=>e==="length"||e==="size"||e==="bg-size",Lc=e=>e==="length",cv=e=>e==="number",fv=e=>e==="family-name",Sc=e=>e==="shadow";var mv=()=>{let e=Ne("color"),o=Ne("font"),t=Ne("text"),a=Ne("font-weight"),r=Ne("tracking"),s=Ne("leading"),n=Ne("breakpoint"),i=Ne("container"),u=Ne("spacing"),l=Ne("radius"),c=Ne("shadow"),d=Ne("inset-shadow"),m=Ne("text-shadow"),f=Ne("drop-shadow"),h=Ne("blur"),x=Ne("perspective"),p=Ne("aspect"),v=Ne("ease"),g=Ne("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],y=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],S=()=>[...y(),$,j],I=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],L=()=>[$,j,u],P=()=>[Io,"full","auto",...L()],A=()=>[ya,"none","subgrid",$,j],U=()=>["auto",{span:["full",ya,$,j]},ya,$,j],F=()=>[ya,"auto",$,j],E=()=>["auto","min","max","fr",$,j],R=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],H=()=>["start","end","center","stretch","center-safe","end-safe"],N=()=>["auto",...L()],te=()=>[Io,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...L()],q=()=>[e,$,j],G=()=>[...y(),cc,uc,{position:[$,j]}],oe=()=>["no-repeat",{repeat:["","x","y","space","round"]}],D=()=>["auto","cover","contain",dv,nv,{size:[$,j]}],z=()=>[tl,wr,Ga],X=()=>["","none","full",l,$,j],_=()=>["",le,wr,Ga],Y=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Q=()=>[le,tl,cc,uc],pe=()=>["","none",h,$,j],we=()=>["none",le,$,j],De=()=>["none",le,$,j],Me=()=>[le,$,j],Ue=()=>[Io,"full",...L()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Jt],breakpoint:[Jt],color:[tv],container:[Jt],"drop-shadow":[Jt],ease:["in","out","in-out"],font:[sv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Jt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Jt],shadow:[Jt],spacing:["px",le],text:[Jt],"text-shadow":[Jt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Io,j,$,p]}],container:["container"],columns:[{columns:[le,j,$,i]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:S()}],overflow:[{overflow:I()}],"overflow-x":[{"overflow-x":I()}],"overflow-y":[{"overflow-y":I()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:P()}],"inset-x":[{"inset-x":P()}],"inset-y":[{"inset-y":P()}],start:[{start:P()}],end:[{end:P()}],top:[{top:P()}],right:[{right:P()}],bottom:[{bottom:P()}],left:[{left:P()}],visibility:["visible","invisible","collapse"],z:[{z:[ya,"auto",$,j]}],basis:[{basis:[Io,"full","auto",i,...L()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[le,Io,"auto","initial","none",j]}],grow:[{grow:["",le,$,j]}],shrink:[{shrink:["",le,$,j]}],order:[{order:[ya,"first","last","none",$,j]}],"grid-cols":[{"grid-cols":A()}],"col-start-end":[{col:U()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":A()}],"row-start-end":[{row:U()}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":E()}],"auto-rows":[{"auto-rows":E()}],gap:[{gap:L()}],"gap-x":[{"gap-x":L()}],"gap-y":[{"gap-y":L()}],"justify-content":[{justify:[...R(),"normal"]}],"justify-items":[{"justify-items":[...H(),"normal"]}],"justify-self":[{"justify-self":["auto",...H()]}],"align-content":[{content:["normal",...R()]}],"align-items":[{items:[...H(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...H(),{baseline:["","last"]}]}],"place-content":[{"place-content":R()}],"place-items":[{"place-items":[...H(),"baseline"]}],"place-self":[{"place-self":["auto",...H()]}],p:[{p:L()}],px:[{px:L()}],py:[{py:L()}],ps:[{ps:L()}],pe:[{pe:L()}],pt:[{pt:L()}],pr:[{pr:L()}],pb:[{pb:L()}],pl:[{pl:L()}],m:[{m:N()}],mx:[{mx:N()}],my:[{my:N()}],ms:[{ms:N()}],me:[{me:N()}],mt:[{mt:N()}],mr:[{mr:N()}],mb:[{mb:N()}],ml:[{ml:N()}],"space-x":[{"space-x":L()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":L()}],"space-y-reverse":["space-y-reverse"],size:[{size:te()}],w:[{w:[i,"screen",...te()]}],"min-w":[{"min-w":[i,"screen","none",...te()]}],"max-w":[{"max-w":[i,"screen","none","prose",{screen:[n]},...te()]}],h:[{h:["screen","lh",...te()]}],"min-h":[{"min-h":["screen","lh","none",...te()]}],"max-h":[{"max-h":["screen","lh",...te()]}],"font-size":[{text:["base",t,wr,Ga]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,al]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",tl,j]}],"font-family":[{font:[lv,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":[le,"none",$,al]}],leading:[{leading:[s,...L()]}],"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:q()}],"text-color":[{text:q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:[le,"from-font","auto",$,Ga]}],"text-decoration-color":[{decoration:q()}],"underline-offset":[{"underline-offset":[le,"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:L()}],"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:G()}],"bg-repeat":[{bg:oe()}],"bg-size":[{bg:D()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ya,$,j],radial:["",$,j],conic:[ya,$,j]},uv,iv]}],"bg-color":[{bg:q()}],"gradient-from-pos":[{from:z()}],"gradient-via-pos":[{via:z()}],"gradient-to-pos":[{to:z()}],"gradient-from":[{from:q()}],"gradient-via":[{via:q()}],"gradient-to":[{to:q()}],rounded:[{rounded:X()}],"rounded-s":[{"rounded-s":X()}],"rounded-e":[{"rounded-e":X()}],"rounded-t":[{"rounded-t":X()}],"rounded-r":[{"rounded-r":X()}],"rounded-b":[{"rounded-b":X()}],"rounded-l":[{"rounded-l":X()}],"rounded-ss":[{"rounded-ss":X()}],"rounded-se":[{"rounded-se":X()}],"rounded-ee":[{"rounded-ee":X()}],"rounded-es":[{"rounded-es":X()}],"rounded-tl":[{"rounded-tl":X()}],"rounded-tr":[{"rounded-tr":X()}],"rounded-br":[{"rounded-br":X()}],"rounded-bl":[{"rounded-bl":X()}],"border-w":[{border:_()}],"border-w-x":[{"border-x":_()}],"border-w-y":[{"border-y":_()}],"border-w-s":[{"border-s":_()}],"border-w-e":[{"border-e":_()}],"border-w-t":[{"border-t":_()}],"border-w-r":[{"border-r":_()}],"border-w-b":[{"border-b":_()}],"border-w-l":[{"border-l":_()}],"divide-x":[{"divide-x":_()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":_()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Y(),"hidden","none"]}],"divide-style":[{divide:[...Y(),"hidden","none"]}],"border-color":[{border:q()}],"border-color-x":[{"border-x":q()}],"border-color-y":[{"border-y":q()}],"border-color-s":[{"border-s":q()}],"border-color-e":[{"border-e":q()}],"border-color-t":[{"border-t":q()}],"border-color-r":[{"border-r":q()}],"border-color-b":[{"border-b":q()}],"border-color-l":[{"border-l":q()}],"divide-color":[{divide:q()}],"outline-style":[{outline:[...Y(),"none","hidden"]}],"outline-offset":[{"outline-offset":[le,$,j]}],"outline-w":[{outline:["",le,wr,Ga]}],"outline-color":[{outline:q()}],shadow:[{shadow:["","none",c,zs,Hs]}],"shadow-color":[{shadow:q()}],"inset-shadow":[{"inset-shadow":["none",d,zs,Hs]}],"inset-shadow-color":[{"inset-shadow":q()}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:q()}],"ring-offset-w":[{"ring-offset":[le,Ga]}],"ring-offset-color":[{"ring-offset":q()}],"inset-ring-w":[{"inset-ring":_()}],"inset-ring-color":[{"inset-ring":q()}],"text-shadow":[{"text-shadow":["none",m,zs,Hs]}],"text-shadow-color":[{"text-shadow":q()}],opacity:[{opacity:[le,$,j]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"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":[le]}],"mask-image-linear-from-pos":[{"mask-linear-from":Q()}],"mask-image-linear-to-pos":[{"mask-linear-to":Q()}],"mask-image-linear-from-color":[{"mask-linear-from":q()}],"mask-image-linear-to-color":[{"mask-linear-to":q()}],"mask-image-t-from-pos":[{"mask-t-from":Q()}],"mask-image-t-to-pos":[{"mask-t-to":Q()}],"mask-image-t-from-color":[{"mask-t-from":q()}],"mask-image-t-to-color":[{"mask-t-to":q()}],"mask-image-r-from-pos":[{"mask-r-from":Q()}],"mask-image-r-to-pos":[{"mask-r-to":Q()}],"mask-image-r-from-color":[{"mask-r-from":q()}],"mask-image-r-to-color":[{"mask-r-to":q()}],"mask-image-b-from-pos":[{"mask-b-from":Q()}],"mask-image-b-to-pos":[{"mask-b-to":Q()}],"mask-image-b-from-color":[{"mask-b-from":q()}],"mask-image-b-to-color":[{"mask-b-to":q()}],"mask-image-l-from-pos":[{"mask-l-from":Q()}],"mask-image-l-to-pos":[{"mask-l-to":Q()}],"mask-image-l-from-color":[{"mask-l-from":q()}],"mask-image-l-to-color":[{"mask-l-to":q()}],"mask-image-x-from-pos":[{"mask-x-from":Q()}],"mask-image-x-to-pos":[{"mask-x-to":Q()}],"mask-image-x-from-color":[{"mask-x-from":q()}],"mask-image-x-to-color":[{"mask-x-to":q()}],"mask-image-y-from-pos":[{"mask-y-from":Q()}],"mask-image-y-to-pos":[{"mask-y-to":Q()}],"mask-image-y-from-color":[{"mask-y-from":q()}],"mask-image-y-to-color":[{"mask-y-to":q()}],"mask-image-radial":[{"mask-radial":[$,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":Q()}],"mask-image-radial-to-pos":[{"mask-radial-to":Q()}],"mask-image-radial-from-color":[{"mask-radial-from":q()}],"mask-image-radial-to-color":[{"mask-radial-to":q()}],"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":y()}],"mask-image-conic-pos":[{"mask-conic":[le]}],"mask-image-conic-from-pos":[{"mask-conic-from":Q()}],"mask-image-conic-to-pos":[{"mask-conic-to":Q()}],"mask-image-conic-from-color":[{"mask-conic-from":q()}],"mask-image-conic-to-color":[{"mask-conic-to":q()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:G()}],"mask-repeat":[{mask:oe()}],"mask-size":[{mask:D()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,j]}],filter:[{filter:["","none",$,j]}],blur:[{blur:pe()}],brightness:[{brightness:[le,$,j]}],contrast:[{contrast:[le,$,j]}],"drop-shadow":[{"drop-shadow":["","none",f,zs,Hs]}],"drop-shadow-color":[{"drop-shadow":q()}],grayscale:[{grayscale:["",le,$,j]}],"hue-rotate":[{"hue-rotate":[le,$,j]}],invert:[{invert:["",le,$,j]}],saturate:[{saturate:[le,$,j]}],sepia:[{sepia:["",le,$,j]}],"backdrop-filter":[{"backdrop-filter":["","none",$,j]}],"backdrop-blur":[{"backdrop-blur":pe()}],"backdrop-brightness":[{"backdrop-brightness":[le,$,j]}],"backdrop-contrast":[{"backdrop-contrast":[le,$,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",le,$,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[le,$,j]}],"backdrop-invert":[{"backdrop-invert":["",le,$,j]}],"backdrop-opacity":[{"backdrop-opacity":[le,$,j]}],"backdrop-saturate":[{"backdrop-saturate":[le,$,j]}],"backdrop-sepia":[{"backdrop-sepia":["",le,$,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":L()}],"border-spacing-x":[{"border-spacing-x":L()}],"border-spacing-y":[{"border-spacing-y":L()}],"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:[le,"initial",$,j]}],ease:[{ease:["linear","initial",v,$,j]}],delay:[{delay:[le,$,j]}],animate:[{animate:["none",g,$,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[x,$,j]}],"perspective-origin":[{"perspective-origin":S()}],rotate:[{rotate:we()}],"rotate-x":[{"rotate-x":we()}],"rotate-y":[{"rotate-y":we()}],"rotate-z":[{"rotate-z":we()}],scale:[{scale:De()}],"scale-x":[{"scale-x":De()}],"scale-y":[{"scale-y":De()}],"scale-z":[{"scale-z":De()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[$,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:S()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ue()}],"translate-x":[{"translate-x":Ue()}],"translate-y":[{"translate-y":Ue()}],"translate-z":[{"translate-z":Ue()}],"translate-none":["translate-none"],accent:[{accent:q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:q()}],"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":L()}],"scroll-mx":[{"scroll-mx":L()}],"scroll-my":[{"scroll-my":L()}],"scroll-ms":[{"scroll-ms":L()}],"scroll-me":[{"scroll-me":L()}],"scroll-mt":[{"scroll-mt":L()}],"scroll-mr":[{"scroll-mr":L()}],"scroll-mb":[{"scroll-mb":L()}],"scroll-ml":[{"scroll-ml":L()}],"scroll-p":[{"scroll-p":L()}],"scroll-px":[{"scroll-px":L()}],"scroll-py":[{"scroll-py":L()}],"scroll-ps":[{"scroll-ps":L()}],"scroll-pe":[{"scroll-pe":L()}],"scroll-pt":[{"scroll-pt":L()}],"scroll-pr":[{"scroll-pr":L()}],"scroll-pb":[{"scroll-pb":L()}],"scroll-pl":[{"scroll-pl":L()}],"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",...q()]}],"stroke-w":[{stroke:[le,wr,Ga,al]}],stroke:[{stroke:["none",...q()]}],"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 Ic=jb(mv);function wa(...e){return Ic(Us(e))}var hv=be.createContext({size:"default",variant:"default",spacing:0});function La({className:e,variant:o,size:t,spacing:a=2,children:r,...s}){return jsx(nc,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:wa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...s,children:jsx(hv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var xv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Ac=createSlice({name:"toolbar",initialState:xv,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:Ot,setPenColor:Ws,setStrokeWidth:sl,setFontSize:TA,setFontFamily:AA,setFontStyle:PA,setFontWeight:DA,setTextDecoration:RA,setTextColor:FA}=Ac.actions,Pc=Ac.reducer;var Dc=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,s]=useState(null),[n,i]=useState(0),[u,l]=useState(null),[c,d]=useState(false),m=useRef(null),f=useRef([]),h=useRef(null),x=useRef(null),p=useRef(null);useEffect(()=>((async()=>{try{let C=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});l(C),d(!0),p.current&&(p.current.srcObject=C);}catch(C){console.error("Error accessing camera:",C),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{h.current&&clearInterval(h.current),u&&u.getTracks().forEach(C=>C.stop());}),[]);let v=()=>{u&&(u.getTracks().forEach(I=>I.stop()),l(null),d(false));},g=async()=>{try{let I=null,C=null;try{I=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(F){console.error("Error accessing camera for recording:",F),alert("Failed to access camera for recording.");return}try{C=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(F){console.warn("Microphone access denied:",F);}let L=[...I.getVideoTracks()];C&&L.push(...C.getAudioTracks());let P=new MediaStream(L),A="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?A="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?A="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?A="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(A="video/webm;codecs=vp8");let U=new MediaRecorder(P,{mimeType:A,videoBitsPerSecond:25e5});m.current=U,f.current=[],U.ondataavailable=F=>{F.data.size>0&&f.current.push(F.data);},U.onstop=()=>{let F=new Blob(f.current,{type:A}),E=document.createElement("video");E.src=URL.createObjectURL(F),E.muted=!0,E.currentTime=.1,E.onseeked=()=>{let R=document.createElement("canvas");R.width=E.videoWidth,R.height=E.videoHeight;let H=R.getContext("2d");H&&(H.drawImage(E,0,0),x.current=R.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(E.src);},P.getTracks().forEach(R=>R.stop()),I&&I.getTracks().forEach(R=>R.stop()),C&&C.getTracks().forEach(R=>R.stop()),h.current&&clearInterval(h.current),s(F),v();},U.onerror=F=>{console.error("MediaRecorder error:",F);},U.start(1e3),a(!0),i(0),h.current=setInterval(()=>{i(F=>F+1);},1e3);}catch(I){console.error("Error starting camera recording:",I),alert("Failed to start recording. Please check permissions.");}},b=()=>{m.current&&t&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),a(false));},y=()=>{if(r){let I=URL.createObjectURL(r),C=document.createElement("a");C.href=I,C.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(I);}},S=I=>{let C=Math.floor(I/60),L=I%60;return `${C.toString().padStart(2,"0")}:${L.toString().padStart(2,"0")}`};return jsx("div",{className:"fixed inset-0 flex items-center justify-center",children:jsxs("div",{className:"relative w-full max-w-2xl overflow-hidden rounded-2xl shadow-2xl",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:g,disabled:!c,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"})})}),!c&&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:b,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:S(n)})]})]})]}),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: ",S(n)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{s(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:y,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&&x.current&&(o(r,x.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"})]})]})]})]})]})})};var Zt=40,Fc=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[s,n]=useState(t?.order||"sequential"),[i,u]=useState(false),l=useRef(null),c=useRef(null);useEffect(()=>{let g=b=>{b.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let d=g=>{let b=g.target.files;if(!b||b.length===0)return;let y=Zt-a.length;if(y<=0){alert(`You can only upload a maximum of ${Zt} images`);return}let S=Array.from(b).slice(0,y);S.length<b.length&&alert(`Only ${y} more images can be added (max ${Zt} total)`);let I=S.map(C=>new Promise((L,P)=>{let A=new FileReader;A.onload=U=>{U.target?.result?L(U.target.result):P(new Error("Failed to read file"));},A.onerror=P,A.readAsDataURL(C);}));Promise.all(I).then(C=>{r(L=>[...L,...C]),c.current&&(c.current.value="");});},m=g=>{g.preventDefault(),u(false);let b=Array.from(g.dataTransfer.files).filter(C=>C.type.startsWith("image/"));if(b.length===0)return;let y=Zt-a.length;if(y<=0){alert(`You can only upload a maximum of ${Zt} images`);return}let S=b.slice(0,y);S.length<b.length&&alert(`Only ${y} more images can be added (max ${Zt} total)`);let I=S.map(C=>new Promise((L,P)=>{let A=new FileReader;A.onload=U=>{U.target?.result?L(U.target.result):P(new Error("Failed to read file"));},A.onerror=P,A.readAsDataURL(C);}));Promise.all(I).then(C=>{r(L=>[...L,...C]);});},f=g=>{g.preventDefault(),u(true);},h=()=>{u(false);},x=g=>{r(b=>b.filter((y,S)=>S!==g));},v=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:l,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:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,s,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>=Zt?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",Zt," images"]}):jsxs("span",{children:[a.length,"/",Zt," images"]})})]}),jsx("input",{ref:c,type:"file",accept:"image/*",multiple:true,onChange:d,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:f,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 ${i?"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:i?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${s==="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 ${s==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${s==="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 ${s==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,b)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${b+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>x(b),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:b+1})]},b))})]}),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(v,document.body)};var Gs={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}},Rv={enabled:true};function ll(e){return e?{tools:{...Gs.tools,...e.tools},actions:{...Gs.actions,...e.actions}}:Gs}var Fv={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}},Ev={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 iy=({isOpen:e,onClose:o,onScreenRecord:t,stageRef:a,onTextAdded:r,showToggleButton:s=true,config:n}={})=>{let i=xe(),u=ee(B=>B.canvas.slides.find(ne=>ne.id===B.canvas.currentSlideId)),l=u?.videos||[],c=u?.editingFlashcard,d=ee(B=>B.toolbar.selectedTool),m=ee(B=>B.toolbar.penColor),f=u?.showMcqForm,h=u?.showFlashcardForm,x=useMemo(()=>ll(n),[n]),{tools:p,actions:v}=x,g=l.some(B=>B.isRecorded&&B.isPlaying),b=ee(B=>B.toolbar.fontSize),y=ee(B=>B.toolbar.fontFamily),S=ee(B=>B.toolbar.fontStyle),I=ee(B=>B.toolbar.fontWeight),C=ee(B=>B.toolbar.textDecoration),L=ee(B=>B.toolbar.textColor),[P,A]=useState(false),[U,F]=useState(false),[E,R]=useState(false),[H,N]=useState(false),[te,q]=useState(false),[G,oe]=useState(true),z=useRef(null),X=useRef(null),Y=[{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(()=>Y.filter(B=>{let ne=p[B.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[p]),Q=[{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"}],pe=useMemo(()=>{let B=p.shapes;return B===false?[]:B===true?Q:Array.isArray(B)?Q.filter(ne=>B.includes(ne.name)):Q},[p.shapes]),we=[{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"}],De=useMemo(()=>{let B=p.activities;return B===false?[]:B===true?we:Array.isArray(B)?we.filter(ne=>B.includes(ne.name)):we},[p.activities]),Me=useMemo(()=>{let B=p.media;return B===false?{photoFrame:false,image:false,video:false}:B===true?{photoFrame:true,image:true,video:true}:Array.isArray(B)?{photoFrame:B.includes("photo-frame"),image:B.includes("image"),video:B.includes("video")}:{photoFrame:true,image:true,video:true}},[p.media]),Ue=useMemo(()=>{let B=p.activities;return B===false?false:B===true?true:Array.isArray(B)?B.includes("flashcard"):true},[p.activities]),re=B=>{let ne=B.target.files;!ne||ne.length===0||(i(Ot("select")),i(dt(false)),N(false),Array.from(ne).forEach(Ie=>{let me=new FileReader;me.onload=se=>{let ie=new window.Image;ie.src=se.target?.result,ie.onload=()=>{let Ve=ie.width/ie.height,qt=300,_t=300,_e=ie.width,Ce=ie.height;_e>qt&&(_e=qt,Ce=_e/Ve),Ce>_t&&(Ce=_t,_e=Ce*Ve),i(ue());let Je=(window.innerWidth-_e)/2,jt=(window.innerHeight-Ce)/2;i(hn({id:v4(),src:ie.src,x:Je,y:jt,width:_e,height:Ce,draggable:true,rotation:0}));};},me.readAsDataURL(Ie);}),B.target.value="");},Mr=async B=>{let ne=B.target.files;if(!(!ne||ne.length===0)){console.log("files",B),i(Ot("select")),i(dt(false)),N(false);for(let Ie of Array.from(ne))try{let me=URL.createObjectURL(Ie),se=document.createElement("video");console.log("video",se),se.src=me,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((Ze,ea)=>{let Ta=setTimeout(()=>ea(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ta),Ze();},se.onerror=()=>{clearTimeout(Ta),ea(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Ze,ea)=>{let Ta=setTimeout(()=>ea(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ta),Ze()):se.onloadeddata=()=>{clearTimeout(Ta),Ze();};});let ie=Math.min(.8,se.duration/2);console.log("Seeking to:",ie),se.currentTime=ie,await new Promise(Ze=>{let ea=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ze();},5e3);se.onseeked=()=>{clearTimeout(ea),console.log("Seek completed"),Ze();};});let Ve=document.createElement("canvas"),qt=se.videoWidth/se.videoHeight,_t=400,_e=400,Ce=se.videoWidth,Je=se.videoHeight;Ce>_t&&(Ce=_t,Je=Ce/qt),Je>_e&&(Je=_e,Ce=Je*qt),Ve.width=Ce,Ve.height=Je;let jt=Ve.getContext("2d",{willReadFrequently:!1});if(!jt)throw new Error("Failed to get canvas context");if(await new Promise(Ze=>setTimeout(Ze,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ce,height:Je}),jt.drawImage(se,0,0,Ce,Je);let ka=Ve.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",ka.length),i(ue());let Ma=(window.innerWidth-Ce)/2,$a=(window.innerHeight-Je)/2,Fr=v4();await Ha(Fr,Ie,ka),i(zr({id:Fr,objectUrl:me,thumbnailDataUrl:ka,videoBlob:Ie,x:Ma,y:$a,width:Ce,height:Je,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${Ie.name}`);}catch(me){console.error("Error processing video:",me),alert(`Failed to process video: ${Ie.name}`);}B.target.value="";}},Tr=(B,ne,Ie)=>{i(ue()),i(Ot("select")),i(dt(false));let me=300,se=300,ie=(window.innerWidth-me)/2,Ve=(window.innerHeight-se)/2;i(Ie?Za({id:Ie,images:B,order:ne,x:ie,y:Ve,width:me,height:se,rotation:0,draggable:true}):Ln({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:B,currentIndex:0,order:ne,x:ie,y:Ve,width:me,height:se,rotation:0,draggable:true})),i(Pa(false));},Ar=()=>{i(ue()),i(Ot("select")),i(dt(false));let B=400,ne=300,Ie=(window.innerWidth-B)/2,me=(window.innerHeight-ne)/2;i(kn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ie,y:me,width:B,height:ne,rotation:0,draggable:true,isCapturing:false})),q(false);},Pr=B=>{let me=(window.innerWidth-100)/2,se=(window.innerHeight-100)/2,ie={};switch(B.name){case "circle":case "ring":case "wedge":case "arc":ie.radius=50,(B.name==="ring"||B.name==="arc")&&(ie.innerRadius=25,ie.outerRadius=50),(B.name==="wedge"||B.name==="arc")&&(ie.angle=B.name==="wedge"?60:90);break;case "ellipse":ie.radiusX=60,ie.radiusY=40;break;case "triangle":ie.radius=50,ie.sides=3;break;case "polygon":ie.radius=50,ie.sides=6;break;case "star":ie.innerRadius=25,ie.outerRadius=50,ie.numPoints=5;break;case "arrow":case "line":ie.points=[0,0,100,0],B.name==="arrow"&&(ie.pointerLength=10,ie.pointerWidth=10);break}let Ve={id:`shape-${Date.now()}`,type:B.name,x:me,y:se,width:100,height:100,rotation:0,color:m,...ie};i(ue()),i(dt(false)),i(Ot(B.name)),i(bn(Ve));},Ia=B=>{if(i(Ot(B)),B==="select")i(dt(false));else if(B==="text"){i(dt(false)),i(ue());let ne=200,Ie=50,me=(window.innerWidth-ne)/2,se=(window.innerHeight-Ie)/2,ie=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;i(yn({id:ie,text:"",x:me,y:se,width:ne,height:Ie,rotation:0,draggable:true,fontSize:b,fontFamily:y,fontStyle:S,fontWeight:I,textDecoration:C,fill:L,align:"left"})),setTimeout(()=>{i(Ho(ie));},100),r&&r(ie);}else i(dt(true));},Dr=()=>{i(Xn()),i(Ot("select")),i(dt(false));},Js=()=>{t?t():a?A(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Zs=()=>{F(true);},Rr=async(B,ne)=>{try{i(Ot("select")),i(dt(!1));let Ie=URL.createObjectURL(B),me=document.createElement("video");me.src=Ie,me.muted=!0,me.playsInline=!0,me.preload="auto",await new Promise((ka,Ma)=>{let $a=setTimeout(()=>Ma(new Error("Metadata load timeout")),1e4);me.onloadedmetadata=()=>{clearTimeout($a),ka();},me.onerror=()=>{clearTimeout($a),Ma(new Error("Failed to load video"));};});let se=640,ie=me.videoWidth/me.videoHeight,Ve=se,qt=Ve/ie,_t=window.innerWidth,_e=window.innerHeight;i(ue());let Ce=(_t-Ve)/2,Je=(_e-qt)/2,jt=v4();await Ha(jt,B,ne),i(zr({id:jt,objectUrl:Ie,thumbnailDataUrl:ne,videoBlob:B,x:Ce,y:Je,width:Ve,height:qt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),A(!1),F(!1);}catch(Ie){console.error("Error adding recorded video to canvas:",Ie),alert("Failed to add video to canvas. Please try again.");}},Qs=B=>{i(Ot("select")),i(dt(false)),i(qo(null)),B&&i(zn(B)),i(sa(!f));},en=()=>{i(Bo(null)),i(Pa(true)),q(false);},Ca=()=>{R(!E);},tn=()=>{N(!H);},an=()=>{q(!te);};return g?null:jsx("div",{className:"konva-editor-root",children:jsxs("div",{className:"fixed top-1/2 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(La,{type:"single",className:"flex flex-col gap-1 border bg-white p-1 shadow-xl",children:Z.map((B,ne)=>jsx("div",{title:B.label,className:`hover:bg-primary/10 mb-1 cursor-pointer rounded-md px-4 py-3 ${B.name===d?"bg-primary/10":""}`,onClick:()=>{if(B.name==="image"){tn(),R(false),q(false),Ia(B.name);return}else if(B.name==="shapes"){Ca(),N(false),q(false),Ia(B.name);return}else if(B.name==="activities"){Ia(B.name),an(),R(false),N(false);return}Ia(B.name),R(false),N(false),q(false);},children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},ne))}),E&&jsx(La,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:pe.map((B,ne)=>jsx("div",{title:B.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",onClick:()=>Pr(B),children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},ne))}),H&&jsxs(La,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Me.photoFrame&&jsx("div",{title:"Photo frame",onClick:Ar,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),Me.image&&jsx("div",{onClick:()=>z.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(Image$2,{weight:"fill",size:24,className:"text-primary"})}),Me.video&&jsx("div",{onClick:()=>X.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(MonitorPlay,{weight:"fill",size:24,className:"text-primary"})})]}),te&&jsxs(La,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Ue&&jsx("div",{title:"Flashcard",onClick:()=>en(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(Cards,{weight:"fill",size:24,className:"text-primary"})}),De.map((B,ne)=>jsx("div",{title:B.label,onClick:()=>Qs(B.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},ne))]})]}),jsx("input",{ref:z,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:re}),jsx("input",{ref:X,type:"file",accept:"video/*",className:"hidden",onChange:Mr}),!t&&P&&a&&jsx(Jo,{onClose:()=>A(false),stageRef:a,onRecordingComplete:Rr}),U&&jsx(Dc,{onClose:()=>F(false),onRecordingComplete:Rr}),h&&jsx(Fc,{editingFlashcard:c,onConfirm:Tr,onCancel:()=>i(Pa(false))}),(v.undo||v.redo||v.screenRecord||v.cameraRecord||v.clear)&&jsxs(La,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[v.undo&&jsx("button",{value:"undo",onClick:()=>i(Yn()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{size:24,weight:"bold"})}),v.redo&&jsx("button",{value:"redo",onClick:()=>i(Jn()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{size:24,weight:"bold"})}),v.screenRecord&&jsx("button",{value:"screen-record",onClick:Js,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#2260DD]",title:"Screen Record",children:jsx(Record,{size:24,weight:"bold"})}),v.cameraRecord&&jsx("button",{value:"camera-record",onClick:Zs,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#804FF2]",title:"Camera Record",children:jsx(Camera,{size:24,weight:"fill"})}),v.clear&&jsx("button",{value:"clear",onClick:()=>Dr(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{size:24,weight:"bold"})})]})]})})},ly=iy;var fl=({onPublish:e,label:o="Publish Slides",className:t})=>{let a=aa(Wo),n=(aa(h=>h.canvas.slides.find(x=>x.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),[i,u]=useState(false),[l,c]=useState(null),[d,m]=useState(null),f=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}u(true),m(null);try{let h=await e(a,x=>{c(x);});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{u(false),setTimeout(()=>{c(null),m(null);},3e3);}};return n?null:jsxs("button",{onClick:f,disabled:i||a.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-3 px-4 py-3 font-medium text-white transition-colors",children:[jsx(Export,{size:24,color:"#fff"})," Publish"]})};var py=({title:e="Untitled",autoSaveMessage:o="Auto-saved just now",onBack:t,onPublish:a,showPublishButton:r=true,showBackButton:s=true,className:n="",rightContent:i,leftContent:u})=>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-6 shadow-sm ${n}`,children:[u||jsxs("div",{className:"flex items-center gap-6 px-2",children:[s&&jsx("button",{onClick:t,className:"h-10 w-10 rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A]",children:jsx(CaretLeft,{size:24,color:"#64758B",weight:"bold"})}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{className:"text-2xl font-medium text-[#000000CC]",children:e}),jsxs("div",{className:"flex items-center gap-2",children:[jsx(CloudArrowUp,{weight:"fill",color:"#63748A",size:20}),jsx("span",{className:"text-base font-medium text-[#63748A]",children:o})]})]})]}),i||r&&a&&jsx(fl,{onPublish:a})]});function ml(e,[o,t]){return Math.min(t,Math.max(o,e))}function Oc(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 Vc(e){let[o,t]=be.useState(void 0);return wo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let s=r[0],n,i;if("borderBoxSize"in s){let u=s.borderBoxSize,l=Array.isArray(u)?u[0]:u;n=l.inlineSize,i=l.blockSize;}else n=e.offsetWidth,i=e.offsetHeight;t({width:n,height:i});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var qc=["PageUp","PageDown"],Uc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Hc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Po="Slider",[pl,gy,xy]=Os(Po),[zc]=ba(Po,[xy]),[by,js]=zc(Po),Wc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:s=1,orientation:n="horizontal",disabled:i=false,minStepsBetweenThumbs:u=0,defaultValue:l=[a],value:c,onValueChange:d=()=>{},onValueCommit:m=()=>{},inverted:f=false,form:h,...x}=e,p=be.useRef(new Set),v=be.useRef(0),b=n==="horizontal"?vy:yy,[y=[],S]=Yt({prop:c,defaultProp:l,onChange:U=>{[...p.current][v.current]?.focus(),d(U);}}),I=be.useRef(y);function C(U){let F=Cy(y,U);A(U,F);}function L(U){A(U,v.current);}function P(){let U=I.current[v.current];y[v.current]!==U&&m(y);}function A(U,F,{commit:E}={commit:false}){let R=Ay(s),H=Py(Math.round((U-a)/s)*s+a,R),N=ml(H,[a,r]);S((te=[])=>{let q=Sy(te,N,F);if(Ty(q,u*s)){v.current=q.indexOf(N);let G=String(q)!==String(te);return G&&E&&m(q),G?q:te}else return te});}return jsx(by,{scope:e.__scopeSlider,name:t,disabled:i,min:a,max:r,valueIndexToChangeRef:v,thumbs:p.current,values:y,orientation:n,form:h,children:jsx(pl.Provider,{scope:e.__scopeSlider,children:jsx(pl.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":i,"data-disabled":i?"":void 0,...x,ref:o,onPointerDown:Xe(x.onPointerDown,()=>{i||(I.current=y);}),min:a,max:r,inverted:f,onSlideStart:i?void 0:C,onSlideMove:i?void 0:L,onSlideEnd:i?void 0:P,onHomeKeyDown:()=>!i&&A(a,0,{commit:true}),onEndKeyDown:()=>!i&&A(r,y.length-1,{commit:true}),onStepKeyDown:({event:U,direction:F})=>{if(!i){let H=qc.includes(U.key)||U.shiftKey&&Uc.includes(U.key)?10:1,N=v.current,te=y[N],q=s*H*F;A(te+q,N,{commit:true});}}})})})})});Wc.displayName=Po;var[Gc,Kc]=zc(Po,{startEdge:"left",endEdge:"right",size:"width",direction:1}),vy=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:s,onSlideStart:n,onSlideMove:i,onSlideEnd:u,onStepKeyDown:l,...c}=e,[d,m]=be.useState(null),f=At(o,b=>m(b)),h=be.useRef(void 0),x=So(r),p=x==="ltr",v=p&&!s||!p&&s;function g(b){let y=h.current||d.getBoundingClientRect(),S=[0,y.width],C=xl(S,v?[t,a]:[a,t]);return h.current=y,C(b-y.left)}return jsx(Gc,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:jsx(_c,{dir:x,"data-orientation":"horizontal",...c,ref:f,style:{...c.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let y=g(b.clientX);n?.(y);},onSlideMove:b=>{let y=g(b.clientX);i?.(y);},onSlideEnd:()=>{h.current=void 0,u?.();},onStepKeyDown:b=>{let S=Hc[v?"from-left":"from-right"].includes(b.key);l?.({event:b,direction:S?-1:1});}})})}),yy=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:s,onSlideMove:n,onSlideEnd:i,onStepKeyDown:u,...l}=e,c=be.useRef(null),d=At(o,c),m=be.useRef(void 0),f=!r;function h(x){let p=m.current||c.current.getBoundingClientRect(),v=[0,p.height],b=xl(v,f?[a,t]:[t,a]);return m.current=p,b(x-p.top)}return jsx(Gc,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(_c,{"data-orientation":"vertical",...l,ref:d,style:{...l.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:x=>{let p=h(x.clientY);s?.(p);},onSlideMove:x=>{let p=h(x.clientY);n?.(p);},onSlideEnd:()=>{m.current=void 0,i?.();},onStepKeyDown:x=>{let v=Hc[f?"from-bottom":"from-top"].includes(x.key);u?.({event:x,direction:v?-1:1});}})})}),_c=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:s,onHomeKeyDown:n,onEndKeyDown:i,onStepKeyDown:u,...l}=e,c=js(Po,t);return jsx(it.span,{...l,ref:o,onKeyDown:Xe(e.onKeyDown,d=>{d.key==="Home"?(n(d),d.preventDefault()):d.key==="End"?(i(d),d.preventDefault()):qc.concat(Uc).includes(d.key)&&(u(d),d.preventDefault());}),onPointerDown:Xe(e.onPointerDown,d=>{let m=d.target;m.setPointerCapture(d.pointerId),d.preventDefault(),c.thumbs.has(m)?m.focus():a(d);}),onPointerMove:Xe(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d);}),onPointerUp:Xe(e.onPointerUp,d=>{let m=d.target;m.hasPointerCapture(d.pointerId)&&(m.releasePointerCapture(d.pointerId),s(d));})})}),jc="SliderTrack",$c=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=js(jc,t);return jsx(it.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});$c.displayName=jc;var hl="SliderRange",Xc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=js(hl,t),s=Kc(hl,t),n=be.useRef(null),i=At(o,n),u=r.values.length,l=r.values.map(m=>Zc(m,r.min,r.max)),c=u>1?Math.min(...l):0,d=100-Math.max(...l);return jsx(it.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:i,style:{...e.style,[s.startEdge]:c+"%",[s.endEdge]:d+"%"}})});Xc.displayName=hl;var gl="SliderThumb",Yc=be.forwardRef((e,o)=>{let t=gy(e.__scopeSlider),[a,r]=be.useState(null),s=At(o,i=>r(i)),n=be.useMemo(()=>a?t().findIndex(i=>i.ref.current===a):-1,[t,a]);return jsx(wy,{...e,ref:s,index:n})}),wy=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...s}=e,n=js(gl,t),i=Kc(gl,t),[u,l]=be.useState(null),c=At(o,g=>l(g)),d=u?n.form||!!u.closest("form"):true,m=Vc(u),f=n.values[a],h=f===void 0?0:Zc(f,n.min,n.max),x=Iy(a,n.values.length),p=m?.[i.size],v=p?ky(p,h,i.direction):0;return be.useEffect(()=>{if(u)return n.thumbs.add(u),()=>{n.thumbs.delete(u);}},[u,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[i.startEdge]:`calc(${h}% + ${v}px)`},children:[jsx(pl.ItemSlot,{scope:e.__scopeSlider,children:jsx(it.span,{role:"slider","aria-label":e["aria-label"]||x,"aria-valuemin":n.min,"aria-valuenow":f,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...s,ref:c,style:f===void 0?{display:"none"}:e.style,onFocus:Xe(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),d&&jsx(Jc,{name:r??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:f},a)]})});Yc.displayName=gl;var Ly="RadioBubbleInput",Jc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),s=At(r,a),n=Oc(o);return be.useEffect(()=>{let i=r.current;if(!i)return;let u=window.HTMLInputElement.prototype,c=Object.getOwnPropertyDescriptor(u,"value").set;if(n!==o&&c){let d=new Event("input",{bubbles:true});c.call(i,o),i.dispatchEvent(d);}},[n,o]),jsx(it.input,{style:{display:"none"},...t,ref:s,defaultValue:o})});Jc.displayName=Ly;function Sy(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,s)=>r-s)}function Zc(e,o,t){let s=100/(t-o)*(e-o);return ml(s,[0,100])}function Iy(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Cy(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 ky(e,o,t){let a=e/2,s=xl([0,50],[0,a]);return (a-s(o)*t)*t}function My(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Ty(e,o){if(o>0){let t=My(e);return Math.min(...t)>=o}return true}function xl(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 Ay(e){return (String(e).split(".")[1]||"").length}function Py(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Qc=Wc,ef=$c,tf=Xc,af=Yc;function rf({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:s,trackClassName:n,thumbClassName:i,...u}){let l=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(Qc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:wa("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),...u,children:[jsx(ef,{"data-slot":"slider-track",className:wa("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(tf,{"data-slot":"slider-range",className:wa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",s)})}),Array.from({length:l.length},(c,d)=>jsx(af,{"data-slot":"slider-thumb",className:wa("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",i)},d))]})}var Fy=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Ey=({colors:e=Fy,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let s=ee(i=>i.toolbar.penColor),n=xe();return jsxs("div",{className:`fixed bottom-6 left-1/2 z-50 flex h-fit w-full max-w-3xl -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-6 shadow-2xl xl:max-w-4xl ${r}`,style:{marginLeft:"-160px"},children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex w-full flex-col px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex w-full items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(rf,{defaultValue:[12],max:28,min:6,step:1,className:"w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:i=>n(sl(i[0]))}),jsx("div",{className:"h-8 w-8 rounded-full bg-black"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(La,{type:"single",className:"flex w-full px-6",children:[e.map(i=>jsx("button",{value:i.value,className:`h-12 w-12 rounded-full border hover:cursor-pointer ${s===i.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:i.value},onClick:()=>n(Ws(i.value))},i.value)),jsxs("label",{className:"relative flex h-12 w-12 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033]",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>n(Ws(i.target.value))}),"+"]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center",children:jsx("label",{className:"relative flex h-12 w-12 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033]",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>n(mn(i.target.value))})})})]})};function By({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var nf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ny=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),vl=e=>{let o=Ny(e);return o.charAt(0).toUpperCase()+o.slice(1)},$s=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),lf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var df={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 cf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:s,iconNode:n,...i},u)=>createElement("svg",{ref:u,...df,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:$s("lucide",r),...!s&&!lf(i)&&{"aria-hidden":"true"},...i},[...n.map(([l,c])=>createElement(l,c)),...Array.isArray(s)?s:[s]]));var Xs=(e,o)=>{let t=forwardRef(({className:a,...r},s)=>createElement(cf,{ref:s,iconNode:o,className:$s(`lucide-${nf(vl(e))}`,`lucide-${e}`,a),...r}));return t.displayName=vl(e),t};var Hy=[["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"}]],Cr=Xs("copy",Hy);var zy=[["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"}]],kr=Xs("trash-2",zy);var mf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:s,onDelete:n})=>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:i=>{i.stopPropagation(),s();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Cr,{size:14})}),!a&&jsx("button",{onClick:i=>{i.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(kr,{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:`Slide ${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 _y=()=>{let e=yt(),o=aa(Wo),t=aa(zo),a=aa(Zn),[r,s]=useState(true),u=(aa(f=>f.canvas.slides.find(h=>h.id===f.canvas.currentSlideId))?.videos||[]).some(f=>f.isRecorded&&f.isPlaying),l=()=>{a&&e(ln());},c=f=>{e(cn(f));},d=f=>{e(un(f));},m=f=>{o.length>1&&e(dn(f));};return u?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:()=>s(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Slides"})]}),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((f,h)=>jsx(mf,{slide:f,index:h,isSelected:f.id===t,isSingleSlide:o.length===1,onSelect:()=>c(f.id),onDuplicate:()=>d(f.id),onDelete:()=>m(f.id)},f.id))}),jsxs("button",{onClick:l,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 Slide"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>s(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var jy="SchooplaEditorDB",$y=1,Sa="slides",yl="schoopla_current_slide_id",wl=()=>new Promise((e,o)=>{let t=indexedDB.open(jy,$y);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Sa)||r.createObjectStore(Sa,{keyPath:"id"});};}),Ll=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await wl(),a=o.transaction([Sa],"readwrite").objectStore(Sa);await new Promise((r,s)=>{let n=a.clear();n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);});for(let r of e)await new Promise((s,n)=>{let i=a.add(r);i.onsuccess=()=>s(!0),i.onerror=()=>n(i.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);}}},Sl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await wl(),t=e.transaction([Sa],"readonly").objectStore(Sa);return new Promise((a,r)=>{let s=t.getAll();s.onsuccess=()=>{e.close();let n=s.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(i=>({id:i.id,width:i.width,height:i.height,x:i.x,y:i.y}))),a(n.length>0?n:null);},s.onerror=()=>{e.close(),r(s.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}}},Ys=async()=>{try{let e=await wl(),t=e.transaction([Sa],"readwrite").objectStore(Sa);await new Promise((a,r)=>{let s=t.clear();s.onsuccess=()=>a(!0),s.onerror=()=>r(s.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(yl),await Eu();}catch(e){console.error("Error clearing local data:",e);}},Il=e=>{try{localStorage.setItem(yl,e);}catch(o){console.error("Error saving current slide ID:",o);}},Cl=()=>{try{return localStorage.getItem(yl)}catch(e){return console.error("Error loading current slide ID:",e),null}},gf=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}};var Xy=["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"],Yy=["canvas/clearCanvas"],Jy=gf((e,o)=>{Ll(e),Il(o);},500),Zy=(e,o)=>{Ll(e),Il(o);},kl=false,xf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;_i(r).catch(s=>{console.error("Error deleting video blob:",s);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,n=e.getState().canvas.slides.find(i=>i.id===r);n&&n.videos&&n.videos.length>0&&n.videos.forEach(i=>{_i(i.id).catch(u=>{console.error("Error deleting video blob:",u);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,s=e.getState(),i=s.canvas.slides.find(u=>u.id===s.canvas.currentSlideId)?.videos.find(u=>u.id===r);i&&i.videoBlob&&setTimeout(()=>{let u=e.getState(),c=u.canvas.slides.find(d=>d.id===u.canvas.currentSlideId)?.videos.find(d=>d.id!==r&&d.x===i.x+20&&d.y===i.y+20);c&&i.videoBlob&&Ha(c.id,i.videoBlob,c.thumbnailDataUrl).catch(d=>{console.error("Error saving duplicated video blob:",d);});},0);}let a=o(t);if(t.type&&Yy.includes(t.type)){if(!kl){kl=true;try{let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;Zy(s,n);}finally{setTimeout(()=>{kl=false;},0);}}}else if(t.type&&Xy.includes(t.type)){let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;Jy(s,n);}return a});new QueryClient;var tw=configureStore({reducer:{toolbar:Pc,canvas:Hl},middleware:e=>e({serializableCheck:false}).concat(xf)});var aw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:s=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:n,quality:a,pixelRatio:r}),u=document.createElement("a");u.download=`${s}.${t}`,u.href=i,document.body.appendChild(u),u.click(),document.body.removeChild(u);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},ow=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((s,n)=>{try{let i=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:i,quality:a,pixelRatio:r});fetch(u).then(l=>l.blob()).then(l=>s(l)).catch(l=>n(l));}catch(i){n(i);}})},rw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,s=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:s,quality:a,pixelRatio:r})};var sw=(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 s=a*a+r*r,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/s)),i=o.x+n*a,u=o.y+n*r;return Math.sqrt(Math.pow(e.x-i,2)+Math.pow(e.y-u,2))},Ml=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],s=e[e.length-1];for(let n=1;n<e.length-1;n++){let i=sw(e[n],r,s);i>t&&(t=i,a=n);}if(t>o){let n=Ml(e.slice(0,a+1),o),i=Ml(e.slice(a),o);return [...n.slice(0,-1),...i]}return [r,s]},nw=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},iw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},bf=(e,o=1.5)=>{if(e.length<=4)return e;let t=nw(e),a=Ml(t,o);return iw(a)},vf=(e,o=1.5)=>({...e,points:bf(e.points,o)}),lw=(e,o=1.5)=>e.map(t=>vf(t,o)),dw=(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 uw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var yf=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((s,n)=>{let i=new Image;i.onload=()=>{let{width:u,height:l}=i;if(u>t||l>a){let h=u/l;u>l?(u=Math.min(u,t),l=u/h):(l=Math.min(l,a),u=l*h);}let c=document.createElement("canvas");c.width=u,c.height=l;let d=c.getContext("2d");if(!d){n(new Error("Failed to get canvas context"));return}d.drawImage(i,0,0,u,l);let m=uw(e),f=c.toDataURL(m,r);s(f);},i.onerror=n,i.src=e;})};var ja=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},Do=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Ro=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",cw=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:s=.85}=o,n=[],i=0;for(let u of e){let l=[],c=[],d=[];for(let m of u.images){let f=m.src;if(t&&f.startsWith("data:"))try{f=await yf(f,{maxWidth:a,maxHeight:r,quality:s});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=ja(f),x=Do(f);i+=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:x};if(m.audioData&&m.audioData.startsWith("data:")){let v=ja(m.audioData),g=Do(m.audioData);i+=v.byteLength,p.audioBuffer=v,p.audioMimeType=g;}l.push(p);}}for(let m of u.videos){let f,h;if(m.videoBlob)f=await m.videoBlob.arrayBuffer(),h=m.videoBlob.type;else if(m.videoData&&m.videoData.startsWith("data:"))f=ja(m.videoData),h=Do(m.videoData);else {console.warn(`Video ${m.id} has no blob or videoData, skipping`);continue}i+=f.byteLength;let x={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:f,mimeType:h};if(m.audioData&&m.audioData.startsWith("data:")){let p=ja(m.audioData),v=Do(m.audioData);i+=p.byteLength,x.audioBuffer=p,x.audioMimeType=v;}c.push(x);}for(let m of u.photoFrames){let f={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=ja(m.capturedImageUrl),x=Do(m.capturedImageUrl);i+=h.byteLength,f.buffer=h,f.mimeType=x;}if(m.audioData&&m.audioData.startsWith("data:")){let h=ja(m.audioData),x=Do(m.audioData);i+=h.byteLength,f.audioBuffer=h,f.audioMimeType=x;}d.push(f);}n.push({...u,images:l,videos:c,photoFrames:d});}return {slides:n,totalSize:i}},fw=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},mw=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((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,draggable:s.draggable,rotation:s.rotation,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,mimeType:s.mimeType,fileKey:`slide_${r}_image_${n}`,audioFileKey:s.audioBuffer?`slide_${r}_image_${n}_audio`:void 0,audioMimeType:s.audioMimeType})),videos:a.videos.map((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,draggable:s.draggable,isPlaying:s.isPlaying,rotation:s.rotation,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,isRecorded:s.isRecorded,mimeType:s.mimeType,fileKey:`slide_${r}_video_${n}`,thumbnailFileKey:`slide_${r}_video_${n}_thumbnail`,audioFileKey:s.audioBuffer?`slide_${r}_video_${n}_audio`:void 0,audioMimeType:s.audioMimeType})),photoFrames:a.photoFrames.map((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,rotation:s.rotation,draggable:s.draggable,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,isCapturing:s.isCapturing,mimeType:s.mimeType,fileKey:s.buffer?`slide_${r}_photoframe_${n}`:void 0,audioFileKey:s.audioBuffer?`slide_${r}_photoframe_${n}_audio`:void 0,audioMimeType:s.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((s,n)=>{let i=new Blob([s.buffer],{type:s.mimeType}),u=`${s.id}.${Ro(s.mimeType)}`;if(o.append(`slide_${r}_image_${n}`,i,u),s.audioBuffer&&s.audioMimeType){let l=new Blob([s.audioBuffer],{type:s.audioMimeType}),c=`${s.id}_audio.${Ro(s.audioMimeType)}`;o.append(`slide_${r}_image_${n}_audio`,l,c);}}),a.videos.forEach((s,n)=>{let i=new Blob([s.buffer],{type:s.mimeType}),u=`${s.id}.${Ro(s.mimeType)}`;if(o.append(`slide_${r}_video_${n}`,i,u),s.thumbnailDataUrl&&s.thumbnailDataUrl.startsWith("data:")){let l=ja(s.thumbnailDataUrl),c=new Blob([l],{type:"image/jpeg"}),d=`${s.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${n}_thumbnail`,c,d);}if(s.audioBuffer&&s.audioMimeType){let l=new Blob([s.audioBuffer],{type:s.audioMimeType}),c=`${s.id}_audio.${Ro(s.audioMimeType)}`;o.append(`slide_${r}_video_${n}_audio`,l,c);}}),a.photoFrames.forEach((s,n)=>{if(s.buffer&&s.mimeType){let i=new Blob([s.buffer],{type:s.mimeType}),u=`${s.id}.${Ro(s.mimeType)}`;o.append(`slide_${r}_photoframe_${n}`,i,u);}if(s.audioBuffer&&s.audioMimeType){let i=new Blob([s.audioBuffer],{type:s.audioMimeType}),u=`${s.id}_audio.${Ro(s.audioMimeType)}`;o.append(`slide_${r}_photoframe_${n}_audio`,i,u);}});}),o};var hw=()=>{let e=yt();useEffect(()=>{(async()=>{try{let t=await Sl(),a=Cl();if(t&&t.length>0){let r=await Fu(),s=t.map(i=>{if(i.videos&&i.videos.length>0){let u=i.videos.map(l=>{let c=r.get(l.id);if(c){let d=Bu(c.blob);return {...l,objectUrl:d,thumbnailDataUrl:c.thumbnailDataUrl,videoBlob:c.blob}}else return l});return {...i,videos:u}}return i}),n=a&&s.find(i=>i.id===a)?a:s[0].id;e(Xa({slides:s,currentSlideId:n}));}}catch(t){console.error("Error loading persisted slides:",t);}})();},[e]);};var Lf=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||""})),Sf=new WeakSet,If=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 Ha(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},gw=()=>{let e=yt(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Sf.has(a))return;Sf.add(a);let{slides:r,currentSlideId:s,skipLocalPersistence:n=true}=a;if(n)try{await Ys(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(l){console.error("Error clearing local data:",l);}let i=s&&r.find(l=>l.id===s)?s:r[0].id,u=Lf(r);e(Xa({slides:u,currentSlideId:i})),await If(u);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:s,skipLocalPersistence:n=true}=a;if(n)try{await Ys(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(l){console.error("Error clearing local data:",l);}let i=s&&r.find(l=>l.id===s)?s:r[0].id,u=Lf(r);e(Xa({slides:u,currentSlideId:i})),await If(u);},[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:
|