@turnix-co/konva-editor 3.0.24 → 3.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ export{default as Konva}from'konva';import*as be from'react';import be__default,
3
3
  `).length,B=s.find(K=>K.id===n)?.fontSize||24,R=E*B*1.2+10;v.width=Math.max(200,g),v.height=Math.max(50,P,R);}else if(h&&i.trim()){let b=h.text(),L=h.width();h.text(i),h.width(void 0);let C=h.width(),M=h.height();h.text(b),h.width(L),v.width=Math.max(200,C+20),v.height=Math.max(50,M+20);}t(Mt(v)),c(null),d(""),t(er(null)),e();}}}};var Od=e=>{let o=useDispatch(),a=useSelector(he)?.shortAnswers||[],s=useRef(new Map),r=useCallback((n,c)=>{let i=n.target;o($o({id:c,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:s,handleShortAnswerDragEnd:r}};var Nd=e=>{let o=useDispatch(),t=useSelector(he),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),s=useCallback((r,n)=>{let c=r.target;o(Yo({id:n,x:c.x(),y:c.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:s}};var qd=e=>{let o=xe(),a=te(he)?.flashcards||[],s=useRef(new Map),r=useRef(new Map),n=useCallback((f,l)=>{if(r.current.has(l))return r.current.get(l);let u=new window.Image;return u.src=f,r.current.set(l,u),u},[]),c=useCallback((f,l)=>{let u=f.target,p=u.id();a.find(h=>h.id===p)&&(o(fo({id:p,x:u.x(),y:u.y()})),l?.());},[a,o]),i=useCallback((f,l)=>{let u=l.target,p=u.scaleX(),y=u.scaleY(),h=u.rotation(),x=Math.max(50,u.width()*p),v=Math.max(50,u.height()*y);u.scaleX(1),u.scaleY(1),u.width(x),u.height(v),o(fo({id:f,width:x,height:v,x:u.x(),y:u.y(),rotation:h})),u.getLayer()?.batchDraw(),e?.();},[o,e]),d=useCallback(f=>{o($n(f)),e?.();},[o,e]),m=useCallback(f=>{o(Yn(f)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:s,handleDragEnd:c,handleFlashcardTransformEnd:i,handleNext:d,handlePrevious:m}};var zd=e=>{let o=xe(),a=te(he)?.photoFrames||[],s=useRef(new Map),[r,n]=useState(new Map),c=useCallback((u,p)=>{console.log("handleDragEnd"),o(Va({id:p,x:u.target.x(),y:u.target.y()})),e?.();},[o,e]),i=useCallback((u,p)=>{let y=p.target,h=y.scaleX(),x=y.scaleY(),v=y.rotation(),b=a.find(M=>M.id===u);if(!b)return;let L=Math.max(100,b.width*h),C=Math.max(100,b.height*x);y.scaleX(1),y.scaleY(1),o(Va({id:u,width:L,height:C,x:y.x(),y:y.y(),rotation:v})),y.getLayer()?.batchDraw(),e?.();},[o,e,a]),d=useCallback(async u=>{try{let p=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(y=>{let h=new Map(y);return h.set(u,p),h}),o(Va({id:u,isCapturing:!0})),e?.(),p}catch(p){return console.error("Error accessing camera:",p),null}},[o,e]),m=useCallback(u=>{let p=r.get(u);p&&(p.getTracks().forEach(y=>y.stop()),n(y=>{let h=new Map(y);return h.delete(u),h}),o(Va({id:u,isCapturing:false})),e?.());},[r,o,e]),f=useCallback((u,p)=>{let y=document.createElement("canvas");y.width=p.videoWidth,y.height=p.videoHeight;let h=y.getContext("2d");if(h){h.drawImage(p,0,0,y.width,y.height);let x=y.toDataURL("image/jpeg",.8);return o(Va({id:u,capturedImageUrl:x,isCapturing:false})),m(u),e?.(),x}return null},[o,m,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(u=>{u.getTracks().forEach(p=>p.stop());});},[]),{photoFrames:a,photoFrameRefs:s,handleDragEnd:c,handlePhotoFrameTransformEnd:i,startCamera:d,stopCamera:m,capturePhoto:f,cameraStreams:r}};var Wd=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),a=useCallback((r,n,c,i,d,m,f,l=[])=>{if(e.current){if(r&&!l.find(y=>y.id===r)?.isPlaying){let y=n.get(r)||c.get(r)||i.get(r)||d.get(r)||m.get(r)||(f?f.get(r):null);if(y){e.current.boundBoxFunc(t),e.current.nodes([y]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),s=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:s,boundBoxFunc:t}};var Dp=(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])},jd=(e,o)=>{let t=st(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let s=useCallback(()=>{if(o.current)try{let n=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});n&&n.startsWith("data:")&&t(zn({id:a.current,thumbnail:n}));}catch(n){console.warn("Could not generate thumbnail (likely CORS issue with images):",n);}},[o,t]),r=Dp(s,500);return {generateThumbnail:s,debouncedGenerateThumbnail:r}};var Ep=e=>e.flatMap(o=>[o[0],o[1]]),Ps=(e,o)=>{let t=Sd(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:a=>a,start:{taper:0,cap:true},end:{taper:0,cap:true}});return Ep(t)};var Xd=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null),c=te(b=>b.toolbar.selectedTool),i=te(b=>b.toolbar.penColor),d=te(b=>b.toolbar.strokeWidth),m=te(b=>b.canvas.isSketchMode),f=te(b=>b.canvas.slides.find(C=>C.id===b.canvas.currentSlideId)?.images.find(C=>C.id===e)),l=f?.annotations||[],u=f?.isDrawingMode||false,p=f?.width||1,y=f?.height||1,h=useCallback(b=>{if(c!=="pen"&&c!=="eraser")return;t.current=true,a.current=false,s.current=[{x:b.x,y:b.y}];let L=b.x/p,C=b.y/y;n({tool:c,points:[L,C],color:i,strokeWidth:d/p,isSketch:m});},[c,i,d,m,p,y]),x=useCallback(b=>{if(!t.current||!r)return;a.current=true;let L=s.current[s.current.length-1];if(Math.sqrt(Math.pow(b.x-L.x,2)+Math.pow(b.y-L.y,2))<2)return;s.current.push({x:b.x,y:b.y});let M;if(m)M=Ps(s.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((g,P)=>P%2===0?g/p:g/y);else {let k=b.x/p,g=b.y/y;M=[...r.points,k,g];}n(k=>k?{...k,points:M}:null);},[m,d,r,p,y]),v=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(Qn({imageId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:u,startDrawing:h,draw:x,stopDrawing:v,tool:c}};var Zd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>{let{annotations:c,activeLine:i,stopDrawing:l,tool:u}=Xd(e.id);useEffect(()=>{let v=t.current.get(e.id);v&&(v.width()!==e.width||v.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:v.width(),konvaHeight:v.height()}),v.width(e.width),v.height(e.height),v.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[l,p]);let y=v=>{{r(e.id);return}},h=v=>{return;},x=v=>{};return jsxs(Group,{listening:u!=="pen"&&u!=="eraser",children:[jsx(Image$1,{id:e.id,ref:v=>{if(v){t.current.set(e.id,v),v.width(e.width),v.height(e.height),v.getLayer()?.batchDraw();let b=v.getStage()?.container();if(b){let L=C=>{let M=v.getStage()?.getPointerPosition();if(M){let k={x:e.x,y:e.y,width:e.width,height:e.height};M.x>=k.x&&M.x<=k.x+k.width&&M.y>=k.y&&M.y<=k.y+k.height&&n(C,e.id,"image");}};b.addEventListener("contextmenu",L),v._contextMenuCleanup=()=>{b.removeEventListener("contextmenu",L);};}}else {let b=t.current.get(e.id);b?._contextMenuCleanup&&b._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:u!=="pen"&&u!=="eraser",onDragEnd:a,onTransformEnd:v=>s(e.id,v),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...u!=="pen"&&u!=="eraser"?{onClick:y,onTap:y,onMouseDown:y,onTouchStart:y,onMouseMove:h,onTouchMove:h,onMouseUp:x,onTouchEnd:x}:{}}),c?.map((v,b)=>{let L=v.points.map((M,k)=>k%2===0?M*e.width+e.x:M*e.height+e.y),C=v.strokeWidth*e.width;return jsx(Line,{points:L,stroke:v.tool==="eraser"?"white":v.color,strokeWidth:C,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:v.tool==="eraser"?"destination-out":"source-over",fill:v.isSketch?v.color:void 0,closed:v.isSketch,listening:false},b)}),i&&jsx(Line,{points:i.points.map((v,b)=>b%2===0?v*e.width+e.x:v*e.height+e.y),stroke:i.tool==="eraser"?"white":i.color,strokeWidth:i.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:i.tool==="eraser"?"destination-out":"source-over",fill:i.isSketch?i.color:void 0,closed:i.isSketch,listening:false},"active")]})});Zd.displayName="ImageWithDrawing";var Ti=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(c=>{let i=o(c);return i?jsx(Zd,{img:c,loadedImage:i,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n},c.id):null})}));Ti.displayName="ImageLayer";var Wp=({src:e,x:o,id:t,y:a,width:s,height:r,isSelected:n,rotation:c=0,onTransformEnd:i,onDragEnd:d})=>{let m=xe(),f=useRef(null),l=u=>{m(Na(u));};return jsxs(Group,{draggable:true,x:o,y:a,width:s,height:r,rotation:c,onDragEnd:d,onTransformEnd:i,children:[jsx(Rect,{width:s,height:r,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${s}px`,height:`${r}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:f,src:e,controls:true,autoPlay:true,onClick:()=>l(t),onSeeking:u=>u.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Qd=Wp;var Jp=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,nodeRef:n})=>{let[c,i]=useState(null),d=useSelector(y=>y.toolbar.selectedTool),m=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let y=new window.Image;y.src=e.thumbnailDataUrl,y.onload=()=>{i(y);};}},[e.thumbnailDataUrl]),!c)return null;let f=e.width/2,l=e.height/2,u=Math.min(e.width,e.height)*.08,p=Math.max(40,Math.min(u,80));return jsxs(Group,{draggable:!m,listening:!m,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...m?{}:{onDragEnd:a,onTransformEnd:s},ref:y=>{if(n(y),y){let h=y.getStage()?.container();if(h){let x=v=>{let b=y.getStage()?.getPointerPosition();if(b){let L={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=L.x&&b.x<=L.x+L.width&&b.y>=L.y&&b.y<=L.y+L.height&&r(v);}};h.addEventListener("contextmenu",x),y._contextMenuCleanup=()=>{h.removeEventListener("contextmenu",x);};}}},children:[jsx(Image$1,{image:c,width:e.width,height:e.height,listening:!m,...m?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:f,y:l,radius:p,fill:"white",listening:!m,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...m?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:f,y:l,radius:p*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!m,...m?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:f+p*.1,y:l,sides:3,radius:p*.35,fill:"white",rotation:90,listening:!m,...m?{}:{onClick:t,onTap:t}})]})},tu=Jp;var Di=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:s,onTransformEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(c=>jsxs(be__default.Fragment,{children:[jsx(tu,{video:c,isSelected:!c.isPlaying&&o===c.id,onClick:()=>a(c.id),onDragEnd:i=>s(c.id,i),onTransformEnd:i=>r(c.id,i),onContextMenu:i=>n(i,c.id,"video"),nodeRef:i=>{i?t.current.set(c.id,i):t.current.delete(c.id);}}),c.isPlaying&&!c.isRecorded&&jsx(Qd,{id:c.id,src:c.objectUrl,x:c.x,y:c.y,width:c.width,height:c.height,isSelected:false,rotation:c.rotation,onTransformEnd:i=>r(c.id,i),onDragEnd:i=>s(c.id,i)})]},c.id))}));Di.displayName="VideoLayer";var Ri=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:s,handleShapeDragStart:r,onContextMenu:n})=>{let c=useSelector(d=>d.toolbar.selectedTool),i=c==="pen"||c==="eraser";return jsx(Fragment,{children:e.map((d,m)=>{let f=d.id||m,l={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!i,listening:!i,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},radius:d.radius||d.width/2,width:d.width,height:d.width},f);case "star":return jsx(Star,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},sides:3,radius:d.radius||d.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},sides:d.sides||6,radius:d.radius||d.width/2},f);case "ellipse":return jsx(Ellipse,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},f);case "ring":return jsx(Ring,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "wedge":return jsx(Wedge,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},radius:d.radius||d.width/2,angle:d.angle||60},f);case "arrow":return jsx(Arrow,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "line":return jsx(Line,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},f)}})})});Ri.displayName="ShapeLayer";var ru=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:s,onContextMenu:r,onDoubleClick:n,editingTextId:c})=>{let i=useSelector(m=>m.toolbar.selectedTool),d=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map(m=>{let f=m.id===c,l=m.fontWeight==="bold",u=l?Math.max(1,m.fontSize/25):0;return jsx(Text,{id:m.id,ref:p=>{p?o.current.set(m.id,p):o.current.delete(m.id);},text:m.text,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:!m.locked&&!f&&!d,listening:!d,fontSize:m.fontSize,fontFamily:m.fontFamily,fontStyle:m.fontStyle,fontWeight:m.fontWeight,textDecoration:m.textDecoration,fill:m.fill,stroke:l?m.fill:void 0,strokeWidth:u,align:m.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...d?{}:{onClick:()=>s(m.id),onTap:()=>s(m.id),onDblClick:()=>n(m.id),onDblTap:()=>n(m.id),onDragEnd:p=>t(p,m.id),onTransformEnd:()=>a(m.id),onContextMenu:p=>{p.evt.preventDefault();let y=p.evt;r(y,m.id,"text");}}},m.id)})})};var Lh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onNext:n,onPrevious:c,nodeRef:i})=>{let[d,m]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let h=new window.Image;h.src=e.images[e.currentIndex],h.onload=()=>{m(h);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let f=8,l=2,u=Math.min(e.width,e.height)*.08,p=Math.max(16,Math.min(u,32)),y=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:s,ref:h=>{if(i(h),h){let x=h.getStage()?.container();if(x){let v=b=>{let L=h.getStage()?.getPointerPosition();if(L){let C={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=C.x&&L.x<=C.x+C.width&&L.y>=C.y&&L.y<=C.y+C.height&&r(b);}};x.addEventListener("contextmenu",v),h._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",v);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,stroke:"#E5E7EB",strokeWidth:l,listening:false}),jsx(Image$1,{x:l+4,y:l+4,image:d,width:e.width-(l+4)*2,height:e.height-(l+4)*2,cornerRadius:f-l,onClick:t,onTap:t}),jsx(Rect,{x:l,y:e.height-50,width:e.width-l*2,height:50,cornerRadius:[0,0,f-l,f-l],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:y+p,y:e.height/2,onClick:h=>{h.cancelBubble=true,c();},onTap:h=>{h.cancelBubble=true,c();},children:[jsx(Circle,{radius:p,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-y-p,y:e.height/2,onClick:h=>{h.cancelBubble=true,n();},onTap:h=>{h.cancelBubble=true,n();},children:[jsx(Circle,{radius:p,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"})]})},iu=Lh;var Bi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onNext:n,onPrevious:c,onContextMenu:i})=>jsx(Fragment,{children:e.map(d=>jsx(iu,{flashcard:d,isSelected:t===d.id,onClick:()=>r(d.id),onDragEnd:a,onTransformEnd:m=>s(d.id,m),onContextMenu:m=>i(m,d.id,"flashcard"),onNext:()=>n(d.id),onPrevious:()=>c(d.id),nodeRef:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);}},d.id))}));Bi.displayName="FlashcardLayer";var du=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null);te(b=>b.toolbar.selectedTool);let i=te(b=>b.toolbar.penColor),d=te(b=>b.toolbar.strokeWidth),m=te(b=>b.canvas.isSketchMode),f=te(b=>b.canvas.slides.find(C=>C.id===b.canvas.currentSlideId)?.photoFrames.find(C=>C.id===e)),l=f?.annotations||[],u=f?.isDrawingMode||false,p=f?.width||1,y=f?.height||1,h=useCallback(b=>{if(!u)return;t.current=true,a.current=false,s.current=[{x:b.x,y:b.y}];let L=b.x/p,C=b.y/y;n({tool:"pen",points:[L,C],color:i,strokeWidth:d/p,isSketch:m});},[u,i,d,m,p,y]),x=useCallback(b=>{if(!t.current||!r)return;a.current=true;let L=s.current[s.current.length-1];if(Math.sqrt(Math.pow(b.x-L.x,2)+Math.pow(b.y-L.y,2))<2)return;s.current.push({x:b.x,y:b.y});let M;if(m)M=Ps(s.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((g,P)=>P%2===0?g/p:g/y);else {let k=b.x/p,g=b.y/y;M=[...r.points,k,g];}n(k=>k?{...k,points:M}:null);},[m,d,r,p,y]),v=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(ti({frameId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:u,startDrawing:h,draw:x,stopDrawing:v}};var Ph=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onStartCamera:n,onCapture:c,cameraStream:i,nodeRef:d})=>{let[m,f]=useState(null),[l,u]=useState(null),p=useRef(null),y=useRef(null),h=useRef(null),x=useRef(null),v=useRef(0),b=33,L=useSelector(q=>q.toolbar.selectedTool),C=L==="pen"||L==="eraser",{annotations:M,activeLine:k,isDrawingMode:g,startDrawing:P,draw:E,stopDrawing:I}=du(e.id);useEffect(()=>{if(!g)return;let q=()=>{I();},Y=()=>{I();};return window.addEventListener("mouseup",q),window.addEventListener("touchend",Y),()=>{window.removeEventListener("mouseup",q),window.removeEventListener("touchend",Y);}},[I,g]),useEffect(()=>{if(e.capturedImageUrl){let q=new window.Image;q.src=e.capturedImageUrl,q.onload=()=>{f(q);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),y.current||(y.current=document.createElement("canvas"));let q=p.current,Y=y.current;q.srcObject=i;let H=()=>{Y.width=q.videoWidth||640,Y.height=q.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",Y.width,Y.height);let U=J=>{if(J-v.current<b){h.current=requestAnimationFrame(U);return}v.current=J;let ee=Y.getContext("2d");if(ee&&q.readyState===q.HAVE_ENOUGH_DATA){ee.drawImage(q,0,0,Y.width,Y.height);let j=Y.toDataURL("image/jpeg",.6),ue=new window.Image;ue.onload=()=>{u(ue);},ue.src=j;}h.current=requestAnimationFrame(U);};h.current=requestAnimationFrame(U);};return q.onloadedmetadata=H,q.readyState>=q.HAVE_METADATA&&H(),q.play().catch(U=>console.error("Error playing video:",U)),()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null);}}return ()=>{u(null),x.current&&(x.current.src="");}},[e.isCapturing,i]);let B=()=>{p.current&&e.isCapturing&&c(p.current);},G=q=>{if(e.capturedImageUrl){if(!g){t();return}let Y=q.currentTarget,H=Y.getAbsoluteTransform().copy(),J=Y.getStage()?.getPointerPosition();if(J){H.invert();let ee=H.point(J);P(ee);}q.cancelBubble=true;}else t();},R=q=>{if(!g||!e.capturedImageUrl)return;let Y=q.currentTarget,H=Y.getAbsoluteTransform().copy(),J=Y.getStage()?.getPointerPosition();if(J){H.invert();let ee=H.point(J);E(ee);}},K=()=>{!g||!e.capturedImageUrl||I();},D=e.isCapturing?l:m,Q=Math.min(e.width,e.height)*.12,V=Math.max(25,Math.min(Q,50)),ae=e.width/2,W=e.height/2;return jsxs(Group,{id:e.id,draggable:!g&&!C,listening:true,x:e.x,y:e.y,...C?{}:{onDragEnd:a,onTransformEnd:s},rotation:e.rotation,width:e.width,height:e.height,ref:q=>{if(d(q),q){let Y=q.getStage()?.container();if(Y){let H=U=>{let J=q.getStage()?.getPointerPosition();if(J){let ee={x:e.x,y:e.y,width:e.width,height:e.height};J.x>=ee.x&&J.x<=ee.x+ee.width&&J.y>=ee.y&&J.y<=ee.y+ee.height&&r(U);}};Y.addEventListener("contextmenu",H),q._contextMenuCleanup=()=>{Y.removeEventListener("contextmenu",H);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:D?"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}}),D&&jsx(Image$1,{image:D,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:G,onTap:G,onMouseDown:G,onTouchStart:G,onMouseMove:R,onTouchMove:R,onMouseUp:K,onTouchEnd:K,...C?{}:{onDragEnd:a,onTransformEnd:s}}),M?.map((q,Y)=>{let H=q.points.map((J,ee)=>ee%2===0?J*e.width:J*e.height),U=q.strokeWidth*e.width;return jsx(Line,{points:H,stroke:q.tool==="eraser"?"white":q.color,strokeWidth:U,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:q.tool==="eraser"?"destination-out":"source-over",fill:q.isSketch?q.color:void 0,closed:q.isSketch,listening:false},Y)}),k&&jsx(Line,{points:k.points.map((q,Y)=>Y%2===0?q*e.width:q*e.height),stroke:k.tool==="eraser"?"white":k.color,strokeWidth:k.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:k.tool==="eraser"?"destination-out":"source-over",fill:k.isSketch?k.color:void 0,closed:k.isSketch,listening:false},"active"),!D&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:W-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:ae-V+6,y:W-60,width:V*1.6,height:V*1.6,radius:V,fill:"white",cornerRadius:8,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?B():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?B():n();}}),jsx(Html,{groupProps:{x:ae-12,y:W-40,width:V*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?B():n();}})})]}),jsx(Text,{x:0,y:W,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:W+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:ae-24,y:W+104,width:V*1.6,height:V*1.6,radius:V,fill:"#096B76",cornerRadius:V,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?B():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?B():n();}}),jsx(Html,{groupProps:{x:ae-8,y:W+120,width:V*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?B():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:ae-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:q=>{q.stopPropagation(),B();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},mu=Ph;var Ui=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onStartCamera:n,onCapture:c,cameraStreams:i,onContextMenu:d})=>jsx(Fragment,{children:e.map(m=>jsx(mu,{photoFrame:m,isSelected:t===m.id,onClick:()=>r(m.id),onDragEnd:f=>a(f,m.id),onTransformEnd:f=>s(m.id,f),onContextMenu:f=>d(f,m.id,"photoFrame"),onStartCamera:()=>n(m.id),onCapture:f=>c(m.id,f),cameraStream:i.get(m.id),nodeRef:f=>{f?o.current.set(m.id,f):o.current.delete(m.id);}},m.id))}));Ui.displayName="PhotoFrameLayer";var xu=({x:e,y:o,onAction:t,onClose:a,type:s,elementId:r="",isDrawingMode:n,menuRef:c})=>{useEffect(()=>{let f=u=>{c?.current&&!c.current.contains(u.target)&&a();},l=u=>{u.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",l);}},[a]);let i=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:n?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(l=>!(l.showForTypes&&!l.showForTypes.includes(s)||l.hideForTypes&&l.hideForTypes.includes(s))),[s,n]),d=(f,l)=>{f==="order"||f==="lock"?t(f,l):(t(f),a());},m=jsx("div",{ref:c,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:i.map((f,l)=>jsxs("button",{onClick:u=>d(f.action,u),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${f.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[f.icon,jsx("span",{className:`font-medium ${f.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:f.label})]}),f.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},l))})});return createPortal(m,document.body)};var bu=({x:e,y:o,items:t,onClose:a})=>{let s=useRef(null);return useEffect(()=>{let r=n=>{s.current&&!s.current.contains(n.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:s,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((r,n)=>jsx("button",{onClick:()=>{r.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:r.label})},n))})})};var yu=createContext(null),zi=()=>useContext(yu);function ag({children:e,className:o="",style:t}){let a=useRef(null),[s,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(yu.Provider,{value:s,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function ze(){let e=zi();return typeof document>"u"?null:e||document.body}var wu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:s,onClose:r})=>{let[n,c]=useState(a),i=useRef(null),d=ze();useEffect(()=>{i.current?.focus();},[]);let m=()=>{s(n),r();},f=u=>{u.key==="Enter"?m():u.key==="Escape"&&r();};return d?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:i,type:"text",value:n,onChange:u=>c(u.target.value),onKeyDown:f,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:r,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:m,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),d):null};var Os=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,s]=useState(e),r=useRef(null),n=ze();useEffect(()=>{let f=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let c=f=>{f.preventDefault(),o(a);},i=(f,l,u)=>{u/=100;let p=l*Math.min(u,1-u)/100,y=h=>{let x=(h+f/30)%12,v=u-p*Math.max(Math.min(x-3,9-x,1),-1);return Math.round(255*v).toString(16).padStart(2,"0")};return `#${y(0)}${y(8)}${y(4)}`},d=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!n)return null;let m=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:r,className:"max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:c,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:f=>s(f.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:f=>s(f.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:f=>{let l=parseInt(f.target.value),u=i(l,100,50);s(u);},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:d.map(f=>jsx("button",{type:"button",onClick:()=>s(f),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===f.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:f},title:f},f))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(m,n)};var wg=({imageSrc:e,onCrop:o})=>{let[t]=Iu(e),a=useRef(null),s=useRef(null),r=useRef(null),n=useMemo(()=>{if(!t)return {width:600,height:400};let p=Math.min(600/t.width,400/t.height);return {width:t.width*p,height:t.height*p}},[t]),c=useMemo(()=>{let l=n.width*.5,u=n.height*.5,p=(n.width-l)/2,y=(n.height-u)/2;return {x:p,y,width:l,height:u}},[n]),[i,d]=useState(c);useEffect(()=>{d(c);},[c]),useEffect(()=>{r.current&&s.current&&(r.current.nodes([s.current]),r.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let m=()=>{let l=s.current;if(!l)return;let u=l.scaleX(),p=l.scaleY();l.scaleX(1),l.scaleY(1),d({x:l.x(),y:l.y(),width:Math.max(20,l.width()*u),height:Math.max(20,l.height()*p)});},f=()=>{let l=s.current;l&&d({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:s,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:f,onTransformEnd:m,dragBoundFunc:l=>{let u=Math.max(0,Math.min(l.x,n.width-i.width)),p=Math.max(0,Math.min(l.y,n.height-i.height));return {x:u,y:p}}}),jsx(Transformer,{ref:r,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(l,u)=>u.width<20||u.height<20||u.x<0||u.y<0||u.x+u.width>n.width||u.y+u.height>n.height?l:u})]})})},Cu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[s,r]=useState({x:0,y:0,width:0,height:0}),[n]=Iu(e),c=ze();useEffect(()=>{let f=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let i=(f,l,u,p)=>{r({x:f,y:l,width:u,height:p});},d=()=>{if(!n)return;let u=Math.min(600/n.width,400/n.height),p=s.x/u,y=s.y/u,h=s.width/u,x=s.height/u,v=document.createElement("canvas");v.width=h,v.height=x;let b=v.getContext("2d");if(!b)return;b.drawImage(n,p,y,h,x,0,0,h,x);let L=v.toDataURL("image/png");o(L);};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(wg,{imageSrc:e,onCrop:i})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:d,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"]})]})]})}),c):null};var dr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let s=ze(),[r,n]=useState(false),[c,i]=useState(null),[d,m]=useState(0),[f,l]=useState(true),u=useRef(null),p=useRef([]),y=useRef(null),h=useRef(null),x=useRef(null),v=useRef(null),b=useRef(null),L=useRef(null);useEffect(()=>()=>{x.current&&cancelAnimationFrame(x.current),y.current&&clearInterval(y.current),h.current&&h.current.getTracks().forEach(E=>E.stop());},[]);let C=async()=>{try{let E,I=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let D=o.current.getLayers();console.log("Konva layers:",D.length),D.forEach((U,J)=>{let ee=U.getChildren();console.log(`Layer ${J} children count:`,ee.length);});let Q=document.createElement("canvas");Q.width=o.current.width(),Q.height=o.current.height();let V=Q.getContext("2d",{willReadFrequently:!1});if(!V){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",Q.width,"x",Q.height),b.current=Q;let ae=()=>{if(V.clearRect(0,0,Q.width,Q.height),D.forEach(U=>{let J=U.getCanvas()._canvas;J&&V.drawImage(J,0,0);}),a?.current){let U=a.current;V.drawImage(U,0,0);}};L.current=ae,o.current.draw(),ae(),await new Promise(U=>setTimeout(U,100)),console.log("Creating captureStream..."),E=Q.captureStream(30),console.log("Canvas stream created, tracks:",E.getTracks().length);let q=E.getVideoTracks()[0];q&&console.log("Video track:",q.label,"state:",q.readyState);let Y=0,H=()=>{ae(),o?.current&&(o.current.getLayers().forEach(J=>{J.batchDraw();}),Y++,Y%60===0&&console.log("Drawing frame:",Y)),x.current=requestAnimationFrame(H);};H();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{I=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(D){console.warn("Microphone access denied:",D);}let B=[...E.getVideoTracks()];I&&B.push(...I.getAudioTracks());let G=new MediaStream(B);h.current=G;let R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8"),console.log("Using mimeType:",R);let K=new MediaRecorder(G,{mimeType:R,videoBitsPerSecond:25e5});u.current=K,p.current=[],K.ondataavailable=D=>{console.log("Data available, size:",D.data.size),D.data.size>0&&p.current.push(D.data);},K.onstop=()=>{console.log("Recording stopped, chunks:",p.current.length);let D=new Blob(p.current,{type:R});console.log("Final blob size:",D.size),o?.current&&L.current&&b.current&&(o.current.draw(),o.current.getLayers().forEach(V=>{V.batchDraw();}),L.current(),v.current=b.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",v.current.length)),G.getTracks().forEach(Q=>Q.stop()),y.current&&clearInterval(y.current),x.current&&(cancelAnimationFrame(x.current),x.current=null),i(D);},K.onerror=D=>{console.error("MediaRecorder error:",D);},console.log("Starting recording..."),K.start(1e3),n(!0),m(0),y.current=setInterval(()=>{m(D=>D+1);},1e3);}catch(E){console.error("Error starting screen recording:",E),alert("Failed to start recording. Please ensure you granted permission.");}},M=()=>{u.current&&r&&(console.log("Stopping recording, state:",u.current.state),u.current.state!=="inactive"&&(u.current.requestData(),setTimeout(()=>{u.current&&u.current.state!=="inactive"&&u.current.stop();},100)),n(false));},k=()=>{if(c){let E=URL.createObjectURL(c),I=document.createElement("a");I.href=E,I.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(I),I.click(),document.body.removeChild(I),URL.revokeObjectURL(E);}},g=E=>{let I=Math.floor(E/60),B=E%60;return `${I.toString().padStart(2,"0")}:${B.toString().padStart(2,"0")}`};if(!s)return null;if(r){let E=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:g(d)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:M,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(E,s)}let P=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!c&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>l(!f),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${f?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:f?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:C,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"]})]})]}),c&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(c),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",g(d)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&c&&v.current&&(t(c,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:k,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),m(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})});return createPortal(P,s)};var Au=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:s})=>{let r=ze(),[n,c]=useState(false),[i,d]=useState(null),[m,f]=useState(false),[l,u]=useState(0),p=useRef(null),y=useRef([]),h=useRef(null),x=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(E=>E.blob()).then(E=>d(E)).catch(E=>console.error("Error loading audio:",E));},[o,i]);let v=async()=>{try{let E=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),I=new MediaRecorder(E);p.current=I,y.current=[],I.ondataavailable=B=>{B.data.size>0&&y.current.push(B.data);},I.onstop=()=>{let B=new Blob(y.current,{type:"audio/webm"});d(B),E.getTracks().forEach(G=>G.stop()),h.current&&clearInterval(h.current);},I.start(),c(!0),u(0),h.current=setInterval(()=>{u(B=>B+1);},1e3);}catch(E){console.error("Error starting audio recording:",E),alert("Failed to start recording. Please allow microphone access.");}},b=()=>{p.current&&n&&(p.current.stop(),c(false));},L=()=>{if(i){let E=URL.createObjectURL(i),I=new Audio(E);x.current=I,I.onended=()=>{f(false),URL.revokeObjectURL(E);},I.play(),f(true);}},C=()=>{x.current&&(x.current.pause(),x.current.currentTime=0,f(false));},M=async()=>{if(i){let E=new FileReader;E.onloadend=()=>{let I=E.result;t(I),s();},E.readAsDataURL(i);}},k=()=>{d(null),a();},g=E=>{let I=Math.floor(E/60),B=E%60;return `${I.toString().padStart(2,"0")}:${B.toString().padStart(2,"0")}`};if(!r)return null;if(n){let E=jsx("div",{className:"pointer-events-none fixed inset-0 z-50",children:jsxs("div",{className:"pointer-events-auto fixed top-[100px] left-1/2 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:g(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:b,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]})});return createPortal(E,r)}let P=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick: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:m?C:L,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"}),m?"Playing...":"Play Audio"]}),jsx("button",{onClick:k,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:M,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:s,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})});return createPortal(P,r)};var At=({audioData:e,x:o,y:t,width:a,scale:s=1,offsetX:r=0,offsetY:n=0,containerTop:c=90,containerRight:i=320})=>{let[d,m]=useState(false),f=useRef(null),l=y=>{if(y.stopPropagation(),d&&f.current)f.current.pause(),f.current.currentTime=0,m(false);else {let h=new Audio(e);f.current=h,h.onended=()=>{m(false);},h.onerror=()=>{console.error("Error playing audio"),m(false);},h.play(),m(true);}},u=(o+a)*s+r-15,p=t*s+n+c-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${d?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${u}px`,top:`${p}px`,width:"30px",height:"30px",zIndex:99},title:d?"Stop Audio":"Play Audio",children:d?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var Ru=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),s=te(he),r=useMemo(()=>{if(!s)return [];let h=[];return s.images?.forEach(x=>{h.push({id:x.id,type:"image",name:"Image",timestamp:x.timestamp||0});}),s.videos?.forEach(x=>{h.push({id:x.id,type:"video",name:"Video",timestamp:x.timestamp||0});}),s.shapes?.forEach(x=>{h.push({id:x.id,type:"shape",name:`${x.type} Shape`,timestamp:x.timestamp||0});}),s.texts?.forEach(x=>{h.push({id:x.id,type:"text",name:x.text.substring(0,20)+(x.text.length>20?"...":""),timestamp:x.timestamp||0});}),s.flashcards?.forEach(x=>{h.push({id:x.id,type:"flashcard",name:`Flashcard (${x.images.length} images)`,timestamp:x.timestamp||0});}),s.photoFrames?.forEach(x=>{h.push({id:x.id,type:"photoFrame",name:"Photo Frame",timestamp:x.timestamp||0});}),s.multipleChoices?.forEach(x=>{h.push({id:x.id,type:"mcq",name:"Multiple Choice",timestamp:x.timestamp||0});}),s.trueFalses?.forEach(x=>{h.push({id:x.id,type:"trueFalse",name:"True/False",timestamp:x.timestamp||0});}),s.shortAnswers?.forEach(x=>{h.push({id:x.id,type:"shortAnswer",name:"Short Answer",timestamp:x.timestamp||0});}),s.LongAnswer?.forEach(x=>{h.push({id:x.id,type:"longAnswer",name:"Long Answer",timestamp:x.timestamp||0});}),s.fillInTheBlanks?.forEach(x=>{h.push({id:x.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:x.timestamp||0});}),s.lines?.forEach(x=>{x.id&&h.push({id:x.id,type:"line",name:"Drawn Line",timestamp:x.timestamp||0});}),h.sort((x,v)=>v.timestamp-x.timestamp)},[s]),[n,c]=useState(r),[i,d]=useState(false);useEffect(()=>{i||c(r);},[r]);let m=h=>{let x="h-5 w-5";switch(h){case "image":return jsx(Image$3,{className:x});case "video":return jsx(VideoCamera,{className:x});case "shape":return jsx(Shapes$1,{className:x});case "text":return jsx(TextT,{className:x});case "flashcard":return jsx(Cards$1,{className:x});case "photoFrame":return jsx(FrameCorners,{className:x});case "line":return jsx(Pen,{className:x});default:return jsx(Question,{className:x})}},u=h=>{d(true),c(h);},p=()=>{d(false);let h=Date.now();n.forEach((x,v)=>{let b=h-v;a(Qo({id:x.id,type:x.type,newTimestamp:b}));});},y=jsxs("div",{className:"konva-editor-root",children:[jsx("div",{className:"fixed inset-0 z-9999 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-10000 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$2,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",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:u,className:"space-y-1",children:n.map(h=>{let x=h.id===e;return jsxs(Reorder.Item,{value:h,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${x?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(h.id,h.type),className:`font-medium ${x?"text-[#096B76]":"text-[#00000099]"}`,children:h.name})}),jsx("div",{className:`${x?"text-[#096B76]":"text-[#00000099]"}`,children:m(h.type)})]},h.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[n.length," Layers"]})]})]})]});return createPortal(y,document.body)};var Eu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>{let n=useSelector(W=>W.toolbar.selectedTool),c=n==="pen"||n==="eraser",[i,d]=useState(new Set),[m,f]=useState(false),[l,u]=useState(null),p=useRef(null);useEffect(()=>{let W=p.current;if(W)return a.current.set(e.id,W),()=>{a.current.delete(e.id);}},[e.id]);let y=new Set(e.data.responseOptions.correctIndex),h=y.size>1,x=W=>{m||d(h?q=>{let Y=new Set(q);return Y.has(W)?Y.delete(W):Y.add(W),Y}:new Set([W]));},v=()=>{i.size>0&&f(true);},b=()=>{f(false),d(new Set);},L=i.size===y.size&&Array.from(i).every(W=>y.has(W)),C=Array.from(i).filter(W=>y.has(W)),M=h&&C.length>0&&!L,k=()=>L?"\u2713 Correct! Great job! \u{1F389}":M?`\u26A0 Partially correct (${C.length}/${y.size})`:"\u2717 Try again!",g=()=>L?{bg:"#dcfce7",text:"#166534"}:M?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},P=55,E=8,I=24,B=60,G=60,R=h&&!m?25:0,K=e.data.feedbackMode==="practice"?48:0,D=12,Q=B+R+(m?G:0),V=e.data.responseOptions.options.length*(P+E),ae=Q+V+D+K+I;return jsxs(Group,{ref:p,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:s,onClick:W=>t(e.id),onTap:W=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:ae,width:e.width,onTransformEnd:W=>o(e.id,W),onContextMenu:W=>{W.cancelBubble=true,r(W.evt,e.id,"mcq");}}),jsx(Text,{x:I+8,y:I,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-I*2,listening:false}),h&&!m&&e.data.feedbackMode==="practice"?jsx(Text,{x:I,y:I+35,text:`Select ${y.size} answers (${i.size}/${y.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-I*2,listening:false}):null,m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:I+24,y:B+R,width:e.width-I*2-40,height:G-20,fill:g().bg,cornerRadius:8}),jsx(Text,{x:I,y:B+R,width:e.width-I*2,height:G-20,text:k(),fontSize:16,fontStyle:"bold",fill:g().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((W,q)=>{let Y=y.has(q),H=i.has(q),U=Q+q*(P+E),J="#e5e7eb",ee="#ffffff",j="#111827";return m&&Y?(J="#22c55e",ee="#dcfce7",j="#1B9D2C"):m&&H&&!Y?(J="#ef4444",ee="#fee2e2",j="#ef4444"):H&&(J="#096B76",ee="#ECFFF8",j="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:I+12,y:U+(P-20)/2,width:20,height:20,fill:H?"#096B76":"white",stroke:H?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:h?4:10,onClick:ue=>{ue.cancelBubble=true,x(q);},onTap:ue=>{ue.cancelBubble=true,x(q);}}),H&&jsx(Text,{x:I+12,y:U+(P-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:I+44,y:U,width:e.width-I*2-60,height:P,fill:ee,stroke:J,strokeWidth:2,cornerRadius:8,onClick:ue=>{ue.cancelBubble=true,x(q);},onTap:ue=>{ue.cancelBubble=true,x(q);}}),jsx(Text,{x:I+60,y:U,width:e.width-I*2-80,height:P,text:W,fontSize:16,fill:j,verticalAlign:"middle",listening:false})]},q)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:Q+e.data.responseOptions.options.length*(P+E)+12,children:[jsxs(Group,{onMouseDown:W=>{W.cancelBubble=true,u("check");},onMouseUp:W=>{W.cancelBubble=true,u(null),v();},onMouseLeave:W=>{W.cancelBubble=true,u(null);},onTouchStart:W=>{W.cancelBubble=true,u("check");},onTouchEnd:W=>{W.cancelBubble=true,u(null),v();},scaleX:l==="check"?.95:1,scaleY:l==="check"?.95:1,children:[jsx(Rect,{x:I+14,width:(e.width-I*2-24)/(m?2:1),height:48,fill:i.size===0||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.cancelBubble=true}),jsx(Text,{x:I+14,width:(e.width-I*2-24)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-I*2)/2+8,onMouseDown:()=>u("reset"),onMouseUp:()=>{u(null),b();},onMouseLeave:()=>u(null),onTouchStart:()=>u("reset"),onTouchEnd:()=>{u(null),b();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:I,width:(e.width-I*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.cancelBubble=true}),jsx(Text,{x:I,width:(e.width-I*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Eu.displayName="MultipleChoice";var Fu=Eu;var _i=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:s})=>{let r=useDispatch(),n=useSelector(H=>H.toolbar.selectedTool),c=n==="pen"||n==="eraser",[i,d]=useState(false),[m,f]=useState(new Set),[l,u]=useState(false),[p,y]=useState(false),[h,x]=useState(0),v=340,b=100,L=window.innerWidth*.4,C=window.innerHeight*.5,M=v+20,k=b+60,g=L-40,P=C-300,E=useRef(null);useEffect(()=>{let H=E.current;if(H)return s.current.set(e.id,H),()=>{s.current.delete(e.id);}},[e.id]);let I=H=>{r(fa({id:e.id,x:H.target.x(),y:H.target.y()}));},B=H=>{let U=H.target,J=U.x(),ee=U.y(),j=window.innerWidth*.2,ke=J+j>M&&J<M+g&&ee+50>k&&ee<k+P;d(ke);},G=(H,U)=>{let J=U.target,ee=J.x(),j=J.y(),ue=window.innerWidth*.2,Me=ee+ue>M&&ee<M+g&&j+50>k&&j<k+P;f(Me?Te=>new Set(Te).add(H):Te=>{let Ne=new Set(Te);return Ne.delete(H),Ne}),d(false);},R=()=>{u(true);},K=()=>{u(false),f(new Set),x(H=>H+1);},D=new Set(e.data.responseOptions.correctIndex),Q=m.size===D.size&&Array.from(m).every(H=>D.has(H)),V=Array.from(m).filter(H=>D.has(H)),ae=V.length>0&&!Q,W=()=>Q?"\u2713 Correct! Great job!":ae?`\u26A0 Partially correct (${V.length}/${D.size})`:"\u2717 Try again!",q=()=>Q?{bg:"#dcfce7",text:"#166534"}:ae?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},Y=()=>l?Q?"#4CAF50":ae?"#f59e0b":"#ef4444":i?"#4CAF50":"#075560";return jsxs(Group,{ref:E,name:"mcq-element",width:L,height:C,draggable:!c,listening:!c,...c?{}:{onClick:H=>a(e.id),onTap:H=>a(e.id),onContextMenu:H=>{H.evt.preventDefault(),o(H.evt,e.id,"mcq");}},children:[jsxs(Group,{x:v,y:b,rotation:e.rotation,onDragEnd:I,children:[jsx(Rect,{fill:"white",stroke:i?"#4CAF50":"#e5e7eb",strokeWidth:i?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?C-100:C-50,width:L,shadowColor:i?"#4CAF50":"transparent",shadowBlur:i?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:g,height:P,fill:"#EBF6F7",stroke:Y(),strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:P+18,width:g-5,height:60,fill:q().bg,cornerRadius:8}),jsx(Text,{x:20,y:P+20,width:g,height:60,text:W(),fontSize:18,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle"})]}),m.size===0&&!l&&jsx(Text,{x:20,y:60,width:g,height:P-60,text:D.size>1?`Drop ${D.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:l?C-200:C-160,children:[jsxs(Group,{onMouseDown:()=>{y(true),R();},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{y(true),R();},onTouchEnd:()=>y(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:g}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:g,height:40,align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{y:50,onMouseDown:K,onTouchStart:K,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:g}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:g,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((H,U)=>{let J=U%2,ee=Math.floor(U/2),j=window.innerWidth*.2,ue=50,ke=10,Me=m.has(U),Te=D.has(U),Ne=l&&Me,ct="transparent";return Ne?ct=Te?"#4CAF50":"#ef4444":Me&&(ct="#4CAF50"),jsxs(Group,{x:340+J*(j+ke),y:b+C-80+ee*(ue+ke),draggable:!l,onDragMove:B,onDragEnd:no=>G(U,no),opacity:l&&!Me?.5:1,children:[jsx(Rect,{width:j-20,height:ue,fill:"white",stroke:ct,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:j-20,height:ue,text:H,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${U}-${h}`)})]})};_i.displayName="MultipleChoiceDragAndDrop";var Bu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Fu,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:c=>s(c,n.id),onContextMenu:r},n.id):jsx(_i,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r},n.id))});var Ou=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(D=>D.toolbar.selectedTool),c=n==="pen"||n==="eraser",[i,d]=useState(null),[m,f]=useState(false),[l,u]=useState(null),p=useRef(null);useEffect(()=>{let D=p.current;if(D)return a.current.set(e.id,D),()=>{a.current.delete(e.id);}},[e.id]);let y=()=>{i!==null&&f(true);},h=()=>{f(false),d(null);},x=e.data.responseOptions.correctAnswer,v=i===x,b=D=>{m||d(D);},L=()=>v?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>v?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},M=70,k=12,g=24,P=60,E=60,I=e.data.feedbackMode==="practice"?48:0,B=12,G=P+(m?E:0),R=2*(M+k),K=G+R+B+I+g;return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:D=>r(D,e.id),onClick:D=>t(e.id),onTap:D=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:K-20,width:e.width,onTransformEnd:D=>o(e.id,D),onContextMenu:D=>{D.cancelBubble=true,s(D.evt,e.id,"trueFalse");}}),jsx(Text,{x:g,y:g,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-g*2,listening:false}),m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:g,y:P,width:e.width-g*2,height:E-10,fill:C().bg,cornerRadius:8}),jsx(Text,{x:g,y:P,width:e.width-g*2,height:E-10,text:L(),fontSize:16,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((D,Q)=>{let V=x===D.value,ae=i===D.value,W=(e.width-g*3)/2,q=g+Q*(W+g),Y=G,H=D.value===true,U=H?"#10b981":"#ef4444",J="#ffffff",ee="#ffffff",j="#e5e7eb";return m&&(V?(ee=H?"#f0fdf4":"#fef2f2",j=H?"#86efac":"#fecaca"):ae&&!V&&(ee="#fee2e2",j="#ef4444")),ae&&!m&&(j="#096B76",ee="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:q,y:Y,width:W,height:M+50,fill:ee,stroke:j,strokeWidth:2,cornerRadius:12,onClick:ue=>{ue.cancelBubble=true,b(D.value);},onTap:ue=>{ue.cancelBubble=true,b(D.value);}}),jsx(Circle,{x:q+W/2,y:Y+40,radius:28,fill:U,listening:false}),H?jsx(Text,{x:q+W/2-14,y:Y+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:J,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:q+W/2-14,y:Y+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:J,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:q,y:Y+85,width:W,height:30,text:D.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},D.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:G+2*(M+k),children:[jsxs(Group,{onMouseDown:D=>{D.cancelBubble=true,u("check");},onMouseUp:D=>{D.cancelBubble=true,u(null),y();},onMouseLeave:D=>{D.cancelBubble=true,u(null);},onTouchStart:D=>{D.cancelBubble=true,u("check");},onTouchEnd:D=>{D.cancelBubble=true,u(null),y();},scaleX:l==="check"?.95:1,scaleY:l==="check"?.95:1,children:[jsx(Rect,{x:g,width:(e.width-g*2-8)/(m?2:1),height:48,fill:i===null||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:D=>D.cancelBubble=true,onTap:D=>D.cancelBubble=true}),jsx(Text,{x:g,width:(e.width-g*2-8)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-g*2)/2+8,onMouseDown:()=>u("reset"),onMouseUp:()=>{u(null),h();},onMouseLeave:()=>u(null),onTouchStart:()=>u("reset"),onTouchEnd:()=>{u(null),h();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:g,width:(e.width-g*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:D=>D.cancelBubble=true,onTap:D=>D.cancelBubble=true}),jsx(Text,{x:g,width:(e.width-g*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ou.displayName="TrueFalse";var Nu=Ou;var vx="#FFFFFF",$i=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),s=useSelector(U=>U.toolbar.selectedTool),r=s==="pen"||s==="eraser",[n,c]=useState(false),[i,d]=useState(null),[m,f]=useState(false),[l,u]=useState(false),[p,y]=useState(0),[h,x]=useState(false),v=340,b=100,L=window.innerWidth*.4,C=window.innerHeight*.5,M=L-40,k=C-300,g=20,P=60,E=M,I=k,B=L*.2-40,G=50,R=useRef(null),K=U=>{a(ma({id:e.id,x:U.target.x(),y:U.target.y()}));},D=U=>{let J=U.target,ee=J.x(),j=J.y(),ue=Math.max(0,Math.min(ee+B,g+E)-Math.max(ee,g)),ke=Math.max(0,Math.min(j+G,P+I)-Math.max(j,P)),Me=ue*ke,Te=B*G;c(Me/Te>=.5);},Q=(U,J)=>{let ee=J.target,j=ee.x(),ue=ee.y(),ke=Math.max(0,Math.min(j+B,g+E)-Math.max(j,g)),Me=Math.max(0,Math.min(ue+G,P+I)-Math.max(ue,P)),Te=ke*Me,Ne=B*G;if(Te/Ne>=.5)d(U);else return;c(false);},V=()=>{f(true);},ae=()=>{f(false),d(null),y(U=>U+1);},W=e.data.responseOptions.correctAnswer,q=i===W,Y=()=>q?"\u2713 Correct! Great job!":"\u2717 Try again!",H=()=>q?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:R,name:"trueFalse-element",width:L,height:C,draggable:!r,listening:!r,...r?{}:{onContextMenu:U=>{U.evt.preventDefault(),o(U.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:v,y:b,rotation:e.rotation,onDragEnd:K,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:m?C:e.data.feedbackMode==="practice"?C-50:C-100,width:L,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:M,height:k,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:M,height:60,fill:H().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:M,height:60,text:Y(),fontSize:18,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle"})]}),i===null&&!m&&jsx(Text,{x:20,y:60,width:M,height:k-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:C-100,children:[jsxs(Group,{onMouseDown:()=>{i!==null&&(u(true),V());},onMouseUp:()=>u(false),onMouseLeave:()=>u(false),onTouchStart:()=>{i!==null&&(u(true),V());},onTouchEnd:()=>u(false),scaleX:l?.95:1,scaleY:l?.95:1,children:[jsx(Rect,{fill:i===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:M}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:M,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:ae,onTouchStart:ae,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:M}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:M,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((U,J)=>{let ee=window.innerWidth*.2,j=50,ue=10,ke=i===U.value,Me=W===U.value,Te=m&&ke,Ne="transparent";return Te?Ne=Me?"#4CAF50":"#ef4444":ke&&(Ne="#4CAF50"),jsxs(Group,{x:16+J*(ee+ue),y:b+C-300,draggable:!m,onDragMove:D,onDragEnd:ct=>Q(U.value,ct),opacity:m&&!ke?.5:1,children:[jsx(Rect,{width:ee-40,height:j,fill:"#075560",stroke:Ne,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:ee-40,height:j,text:U.label,fontSize:18,fontStyle:"bold",fill:vx,align:"center",verticalAlign:"middle",listening:false})]},`${U.value}-${p}`)})]})})};$i.displayName="TrueFalseDragAndDrop";var Vu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Nu,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s},n.id):jsx($i,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r},n.id))});var ba=new WeakMap,Mo=new WeakMap,hr={current:[]},Ji=false,pr=0,mr=new Set,zs=new Map;function qu(e){let o=Array.from(e).sort((t,a)=>t instanceof zt&&t.options.deps.includes(a)?1:a instanceof zt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(hr.current.includes(t))continue;hr.current.push(t),t.recompute();let a=Mo.get(t);if(a)for(let s of a){let r=ba.get(s);r&&qu(r);}}}function Lx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Sx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Ws(e){if(pr>0&&!zs.has(e)&&zs.set(e,e.prevState),mr.add(e),!(pr>0)&&!Ji)try{for(Ji=!0;mr.size>0;){let o=Array.from(mr);mr.clear();for(let t of o){let a=zs.get(t)??t.prevState;t.prevState=a,Lx(t);}for(let t of o){let a=ba.get(t);a&&(hr.current.push(t),qu(a));}for(let t of o){let a=ba.get(t);if(a)for(let s of a)Sx(s);}}}finally{Ji=false,hr.current=[],zs.clear();}}function xt(e){pr++;try{e();}finally{if(pr--,pr===0){let o=mr.values().next().value;o&&Ws(o);}}}function Hu(e){return typeof e=="function"}var Yt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var s,r;this.listeners.add(a);let n=(r=(s=this.options)==null?void 0:s.onSubscribe)==null?void 0:r.call(s,a,this);return ()=>{this.listeners.delete(a),n?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,s;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):Hu(o)?this.state=o(this.prevState):this.state=o,(s=(a=this.options)==null?void 0:a.onUpdate)==null||s.call(a),Ws(this);}};var zt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),s=new Array(t);for(let r=0;r<t;r++){let n=this.options.deps[r];a[r]=n.prevState,s[r]=n.state;}return this.lastSeenDepValues=s,{prevDepVals:a,currDepVals:s,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let s=this.getDepVals();this.state=this.options.fn(s),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let r of this.options.deps)r instanceof e&&r.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:s}=this.getDepVals();for(let r=0;r<s.length;r++)if(s[r]!==a[r]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,s;this.listeners.add(t);let r=(s=(a=this.options).onSubscribe)==null?void 0:s.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof Yt){let a=ba.get(t);a||(a=new Set,ba.set(t,a)),a.add(this);let s=Mo.get(this);s||(s=new Set,Mo.set(this,s)),s.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof Yt){let a=ba.get(t);a&&a.delete(this);let s=Mo.get(this);s&&s.delete(t);}}};function Ix(e){return typeof e=="function"}function Zi(e,...o){return Ix(e)?e(...o):e}function Uu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var va,it,at,gr,ya,Wa,ea,To,xr,Gs,br,Ao,Ga=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:s=1e3}){Re(this,va,true);Re(this,it);Re(this,at);Re(this,gr);Re(this,ya);Re(this,Wa);Re(this,ea);Re(this,To);Re(this,xr,0);Re(this,Gs,5);Re(this,br,()=>{this.debugLog("Connected to event bus"),Ie(this,Wa,true),this.debugLog("Emitting queued events",_(this,ya)),_(this,ya).forEach(o=>this.emitEventToBus(o)),Ie(this,ya,[]),this.stopConnectLoop(),_(this,at).call(this).removeEventListener("tanstack-connect-success",_(this,br));});Re(this,Ao,()=>{if(_(this,at).call(this).addEventListener("tanstack-connect-success",_(this,br)),_(this,xr)<_(this,Gs)){hd(this,xr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}_(this,at).call(this).removeEventListener("tanstack-connect",_(this,Ao)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Ie(this,it,o),Ie(this,va,a),Ie(this,at,this.getGlobalTarget),Ie(this,gr,t),this.debugLog(" Initializing event subscription for plugin",_(this,it)),Ie(this,ya,[]),Ie(this,Wa,false),Ie(this,ea,null),Ie(this,To,s);}startConnectLoop(){_(this,ea)!==null||_(this,Wa)||(this.debugLog(`Starting connect loop (every ${_(this,To)}ms)`),Ie(this,ea,setInterval(_(this,Ao),_(this,To))));}stopConnectLoop(){_(this,ea)!==null&&(clearInterval(_(this,ea)),Ie(this,ea,null),this.debugLog("Stopped connect loop"));}debugLog(...o){_(this,gr)&&console.log(`\u{1F334} [tanstack-devtools:${_(this,it)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return _(this,it)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});_(this,at).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{_(this,at).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!_(this,va)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!_(this,Wa)){this.debugLog("Bus not available, will be pushed as soon as connected"),_(this,ya).push({type:`${_(this,it)}:${o}`,payload:t,pluginId:_(this,it)}),typeof CustomEvent<"u"&&(_(this,Ao).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${_(this,it)}:${o}`,payload:t,pluginId:_(this,it)})}on(o,t){let a=`${_(this,it)}:${o}`;if(!_(this,va))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let s=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return _(this,at).call(this).addEventListener(a,s),this.debugLog("Registered event to bus",a),()=>{_(this,at).call(this).removeEventListener(a,s);}}onAll(o){if(!_(this,va))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;o(s);};return _(this,at).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,at).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!_(this,va))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;_(this,it)&&s.pluginId!==_(this,it)||o(s);};return _(this,at).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,at).call(this).removeEventListener("tanstack-devtools-global",t)}};va=new WeakMap,it=new WeakMap,at=new WeakMap,gr=new WeakMap,ya=new WeakMap,Wa=new WeakMap,ea=new WeakMap,To=new WeakMap,xr=new WeakMap,Gs=new WeakMap,br=new WeakMap,Ao=new WeakMap;var Qi=class extends Ga{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},zu=(e,o)=>{el.emit(e,o);},el=new Qi;function Wu(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Cx={enabled:true,leading:true,trailing:true,wait:0},wa,bt,Ka,_a,ja,Po,Ks=class{constructor(o,t){Re(this,wa);Re(this,bt);Re(this,Ka);Re(this,_a);Re(this,ja);Re(this,Po);this.fn=o,this.store=new Yt(Wu()),this.setOptions=a=>{this.options={...this.options,...a},_(this,Ka).call(this)||this.cancel();},Ie(this,bt,a=>{this.store.setState(s=>{let r={...s,...a},{isPending:n}=r;return {...r,status:_(this,Ka).call(this)?n?"pending":"idle":"disabled"}}),zu("Throttler",this);}),Ie(this,Ka,()=>!!Zi(this.options.enabled,this)),Ie(this,_a,()=>Zi(this.options.wait,this)),this.maybeExecute=(...a)=>{_(this,bt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let s=Date.now(),r=s-this.store.state.lastExecutionTime,n=_(this,_a).call(this);if(this.options.leading&&r>=n)_(this,ja).call(this,...a);else if(_(this,bt).call(this,{lastArgs:a}),!_(this,wa)&&this.options.trailing){let c=this.store.state.lastExecutionTime?s-this.store.state.lastExecutionTime:0,i=n-c;_(this,bt).call(this,{isPending:true}),Ie(this,wa,setTimeout(()=>{let{lastArgs:d}=this.store.state;d!==void 0&&_(this,ja).call(this,...d);},i));}},Ie(this,ja,(...a)=>{if(!_(this,Ka).call(this))return;this.fn(...a);let s=Date.now(),r=s+_(this,_a).call(this);_(this,Po).call(this),_(this,bt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:s,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||_(this,bt).call(this,{nextExecutionTime:void 0});},_(this,_a).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&_(this,ja).call(this,...this.store.state.lastArgs);},Ie(this,Po,()=>{_(this,wa)&&(clearTimeout(_(this,wa)),Ie(this,wa,void 0));}),this.cancel=()=>{_(this,Po).call(this),_(this,bt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{_(this,bt).call(this,Wu());},this.key=Uu(t.key),this.options={...Cx,...t},_(this,bt).call(this,this.options.initialState??{}),el.on("d-Throttler",a=>{a.payload.key===this.key&&(_(this,bt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};wa=new WeakMap,bt=new WeakMap,Ka=new WeakMap,_a=new WeakMap,ja=new WeakMap,Po=new WeakMap;function tl(e,o){return new Ks(e,o).maybeExecute}function La(e,o){return typeof e=="function"?e(o):e}function Sa(e,o){return $s(o).reduce((a,s)=>{if(a===null)return null;if(typeof a<"u")return a[s]},e)}function Do(e,o,t){let a=$s(o);function s(r){if(!a.length)return La(t,r);let n=a.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[n]:s(r[n])}):{[n]:s()};if(Array.isArray(r)&&typeof n=="number"){let c=r.slice(0,n);return [...c.length?c:new Array(n),s(r[n]),...r.slice(n+1)]}return [...new Array(n),s()]}return s(e)}function ol(e,o){let t=$s(o);function a(s){if(!s)return;if(t.length===1){let n=t[0];if(Array.isArray(s)&&typeof n=="number")return s.filter((d,m)=>m!==n);let{[n]:c,...i}=s;return i}let r=t.shift();if(typeof r=="string"&&typeof s=="object")return {...s,[r]:a(s[r])};if(typeof r=="number"&&Array.isArray(s)){if(r>=s.length)return s;let n=s.slice(0,r);return [...n.length?n:new Array(r),a(s[r]),...s.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var kx=/^(\d+)$/gm,Mx=/\.(\d+)(?=\.)/gm,Tx=/^(\d+)\./gm,Ax=/\.(\d+$)/gm,Px=/\.{2,}/gm,al="__int__",_s=`${al}$1`;function $s(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(kx,_s).replace(Mx,`.${_s}.`).replace(Tx,`${_s}.`).replace(Ax,`.${_s}`).replace(Px,".").split(".").map(o=>{if(o.startsWith(al)){let t=o.substring(al.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function rl(e){return !(Array.isArray(e)&&e.length===0)}function Ro(e,o){let t=a=>a.validators.filter(Boolean).map(s=>({cause:s.cause,validate:s.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Eo(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:s,onDynamicAsyncDebounceMs:r}=o.validators||{},n=t??0,c=i=>i.validators.filter(Boolean).map(d=>{let m=d?.cause||e,f=n;switch(m){case "change":f=s??n;break;case "blur":f=a??n;break;case "dynamic":f=r??n;break;case "submit":f=0;break}return e==="submit"&&(f=0),{cause:m,validate:d.fn,debounceMs:f}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:c})}var vr=e=>!!e&&typeof e=="object"&&"fields"in e;function Ia(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[s,r]of e)if(!o.has(s)||!Object.is(r,o.get(s)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let s of e)if(!o.has(s))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let s of t)if(!a.includes(s)||!Ia(e[s],o[s]))return false;return true}var Ys=({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},Js=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Xe(e,o){return e==null?o:{...e,...o}}var Xa=256,Xs=[],js;for(;Xa--;)Xs[Xa]=(Xa+256).toString(16).substring(1);function sl(){let e=0,o,t="";if(!js||Xa+16>256){for(js=new Array(256),e=256;e--;)js[e]=256*Math.random()|0;e=0,Xa=0;}for(;e<16;e++)o=js[Xa+e],e===6?t+=Xs[o&15|64]:e===8?t+=Xs[o&63|128]:t+=Xs[o],e&1&&e>1&&e<11&&(t+="-");return Xa++,t}var Ca=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},s={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,s,r,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[s,n],form:e.form});case "change":return e.runValidation({validators:[a,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Dx(e,o){let t=new Map;for(let a of e){let s=a.path??[],r=o,n="";for(let c=0;c<s.length;c++){let i=s[c];if(i===void 0)continue;let d=typeof i=="object"?i.key:i,m=Number(d);Array.isArray(r)&&!Number.isNaN(m)?n+=`[${m}]`:n+=(c>0?".":"")+String(d),typeof r=="object"&&r!==null?r=r[d]:r=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var Gu=(e,o)=>{let t=Dx(e,o);return {form:t,fields:t}},ka={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:Gu(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:Gu(a.issues,e)}},Zs=e=>!!e&&"~standard"in e;var Fo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function yr(e){function o(f,l,u,p){let y=a(f,l,u,p);({insert:()=>c(y,f,l),remove:()=>i(y),swap:()=>p!==void 0&&m(y,f,l,p),move:()=>p!==void 0&&d(y,f,l,p)})[u]();}function t(f,l){return `${f}[${l}]`}function a(f,l,u,p){let y=[t(f,l)];if(u==="swap")y.push(t(f,p));else if(u==="move"){let[h,x]=[Math.min(l,p),Math.max(l,p)];for(let v=h;v<=x;v++)y.push(t(f,v));}else {let h=e.getFieldValue(f),x=Array.isArray(h)?h.length:0;for(let v=l+1;v<x;v++)y.push(t(f,v));}return Object.keys(e.fieldInfo).filter(h=>y.some(x=>h.startsWith(x)))}function s(f,l){return f.replace(/\[(\d+)\]/,(u,p)=>{let y=parseInt(p,10);return `[${l==="up"?y+1:Math.max(0,y-1)}]`})}function r(f,l){(l==="up"?f:[...f].reverse()).forEach(p=>{let y=s(p.toString(),l),h=e.getFieldMeta(y);h?e.setFieldMeta(p,h):e.setFieldMeta(p,n());});}let n=()=>Fo,c=(f,l,u)=>{r(f,"down"),f.forEach(p=>{p.toString().startsWith(t(l,u))&&e.setFieldMeta(p,n());});},i=f=>{r(f,"up");},d=(f,l,u,p)=>{let y=new Map(Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(l,u))).map(h=>[h,e.getFieldMeta(h)]));r(f,u<p?"up":"down"),Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(l,p))).forEach(h=>{let x=h.replace(t(l,p),t(l,u)),v=y.get(x);v&&e.setFieldMeta(h,v);});},m=(f,l,u,p)=>{f.forEach(y=>{if(!y.toString().startsWith(t(l,u)))return;let h=y.toString().replace(t(l,u),t(l,p)),[x,v]=[e.getFieldMeta(y),e.getFieldMeta(h)];x&&e.setFieldMeta(h,x),v&&e.setFieldMeta(y,v);});};return {handleArrayFieldMetaShift:o}}var nl=class extends Ga{constructor(){super({pluginId:"form-devtools"});}},vt=new nl;function il(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var Lr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),s=this.store.mount(),r=()=>{a(),s(),vt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return vt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let s=this.options;this.options=a;let r=!!a.transform?.deps?.some((i,d)=>i!==this.prevTransformArray[d]),n=a.defaultValues&&!Ia(a.defaultValues,s.defaultValues)&&!this.state.isTouched,c=!Ia(a.defaultState,s.defaultState)&&!this.state.isTouched;!n&&!c&&!r||(xt(()=>{this.baseStore.setState(()=>il(Object.assign({},this.state,c?a.defaultState:{},n?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),vt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,s)=>{let{fieldMeta:r}=this.state,n=this.resetFieldMeta(r);a&&!s?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>il({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let s=[];return xt(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let c=n.instance;s.push(Promise.resolve().then(()=>c.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(s)).flat()},this.validateArrayFieldsStartingFrom=async(a,s,r)=>{let n=this.getFieldValue(a),c=Array.isArray(n)?Math.max(n.length-1,0):null,i=[`${a}[${s}]`];for(let l=s+1;l<=(c??0);l++)i.push(`${a}[${l}]`);let d=Object.keys(this.fieldInfo).filter(l=>i.some(u=>l.startsWith(u))),m=[];return xt(()=>{d.forEach(l=>{m.push(Promise.resolve().then(()=>this.validateField(l,r)));});}),(await Promise.all(m)).flat()},this.validateField=(a,s)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(n=>({...n,isTouched:true})),r.validate(s)):[]},this.validateSync=a=>{let s=Ro(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ca}),r=false,n={};return xt(()=>{for(let d of s){if(!d.validate)continue;let m=this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:f,fieldErrors:l}=Qs(m),u=wr(d.cause);for(let p of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[p]===void 0)continue;let y=this.getFieldMeta(p);if(!y)continue;let{errorMap:h,errorSourceMap:x}=y,v=l?.[p],{newErrorValue:b,newSource:L}=Ys({newFormValidatorError:v,isPreviousErrorFromFormValidator:x?.[u]==="form",previousErrorValue:h?.[u]});L==="form"&&(n[p]={...n[p],[u]:v}),h?.[u]!==b&&this.setFieldMeta(p,C=>({...C,errorMap:{...C.errorMap,[u]:b},errorSourceMap:{...C.errorSourceMap,[u]:L}}));}this.state.errorMap?.[u]!==f&&this.baseStore.setState(p=>({...p,errorMap:{...p.errorMap,[u]:f}})),(f||l)&&(r=!0);}let c=wr("submit");this.state.errorMap?.[c]&&a!=="submit"&&!r&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[c]:void 0}}));let i=wr("server");this.state.errorMap?.[i]&&a!=="server"&&!r&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[i]:void 0}}));}),{hasErrored:r,fieldsErrorMap:n}},this.validateAsync=async a=>{let s=Eo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ca});this.state.isFormValidating||this.baseStore.setState(d=>({...d,isFormValidating:true}));let r=[],n;for(let d of s){if(!d.validate)continue;let m=wr(d.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[m]={lastAbortController:l},r.push(new Promise(async u=>{let p;try{p=await new Promise((v,b)=>{setTimeout(async()=>{if(l.signal.aborted)return v(void 0);try{v(await this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(L){b(L);}},d.debounceMs);});}catch(v){p=v;}let{formError:y,fieldErrors:h}=Qs(p);h&&(n=n?{...n,...h}:h);let x=wr(d.cause);for(let v of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[v]===void 0)continue;let b=this.getFieldMeta(v);if(!b)continue;let{errorMap:L,errorSourceMap:C}=b,M=n?.[v],{newErrorValue:k,newSource:g}=Ys({newFormValidatorError:M,isPreviousErrorFromFormValidator:C?.[x]==="form",previousErrorValue:L?.[x]});L?.[x]!==k&&this.setFieldMeta(v,P=>({...P,errorMap:{...P.errorMap,[x]:k},errorSourceMap:{...P.errorSourceMap,[x]:g}}));}this.baseStore.setState(v=>({...v,errorMap:{...v.errorMap,[x]:y}})),u(n?{fieldErrors:n,errorMapKey:x}:void 0);}));}let c=[],i={};if(r.length){c=await Promise.all(r);for(let d of c)if(d?.fieldErrors){let{errorMapKey:m}=d;for(let[f,l]of Object.entries(d.fieldErrors)){let p={...i[f]||{},[m]:l};i[f]=p;}}}return this.baseStore.setState(d=>({...d,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:s,fieldsErrorMap:r}=this.validateSync(a);return s&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Sa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var s;return (s=this.fieldInfo)[a]||(s[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,s)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:La(s,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((s,r)=>{let n=r;return s[n]=Fo,s},{}),this.setFieldValue=(a,s,r)=>{let n=r?.dontUpdateMeta??false,c=r?.dontRunListeners??false,i=r?.dontValidate??false;xt(()=>{n||this.setFieldMeta(a,d=>({...d,isTouched:!0,isDirty:!0,errorMap:{...d?.errorMap,onMount:void 0}})),this.baseStore.setState(d=>({...d,values:Do(d.values,a,s)}));}),c||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(n=>{let c=a.toString();return n!==c&&n.startsWith(c)}),a];this.baseStore.setState(n=>{let c={...n};return r.forEach(i=>{c.values=ol(c.values,i),delete this.fieldInfo[i],delete c.fieldMetaBase[i];}),c});},this.pushFieldValue=(a,s,r)=>{this.setFieldValue(a,n=>[...Array.isArray(n)?n:[],s],r);},this.insertFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,i=>[...i.slice(0,s),r,...i.slice(s)],Xe(n,{dontValidate:true}));let c=n?.dontValidate??false;c||await this.validateField(a,"change"),yr(this).handleArrayFieldMetaShift(a,s,"insert"),c||await this.validateArrayFieldsStartingFrom(a,s,"change");},this.replaceFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,i=>i.map((d,m)=>m===s?r:d),Xe(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.removeFieldValue=async(a,s,r)=>{let n=this.getFieldValue(a),c=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,d=>d.filter((m,f)=>f!==s),Xe(r,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"remove"),c!==null){let d=`${a}[${c}]`;this.deleteField(d);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.swapFieldValues=(a,s,r,n)=>{this.setFieldValue(a,i=>{let d=i[s],m=i[r];return Do(Do(i,`${s}`,m),`${r}`,d)},Xe(n,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"swap",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,s,r,n)=>{this.setFieldValue(a,i=>{let d=[...i];return d.splice(r,0,d.splice(s,1)[0]),d},Xe(n,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"move",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,s)=>{let r=this.getFieldValue(a),n=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],Xe(s,{dontValidate:true})),n!==null)for(let i=0;i<=n;i++){let d=`${a}[${i}]`;this.deleteField(d);}(s?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:Fo},values:this.options.defaultValues?Do(s.values,a,Sa(this.options.defaultValues,a)):s.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[s,r])=>(Object.keys(r).length&&r.errors.length&&(a[s]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>ka.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>ka.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??sl(),this._devtoolsSubmissionOverride=false,this.baseStore=new Yt(il({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new zt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,c=a?.[0],i=s[0],d=0,m={};for(let f of Object.keys(i.fieldMetaBase)){let l=i.fieldMetaBase[f],u=c?.fieldMetaBase[f],p=n?.[f],y=Sa(i.values,f),h=p?.errors;if(!u||l.errorMap!==u.errorMap){h=Object.values(l.errorMap??{}).filter(C=>C!==void 0);let L=this.getFieldInfo(f)?.instance;L&&!L.options.disableErrorFlat&&(h=h?.flat(1));}let x=!rl(h??[]),v=!l.isDirty,b=Ia(y,Sa(this.options.defaultValues,f))||Ia(y,this.getFieldInfo(f)?.instance?.options.defaultValue);if(p&&p.isPristine===v&&p.isValid===x&&p.isDefaultValue===b&&p.errors===h&&l===u){m[f]=p,d++;continue}m[f]={...l,errors:h,isPristine:v,isValid:x,isDefaultValue:b};}return Object.keys(i.fieldMetaBase).length&&n&&d===Object.keys(i.fieldMetaBase).length?n:m}}),this.store=new zt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,c=a?.[0],i=s[0],d=s[1],m=Object.values(d).filter(Boolean),f=m.some(R=>R.isValidating),l=m.every(R=>R.isValid),u=m.some(R=>R.isTouched),p=m.some(R=>R.isBlurred),y=m.every(R=>R.isDefaultValue),h=u&&i.errorMap?.onMount,x=m.some(R=>R.isDirty),v=!x,b=!!(i.errorMap?.onMount||m.some(R=>R?.errorMap?.onMount)),L=!!f,C=n?.errors??[];(!c||i.errorMap!==c.errorMap)&&(C=Object.values(i.errorMap).reduce((R,K)=>K===void 0?R:K&&vr(K)?(R.push(K.form),R):(R.push(K),R),[]));let M=C.length===0,k=l&&M,g=this.options.canSubmitWhenInvalid??false,P=i.submissionAttempts===0&&!u&&!b||!L&&!i.isSubmitting&&k||g,E=i.errorMap;if(h&&(C=C.filter(R=>R!==i.errorMap.onMount),E=Object.assign(E,{onMount:void 0})),n&&c&&n.errorMap===E&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===C&&n.isFieldsValidating===f&&n.isFieldsValid===l&&n.isFormValid===M&&n.isValid===k&&n.canSubmit===P&&n.isTouched===u&&n.isBlurred===p&&n.isPristine===v&&n.isDefaultValue===y&&n.isDirty===x&&Ia(c,i))return n;let I={...i,errorMap:E,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:f,isFieldsValid:l,isFormValid:M,isValid:k,canSubmit:P,isTouched:u,isBlurred:p,isPristine:v,isDefaultValue:y,isDirty:x},B=this.options.transform?.deps??[];if(B.length!==this.prevTransformArray.length||B.some((R,K)=>R!==this.prevTransformArray[K])){let R=Object.assign({},this,{state:I});this.options.transform?.fn(R),I=R.state,this.prevTransformArray=B;}return I}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=tl(a=>vt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),vt.on("request-form-state",a=>{a.payload.id===this._formId&&vt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),vt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),vt.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 Zs(o.validate)?ka[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(s=>({...s,isSubmitted:false,submissionAttempts:s.submissionAttempts+1,isSubmitSuccessful:false})),xt(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance&&(s.instance.state.meta.isTouched||s.instance.setMeta(r=>({...r,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(s=>({...s,isSubmitting:true}));let a=()=>{this.baseStore.setState(s=>({...s,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(s=>s.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}xt(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance?.options.listeners?.onSubmit?.({value:s.instance.state.value,fieldApi:s.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),xt(()=>{this.baseStore.setState(s=>({...s,isSubmitted:!0,isSubmitSuccessful:!0})),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(s){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:s}),a(),s}}setErrorMap(o){xt(()=>{Object.entries(o).forEach(([t,a])=>{let s=t;if(vr(a)){let{formError:r,fieldErrors:n}=Qs(a);for(let c of Object.keys(this.fieldInfo))this.getFieldMeta(c)&&this.setFieldMeta(c,d=>({...d,errorMap:{...d.errorMap,[s]:n?.[c]},errorSourceMap:{...d.errorSourceMap,[s]:"form"}}));this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[s]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[s]:a}}));});});}};function Qs(e){if(e){if(vr(e)){let o=Qs(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function wr(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 Sr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:s}=this.options.validators||{};if(s){let r=this.runValidator({validate:s,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:r},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let s=Sa(t.form.options.defaultValues,t.name),r=t.defaultValue??s;a?this.setValue(n=>n||r,{dontUpdateMeta:true}):r!==void 0&&this.setValue(r,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Xe(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,Xe(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,s)=>{this.form.insertFieldValue(this.name,t,a,Xe(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,s)=>{this.form.replaceFieldValue(this.name,t,a,Xe(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Xe(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,s)=>{this.form.swapFieldValues(this.name,t,a,Xe(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,s)=>{this.form.moveFieldValues(this.name,t,a,Xe(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Xe(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),s=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:n,onBlurListenTo:c}=r.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&s.push(r.instance),t==="blur"&&c?.includes(this.name)&&s.push(r.instance);}return s},this.validateSync=(t,a)=>{let s=Ro(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ca}),n=this.getLinkedFields(t).reduce((d,m)=>{let f=Ro(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Ca});return f.forEach(l=>{l.field=m;}),d.concat(f)},[]),c=false;xt(()=>{let d=(m,f)=>{let l=en(f.cause),u=f.validate?Ku(m.runValidator({validate:f.validate,value:{value:m.store.state.value,validationSource:"field",fieldApi:m},type:"validate"})):void 0,p=a[l],{newErrorValue:y,newSource:h}=Js({formLevelError:p,fieldLevelError:u});m.state.meta.errorMap?.[l]!==y&&m.setMeta(x=>({...x,errorMap:{...x.errorMap,[l]:y},errorSourceMap:{...x.errorSourceMap,[l]:h}})),y&&(c=!0);};for(let m of s)d(this,m);for(let m of n)m.validate&&d(m.field,m);});let i=en("submit");return this.state.meta.errorMap?.[i]&&t!=="submit"&&!c&&this.setMeta(d=>({...d,errorMap:{...d.errorMap,[i]:void 0},errorSourceMap:{...d.errorSourceMap,[i]:void 0}})),{hasErrored:c}},this.validateAsync=async(t,a)=>{let s=Eo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ca}),r=await a,n=this.getLinkedFields(t),c=n.reduce((l,u)=>{let p=Eo(t,{...u.options,form:u.form,validationLogic:u.form.options.validationLogic||Ca});return p.forEach(y=>{y.field=u;}),l.concat(p)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of n)l.setMeta(u=>({...u,isValidating:true}));let i=[],d=[],m=(l,u,p)=>{let y=en(u.cause);l.getInfo().validationMetaMap[y]?.lastAbortController.abort();let x=new AbortController;this.getInfo().validationMetaMap[y]={lastAbortController:x},p.push(new Promise(async v=>{let b;try{b=await new Promise((g,P)=>{this.timeoutIds.validations[u.cause]&&clearTimeout(this.timeoutIds.validations[u.cause]),this.timeoutIds.validations[u.cause]=setTimeout(async()=>{if(x.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:u.validate,value:{value:l.store.state.value,fieldApi:l,signal:x.signal,validationSource:"field"},type:"validateAsync"}));}catch(E){P(E);}},u.debounceMs);});}catch(g){b=g;}if(x.signal.aborted)return v(void 0);let L=Ku(b),C=r[this.name]?.[y],{newErrorValue:M,newSource:k}=Js({formLevelError:C,fieldLevelError:L});l.setMeta(g=>({...g,errorMap:{...g?.errorMap,[y]:M},errorSourceMap:{...g.errorSourceMap,[y]:k}})),v(M);}));};for(let l of s)l.validate&&m(this,l,i);for(let l of c)l.validate&&m(l.field,l,d);let f=[];(i.length||d.length)&&(f=await Promise.all(i),await Promise.all(d)),this.setMeta(l=>({...l,isValidating:false}));for(let l of n)l.setMeta(u=>({...u,isValidating:false}));return f.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:s}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,s[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[en(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=>ka.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>ka.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new zt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Fo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Zs(o.validate)?ka[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 Ku(e){if(e)return e}function en(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 tn(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Ex)}function Ex(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,s]of e)if(!o.has(a)||!Object.is(s,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=_u(e);if(t.length!==_u(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 _u(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Bo=typeof window<"u"?useLayoutEffect:useEffect;function Hx(e){let[o]=useState(()=>{let a=new Sr({...e,form:e.form,name:e.name});return a.Field=ll,a});return Bo(o.mount,[o]),Bo(()=>{o.update(e);}),tn(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var ll=(({children:e,...o})=>{let t=Hx(o),a=useMemo(()=>La(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Wx({form:e,selector:o,children:t}){let a=tn(e.store,o);return La(t,a)}function dl(e){let o=useId(),[t]=useState(()=>{let a=new Lr({...e,formId:o}),s=a;return s.Field=function(n){return jsx(ll,{...n,form:a})},s.Subscribe=function(n){return jsx(Wx,{form:a,selector:n.selector,children:n.children})},s});return Bo(t.mount,[]),Bo(()=>{t.update(e);}),t}function ul({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 Qx=({editElement:e})=>{let o=useDispatch(),t=useSelector(he),a=useRef(null),s=ze(),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[c,i]=useState(n),d=dl({defaultValues:{questionType:n,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:l})=>{if(l.questionType==="true-false"){let u={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctAnswer:l.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?ma(u):oi(u));}else if(l.questionType==="multiple-choice"){let u={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctIndex:l.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?fa(u):ai(u));}else if(l.questionType==="short-answer"){let u={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?$o(u):ri(u));}else if(l.questionType==="fill-in-the-blank"){let u={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Jo(u):ni(u));}else if(l.questionType==="long-answer"){let u={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctLongAnswer:l.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Yo(u):si(u));}o(pa(false));}}),m=()=>{o(pa(false));};if(!s)return null;let f=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:l=>{l.preventDefault(),l.stopPropagation(),d.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{m();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(d.Field,{name:"questionType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:u=>{l.handleChange(u.target.value),i(u.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(ul,{field:l})]})}),c&&!["short-answer","fill-in-the-blank","long-answer"].includes(c)&&jsx(d.Field,{name:"responseType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:u=>l.handleChange(u.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(ul,{field:l})]})})]}),jsx(d.Field,{name:"feedbackMode",children:l=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${c==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:c==="long-answer",onClick:()=>l.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:c==="long-answer",onClick:()=>l.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),c==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(ul,{field:l})]})}),jsx(d.Field,{name:"question",validators:{onChange:({value:l})=>l?void 0:"A question is required"},children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:l.state.value,onChange:u=>l.handleChange(u.target.value),onBlur:l.handleBlur,placeholder:"Enter Your Question"})}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),c==="true-false"&&jsx(d.Field,{name:"responseOptions.correctAnswer",children:l=>{let u=l.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>l.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${u===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),u===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>l.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${u===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),u===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),c==="multiple-choice"&&jsx(d.Field,{name:"responseOptions",validators:{onChange:({value:l})=>{if(l.options.filter(p=>!p.trim()).length>0)return "All options must have text";if(!l.correctIndex||l.correctIndex.length===0)return "Please select at least one correct answer"}},children:l=>{let u=(x,v)=>{let b=[...l.state.value.options];b[x]=v,l.handleChange({...l.state.value,options:b});},p=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},y=x=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let v=l.state.value.options.filter((L,C)=>C!==x),b=l.state.value.correctIndex?.filter(L=>L!==x).map(L=>L>x?L-1:L);l.handleChange({...l.state.value,options:v,correctIndex:b});},h=x=>{let v=l.state.value.correctIndex||[];if(v.includes(x))l.handleChange({...l.state.value,correctIndex:v.filter(L=>L!==x)});else {if(v.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...v,x]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:l.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:l.state.value.options.map((x,v)=>{let b=!x.trim(),L=l.state.value.correctIndex?.includes(v),C=l.state.meta.isTouched&&b;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>h(v),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${L?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:L&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${C?"border-red-500 bg-red-50":L?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${v+1}`,value:x,onChange:M=>u(v,M.target.value),onBlur:l.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),l.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>y(v),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},v)})}),jsx("button",{type:"button",onClick:p,disabled:l.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),l.state.value.correctIndex.length===0||l.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:l.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(c==="short-answer"||c==="fill-in-the-blank")&&jsx(d.Field,{name:"responseOptions.correctShortAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:l.state.value,onChange:u=>{l.handleChange(u.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),c==="long-answer"&&jsx(d.Field,{name:"responseOptions.correctLongAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:l.state.value,onChange:u=>{l.handleChange(u.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),jsx(d.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,u])=>jsx("button",{type:"submit",disabled:!l,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:u?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,s)},$u=Qx;var Qu=({text:e,position:o})=>{let t=xe(),a=d=>{t(ce()),t(Mt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+d))}));},s=d=>{t(ce()),t(Mt({id:e.id,fill:d}));},r=()=>{t(ce()),t(Mt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ce()),t(Mt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},c=()=>{t(ce()),t(Mt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},i=d=>{t(ce()),t(Mt({id:e.id,fontFamily:d}));};return jsxs("div",{className:"fixed z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:"50%",top:`${Math.max(60,o.y-60)}px`,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:d=>d.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:d=>i(d.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:r,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:[jsx(TextB,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextB,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:n,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:c,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:[jsx(TextUnderline,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextUnderline,{size:16,weight:"bold",className:"hidden sm:block"})]})]}),jsx("div",{className:"border-l border-gray-200 pl-1",children:jsx("input",{type:"color",value:e.fill,onChange:d=>s(d.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var tc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:s,scale:r,textareaRef:n})=>{let c=useRef(null),i=useMemo(()=>({fontSize:`${e.fontSize*r}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,r]),d=useCallback(m=>{m.style.height="auto",m.style.height=`${m.scrollHeight}px`;let f=document.createElement("span");f.style.font=window.getComputedStyle(m).font,f.style.fontSize=m.style.fontSize,f.style.fontFamily=m.style.fontFamily,f.style.fontWeight=m.style.fontWeight,f.style.fontStyle=m.style.fontStyle,f.style.visibility="hidden",f.style.position="absolute",f.style.whiteSpace="pre";let l=m.value.split(`
4
4
  `),u=0;document.body.appendChild(f);for(let y of l){f.textContent=y||" ";let h=f.offsetWidth;h>u&&(u=h);}document.body.removeChild(f);let p=10;m.style.width=`${Math.max(200,u+p+20)}px`;},[]);return useEffect(()=>{let m=c.current;m&&(m.style.fontSize=`${e.fontSize*r}px`,m.style.fontFamily=e.fontFamily,m.style.fontStyle=e.fontStyle,m.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",m.style.textDecoration=e.textDecoration,m.style.color=e.fill,d(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,d]),jsx("div",{style:{position:"absolute",top:`${s.top}px`,left:`${s.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(c.current=m,n.current=m,m){m.focus();let f=m.value.length;m.setSelectionRange(f,f),d(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:i},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var ac=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(R=>R.toolbar.selectedTool),c=n==="pen"||n==="eraser",i=useRef(null),[d,m]=useState(""),[f,l]=useState(false),[u,p]=useState(null);useEffect(()=>{let R=i.current;if(R)return a.current.set(e.id,R),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=f&&d.trim().toLowerCase()===y,x=()=>{l(false),m("");},v=()=>h?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",b=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,C=60,M=f?40:0,k=f?54:20,g=50,P=12,E=e.data.feedbackMode==="practice"?48:0,I=12,B=30,G=C+M+B+g+P+I+E+L;return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:G,name:"sa-element",...c?{}:{onDragEnd:r,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:G,onTransformEnd:R=>t(e.id,R),onContextMenu:R=>{R.cancelBubble=true,s(R.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+M+B-k,width:e.width-L*2+4,height:g+6,fill:"#ffffff",stroke:h?"#22c55e":f?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:C+M+B-k},divProps:{style:{width:`${e.width-L*2-4}px`,height:`${g}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:R=>m(R.target.value),disabled:f,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:f?"none":"auto"}})}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C+80,width:e.width/2+24,height:M,fill:b().bg,cornerRadius:8}),jsx(Text,{x:36,y:C+80,width:e.width-L*2,height:M,text:v(),fontSize:12,fontStyle:"bold",fill:b().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:C+M+B+g+P+I,children:[jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,p("check");},onMouseUp:R=>{R.cancelBubble=true,p(null),d.length>0&&l(true);},onMouseLeave:R=>{R.cancelBubble=true,p(null);},onTouchStart:R=>{R.cancelBubble=true,p("check");},onTouchEnd:R=>{R.cancelBubble=true,p(null),d.length>0&&l(true);},scaleX:u==="check"?.95:1,scaleY:u==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(f?2:1),height:48,fill:d.length===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),x();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),x();},scaleX:u==="reset"?.95:1,scaleY:u==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.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})]})]})]})});ac.displayName="ShortAnswer";var oc=ac;var sc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(oc,{shortAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:c=>r(c,n.id)},n.id))});var nc=e=>{let o=useDispatch(),a=useSelector(he)?.fillInTheBlanks||[],s=useRef(new Map),r=useCallback((n,c)=>{let i=n.target;o(Jo({id:c,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:s,handleFillInTheBlanksDragEnd:r}};var Dt=24,ml=51,Ar=64,ic=15,rn=32,lc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:s,fibRefs:r})=>{let n=useSelector(g=>g.toolbar.selectedTool),c=n==="pen"||n==="eraser",i=useRef(null),[d,m]=useState(""),[f,l]=useState(false),[u,p]=useState(null);useEffect(()=>{let g=i.current;if(g)return r.current.set(e.id,g),()=>{r.current.delete(e.id);}},[e.id,r]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=f&&d.trim().toLowerCase()===y,x=()=>{l(false),m("");},v=()=>{d.length>0&&l(true);},b=e.width-Dt*2,L=(b-ic)/2,C=e.data.feedbackMode==="practice",M=useMemo(()=>{let g=Dt,P=g;g+=60;let E=g;g+=35;let I=g;g+=ml+16;let B=g;f&&(g+=rn+16);let G=g;return C&&(g+=Ar),g+=Dt,{questionY:P,helperTextY:E,inputY:I,feedbackY:B,buttonsY:G,totalHeight:g}},[f,C]),k=()=>f?h?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...c?{}:{onDragEnd:g=>a(g,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:M.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:g=>t(e.id,g),onContextMenu:g=>{g.cancelBubble=true,s?.(g.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Dt,y:M.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:b,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Dt,y:M.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:b,listening:false}),jsx(Rect,{x:Dt,y:M.inputY,width:b,height:ml,fill:"#ffffff",stroke:k(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Dt,y:M.inputY},divProps:{style:{width:`${b}px`,height:`${ml}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:g=>m(g.target.value),disabled:f,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),f&&jsxs(Group,{y:M.feedbackY,children:[jsx(Rect,{x:Dt,width:h?206:140,height:rn,fill:h?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:h?"\u2713":"\u2717",x:Dt+10,y:0,width:16,height:rn,fontSize:14,fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:h?"Right Answer, Great Job!":"Wrong Answer",x:Dt+30,y:0,height:rn,fontSize:14,fontStyle:"600",fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),C&&jsxs(Group,{y:M.buttonsY,children:[jsxs(Group,{x:Dt,onMouseDown:g=>{g.cancelBubble=true,p("reset");},onMouseUp:g=>{g.cancelBubble=true,p(null),x();},onMouseLeave:g=>{g.cancelBubble=true,p(null);},onTouchStart:g=>{g.cancelBubble=true,p("reset");},onTouchEnd:g=>{g.cancelBubble=true,p(null),x();},scaleX:u==="reset"?.98:1,scaleY:u==="reset"?.98:1,children:[jsx(Rect,{width:L,height:Ar,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:L,height:Ar,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Dt+L+ic,onMouseDown:g=>{g.cancelBubble=true,p("submit");},onMouseUp:g=>{g.cancelBubble=true,p(null),v();},onMouseLeave:g=>{g.cancelBubble=true,p(null);},onTouchStart:g=>{g.cancelBubble=true,p("submit");},onTouchEnd:g=>{g.cancelBubble=true,p(null),v();},scaleX:u==="submit"?.98:1,scaleY:u==="submit"?.98:1,children:[jsx(Rect,{width:L,height:Ar,fill:d.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:L,height:Ar,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});lc.displayName="FillInTheBlanks";var dc=lc;var cc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r})=>jsx(Fragment,{children:e.map(n=>jsx(dc,{fillInTheBlank:n,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r},n.id))});var xl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(G=>G.toolbar.selectedTool),c=n==="pen"||n==="eraser",i=useRef(null),[d,m]=useState(""),[f,l]=useState(false),[u,p]=useState(null);useEffect(()=>{let G=i.current;if(G)return a.current.set(e.id,G),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=f&&d.trim().toLowerCase()===y,x=()=>{l(false),m("");},v=()=>h?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",b=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,C=60,M=f?60:0,k=120,g=12,P=48,E=12,I=30,B=C+M+I+k+g+E+P+L;return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...c?{}:{onDragEnd:r,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:G=>{let R=i.current?.getStage()?.getPointerPosition();if(!R||!s)return;let K={x:e.x,y:e.y,width:e.width,height:e.height};R.x>=K.x&&R.x<=K.x+K.width&&R.y>=K.y&&R.y<=K.y+K.height&&s(G.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:B,onTransformEnd:G=>t(e.id,G)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C,width:e.width-L*2,height:M,fill:b().bg,cornerRadius:8}),jsx(Text,{x:L,y:C,width:e.width-L*2,height:M,text:v(),fontSize:14,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:C+M+g,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+M+I,width:e.width-L*2,height:k,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:C+M+I},divProps:{style:{width:`${e.width-L*2}px`,height:`${k}px`,pointerEvents:f?"none":"auto"}},children:jsx("textarea",{value:d,onChange:G=>m(G.target.value),disabled:f,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:f?"none":"auto"}})}),jsx(Group,{y:C+M+I+k+g+E,children:f&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),x();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),x();},scaleX:u==="reset"?.95:1,scaleY:u==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});xl.displayName="LongAnswer";var mc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(xl,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:c=>r(c,n.id)},n.id))});var Ya=1600,Ja=900,xc=3200,bc=1800,Bb=.4,Ob=1.5,Nb=e=>{let o=0,t=0,a=Ya,s=Ja;if(!e)return {minX:o,minY:t,maxX:a,maxY:s,width:Ya,height:Ja};let r=(i,d,m,f)=>{o=Math.min(o,i),t=Math.min(t,d),a=Math.max(a,i+m),s=Math.max(s,d+f);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let d=i.x||0,m=i.y||0,f=i.scaleX||1,l=i.scaleY||1;for(let u=0;u<i.points.length;u+=2){let p=d+i.points[u]*f,y=m+i.points[u+1]*l;o=Math.min(o,p),t=Math.min(t,y),a=Math.max(a,p),s=Math.max(s,y);}}}),e.images?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>r(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>r(i.x,i.y,i.width,i.height));let n=Math.min(a-o,xc),c=Math.min(s-t,bc);return o=Math.max(o,a-xc),t=Math.max(t,s-bc),{minX:o,minY:t,maxX:a,maxY:s,width:n,height:c}},Vb=(e,o,t={minX:0,minY:0,maxX:Ya,maxY:Ja,width:Ya,height:Ja})=>{let a=Math.max(t.width,Ya),s=Math.max(t.height,Ja),r=e/o,n=a/s,c,i,d,f=0;if(r>n){i=s,c=Math.round(i*r),d=o/i;}else {c=a,i=Math.round(c/r),d=e/c;let l=s*d;f=(o-l)/2;}return d=Math.max(Bb,Math.min(Ob,d)),{scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:c,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},vc=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},qb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:s={enabled:true}}={})=>{let r=st(),n=ze(),c=te(w=>w.toolbar.selectedTool),i=te(he),d=te(mo),f=(i?.videos||[]).find(w=>w.isRecorded&&w.isPlaying),l=!!f,u=useCallback(()=>{f&&r(Na(f.id));},[r,f]),p=i?.editingActivity,y=i?.showMcqForm,h=i?.lines||[],x=useRef(null),v=useRef(null),[b,L]=useState(null),[C,M]=useState(""),k=useRef(null),[g,P]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Ya,stageHeight:Ja,offsetX:0,offsetY:0,baseWidth:Ya,baseHeight:Ja,contentOffsetX:0,contentOffsetY:0}),E=useMemo(()=>Nb(i||null),[d]),[I,B]=useState(null),[G,R]=useState(null),[K,D]=useState(null),[Q,V]=useState(null),[ae,W]=useState(null),[q,Y]=useState(null),[H,U]=useState(null),[J,ee]=useState(false),[j,ue]=useState(null),[ke,Me]=useState(false),Te=useRef(null),Ne=useRef(null),ct=useRef(null),{debouncedGenerateThumbnail:no}=jd(d,x);useEffect(()=>{let w=()=>{if(v.current){let A=v.current.getBoundingClientRect(),O=Vb(A.width,A.height,E);P(O);}};w();let S=new ResizeObserver(w);return v.current&&S.observe(v.current),window.addEventListener("resize",w),()=>{S.disconnect(),window.removeEventListener("resize",w);}},[E]),useEffect(()=>{if(x.current){let w=x.current.container();w&&(w.style.cursor="");}},[c]);let ne=useCallback(()=>{x.current&&requestAnimationFrame(()=>{if(!x.current)return;x.current.getLayers().forEach(O=>O.batchDraw());let S=1/6,A=x.current.toDataURL({pixelRatio:S});M(A),no();});},[no]),Hr=useRef(d);useEffect(()=>{Hr.current!==d&&(Hr.current=d,ne());},[d,ne]);let Ur=useRef(null),Fa=useRef(true);useEffect(()=>{if(!i)return;let w=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),S=Ur.current?.count!==w;!Fa.current&&S&&setTimeout(()=>{ne();},100),Ur.current={slideId:d,count:w},Fa.current=false;},[i,d,ne]),useEffect(()=>{x.current&&e&&e(x);},[e]),useEffect(()=>{ct.current&&a&&a(ct);},[a]);let{startDrawing:zr,draw:Wr,stopDrawing:Gr,setCanvasRef:Kr,tool:kn,color:Mn,strokeWidth:Tn,isSketchMode:An}=yd(ne),Ba=useRef(new Map),{images:F,getLoadedImage:se,imageRefs:ve,handleDragEnd:ge,handleImageTransformEnd:re}=Md(ne),{videos:le,videoRefs:we,handleVideoClick:Ke,handleVideoDragEnd:Ot,handleVideoTransformEnd:ft}=Pd(ne),{multipleChoice:Pe,handleMcqTransform:Ue,mcqRefs:Lt,handleDragEnd:da}=Td(ne),{trueFalse:Pn,handleTrueFalseTransform:Dn,trueFalseRefs:Oa,handleTrueFalseDragEnd:Nt}=Ad(ne),{shortAnswers:ua,saRefs:Vt,handleShortAnswerDragEnd:cm}=Od(ne),{longAnswers:fm,handleLongAnswerDragEnd:mm}=Nd(ne),{fillInTheBlanks:pm,handleFillInTheBlanksDragEnd:hm,fibRefs:_r}=nc(ne),{transformerRef:fe,boundBoxFunc:St}=Wd(),{shapes:gm,shapeRefs:jr,isDragging:od,handleShapeDragEnd:xm,handleShapeResizeEnd:bm}=Ed(ne),{texts:jo,textRefs:ca,handleDragEnd:vm,handleTransformEnd:ym,handleDoubleClick:wm,startEditing:Xr,editingTextId:pe,editingValue:rd,handleEditingChange:sd,finishEditing:Rn}=Bd(ne,Te);useEffect(()=>{t&&t(Xr);},[t,Xr]);let $r=te(w=>w.canvas.editingTextId);useEffect(()=>{$r&&$r!==pe&&Xr($r);},[$r,pe,Xr]);let{flashcards:Lm,flashcardRefs:Yr,handleDragEnd:Sm,handleFlashcardTransformEnd:Im,handleNext:Cm,handlePrevious:km}=qd(ne),{photoFrames:nd,photoFrameRefs:Jr,handleDragEnd:Mm,handlePhotoFrameTransformEnd:Tm,startCamera:Am,capturePhoto:Pm,cameraStreams:Dm}=zd(ne);useEffect(()=>{if(fe.current){if(pe){fe.current.nodes([]),fe.current.getLayer()?.batchDraw();return}if(b&&!le.find(A=>A.id===b)?.isPlaying){let A=Ba.current.get(b)||ve.current.get(b)||we.current.get(b)||jr.current.get(b)||ca.current.get(b)||Lt.current.get(b)||Yr.current.get(b)||Jr.current.get(b)||Vt.current.get(b)||Oa.current.get(b)||_r.current.get(b);if(A){let O=A.attrs?.locked;if(A.visible()&&O!==true){fe.current.nodes([A]),fe.current.getLayer()?.batchDraw();return}}}fe.current.nodes([]),fe.current.getLayer()?.batchDraw();}},[b,pe,le,Ba,ve,we,jr,ca,Yr,Jr,nd,Lt,Oa,_r,fe]);let _e=useCallback(w=>{L(w),o?.(w);},[o]),io=useCallback(()=>{L(null),o?.(null),fe.current&&(fe.current.nodes([]),fe.current.getLayer()?.batchDraw());},[fe,o]),id=useCallback(w=>i?i.lines?.some(S=>S.id===w)?"line":i.images?.some(S=>S.id===w)?"image":i.videos?.some(S=>S.id===w)?"video":i.shapes?.some(S=>S.id===w)?"shape":i.texts?.some(S=>S.id===w)?"text":i.flashcards?.some(S=>S.id===w)?"flashcard":i.photoFrames?.some(S=>S.id===w)?"photoFrame":i.multipleChoices?.some(S=>S.id===w)?"mcq":i.trueFalses?.some(S=>S.id===w)?"trueFalse":i.shortAnswers?.some(S=>S.id===w)?"shortAnswer":i.LongAnswer?.some(S=>S.id===w)?"longAnswer":i.fillInTheBlanks?.some(S=>S.id===w)?"fillInTheBlanks":null:null,[i]),ld=useCallback((w,S)=>{switch(r(ce()),S){case "line":r(Ms(w));break;case "image":r(Qr(w));break;case "video":r(os(w));break;case "shape":r(ns(w));break;case "text":r(is(w));break;case "flashcard":r(ds(w));break;case "photoFrame":r(cs(w));break;case "mcq":r(ms(w));break;case "trueFalse":r(hs(w));break;case "shortAnswer":r(xs(w));break;case "longAnswer":r(vs(w));break;case "fillInTheBlanks":r(ws(w));break}io(),ne();},[r,io,ne]);useEffect(()=>{let w=S=>{if(S.key!=="Delete"||!b||pe)return;let A=document.activeElement;if(A instanceof HTMLInputElement||A instanceof HTMLTextAreaElement||A?.getAttribute("contenteditable")==="true")return;S.preventDefault();let De=id(b);De&&ld(b,De);};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[b,pe,id,ld]),useEffect(()=>{let w=fe.current;return ()=>{w&&w.nodes([]);}},[d]),useEffect(()=>{let w=S=>{pe&&S.target.tagName!=="TEXTAREA"&&Rn();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[pe,Rn]),useEffect(()=>{let w=pe||b;if(!w||b&&pe){R(null);return}let S=ca.current.get(w),A=x.current;if(!S||!A){R(null);return}let O=A.container().getBoundingClientRect(),De=S.absolutePosition(),Le=A.scaleX();R({x:O.left+(De.x+S.width()*Le/2)*Le,y:O.top+De.y*Le});},[b,pe,jo,ca]),useEffect(()=>{if(!pe){D(null);return}let w=ca.current.get(pe),S=x.current;if(!w||!S){D(null);return}let A=S.container().getBoundingClientRect(),O=w.absolutePosition(),De=S.scaleX();D({top:A.top+O.y*De,left:A.left+O.x*De,scale:De});},[pe,jo,ca]);let dd=useCallback(w=>{let S=w.target.getClassName(),A=w.target===w.target.getStage(),O=S==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",De=S==="Image",Le=S==="Text",oe=S==="Group"||w.target.getParent()?.getClassName()==="Group",qt=S==="Circle"||S==="Star"||S==="RegularPolygon"||S==="Ellipse"||S==="Ring"||S==="Wedge"||S==="Arrow"||S==="Line"||S==="Arc"||S==="Rect"&&w.target.attrs.id,Ct=S==="Group";if(A&&!O&&!De&&!Le&&!oe&&!qt&&!Ct&&io(),!(c==="pen"||c==="eraser")&&(De||Le||O||oe||qt||Ct))return;let Ye=w.target.getStage()?.getPointerPosition();if(!Ye)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(c)){let N=vc(Ye,g);zr(N);}},[c,zr,io,g]),ud=useCallback(w=>{if(od)return;let S=w.target.getStage()?.getPointerPosition();if(!S)return;let A=vc(S,g);Wr(A);},[Wr,od,g]),cd=useCallback(()=>{Gr();},[Gr]),Rm=useCallback(w=>{ge(w,ne);},[ge,ne]),Em=useCallback(w=>{Ke(w),_e(w);},[Ke,_e]),It=useCallback((w,S,A)=>{if(w.preventDefault(),!s.enabled)return;let O=w.clientX,De=w.clientY,Le=k.current?.offsetHeight||450,oe=k.current?.offsetWidth||450,qt=window.innerHeight,Ct=window.innerWidth,rt=O,Ye=De;De+Le>qt&&(Ye=De-Le),O+oe>Ct&&(rt=O-oe),B({x:rt,y:Ye,elementId:S,elementType:A}),_e(S);},[_e,s.enabled]),fd=useCallback(w=>{r(Zo(w)),r(pa(true));},[r]),Fm=useCallback(w=>{r(Xo(w)),r(qa(true));},[r]),Bm=useCallback((w,S)=>{if(!I)return;let{elementId:A,elementType:O}=I;switch(w){case "order":if(S){let T=S.target.getBoundingClientRect();V({x:T.right+5,y:T.top,type:"order"});}break;case "lock":if(S){let T=S.target.getBoundingClientRect();V({x:T.right+5,y:T.top,type:"lock"});}break;case "link":if(B(null),O==="line")break;let De=i?O==="image"?i.images.find(T=>T.id===A):i.videos.find(T=>T.id===A):null;W({type:"link",defaultValue:De?.link||""});break;case "voice":if(B(null),O==="line")break;let Le=i?O==="image"?i.images.find(T=>T.id===A):O==="video"?i.videos.find(T=>T.id===A):O==="text"?i.texts.find(T=>T.id===A):O==="flashcard"?i.flashcards.find(T=>T.id===A):O==="photoFrame"?i.photoFrames.find(T=>T.id===A):O==="mcq"?i.multipleChoices.find(T=>T.id===A):O==="fillInTheBlanks"?i.fillInTheBlanks.find(T=>T.id===A):O==="longAnswer"?i.LongAnswer.find(T=>T.id===A):O==="shortAnswer"?i.shortAnswers.find(T=>T.id===A):O==="trueFalse"?i.trueFalses.find(T=>T.id===A):O==="shape"?i.shapes.find(T=>T.id===A):null:null;ue({elementId:A,elementType:O,existingAudio:Le?.audioData});break;case "edit":B(null);let oe=null;O==="mcq"?oe=i?.multipleChoices.find(T=>T.id===A):O==="trueFalse"?oe=i?.trueFalses.find(T=>T.id===A):O==="shortAnswer"?oe=i?.shortAnswers.find(T=>T.id===A):O==="longAnswer"?oe=i?.LongAnswer.find(T=>T.id===A):O==="fillInTheBlanks"&&(oe=i?.fillInTheBlanks.find(T=>T.id===A)),oe&&fd(oe);break;case "editFlashcard":B(null);let qt=i?.flashcards.find(T=>T.id===A);qt&&Fm(qt);break;case "color":B(null);let Ct=i?.shapes.find(T=>T.id===A);Y({elementId:A,elementType:"shape",defaultColor:Ct?.color||"#096B76"});break;case "crop":if(B(null),O==="image"){let T=i?.images.find(zm=>zm.id===A);T&&U({elementId:A,imageSrc:T.src});}break;case "draw":B(null),O==="image"?r(Zn(A)):O==="photoFrame"&&r(ei(A));break;case "duplicate":r(ce()),O==="line"?r(fi(A)):O==="image"?r(es(A)):O==="video"?r(rs(A)):O==="shape"?r(ss(A)):O==="text"?r(ls(A)):O==="flashcard"?r(us(A)):O==="photoFrame"?r(fs(A)):O==="mcq"?r(ps(A)):O==="trueFalse"?r(gs(A)):O==="shortAnswer"?r(bs(A)):O==="fillInTheBlanks"?r(Ls(A)):O==="longAnswer"&&r(ys(A)),ne();break;case "infinite-clone":r(ce());let rt=5;for(let T=0;T<rt;T++)O==="image"?r(es(A)):O==="video"?r(rs(A)):O==="shape"?r(ss(A)):O==="text"?r(ls(A)):O==="flashcard"?r(us(A)):O==="photoFrame"?r(fs(A)):O==="mcq"?r(ps(A)):O==="trueFalse"?r(gs(A)):O==="shortAnswer"?r(bs(A)):O==="fillInTheBlanks"?r(Ls(A)):O==="longAnswer"&&r(ys(A));ne();break;case "make-response":if(B(null),O==="line")break;let Ye=`#response-${A}`;r(ce()),r(Ss({id:A,type:O,link:Ye})),(i?O==="image"?i.images.find(T=>T.id===A):O==="video"?i.videos.find(T=>T.id===A):O==="shape"?i.shapes.find(T=>T.id===A):O==="flashcard"?i.flashcards.find(T=>T.id===A):O==="photoFrame"?i.photoFrames.find(T=>T.id===A):i.multipleChoices.find(T=>T.id===A):null)?.altText||r(Is({id:A,type:O,altText:"Interactive response area"})),ne(),console.log(`Element ${A} marked as interactive response area`);break;case "accessibility":if(B(null),O==="line")break;let N=i?O==="image"?i.images.find(T=>T.id===A):O==="video"?i.videos.find(T=>T.id===A):O==="shape"?i.shapes.find(T=>T.id===A):null:null;W({type:"altText",defaultValue:N?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),B(null),Me(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ce()),O==="line"?r(Ms(A)):O==="image"?r(Qr(A)):O==="video"?r(os(A)):O==="shape"?r(ns(A)):O==="text"?r(is(A)):O==="flashcard"?r(ds(A)):O==="photoFrame"?r(cs(A)):O==="mcq"?r(ms(A)):O==="trueFalse"?r(hs(A)):O==="shortAnswer"?r(xs(A)):O==="longAnswer"?r(vs(A)):O==="fillInTheBlanks"&&r(ws(A)),io(),ne();break}},[I,r,ne,io,i,fd]),Om=useCallback(()=>{B(null),V(null);},[]),En=useCallback(w=>{if(!I)return;let{elementId:S,elementType:A}=I;switch(r(ce()),w){case "bring-to-front":A!=="line"&&r(li({id:S,type:A}));break;case "send-to-back":A!=="line"&&r(di({id:S,type:A}));break;case "lock":case "unlock":A!=="line"&&r(ui({id:S,type:A}));break}ne(),B(null),V(null);},[I,r,ne]),Nm=useCallback(w=>{if(!I||!ae)return;let{elementId:S,elementType:A}=I;r(ce()),ae.type==="link"&&A!=="line"?r(Ss({id:S,type:A,link:w})):ae.type==="altText"&&A!=="line"&&r(Is({id:S,type:A,altText:w})),ne(),W(null);},[I,ae,r,ne]),Vm=useCallback(w=>{if(!j)return;let{elementId:S,elementType:A}=j;r(ce()),r(Cs({id:S,type:A,audioData:w})),ne(),ue(null);},[j,r,ne]),qm=useCallback(()=>{if(!j)return;let{elementId:w,elementType:S}=j;r(ce()),r(Cs({id:w,type:S,audioData:""})),ne();},[j,r,ne]),Hm=useCallback(w=>{if(!q)return;let{elementId:S}=q;r(ce()),r(co({id:S,color:w})),ne(),Y(null);},[q,r,ne]),Um=useCallback(w=>{if(!H)return;let{elementId:S}=H;r(ce()),r(uo({id:S,src:w})),ne(),U(null);},[H,r,ne]);return jsxs("div",{ref:v,className:"fixed inset-0",style:{cursor:c==="pen"?"crosshair":c==="eraser"?"":"default"},children:[c==="pen"&&jsx(Cd,{ref:w=>{if(Ne.current=w,Kr(w),w){let S=w.getCanvasElement();S&&(ct.current=S,a&&a(ct));}},width:g.baseWidth,height:g.baseHeight,tool:kn,color:Mn,strokeWidth:Tn/g.scale,isSketchMode:An,xOffset:g.contentOffsetX,yOffset:g.contentOffsetY-g.offsetY/g.scale,style:{width:g.stageWidth,height:g.stageHeight}}),jsxs(Stage,{ref:x,width:g.stageWidth,height:g.stageHeight,scaleX:g.scaleX,scaleY:g.scaleY,x:g.offsetX,y:0,onMouseDown:dd,onMouseMove:ud,onMouseUp:cd,onTouchStart:dd,onTouchMove:ud,onTouchEnd:cd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:g.baseWidth,height:g.stageHeight/g.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-g.contentOffsetX,y:g.offsetY/g.scale-g.contentOffsetY,children:(()=>{let w=[];return h.forEach((S,A)=>{w.push({type:"line",timestamp:S.timestamp||A,element:{...S,id:S.id??`line-${A}`},index:A});}),gm.forEach(S=>{w.push({type:"shape",timestamp:S.timestamp||0,element:S});}),F.forEach(S=>{w.push({type:"image",timestamp:S.timestamp||0,element:S});}),le.forEach(S=>{w.push({type:"video",timestamp:S.timestamp||0,element:S});}),jo.forEach(S=>{w.push({type:"text",timestamp:S.timestamp||0,element:S});}),Lm.forEach(S=>{w.push({type:"flashcard",timestamp:S.timestamp||0,element:S});}),nd.forEach(S=>{w.push({type:"photoFrame",timestamp:S.timestamp||0,element:S});}),Pe.forEach(S=>{w.push({type:"mcq",timestamp:S.timestamp||0,element:S});}),Pn.forEach(S=>{w.push({type:"trueFalse",timestamp:S.timestamp||0,element:S});}),ua.forEach(S=>{w.push({type:"shortAnswer",timestamp:S.timestamp||0,element:S});}),fm.forEach(S=>{w.push({type:"longAnswer",timestamp:S.timestamp||0,element:S});}),pm.forEach(S=>{w.push({type:"fillInTheBlanks",timestamp:S.timestamp||0,element:S});}),w.sort((S,A)=>S.timestamp-A.timestamp),w.map((S,A)=>{let O=`${S.type}-${"id"in S.element&&S.element.id||S.index||A}`,De="id"in S.element?S.element.id:void 0,Le=De&&b===De;switch(S.type){case "line":let oe=S.element,qt=S.index||0,Ct=oe.tool==="eraser",rt=oe.isSketch&&oe.tool==="pen",Ye=oe.isSketch&&Ct,kt=oe.id||`line-${qt}`;return oe.x===void 0&&(oe.x=0),oe.y===void 0&&(oe.y=0),oe.scaleX===void 0&&(oe.scaleX=1),oe.scaleY===void 0&&(oe.scaleY=1),oe.rotation===void 0&&(oe.rotation=0),c==="eraser"?jsx(Group,{x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,children:jsx(Line,{points:oe.points||[],stroke:rt||Ye?void 0:oe.color,strokeWidth:rt||Ye?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:rt||Ye?Ct?"black":oe.color:void 0,closed:rt||Ye,tension:0,globalCompositeOperation:Ct?"destination-out":"source-over",listening:true,onClick:()=>{r(ce()),r(Zr(qt));},onTap:()=>{r(ce()),r(Zr(qt));},hitStrokeWidth:Math.max(20,(oe.strokeWidth??0)*2),onMouseEnter:N=>{let T=N.target.getStage();T&&(T.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:N=>{let T=N.target.getStage();T&&(T.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:kt,ref:N=>{N?Ba.current.set(kt,N):Ba.current.delete(kt);},x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,draggable:c==="select",listening:c==="select",onClick:()=>{c==="select"&&(console.log("Line clicked:",kt),_e(kt));},onTap:()=>{c==="select"&&(console.log("Line tapped:",kt),_e(kt));},onDragEnd:N=>{r(ce()),r(ks({id:kt,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),ne();},onTransformEnd:N=>{r(ce()),r(ks({id:kt,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),ne();},onMouseEnter:N=>{if(c==="select"){let T=N.target.getStage();T&&(T.container().style.cursor="move");}},onMouseLeave:N=>{if(c==="select"){let T=N.target.getStage();T&&(T.container().style.cursor="default");}},onContextMenu:N=>{let T=N.evt;T.preventDefault(),It(T,kt,"line");},children:jsx(Line,{points:oe.points||[],stroke:rt||Ye?void 0:oe.color,strokeWidth:rt||Ye?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:rt||Ye?Ct?"black":oe.color:void 0,closed:rt||Ye,tension:0,globalCompositeOperation:Ct?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Ba.current.get(b);console.log("Line Transformer - selectedId:",b,"node found:",!!T),T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:St,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(Ri,{onSelect:_e,shapes:[S.element],shapeRefs:jr,handleShapeDragEnd:xm,handleShapeResizeEnd:bm,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=jr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Ti,{images:[S.element],getLoadedImage:se,imageRefs:ve,onDragEnd:Rm,onTransform:re,onSelect:_e,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=ve.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Di,{videos:[S.element],selectedId:b,videoRefs:we,onVideoClick:Em,onDragEnd:Ot,onTransformEnd:ft,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=we.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(ru,{texts:[S.element],textRefs:ca,onDragEnd:vm,onTransformEnd:ym,onSelect:_e,onContextMenu:It,onDoubleClick:wm,editingTextId:pe,editingValue:rd,onEditingChange:sd}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=ca.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Bi,{flashcards:[S.element],flashcardRefs:Yr,selectedId:b,onDragEnd:Sm,onTransform:Im,onSelect:_e,onNext:Cm,onPrevious:km,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Yr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Ui,{photoFrames:[S.element],photoFrameRefs:Jr,selectedId:b,onDragEnd:Mm,onTransform:Tm,onSelect:_e,onStartCamera:Am,onCapture:Pm,cameraStreams:Dm,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Jr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Bu,{handleMcqTransform:Ue,multipleChoice:[S.element],handleSelect:_e,mcqRefs:Lt,handleDragEnd:da,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Lt.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Vu,{trueFalses:[S.element],handleTrueFalseTransform:Dn,handleSelect:_e,trueFalseRefs:Oa,onContextMenu:It,handleDragEnd:Nt}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Oa.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(sc,{shortAnswers:[S.element],handleSelect:_e,handleTransform:Ue,saRefs:Vt,onContextMenu:It,handleDragEnd:cm}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Vt.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(mc,{longAnswer:[S.element],handleSelect:_e,handleTransform:Ue,saRefs:Vt,onContextMenu:It,handleDragEnd:mm}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Vt.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(cc,{fillInTheBlanks:[S.element],handleSelect:_e,handleTransform:Ue,onContextMenu:It,handleDragEnd:hm,fibRefs:_r}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=_r.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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}})})()})]}),I&&jsx(xu,{menuRef:k,x:I.x,y:I.y,type:I.elementType,onAction:Bm,onClose:Om,isDrawingMode:I.elementType==="image"?i?.images.find(w=>w.id===I.elementId)?.isDrawingMode:I.elementType==="photoFrame"?i?.photoFrames.find(w=>w.id===I.elementId)?.isDrawingMode:false}),Q&&I&&jsx(bu,{x:Q.x,y:Q.y,items:Q.type==="order"?[{label:"Bring to Front",onClick:()=>En("bring-to-front")},{label:"Send to Back",onClick:()=>En("send-to-back")}]:[{label:i&&(I.elementType==="image"?i.images.find(w=>w.id===I.elementId)?.locked:i.videos.find(w=>w.id===I.elementId)?.locked)?"Unlock":"Lock",onClick:()=>En(i&&(I.elementType==="image"?i.images.find(w=>w.id===I.elementId)?.locked:i.videos.find(w=>w.id===I.elementId)?.locked)?"unlock":"lock")}],onClose:()=>V(null)}),ae&&jsx(wu,{title:ae.type==="link"?"Add Link":"Add Alt Text",label:ae.type==="link"?"URL":"Alternative Text",placeholder:ae.type==="link"?"https://example.com":"Describe this image/video",defaultValue:ae.defaultValue,onSave:Nm,onClose:()=>W(null)}),q&&jsx(Os,{defaultColor:q.defaultColor,onConfirm:Hm,onCancel:()=>Y(null)}),H&&jsx(Cu,{imageSrc:H.imageSrc,onConfirm:Um,onCancel:()=>U(null)}),J&&jsx(dr,{onClose:()=>ee(false),stageRef:x}),j&&jsx(Au,{elementId:j.elementId,elementType:j.elementType,existingAudio:j.existingAudio,onSave:Vm,onDelete:qm,onClose:()=>ue(null)}),ke&&jsx(Ru,{selectedElementId:b||void 0,onClose:()=>Me(false),onSelectElement:w=>{_e(w),Me(false);}}),i?.images.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.videos.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.shapes?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.texts?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.flashcards?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),y&&jsx($u,{editElement:p}),G&&(()=>{let w=pe||b;if(!w)return null;let S=jo.find(A=>A.id===w);return S?jsx(Qu,{text:S,position:G}):null})(),K&&pe&&(()=>{let w=jo.find(S=>S.id===pe);return w?jsx(tc,{text:w,editingValue:rd,onEditingChange:sd,onFinish:Rn,position:{top:K.top,left:K.left},scale:K.scale,textareaRef:Te},pe):null})(),l&&n&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:f?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:u})}),jsx("button",{onClick:u,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X$1,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),n)]})},Hb=qb;function bl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Ze(e,o,{checkForDefaultPrevented:t=true}={}){return function(s){if(e?.(s),t===false||!s.defaultPrevented)return o?.(s)}}function yc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Dr(...e){return o=>{let t=false,a=e.map(s=>{let r=yc(s,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let s=0;s<a.length;s++){let r=a[s];typeof r=="function"?r():yc(e[s],null);}}}}function Ft(...e){return be.useCallback(Dr(...e),e)}function Ma(e,o=[]){let t=[];function a(r,n){let c=be.createContext(n),i=t.length;t=[...t,n];let d=f=>{let{scope:l,children:u,...p}=f,y=l?.[e]?.[i]||c,h=be.useMemo(()=>p,Object.values(p));return jsx(y.Provider,{value:h,children:u})};d.displayName=r+"Provider";function m(f,l){let u=l?.[e]?.[i]||c,p=be.useContext(u);if(p)return p;if(n!==void 0)return n;throw new Error(`\`${f}\` must be used within \`${r}\``)}return [d,m]}let s=()=>{let r=t.map(n=>be.createContext(n));return function(c){let i=c?.[e]||r;return be.useMemo(()=>({[`__scope${e}`]:{...c,[e]:i}}),[c,i])}};return s.scopeName=e,[a,Wb(s,...o)]}function Wb(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(r){let n=a.reduce((c,{useScope:i,scopeName:d})=>{let f=i(r)[`__scope${d}`];return {...c,...f}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var No=globalThis?.document?be.useLayoutEffect:()=>{};var Gb=be[" useInsertionEffect ".trim().toString()]||No;function aa({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[s,r,n]=Kb({defaultProp:o,onChange:t}),c=e!==void 0,i=c?e:s;{let m=be.useRef(e!==void 0);be.useEffect(()=>{let f=m.current;f!==c&&console.warn(`${a} is changing from ${f?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=c;},[c,a]);}let d=be.useCallback(m=>{if(c){let f=_b(m)?m(e):m;f!==e&&n.current?.(f);}else r(m);},[c,e,r,n]);return [i,d]}function Kb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),s=be.useRef(t),r=be.useRef(o);return Gb(()=>{r.current=o;},[o]),be.useEffect(()=>{s.current!==t&&(r.current?.(t),s.current=t);},[t,s]),[t,a,r]}function _b(e){return typeof e=="function"}var jb=be.createContext(void 0);function Vo(e){let o=be.useContext(jb);return e||o||"ltr"}function Sc(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 Cc(e){let[o,t]=be.useState(void 0);return No(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;let r=s[0],n,c;if("borderBoxSize"in r){let i=r.borderBoxSize,d=Array.isArray(i)?i[0]:i;n=d.inlineSize,c=d.blockSize;}else n=e.offsetWidth,c=e.offsetHeight;t({width:n,height:c});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function Mc(e){let o=Xb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,c=be.Children.toArray(r),i=c.find(Yb);if(i){let d=i.props.children,m=c.map(f=>f===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(d)?be.cloneElement(d,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function Xb(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=Zb(s),c=Jb(r,s.props);return s.type!==be.Fragment&&(c.ref=a?Dr(a,n):n),be.cloneElement(s,c)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var $b=Symbol("radix.slottable");function Yb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$b}function Jb(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...c)=>{let i=r(...c);return s(...c),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function Zb(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 tv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],dt=tv.reduce((e,o)=>{let t=Mc(`Primitive.${o}`),a=be.forwardRef((s,r)=>{let{asChild:n,...c}=s,i=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...c,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function vl(e){let o=av(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,c=be.Children.toArray(r),i=c.find(rv);if(i){let d=i.props.children,m=c.map(f=>f===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(d)?be.cloneElement(d,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function av(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=nv(s),c=sv(r,s.props);return s.type!==be.Fragment&&(c.ref=a?Dr(a,n):n),be.cloneElement(s,c)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var ov=Symbol("radix.slottable");function rv(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ov}function sv(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...c)=>{let i=r(...c);return s(...c),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function nv(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 cn(e){let o=e+"CollectionProvider",[t,a]=Ma(o),[s,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=y=>{let{scope:h,children:x}=y,v=be__default.useRef(null),b=be__default.useRef(new Map).current;return jsx(s,{scope:h,itemMap:b,collectionRef:v,children:x})};n.displayName=o;let c=e+"CollectionSlot",i=vl(c),d=be__default.forwardRef((y,h)=>{let{scope:x,children:v}=y,b=r(c,x),L=Ft(h,b.collectionRef);return jsx(i,{ref:L,children:v})});d.displayName=c;let m=e+"CollectionItemSlot",f="data-radix-collection-item",l=vl(m),u=be__default.forwardRef((y,h)=>{let{scope:x,children:v,...b}=y,L=be__default.useRef(null),C=Ft(h,L),M=r(m,x);return be__default.useEffect(()=>(M.itemMap.set(L,{ref:L,...b}),()=>void M.itemMap.delete(L))),jsx(l,{[f]:"",ref:C,children:v})});u.displayName=m;function p(y){let h=r(e+"CollectionConsumer",y);return be__default.useCallback(()=>{let v=h.collectionRef.current;if(!v)return [];let b=Array.from(v.querySelectorAll(`[${f}]`));return Array.from(h.itemMap.values()).sort((M,k)=>b.indexOf(M.ref.current)-b.indexOf(k.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:n,Slot:d,ItemSlot:u},p,a]}var Pc=["PageUp","PageDown"],Dc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Rc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},qo="Slider",[wl,lv,dv]=cn(qo),[Ec]=Ma(qo,[dv]),[uv,fn]=Ec(qo),Fc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:s=100,step:r=1,orientation:n="horizontal",disabled:c=false,minStepsBetweenThumbs:i=0,defaultValue:d=[a],value:m,onValueChange:f=()=>{},onValueCommit:l=()=>{},inverted:u=false,form:p,...y}=e,h=be.useRef(new Set),x=be.useRef(0),b=n==="horizontal"?cv:fv,[L=[],C]=aa({prop:m,defaultProp:d,onChange:I=>{[...h.current][x.current]?.focus(),f(I);}}),M=be.useRef(L);function k(I){let B=xv(L,I);E(I,B);}function g(I){E(I,x.current);}function P(){let I=M.current[x.current];L[x.current]!==I&&l(L);}function E(I,B,{commit:G}={commit:false}){let R=wv(r),K=Lv(Math.round((I-a)/r)*r+a,R),D=bl(K,[a,s]);C((Q=[])=>{let V=hv(Q,D,B);if(yv(V,i*r)){x.current=V.indexOf(D);let ae=String(V)!==String(Q);return ae&&G&&l(V),ae?V:Q}else return Q});}return jsx(uv,{scope:e.__scopeSlider,name:t,disabled:c,min:a,max:s,valueIndexToChangeRef:x,thumbs:h.current,values:L,orientation:n,form:p,children:jsx(wl.Provider,{scope:e.__scopeSlider,children:jsx(wl.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":c,"data-disabled":c?"":void 0,...y,ref:o,onPointerDown:Ze(y.onPointerDown,()=>{c||(M.current=L);}),min:a,max:s,inverted:u,onSlideStart:c?void 0:k,onSlideMove:c?void 0:g,onSlideEnd:c?void 0:P,onHomeKeyDown:()=>!c&&E(a,0,{commit:true}),onEndKeyDown:()=>!c&&E(s,L.length-1,{commit:true}),onStepKeyDown:({event:I,direction:B})=>{if(!c){let K=Pc.includes(I.key)||I.shiftKey&&Dc.includes(I.key)?10:1,D=x.current,Q=L[D],V=r*K*B;E(Q+V,D,{commit:true});}}})})})})});Fc.displayName=qo;var[Bc,Oc]=Ec(qo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),cv=be.forwardRef((e,o)=>{let{min:t,max:a,dir:s,inverted:r,onSlideStart:n,onSlideMove:c,onSlideEnd:i,onStepKeyDown:d,...m}=e,[f,l]=be.useState(null),u=Ft(o,b=>l(b)),p=be.useRef(void 0),y=Vo(s),h=y==="ltr",x=h&&!r||!h&&r;function v(b){let L=p.current||f.getBoundingClientRect(),C=[0,L.width],k=Il(C,x?[t,a]:[a,t]);return p.current=L,k(b-L.left)}return jsx(Bc,{scope:e.__scopeSlider,startEdge:x?"left":"right",endEdge:x?"right":"left",direction:x?1:-1,size:"width",children:jsx(Nc,{dir:y,"data-orientation":"horizontal",...m,ref:u,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let L=v(b.clientX);n?.(L);},onSlideMove:b=>{let L=v(b.clientX);c?.(L);},onSlideEnd:()=>{p.current=void 0,i?.();},onStepKeyDown:b=>{let C=Rc[x?"from-left":"from-right"].includes(b.key);d?.({event:b,direction:C?-1:1});}})})}),fv=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:s,onSlideStart:r,onSlideMove:n,onSlideEnd:c,onStepKeyDown:i,...d}=e,m=be.useRef(null),f=Ft(o,m),l=be.useRef(void 0),u=!s;function p(y){let h=l.current||m.current.getBoundingClientRect(),x=[0,h.height],b=Il(x,u?[a,t]:[t,a]);return l.current=h,b(y-h.top)}return jsx(Bc,{scope:e.__scopeSlider,startEdge:u?"bottom":"top",endEdge:u?"top":"bottom",size:"height",direction:u?1:-1,children:jsx(Nc,{"data-orientation":"vertical",...d,ref:f,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{let h=p(y.clientY);r?.(h);},onSlideMove:y=>{let h=p(y.clientY);n?.(h);},onSlideEnd:()=>{l.current=void 0,c?.();},onStepKeyDown:y=>{let x=Rc[u?"from-bottom":"from-top"].includes(y.key);i?.({event:y,direction:x?-1:1});}})})}),Nc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:s,onSlideEnd:r,onHomeKeyDown:n,onEndKeyDown:c,onStepKeyDown:i,...d}=e,m=fn(qo,t);return jsx(dt.span,{...d,ref:o,onKeyDown:Ze(e.onKeyDown,f=>{f.key==="Home"?(n(f),f.preventDefault()):f.key==="End"?(c(f),f.preventDefault()):Pc.concat(Dc).includes(f.key)&&(i(f),f.preventDefault());}),onPointerDown:Ze(e.onPointerDown,f=>{let l=f.target;l.setPointerCapture(f.pointerId),f.preventDefault(),m.thumbs.has(l)?l.focus():a(f);}),onPointerMove:Ze(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f);}),onPointerUp:Ze(e.onPointerUp,f=>{let l=f.target;l.hasPointerCapture(f.pointerId)&&(l.releasePointerCapture(f.pointerId),r(f));})})}),Vc="SliderTrack",qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=fn(Vc,t);return jsx(dt.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...a,ref:o})});qc.displayName=Vc;var Ll="SliderRange",Hc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=fn(Ll,t),r=Oc(Ll,t),n=be.useRef(null),c=Ft(o,n),i=s.values.length,d=s.values.map(l=>Wc(l,s.min,s.max)),m=i>1?Math.min(...d):0,f=100-Math.max(...d);return jsx(dt.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...a,ref:c,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:f+"%"}})});Hc.displayName=Ll;var Sl="SliderThumb",Uc=be.forwardRef((e,o)=>{let t=lv(e.__scopeSlider),[a,s]=be.useState(null),r=Ft(o,c=>s(c)),n=be.useMemo(()=>a?t().findIndex(c=>c.ref.current===a):-1,[t,a]);return jsx(mv,{...e,ref:r,index:n})}),mv=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:s,...r}=e,n=fn(Sl,t),c=Oc(Sl,t),[i,d]=be.useState(null),m=Ft(o,v=>d(v)),f=i?n.form||!!i.closest("form"):true,l=Cc(i),u=n.values[a],p=u===void 0?0:Wc(u,n.min,n.max),y=gv(a,n.values.length),h=l?.[c.size],x=h?bv(h,p,c.direction):0;return be.useEffect(()=>{if(i)return n.thumbs.add(i),()=>{n.thumbs.delete(i);}},[i,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[c.startEdge]:`calc(${p}% + ${x}px)`},children:[jsx(wl.ItemSlot,{scope:e.__scopeSlider,children:jsx(dt.span,{role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":n.min,"aria-valuenow":u,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...r,ref:m,style:u===void 0?{display:"none"}:e.style,onFocus:Ze(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),f&&jsx(zc,{name:s??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:u},a)]})});Uc.displayName=Sl;var pv="RadioBubbleInput",zc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let s=be.useRef(null),r=Ft(s,a),n=Sc(o);return be.useEffect(()=>{let c=s.current;if(!c)return;let i=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(i,"value").set;if(n!==o&&m){let f=new Event("input",{bubbles:true});m.call(c,o),c.dispatchEvent(f);}},[n,o]),jsx(dt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});zc.displayName=pv;function hv(e=[],o,t){let a=[...e];return a[t]=o,a.sort((s,r)=>s-r)}function Wc(e,o,t){let r=100/(t-o)*(e-o);return bl(r,[0,100])}function gv(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function xv(e,o){if(e.length===1)return 0;let t=e.map(s=>Math.abs(s-o)),a=Math.min(...t);return t.indexOf(a)}function bv(e,o,t){let a=e/2,r=Il([0,50],[0,a]);return (a-r(o)*t)*t}function vv(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function yv(e,o){if(o>0){let t=vv(e);return Math.min(...t)>=o}return true}function Il(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 wv(e){return (String(e).split(".")[1]||"").length}function Lv(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Gc=Fc,Kc=qc,_c=Hc,jc=Uc;function Xc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(o=0;o<s;o++)e[o]&&(t=Xc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function mn(){for(var e,o,t=0,a="",s=arguments.length;t<s;t++)(e=arguments[t])&&(o=Xc(e))&&(a&&(a+=" "),a+=o);return a}var Iv=(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},Cv=(e,o)=>({classGroupId:e,validator:o}),Qc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var $c=[],kv="arbitrary..",Mv=e=>{let o=Av(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return Tv(n);let c=n.split("-"),i=c[0]===""&&c.length>1?1:0;return ef(c,i,o)},getConflictingClassGroupIds:(n,c)=>{if(c){let i=a[n],d=t[n];return i?d?Iv(d,i):i:d||$c}return t[n]||$c}}},ef=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let s=e[o],r=t.nextPart.get(s);if(r){let d=ef(e,o+1,r);if(d)return d}let n=t.validators;if(n===null)return;let c=o===0?e.join("-"):e.slice(o).join("-"),i=n.length;for(let d=0;d<i;d++){let m=n[d];if(m.validator(c))return m.classGroupId}},Tv=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?kv+a:void 0})(),Av=e=>{let{theme:o,classGroups:t}=e;return Pv(t,o)},Pv=(e,o)=>{let t=Qc();for(let a in e){let s=e[a];Ml(s,t,a,o);}return t},Ml=(e,o,t,a)=>{let s=e.length;for(let r=0;r<s;r++){let n=e[r];Dv(n,o,t,a);}},Dv=(e,o,t,a)=>{if(typeof e=="string"){Rv(e,o,t);return}if(typeof e=="function"){Ev(e,o,t,a);return}Fv(e,o,t,a);},Rv=(e,o,t)=>{let a=e===""?o:tf(o,e);a.classGroupId=t;},Ev=(e,o,t,a)=>{if(Bv(e)){Ml(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Cv(t,e));},Fv=(e,o,t,a)=>{let s=Object.entries(e),r=s.length;for(let n=0;n<r;n++){let[c,i]=s[n];Ml(i,tf(o,c),t,a);}},tf=(e,o)=>{let t=e,a=o.split("-"),s=a.length;for(let r=0;r<s;r++){let n=a[r],c=t.nextPart.get(n);c||(c=Qc(),t.nextPart.set(n,c)),t=c;}return t},Bv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Ov=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),s=(r,n)=>{t[r]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let n=t[r];if(n!==void 0)return n;if((n=a[r])!==void 0)return s(r,n),n},set(r,n){r in t?t[r]=n:s(r,n);}}};var Nv=[],Yc=(e,o,t,a,s)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:s}),Vv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=s=>{let r=[],n=0,c=0,i=0,d,m=s.length;for(let y=0;y<m;y++){let h=s[y];if(n===0&&c===0){if(h===":"){r.push(s.slice(i,y)),i=y+1;continue}if(h==="/"){d=y;continue}}h==="["?n++:h==="]"?n--:h==="("?c++:h===")"&&c--;}let f=r.length===0?s:s.slice(i),l=f,u=false;f.endsWith("!")?(l=f.slice(0,-1),u=true):f.startsWith("!")&&(l=f.slice(1),u=true);let p=d&&d>i?d-i:void 0;return Yc(r,u,l,p)};if(o){let s=o+":",r=a;a=n=>n.startsWith(s)?r(n.slice(s.length)):Yc(Nv,false,n,void 0,true);}if(t){let s=a;a=r=>t({className:r,parseClassName:s});}return a},qv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],s=[];for(let r=0;r<t.length;r++){let n=t[r],c=n[0]==="[",i=o.has(n);c||i?(s.length>0&&(s.sort(),a.push(...s),s=[]),a.push(n)):s.push(n);}return s.length>0&&(s.sort(),a.push(...s)),a}},Hv=e=>({cache:Ov(e.cacheSize),parseClassName:Vv(e),sortModifiers:qv(e),...Mv(e)}),Uv=/\s+/,zv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:s,sortModifiers:r}=o,n=[],c=e.trim().split(Uv),i="";for(let d=c.length-1;d>=0;d-=1){let m=c[d],{isExternal:f,modifiers:l,hasImportantModifier:u,baseClassName:p,maybePostfixModifierPosition:y}=t(m);if(f){i=m+(i.length>0?" "+i:i);continue}let h=!!y,x=a(h?p.substring(0,y):p);if(!x){if(!h){i=m+(i.length>0?" "+i:i);continue}if(x=a(p),!x){i=m+(i.length>0?" "+i:i);continue}h=false;}let v=l.length===0?"":l.length===1?l[0]:r(l).join(":"),b=u?v+"!":v,L=b+x;if(n.indexOf(L)>-1)continue;n.push(L);let C=s(x,h);for(let M=0;M<C.length;++M){let k=C[M];n.push(b+k);}i=m+(i.length>0?" "+i:i);}return i},Wv=(...e)=>{let o=0,t,a,s="";for(;o<e.length;)(t=e[o++])&&(a=af(t))&&(s&&(s+=" "),s+=a);return s},af=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=af(e[a]))&&(t&&(t+=" "),t+=o);return t},Gv=(e,...o)=>{let t,a,s,r,n=i=>{let d=o.reduce((m,f)=>f(m),e());return t=Hv(d),a=t.cache.get,s=t.cache.set,r=c,c(i)},c=i=>{let d=a(i);if(d)return d;let m=zv(i,t);return s(i,m),m};return r=n,(...i)=>r(Wv(...i))},Kv=[],He=e=>{let o=t=>t[e]||Kv;return o.isThemeGetter=true,o},of=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,rf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,_v=/^\d+\/\d+$/,jv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Xv=/\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$/,$v=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Yv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Jv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ho=e=>_v.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ta=e=>!!e&&Number.isInteger(Number(e)),Cl=e=>e.endsWith("%")&&de(e.slice(0,-1)),oa=e=>jv.test(e),Zv=()=>true,Qv=e=>Xv.test(e)&&!$v.test(e),sf=()=>false,ey=e=>Yv.test(e),ty=e=>Jv.test(e),ay=e=>!X(e)&&!$(e),oy=e=>Uo(e,df,sf),X=e=>of.test(e),Qa=e=>Uo(e,uf,Qv),kl=e=>Uo(e,ly,de),Jc=e=>Uo(e,nf,sf),ry=e=>Uo(e,lf,ty),pn=e=>Uo(e,cf,ey),$=e=>rf.test(e),Rr=e=>zo(e,uf),sy=e=>zo(e,dy),Zc=e=>zo(e,nf),ny=e=>zo(e,df),iy=e=>zo(e,lf),hn=e=>zo(e,cf,true),Uo=(e,o,t)=>{let a=of.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},zo=(e,o,t=false)=>{let a=rf.exec(e);return a?a[1]?o(a[1]):t:false},nf=e=>e==="position"||e==="percentage",lf=e=>e==="image"||e==="url",df=e=>e==="length"||e==="size"||e==="bg-size",uf=e=>e==="length",ly=e=>e==="number",dy=e=>e==="family-name",cf=e=>e==="shadow";var uy=()=>{let e=He("color"),o=He("font"),t=He("text"),a=He("font-weight"),s=He("tracking"),r=He("leading"),n=He("breakpoint"),c=He("container"),i=He("spacing"),d=He("radius"),m=He("shadow"),f=He("inset-shadow"),l=He("text-shadow"),u=He("drop-shadow"),p=He("blur"),y=He("perspective"),h=He("aspect"),x=He("ease"),v=He("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],C=()=>[...L(),$,X],M=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],g=()=>[$,X,i],P=()=>[Ho,"full","auto",...g()],E=()=>[Ta,"none","subgrid",$,X],I=()=>["auto",{span:["full",Ta,$,X]},Ta,$,X],B=()=>[Ta,"auto",$,X],G=()=>["auto","min","max","fr",$,X],R=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],K=()=>["start","end","center","stretch","center-safe","end-safe"],D=()=>["auto",...g()],Q=()=>[Ho,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...g()],V=()=>[e,$,X],ae=()=>[...L(),Zc,Jc,{position:[$,X]}],W=()=>["no-repeat",{repeat:["","x","y","space","round"]}],q=()=>["auto","cover","contain",ny,oy,{size:[$,X]}],Y=()=>[Cl,Rr,Qa],H=()=>["","none","full",d,$,X],U=()=>["",de,Rr,Qa],J=()=>["solid","dashed","dotted","double"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],j=()=>[de,Cl,Zc,Jc],ue=()=>["","none",p,$,X],ke=()=>["none",de,$,X],Me=()=>["none",de,$,X],Te=()=>[de,$,X],Ne=()=>[Ho,"full",...g()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[oa],breakpoint:[oa],color:[Zv],container:[oa],"drop-shadow":[oa],ease:["in","out","in-out"],font:[ay],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[oa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[oa],shadow:[oa],spacing:["px",de],text:[oa],"text-shadow":[oa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ho,X,$,h]}],container:["container"],columns:[{columns:[de,X,$,c]}],"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:C()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],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:[Ta,"auto",$,X]}],basis:[{basis:[Ho,"full","auto",c,...g()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Ho,"auto","initial","none",X]}],grow:[{grow:["",de,$,X]}],shrink:[{shrink:["",de,$,X]}],order:[{order:[Ta,"first","last","none",$,X]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:I()}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:I()}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:g()}],"gap-x":[{"gap-x":g()}],"gap-y":[{"gap-y":g()}],"justify-content":[{justify:[...R(),"normal"]}],"justify-items":[{"justify-items":[...K(),"normal"]}],"justify-self":[{"justify-self":["auto",...K()]}],"align-content":[{content:["normal",...R()]}],"align-items":[{items:[...K(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...K(),{baseline:["","last"]}]}],"place-content":[{"place-content":R()}],"place-items":[{"place-items":[...K(),"baseline"]}],"place-self":[{"place-self":["auto",...K()]}],p:[{p:g()}],px:[{px:g()}],py:[{py:g()}],ps:[{ps:g()}],pe:[{pe:g()}],pt:[{pt:g()}],pr:[{pr:g()}],pb:[{pb:g()}],pl:[{pl:g()}],m:[{m:D()}],mx:[{mx:D()}],my:[{my:D()}],ms:[{ms:D()}],me:[{me:D()}],mt:[{mt:D()}],mr:[{mr:D()}],mb:[{mb:D()}],ml:[{ml:D()}],"space-x":[{"space-x":g()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":g()}],"space-y-reverse":["space-y-reverse"],size:[{size:Q()}],w:[{w:[c,"screen",...Q()]}],"min-w":[{"min-w":[c,"screen","none",...Q()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[n]},...Q()]}],h:[{h:["screen","lh",...Q()]}],"min-h":[{"min-h":["screen","lh","none",...Q()]}],"max-h":[{"max-h":["screen","lh",...Q()]}],"font-size":[{text:["base",t,Rr,Qa]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,kl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Cl,X]}],"font-family":[{font:[sy,X,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,$,X]}],"line-clamp":[{"line-clamp":[de,"none",$,kl]}],leading:[{leading:[r,...g()]}],"list-image":[{"list-image":["none",$,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:V()}],"text-color":[{text:V()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",$,Qa]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[de,"auto",$,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:g()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:ae()}],"bg-repeat":[{bg:W()}],"bg-size":[{bg:q()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ta,$,X],radial:["",$,X],conic:[Ta,$,X]},iy,ry]}],"bg-color":[{bg:V()}],"gradient-from-pos":[{from:Y()}],"gradient-via-pos":[{via:Y()}],"gradient-to-pos":[{to:Y()}],"gradient-from":[{from:V()}],"gradient-via":[{via:V()}],"gradient-to":[{to:V()}],rounded:[{rounded:H()}],"rounded-s":[{"rounded-s":H()}],"rounded-e":[{"rounded-e":H()}],"rounded-t":[{"rounded-t":H()}],"rounded-r":[{"rounded-r":H()}],"rounded-b":[{"rounded-b":H()}],"rounded-l":[{"rounded-l":H()}],"rounded-ss":[{"rounded-ss":H()}],"rounded-se":[{"rounded-se":H()}],"rounded-ee":[{"rounded-ee":H()}],"rounded-es":[{"rounded-es":H()}],"rounded-tl":[{"rounded-tl":H()}],"rounded-tr":[{"rounded-tr":H()}],"rounded-br":[{"rounded-br":H()}],"rounded-bl":[{"rounded-bl":H()}],"border-w":[{border:U()}],"border-w-x":[{"border-x":U()}],"border-w-y":[{"border-y":U()}],"border-w-s":[{"border-s":U()}],"border-w-e":[{"border-e":U()}],"border-w-t":[{"border-t":U()}],"border-w-r":[{"border-r":U()}],"border-w-b":[{"border-b":U()}],"border-w-l":[{"border-l":U()}],"divide-x":[{"divide-x":U()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":U()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:V()}],"border-color-x":[{"border-x":V()}],"border-color-y":[{"border-y":V()}],"border-color-s":[{"border-s":V()}],"border-color-e":[{"border-e":V()}],"border-color-t":[{"border-t":V()}],"border-color-r":[{"border-r":V()}],"border-color-b":[{"border-b":V()}],"border-color-l":[{"border-l":V()}],"divide-color":[{divide:V()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,$,X]}],"outline-w":[{outline:["",de,Rr,Qa]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",m,hn,pn]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",f,hn,pn]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:U()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[de,Qa]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":U()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",l,hn,pn]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[de,$,X]}],"mix-blend":[{"mix-blend":[...ee(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ee()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":j()}],"mask-image-linear-to-pos":[{"mask-linear-to":j()}],"mask-image-linear-from-color":[{"mask-linear-from":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"mask-image-t-from-pos":[{"mask-t-from":j()}],"mask-image-t-to-pos":[{"mask-t-to":j()}],"mask-image-t-from-color":[{"mask-t-from":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"mask-image-r-from-pos":[{"mask-r-from":j()}],"mask-image-r-to-pos":[{"mask-r-to":j()}],"mask-image-r-from-color":[{"mask-r-from":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"mask-image-b-from-pos":[{"mask-b-from":j()}],"mask-image-b-to-pos":[{"mask-b-to":j()}],"mask-image-b-from-color":[{"mask-b-from":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"mask-image-l-from-pos":[{"mask-l-from":j()}],"mask-image-l-to-pos":[{"mask-l-to":j()}],"mask-image-l-from-color":[{"mask-l-from":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"mask-image-x-from-pos":[{"mask-x-from":j()}],"mask-image-x-to-pos":[{"mask-x-to":j()}],"mask-image-x-from-color":[{"mask-x-from":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"mask-image-y-from-pos":[{"mask-y-from":j()}],"mask-image-y-to-pos":[{"mask-y-to":j()}],"mask-image-y-from-color":[{"mask-y-from":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[$,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":j()}],"mask-image-radial-to-pos":[{"mask-radial-to":j()}],"mask-image-radial-from-color":[{"mask-radial-from":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":j()}],"mask-image-conic-to-pos":[{"mask-conic-to":j()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:ae()}],"mask-repeat":[{mask:W()}],"mask-size":[{mask:q()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,X]}],filter:[{filter:["","none",$,X]}],blur:[{blur:ue()}],brightness:[{brightness:[de,$,X]}],contrast:[{contrast:[de,$,X]}],"drop-shadow":[{"drop-shadow":["","none",u,hn,pn]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",de,$,X]}],"hue-rotate":[{"hue-rotate":[de,$,X]}],invert:[{invert:["",de,$,X]}],saturate:[{saturate:[de,$,X]}],sepia:[{sepia:["",de,$,X]}],"backdrop-filter":[{"backdrop-filter":["","none",$,X]}],"backdrop-blur":[{"backdrop-blur":ue()}],"backdrop-brightness":[{"backdrop-brightness":[de,$,X]}],"backdrop-contrast":[{"backdrop-contrast":[de,$,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,$,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,$,X]}],"backdrop-invert":[{"backdrop-invert":["",de,$,X]}],"backdrop-opacity":[{"backdrop-opacity":[de,$,X]}],"backdrop-saturate":[{"backdrop-saturate":[de,$,X]}],"backdrop-sepia":[{"backdrop-sepia":["",de,$,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":g()}],"border-spacing-x":[{"border-spacing-x":g()}],"border-spacing-y":[{"border-spacing-y":g()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",$,X]}],ease:[{ease:["linear","initial",x,$,X]}],delay:[{delay:[de,$,X]}],animate:[{animate:["none",v,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,$,X]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:ke()}],"rotate-x":[{"rotate-x":ke()}],"rotate-y":[{"rotate-y":ke()}],"rotate-z":[{"rotate-z":ke()}],scale:[{scale:Me()}],"scale-x":[{"scale-x":Me()}],"scale-y":[{"scale-y":Me()}],"scale-z":[{"scale-z":Me()}],"scale-3d":["scale-3d"],skew:[{skew:Te()}],"skew-x":[{"skew-x":Te()}],"skew-y":[{"skew-y":Te()}],transform:[{transform:[$,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ne()}],"translate-x":[{"translate-x":Ne()}],"translate-y":[{"translate-y":Ne()}],"translate-z":[{"translate-z":Ne()}],"translate-none":["translate-none"],accent:[{accent:V()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:V()}],"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",$,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":g()}],"scroll-mx":[{"scroll-mx":g()}],"scroll-my":[{"scroll-my":g()}],"scroll-ms":[{"scroll-ms":g()}],"scroll-me":[{"scroll-me":g()}],"scroll-mt":[{"scroll-mt":g()}],"scroll-mr":[{"scroll-mr":g()}],"scroll-mb":[{"scroll-mb":g()}],"scroll-ml":[{"scroll-ml":g()}],"scroll-p":[{"scroll-p":g()}],"scroll-px":[{"scroll-px":g()}],"scroll-py":[{"scroll-py":g()}],"scroll-ps":[{"scroll-ps":g()}],"scroll-pe":[{"scroll-pe":g()}],"scroll-pt":[{"scroll-pt":g()}],"scroll-pr":[{"scroll-pr":g()}],"scroll-pb":[{"scroll-pb":g()}],"scroll-pl":[{"scroll-pl":g()}],"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",$,X]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[de,Rr,Qa,kl]}],stroke:[{stroke:["none",...V()]}],"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 ff=Gv(uy);function Aa(...e){return ff(mn(e))}function gn({className:e,defaultValue:o,value:t,min:a=0,max:s=100,rangeClassName:r,trackClassName:n,thumbClassName:c,...i}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,s],[t,o,a,s]);return jsxs(Gc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:s,className:Aa("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[jsx(Kc,{"data-slot":"slider-track",className:Aa("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(_c,{"data-slot":"slider-range",className:Aa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:d.length},(m,f)=>jsx(jc,{"data-slot":"slider-thumb",className:Aa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",c)},f))]})}var fy="SchooplaVideoStorage";var Zt="videos",xn=()=>new Promise((e,o)=>{let t=indexedDB.open(fy,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Zt)||s.createObjectStore(Zt,{keyPath:"id"});};}),eo=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await xn(),r=a.transaction([Zt],"readwrite").objectStore(Zt),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((c,i)=>{let d=r.put(n);d.onsuccess=()=>c(!0),d.onerror=()=>i(d.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var pf=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await xn(),t=e.transaction([Zt],"readonly").objectStore(Zt);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result,c=new Map;n.forEach(i=>{c.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${c.size} video blobs from IndexedDB`),a(c);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Al=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await xn(),a=o.transaction([Zt],"readwrite").objectStore(Zt);await new Promise((s,r)=>{let n=a.delete(e);n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},hf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await xn(),t=e.transaction([Zt],"readwrite").objectStore(Zt);await new Promise((a,s)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>s(r.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},gf=e=>URL.createObjectURL(e);var my=be[" useId ".trim().toString()]||(()=>{}),py=0;function xf(e){let[o,t]=be.useState(my());return No(()=>{t(a=>a??String(py++));},[e]),(o?`radix-${o}`:"")}function bf(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var Dl="rovingFocusGroup.onEntryFocus",hy={bubbles:false,cancelable:true},Er="RovingFocusGroup",[Rl,vf,gy]=cn(Er),[xy,El]=Ma(Er,[gy]),[by,vy]=xy(Er),yf=be.forwardRef((e,o)=>jsx(Rl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Rl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(yy,{...e,ref:o})})}));yf.displayName=Er;var yy=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:s=false,dir:r,currentTabStopId:n,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:i,onEntryFocus:d,preventScrollOnEntryFocus:m=false,...f}=e,l=be.useRef(null),u=Ft(o,l),p=Vo(r),[y,h]=aa({prop:n,defaultProp:c??null,onChange:i,caller:Er}),[x,v]=be.useState(false),b=bf(d),L=vf(t),C=be.useRef(false),[M,k]=be.useState(0);return be.useEffect(()=>{let g=l.current;if(g)return g.addEventListener(Dl,b),()=>g.removeEventListener(Dl,b)},[b]),jsx(by,{scope:t,orientation:a,dir:p,loop:s,currentTabStopId:y,onItemFocus:be.useCallback(g=>h(g),[h]),onItemShiftTab:be.useCallback(()=>v(true),[]),onFocusableItemAdd:be.useCallback(()=>k(g=>g+1),[]),onFocusableItemRemove:be.useCallback(()=>k(g=>g-1),[]),children:jsx(dt.div,{tabIndex:x||M===0?-1:0,"data-orientation":a,...f,ref:u,style:{outline:"none",...e.style},onMouseDown:Ze(e.onMouseDown,()=>{C.current=true;}),onFocus:Ze(e.onFocus,g=>{let P=!C.current;if(g.target===g.currentTarget&&P&&!x){let E=new CustomEvent(Dl,hy);if(g.currentTarget.dispatchEvent(E),!E.defaultPrevented){let I=L().filter(D=>D.focusable),B=I.find(D=>D.active),G=I.find(D=>D.id===y),K=[B,G,...I].filter(Boolean).map(D=>D.ref.current);Sf(K,m);}}C.current=false;}),onBlur:Ze(e.onBlur,()=>v(false))})})}),wf="RovingFocusGroupItem",Lf=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:s=false,tabStopId:r,children:n,...c}=e,i=xf(),d=r||i,m=vy(wf,t),f=m.currentTabStopId===d,l=vf(t),{onFocusableItemAdd:u,onFocusableItemRemove:p,currentTabStopId:y}=m;return be.useEffect(()=>{if(a)return u(),()=>p()},[a,u,p]),jsx(Rl.ItemSlot,{scope:t,id:d,focusable:a,active:s,children:jsx(dt.span,{tabIndex:f?0:-1,"data-orientation":m.orientation,...c,ref:o,onMouseDown:Ze(e.onMouseDown,h=>{a?m.onItemFocus(d):h.preventDefault();}),onFocus:Ze(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:Ze(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){m.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let x=Sy(h,m.orientation,m.dir);if(x!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let b=l().filter(L=>L.focusable).map(L=>L.ref.current);if(x==="last")b.reverse();else if(x==="prev"||x==="next"){x==="prev"&&b.reverse();let L=b.indexOf(h.currentTarget);b=m.loop?Iy(b,L+1):b.slice(L+1);}setTimeout(()=>Sf(b));}}),children:typeof n=="function"?n({isCurrentTabStop:f,hasTabStop:y!=null}):n})})});Lf.displayName=wf;var wy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Ly(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Sy(e,o,t){let a=Ly(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return wy[a]}function Sf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Iy(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var If=yf,Cf=Lf;var Mf="Toggle",Fl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:s,...r}=e,[n,c]=aa({prop:t,onChange:s,defaultProp:a??false,caller:Mf});return jsx(dt.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:Ze(e.onClick,()=>{e.disabled||c(!n);})})});Fl.displayName=Mf;var Pa="ToggleGroup",[Af]=Ma(Pa,[El]),Pf=El(),Bl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(My,{...a,ref:o});if(t==="multiple")return jsx(Ty,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Pa}\``)});Bl.displayName=Pa;var[Df,Rf]=Af(Pa),My=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,c]=aa({prop:t,defaultProp:a??"",onChange:s,caller:Pa});return jsx(Df,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:c,onItemDeactivate:be__default.useCallback(()=>c(""),[c]),children:jsx(Ef,{...r,ref:o})})}),Ty=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,c]=aa({prop:t,defaultProp:a??[],onChange:s,caller:Pa}),i=be__default.useCallback(m=>c((f=[])=>[...f,m]),[c]),d=be__default.useCallback(m=>c((f=[])=>f.filter(l=>l!==m)),[c]);return jsx(Df,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:i,onItemDeactivate:d,children:jsx(Ef,{...r,ref:o})})});Bl.displayName=Pa;var[Ay,Py]=Af(Pa),Ef=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:s=true,orientation:r,dir:n,loop:c=true,...i}=e,d=Pf(t),m=Vo(n),f={role:"group",dir:m,...i};return jsx(Ay,{scope:t,rovingFocus:s,disabled:a,children:s?jsx(If,{asChild:true,...d,orientation:r,dir:m,loop:c,children:jsx(dt.div,{...f,ref:o})}):jsx(dt.div,{...f,ref:o})})}),bn="ToggleGroupItem",Dy=be__default.forwardRef((e,o)=>{let t=Rf(bn,e.__scopeToggleGroup),a=Py(bn,e.__scopeToggleGroup),s=Pf(e.__scopeToggleGroup),r=t.value.includes(e.value),n=a.disabled||e.disabled,c={...e,pressed:r,disabled:n},i=be__default.useRef(null);return a.rovingFocus?jsx(Cf,{asChild:true,...s,focusable:!n,active:r,ref:i,children:jsx(Tf,{...c,ref:o})}):jsx(Tf,{...c,ref:o})});Dy.displayName=bn;var Tf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...s}=e,r=Rf(bn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=r.type==="single"?n:void 0;return jsx(Fl,{...c,...s,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Ff=Bl;var Fy=be.createContext({size:"default",variant:"default",spacing:0});function Da({className:e,variant:o,size:t,spacing:a=1,children:s,...r}){return jsx(Ff,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Aa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Fy.Provider,{value:{variant:o,size:t,spacing:a},children:s})})}var Oy={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},qf=createSlice({name:"toolbar",initialState:Oy,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:_t,setPenColor:Go,setStrokeWidth:Fr,setFontSize:wD,setFontFamily:LD,setFontStyle:SD,setFontWeight:ID,setTextDecoration:CD,setTextColor:kD}=qf.actions,Hf=qf.reducer;var Uf=({onClose:e,onRecordingComplete:o})=>{let t=ze(),[a,s]=useState(false),[r,n]=useState(null),[c,i]=useState(0),[d,m]=useState(null),[f,l]=useState(false),u=useRef(null),p=useRef([]),y=useRef(null),h=useRef(null),x=useRef(null);useEffect(()=>((async()=>{try{let P=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(P),l(!0),x.current&&(x.current.srcObject=P);}catch(P){console.error("Error accessing camera:",P),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{y.current&&clearInterval(y.current),d&&d.getTracks().forEach(P=>P.stop());}),[]);let v=()=>{d&&(d.getTracks().forEach(g=>g.stop()),m(null),l(false));},b=async()=>{try{let g=null,P=null;try{g=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(R){console.error("Error accessing camera for recording:",R),alert("Failed to access camera for recording.");return}try{P=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(R){console.warn("Microphone access denied:",R);}let E=[...g.getVideoTracks()];P&&E.push(...P.getAudioTracks());let I=new MediaStream(E),B="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?B="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?B="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?B="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(B="video/webm;codecs=vp8");let G=new MediaRecorder(I,{mimeType:B,videoBitsPerSecond:25e5});u.current=G,p.current=[],G.ondataavailable=R=>{R.data.size>0&&p.current.push(R.data);},G.onstop=()=>{let R=new Blob(p.current,{type:B}),K=document.createElement("video");K.src=URL.createObjectURL(R),K.muted=!0,K.currentTime=.1,K.onseeked=()=>{let D=document.createElement("canvas");D.width=K.videoWidth,D.height=K.videoHeight;let Q=D.getContext("2d");Q&&(Q.drawImage(K,0,0),h.current=D.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(K.src);},I.getTracks().forEach(D=>D.stop()),g&&g.getTracks().forEach(D=>D.stop()),P&&P.getTracks().forEach(D=>D.stop()),y.current&&clearInterval(y.current),n(R),v();},G.onerror=R=>{console.error("MediaRecorder error:",R);},G.start(1e3),s(!0),i(0),y.current=setInterval(()=>{i(R=>R+1);},1e3);}catch(g){console.error("Error starting camera recording:",g),alert("Failed to start recording. Please check permissions.");}},L=()=>{u.current&&a&&(u.current.state!=="inactive"&&(u.current.requestData(),setTimeout(()=>{u.current&&u.current.state!=="inactive"&&u.current.stop();},100)),s(false));},C=()=>{if(r){let g=URL.createObjectURL(r),P=document.createElement("a");P.href=g,P.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(g);}},M=g=>{let P=Math.floor(g/60),E=g%60;return `${P.toString().padStart(2,"0")}:${E.toString().padStart(2,"0")}`};if(!t)return null;let k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:g=>{g.target===g.currentTarget&&e(),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",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:g=>g.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:x,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:b,disabled:!f,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!f&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:L,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:M(c)})]})]})]}),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: ",M(c)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:C,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&h.current&&(o(r,h.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(k,t)};var ra=40,Wf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,s]=useState(t?.images||[]),[r,n]=useState(t?.order||"sequential"),[c,i]=useState(false),d=useRef(null),m=ze(),f=useRef(null);useEffect(()=>{let b=L=>{L.key==="Escape"&&o();};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[o]);let l=b=>{let L=b.target.files;if(!L||L.length===0)return;let C=ra-a.length;if(C<=0){alert(`You can only upload a maximum of ${ra} images`);return}let M=Array.from(L).slice(0,C);M.length<L.length&&alert(`Only ${C} more images can be added (max ${ra} total)`);let k=M.map(g=>new Promise((P,E)=>{let I=new FileReader;I.onload=B=>{B.target?.result?P(B.target.result):E(new Error("Failed to read file"));},I.onerror=E,I.readAsDataURL(g);}));Promise.all(k).then(g=>{s(P=>[...P,...g]),f.current&&(f.current.value="");});},u=b=>{b.preventDefault(),i(false);let L=Array.from(b.dataTransfer.files).filter(g=>g.type.startsWith("image/"));if(L.length===0)return;let C=ra-a.length;if(C<=0){alert(`You can only upload a maximum of ${ra} images`);return}let M=L.slice(0,C);M.length<L.length&&alert(`Only ${C} more images can be added (max ${ra} total)`);let k=M.map(g=>new Promise((P,E)=>{let I=new FileReader;I.onload=B=>{B.target?.result?P(B.target.result):E(new Error("Failed to read file"));},I.onerror=E,I.readAsDataURL(g);}));Promise.all(k).then(g=>{s(P=>[...P,...g]);});},p=b=>{b.preventDefault(),i(true);},y=()=>{i(false);},h=b=>{s(L=>L.filter((C,M)=>M!==b));},x=b=>{if(b.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!m)return null;let v=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:b=>{b.target===b.currentTarget&&o(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{ref:d,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:b=>b.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:x,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=ra?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ra," images"]}):jsxs("span",{children:[a.length,"/",ra," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:u,onDragOver:p,onDragLeave:y,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${c?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:c?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((b,L)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:b,alt:`Flashcard ${L+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>h(L),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:L+1})]},L))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(v,m)};var vn={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}},Zy={enabled:true};function ql(e){return e?{tools:{...vn.tools,...e.tools},actions:{...vn.actions,...e.actions}}:vn}var Qy={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}},ew={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 Tw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:s}={})=>{let r=xe(),n=te(F=>F.canvas.slides.find(se=>se.id===F.canvas.currentSlideId)),c=n?.videos||[],i=n?.editingFlashcard,d=te(F=>F.toolbar.selectedTool),m=te(F=>F.toolbar.penColor),f=te(F=>F.toolbar.strokeWidth),l=n?.showMcqForm,u=n?.showFlashcardForm,p=useRef(null),y=useMemo(()=>ql(s),[s]),{tools:h,actions:x}=y,v=c.some(F=>F.isRecorded&&F.isPlaying),b=te(F=>F.toolbar.fontSize),L=te(F=>F.toolbar.fontFamily),C=te(F=>F.toolbar.fontStyle),M=te(F=>F.toolbar.fontWeight),k=te(F=>F.toolbar.textDecoration),g=te(F=>F.toolbar.textColor),[P,E]=useState(false),[I,B]=useState(false),[G,R]=useState(false),[K,D]=useState(false),[Q,V]=useState(false),[ae,W]=useState(false),[q,Y]=useState(false),H=useRef(null),U=useRef(null),J=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),ee=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),j=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],[]),ue=useMemo(()=>J.filter(F=>{let se=h[F.configKey];return typeof se=="boolean"?se:Array.isArray(se)?se.length>0:true}),[h,J]),ke=useMemo(()=>{let F=h.shapes;return F===false?[]:F===true?ee:Array.isArray(F)?ee.filter(se=>F.includes(se.name)):ee},[h.shapes,ee]),Me=useMemo(()=>{let F=h.activities;return F===false?[]:F===true?j:Array.isArray(F)?j.filter(se=>F.includes(se.name)):j},[h.activities,j]),Te=useMemo(()=>{let F=h.media;return F===false?{photoFrame:false,image:false,video:false}:F===true?{photoFrame:true,image:true,video:true}:Array.isArray(F)?{photoFrame:F.includes("photo-frame"),image:F.includes("image"),video:F.includes("video")}:{photoFrame:true,image:true,video:true}},[h.media]),Ne=useMemo(()=>{let F=h.activities;return F===false?false:F===true?true:Array.isArray(F)?F.includes("flashcard"):true},[h.activities]),ct=F=>{let se=F.target.files;!se||se.length===0||(r(_t("select")),r(pt(false)),D(false),Array.from(se).forEach(ve=>{let ge=new FileReader;ge.onload=re=>{let le=new window.Image;le.src=re.target?.result,le.onload=()=>{let we=le.width/le.height,Ke=300,Ot=300,ft=le.width,Pe=le.height;ft>Ke&&(ft=Ke,Pe=ft/we),Pe>Ot&&(Pe=Ot,ft=Pe*we),r(ce());let Ue=960-ft/2,Lt=540-Pe/2;r(Kn({id:v4(),src:le.src,x:Ue,y:Lt,width:ft,height:Pe,draggable:true,rotation:0}));};},ge.readAsDataURL(ve);}),F.target.value="");},no=async F=>{let se=F.target.files;if(!(!se||se.length===0)){console.log("files",F),r(_t("select")),r(pt(false)),D(false);for(let ve of Array.from(se))try{let ge=URL.createObjectURL(ve),re=document.createElement("video");console.log("video",re),re.src=ge,re.muted=!0,re.playsInline=!0,re.preload="auto",re.load(),await new Promise((Nt,ua)=>{let Vt=setTimeout(()=>ua(new Error("Metadata load timeout")),1e4);re.onloadedmetadata=()=>{clearTimeout(Vt),Nt();},re.onerror=()=>{clearTimeout(Vt),ua(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:re.duration,width:re.videoWidth,height:re.videoHeight}),await new Promise((Nt,ua)=>{let Vt=setTimeout(()=>ua(new Error("Video load timeout")),1e4);re.readyState>=2?(clearTimeout(Vt),Nt()):re.onloadeddata=()=>{clearTimeout(Vt),Nt();};});let le=Math.min(.8,re.duration/2);console.log("Seeking to:",le),re.currentTime=le,await new Promise(Nt=>{let ua=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Nt();},5e3);re.onseeked=()=>{clearTimeout(ua),console.log("Seek completed"),Nt();};});let we=document.createElement("canvas"),Ke=re.videoWidth/re.videoHeight,Ot=400,ft=400,Pe=re.videoWidth,Ue=re.videoHeight;Pe>Ot&&(Pe=Ot,Ue=Pe/Ke),Ue>ft&&(Ue=ft,Pe=Ue*Ke),we.width=Pe,we.height=Ue;let Lt=we.getContext("2d",{willReadFrequently:!1});if(!Lt)throw new Error("Failed to get canvas context");if(await new Promise(Nt=>setTimeout(Nt,100)),re.videoWidth===0||re.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Pe,height:Ue}),Lt.drawImage(re,0,0,Pe,Ue);let da=we.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",da.length),r(ce());let Pn=960-Pe/2,Dn=540-Ue/2,Oa=v4();await eo(Oa,ve,da),r(ts({id:Oa,objectUrl:ge,thumbnailDataUrl:da,videoBlob:ve,x:Pn,y:Dn,width:Pe,height:Ue,draggable:!0,isPlaying:!1,rotation:0})),re.src="",re.load(),console.log(`Video uploaded: ${ve.name}`);}catch(ge){console.error("Error processing video:",ge),alert(`Failed to process video: ${ve.name}`);}F.target.value="";}},ne=(F,se,ve)=>{r(ce()),r(_t("select")),r(pt(false));let ge=300,re=300,le=960-ge/2,we=540-re/2;r(ve?fo({id:ve,images:F,order:se,x:le,y:we,width:ge,height:re,rotation:0,draggable:true}):Xn({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:F,currentIndex:0,order:se,x:le,y:we,width:ge,height:re,rotation:0,draggable:true})),r(qa(false));},Hr=()=>{r(ce()),r(_t("select")),r(pt(false));let F=400,se=300,ve=800-F/2,ge=450-se/2;if(t?.current){let re=t.current,le=re.scaleX()||1,we=re.scaleY()||1,Ke=re.width()/le,Ot=re.height()/we;ve=Ke/2-F/2,ge=Ot/2-se/2;}r(Jn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ve,y:ge,width:F,height:se,rotation:0,draggable:true,isCapturing:false})),V(false);},Ur=F=>{let le={};switch(F.name){case "circle":case "ring":case "wedge":case "arc":le.radius=50,(F.name==="ring"||F.name==="arc")&&(le.innerRadius=25,le.outerRadius=50),(F.name==="wedge"||F.name==="arc")&&(le.angle=F.name==="wedge"?60:90);break;case "ellipse":le.radiusX=60,le.radiusY=40;break;case "triangle":le.radius=50,le.sides=3;break;case "polygon":le.radius=50,le.sides=6;break;case "star":le.innerRadius=25,le.outerRadius=50,le.numPoints=5;break;case "arrow":case "line":le.points=[0,0,100,0],F.name==="arrow"&&(le.pointerLength=10,le.pointerWidth=10);break}let we={id:`shape-${Date.now()}`,type:F.name,x:910,y:490,width:100,height:100,rotation:0,color:m,...le};r(ce()),r(pt(false)),r(_t(F.name)),r(_n(we));},Fa=F=>{if(r(_t(F)),F==="select")r(pt(false));else if(F==="text"){r(pt(false)),r(ce());let se=200,ve=50,ge=960-se/2,re=540-ve/2,we=window.innerWidth<768?Math.max(b,32):b,Ke=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(jn({id:Ke,text:"",x:ge,y:re,width:se,height:ve,rotation:0,draggable:true,fontSize:we,fontFamily:L,fontStyle:C,fontWeight:M,textDecoration:k,fill:g,align:"left"})),setTimeout(()=>{r(er(Ke));},100),a&&a(Ke);}else r(pt(true));},zr=()=>{r(mi()),r(_t("select")),r(pt(false));},Wr=()=>{o?o():t?E(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Gr=()=>{B(true);},Kr=async(F,se)=>{try{r(_t("select")),r(pt(!1));let ve=URL.createObjectURL(F),ge=document.createElement("video");ge.src=ve,ge.muted=!0,ge.playsInline=!0,ge.preload="auto",await new Promise((Ue,Lt)=>{let da=setTimeout(()=>Lt(new Error("Metadata load timeout")),1e4);ge.onloadedmetadata=()=>{clearTimeout(da),Ue();},ge.onerror=()=>{clearTimeout(da),Lt(new Error("Failed to load video"));};});let re=640,le=ge.videoWidth/ge.videoHeight,we=re,Ke=we/le;r(ce());let Ot=960-we/2,ft=540-Ke/2,Pe=v4();await eo(Pe,F,se),r(ts({id:Pe,objectUrl:ve,thumbnailDataUrl:se,videoBlob:F,x:Ot,y:ft,width:we,height:Ke,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),E(!1),B(!1);}catch(ve){console.error("Error adding recorded video to canvas:",ve),alert("Failed to add video to canvas. Please try again.");}},kn=F=>{r(_t("select")),r(pt(false)),r(Zo(null)),F&&r(ii(F)),r(pa(!l));},Mn=()=>{r(Xo(null)),r(qa(true)),V(false);},Tn=()=>{R(!G);},An=()=>{D(!K);},Ba=()=>{V(!Q);};return useEffect(()=>{if(!q)return;let F=se=>{p.current&&!p.current.contains(se.target)&&Y(false);};return document.addEventListener("mousedown",F),()=>{document.removeEventListener("mousedown",F);}},[q]),v?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Da,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:ue.map((F,se)=>jsx("div",{title:F.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 ${F.name===d?"bg-primary/10":""}`,onClick:()=>{if(F.name==="image"){An(),R(false),V(false),Fa(F.name);return}else if(F.name==="shapes"){Tn(),D(false),V(false),Fa(F.name);return}else if(F.name==="activities"){Fa(F.name),Ba(),R(false),D(false);return}Fa(F.name),R(false),D(false),V(false);},children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},se))}),G&&jsx(Da,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:ke.map((F,se)=>jsx("div",{title:F.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Ur(F),children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},se))}),K&&jsxs(Da,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Te.photoFrame&&jsx("div",{title:"Photo frame",onClick:Hr,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Te.image&&jsx("div",{title:"Image",onClick:()=>H.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Te.video&&jsx("div",{title:"Video",onClick:()=>U.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),Q&&jsxs(Da,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Ne&&jsx("div",{title:"Flashcard",onClick:()=>Mn(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),Me.map((F,se)=>jsx("div",{title:F.label,onClick:()=>kn(F.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},se))]})]}),(x.undo||x.redo||x.screenRecord||x.cameraRecord||x.clear)&&jsxs(Da,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[x.undo&&jsx("button",{value:"undo",onClick:()=>r(pi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.redo&&jsx("button",{value:"redo",onClick:()=>r(hi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.screenRecord&&jsx("button",{value:"screen-record",onClick:Wr,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6279F8] md:block",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl"})}),jsx("button",{title:"Pen Color",onClick:()=>W(true),className:"relative mx-4 my-2 flex cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-white text-xl md:hidden",style:{borderColor:m},children:jsx("div",{className:"h-5 w-5 rounded-full border-2 border-white shadow-sm",style:{backgroundColor:m}})}),jsxs("div",{ref:p,className:"relative md:hidden",children:[jsx("button",{title:"Pen Size",onClick:()=>Y(!q),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${q?"bg-primary/10":""}`,children:jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border-2 border-[#FFFFFF80] bg-[#000000CC]",children:jsx("span",{className:"text-xs font-semibold text-white",children:f})})}),q&&jsxs("div",{className:"absolute top-1/2 left-full z-50 ml-2 w-48 -translate-y-1/2 rounded-lg border bg-white p-4 shadow-xl",children:[jsx("p",{className:"mb-3 text-xs font-semibold text-black/40",children:"PEN SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 shrink-0 rounded-full bg-black"}),jsx(gn,{defaultValue:[12],max:28,min:6,step:1,className:"w-full",value:[f],rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:F=>r(Fr(F[0]))}),jsx("div",{className:"h-5 w-5 shrink-0 rounded-full bg-black"})]})]})]}),x.cameraRecord&&jsx("button",{value:"camera-record",onClick:Gr,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6BBB93] md:block",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl"})}),x.clear&&jsx("button",{value:"clear",onClick:()=>zr(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl"})})]})]}),jsx("input",{ref:H,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:ct}),jsx("input",{ref:U,type:"file",accept:"video/*",className:"hidden",onChange:no}),!o&&P&&t&&jsx(dr,{onClose:()=>E(false),stageRef:t,onRecordingComplete:Kr}),I&&jsx(Uf,{onClose:()=>B(false),onRecordingComplete:Kr}),u&&jsx(Wf,{editingFlashcard:i,onConfirm:ne,onCancel:()=>r(qa(false))}),ae&&jsx(Os,{defaultColor:m,onConfirm:F=>{r(Go(F)),W(false);},onCancel:()=>W(false)})]})},Aw=Tw;var Gl=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let s=mt(po),r=mt(vi),n=a?r:s,c=mt(tr),m=(mt(v=>v.canvas.slides.find(b=>b.id===v.canvas.currentSlideId))?.videos||[]).some(v=>v.isRecorded&&v.isPlaying),[f,l]=useState(false),[u,p]=useState(null),[y,h]=useState(null),x=async()=>{if(s.length===0){h({type:"error",message:"No slides to publish"});return}if(!e){h({type:"error",message:"No publish handler provided"});return}l(true),h(null);try{let v=await e(n,c,b=>{p(b);});v.success?h({type:"success",message:v.message}):h({type:"error",message:v.message});}catch(v){h({type:"error",message:v instanceof Error?v.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{p(null),h(null);},3e3);}};return m?null:jsxs("button",{onClick:x,disabled:f||s.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var Fw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:s,onDescriptionChange:r,showPublishButton:n=true,showBackButton:c=true,editableTitle:i=true,editableDescription:d=true,className:m="",rightContent:f,leftContent:l,includeInactiveSlides:u=false})=>{let p=st(),y=mt(tr),h=mt(wi),x=e??(h?y.title:"")??"Untitled",v=o??(h?y.description:"")??"Add a description...",[b,L]=useState(false),[C,M]=useState(false),[k,g]=useState(x),[P,E]=useState(v),I=useRef(null),B=useRef(null);useEffect(()=>{g(x);},[x]),useEffect(()=>{E(v);},[v]),useEffect(()=>{b&&I.current&&(I.current.focus(),I.current.select());},[b]),useEffect(()=>{C&&B.current&&(B.current.focus(),B.current.select());},[C]);let G=()=>{i&&L(true);},R=()=>{d&&M(true);},K=()=>{L(false),k.trim()&&k!==x?s?s(k.trim()):p(gi(k.trim())):k.trim()||g(x);},D=()=>{M(false),P.trim()&&P!==v?r?r(P.trim()):p(xi(P.trim())):P.trim()||E(v);},Q=ae=>{ae.key==="Enter"?K():ae.key==="Escape"&&(g(x),L(false));},V=ae=>{ae.key==="Enter"?D():ae.key==="Escape"&&(E(v),M(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${m}`,children:[l||jsxs("div",{className:"flex items-center gap-6",children:[c&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[b?jsx("input",{ref:I,type:"text",value:k,onChange:ae=>g(ae.target.value),onBlur:K,onKeyDown:Q,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:G,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${i?"hover:border-primary cursor-text":""}`,children:k}),C?jsx("input",{ref:B,type:"text",value:P,onChange:ae=>E(ae.target.value),onBlur:D,onKeyDown:V,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:R,title:P,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${d?"hover:border-primary cursor-text":""}`,children:P})]})]}),f||n&&a&&jsx(Gl,{onPublish:a,includeInactiveSlides:u})]})};var Hw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Uw=({colors:e=Hw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:s=""})=>{let[r,n]=useState(true),c=te(he),i=te(l=>l.toolbar.penColor),d=te(l=>l.toolbar.strokeWidth),m=c?.backgroundColor,f=xe();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:r?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:px-8 2xl:py-6 ${s}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(gn,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[d],onValueChange:l=>f(Fr(l[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"COLOR"}),jsxs(Da,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${i===l.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:l.value},onClick:()=>f(Go(l.value))},l.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>f(Go(l.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-xs font-semibold whitespace-nowrap text-[#00000066] 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] lg:h-12 lg:w-12",style:{backgroundColor:m},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>f(Wn(l.target.value))})})]})}),jsx("div",{className:"absolute -top-4 left-1/2 flex flex-col items-center justify-between px-2",children:jsx("button",{onClick:()=>n(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{size:20,weight:"bold",className:"text-gray-600"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>n(true),className:"fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var jf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),zw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),_l=e=>{let o=zw(e);return o.charAt(0).toUpperCase()+o.slice(1)},Sn=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Xf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var $f={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 Jf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:n,...c},i)=>createElement("svg",{ref:i,...$f,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Sn("lucide",s),...!r&&!Xf(c)&&{"aria-hidden":"true"},...c},[...n.map(([d,m])=>createElement(d,m)),...Array.isArray(r)?r:[r]]));var In=(e,o)=>{let t=forwardRef(({className:a,...s},r)=>createElement(Jf,{ref:r,iconNode:o,className:Sn(`lucide-${jf(_l(e))}`,`lucide-${e}`,a),...s}));return t.displayName=_l(e),t};var _w=[["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"}]],Nr=In("copy",_w);var jw=[["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"}]],Vr=In("trash-2",jw);var Qf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:s,onDuplicate:r,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:s,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:c=>{c.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Nr,{size:14})}),!a&&jsx("button",{onClick:c=>{c.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(Vr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var Jw=({softDelete:e=false})=>{let o=st(),t=mt(po),a=mt(mo),s=mt(yi),[r,n]=useState(true),d=(mt(p=>p.canvas.slides.find(y=>y.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),m=()=>{s&&o(Vn());},f=p=>{o(Un(p));},l=p=>{o(Hn(p));},u=p=>{t.length>1&&o(qn({id:p,softDelete:e}));};return d?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((p,y)=>jsx(Qf,{slide:p,index:y,isSelected:p.id===a,isSingleSlide:t.length===1,onSelect:()=>f(p.id),onDuplicate:()=>l(p.id),onDelete:()=>u(p.id)},p.id))}),jsxs("button",{onClick:m,disabled:!s,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${s?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var Zw="SchooplaEditorDB",Qw=1,Ra="slides",Ea="metadata",jl="schoopla_current_slide_id",am="presentation_metadata",qr=()=>new Promise((e,o)=>{let t=indexedDB.open(Zw,Qw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Ra)||s.createObjectStore(Ra,{keyPath:"id"}),s.objectStoreNames.contains(Ea)||s.createObjectStore(Ea,{keyPath:"id"});};}),Xl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await qr(),a=o.transaction([Ra],"readwrite").objectStore(Ra);await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);});for(let s of e)await new Promise((r,n)=>{let c=a.add(s);c.onsuccess=()=>r(!0),c.onerror=()=>n(c.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},$l=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await qr(),t=e.transaction([Ra],"readonly").objectStore(Ra);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(c=>({id:c.id,width:c.width,height:c.height,x:c.x,y:c.y}))),a(n.length>0?n:null);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Cn=async()=>{try{let e=await qr(),o=e.transaction([Ra,Ea],"readwrite"),t=o.objectStore(Ra),a=o.objectStore(Ea);await new Promise((s,r)=>{let n=t.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(jl),localStorage.removeItem("schoopla_presentation_metadata"),await hf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Yl=e=>{try{localStorage.setItem(jl,e);}catch(o){console.error("Error saving current slide ID:",o);}},Jl=()=>{try{return localStorage.getItem(jl)}catch(e){return console.error("Error loading current slide ID:",e),null}},Zl=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Ql=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await qr(),a=o.transaction([Ea],"readwrite").objectStore(Ea);await new Promise((s,r)=>{let n=a.put({id:am,...e});n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},ed=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await qr(),t=e.transaction([Ea],"readonly").objectStore(Ea);return new Promise((a,s)=>{let r=t.get(am);r.onsuccess=()=>{e.close();let n=r.result;if(n){let{id:c,...i}=n;console.log("\u2705 Loaded presentation metadata:",i),a(i);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var eL=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides","canvas/updateSlideThumbnail"],tL=["canvas/clearCanvas"],aL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],oL=Zl((e,o)=>{Xl(e),Yl(o);},500),rL=Zl(e=>{Ql(e);},500),sL=(e,o)=>{Xl(e),Yl(o);},td=false,om=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let s=t.payload;Al(s).catch(r=>{console.error("Error deleting video blob:",r);});}if(t.type==="canvas/deleteSlide"&&t.payload){let s=t.payload,n=e.getState().canvas.slides.find(c=>c.id===s);n&&n.videos&&n.videos.length>0&&n.videos.forEach(c=>{Al(c.id).catch(i=>{console.error("Error deleting video blob:",i);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let s=t.payload,r=e.getState(),c=r.canvas.slides.find(i=>i.id===r.canvas.currentSlideId)?.videos.find(i=>i.id===s);c&&c.videoBlob&&setTimeout(()=>{let i=e.getState(),m=i.canvas.slides.find(f=>f.id===i.canvas.currentSlideId)?.videos.find(f=>f.id!==s&&f.x===c.x+20&&f.y===c.y+20);m&&c.videoBlob&&eo(m.id,c.videoBlob,m.thumbnailDataUrl).catch(f=>{console.error("Error saving duplicated video blob:",f);});},0);}let a=o(t);if(t.type&&tL.includes(t.type)){if(!td){td=true;try{let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;sL(r,n);}finally{setTimeout(()=>{td=false;},0);}}}else if(t.type&&eL.includes(t.type)){let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;oL(r,n);}else if(t.type&&aL.includes(t.type)){let s=e.getState(),{presentationMetadata:r}=s.canvas;rL(r);}return a});new QueryClient;var lL=configureStore({reducer:{toolbar:Hf,canvas:bd},middleware:e=>e({serializableCheck:false}).concat(om)});var dL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2,fileName:r=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",c=e.toDataURL({mimeType:n,quality:a,pixelRatio:s}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=c,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},uL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o;return new Promise((r,n)=>{try{let c=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:c,quality:a,pixelRatio:s});fetch(i).then(d=>d.blob()).then(d=>r(d)).catch(d=>n(d));}catch(c){n(c);}})},cL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:s})};var fL=(e,o,t)=>{let a=t.x-o.x,s=t.y-o.y;if(a===0&&s===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+s*s,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*s)/r)),c=o.x+n*a,i=o.y+n*s;return Math.sqrt(Math.pow(e.x-c,2)+Math.pow(e.y-i,2))},ad=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,s=e[0],r=e[e.length-1];for(let n=1;n<e.length-1;n++){let c=fL(e[n],s,r);c>t&&(t=c,a=n);}if(t>o){let n=ad(e.slice(0,a+1),o),c=ad(e.slice(a),o);return [...n.slice(0,-1),...c]}return [s,r]},mL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},pL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},rm=(e,o=1.5)=>{if(e.length<=4)return e;let t=mL(e),a=ad(t,o);return pL(a)},sm=(e,o=1.5)=>({...e,points:rm(e.points,o)}),hL=(e,o=1.5)=>e.map(t=>sm(t,o)),gL=(e,o)=>{let t=e.length/2,a=o.length/2,s=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${s}%`}};var xL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var nm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:s=.85}=o;return new Promise((r,n)=>{let c=new Image;c.onload=()=>{let{width:i,height:d}=c;if(i>t||d>a){let p=i/d;i>d?(i=Math.min(i,t),d=i/p):(d=Math.min(d,a),i=d*p);}let m=document.createElement("canvas");m.width=i,m.height=d;let f=m.getContext("2d");if(!f){n(new Error("Failed to get canvas context"));return}f.drawImage(c,0,0,i,d);let l=xL(e),u=m.toDataURL(l,s);r(u);},c.onerror=n,c.src=e;})};var so=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return a.buffer},Ko=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",_o=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",bL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:s=1080,imageQuality:r=.85}=o,n=[],c=0;for(let i of e){let d=[],m=[],f=[];for(let l of i.images){let u=l.src;if(t&&u.startsWith("data:"))try{u=await nm(u,{maxWidth:a,maxHeight:s,quality:r});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(u.startsWith("data:")){let p=so(u),y=Ko(u);c+=p.byteLength;let h={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,buffer:p,mimeType:y};if(l.audioData&&l.audioData.startsWith("data:")){let x=so(l.audioData),v=Ko(l.audioData);c+=x.byteLength,h.audioBuffer=x,h.audioMimeType=v;}d.push(h);}}for(let l of i.videos){let u,p;if(l.videoBlob)u=await l.videoBlob.arrayBuffer(),p=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))u=so(l.videoData),p=Ko(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}c+=u.byteLength;let y={id:l.id,thumbnailDataUrl:l.thumbnailDataUrl,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,isPlaying:l.isPlaying,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isRecorded:l.isRecorded,buffer:u,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let h=so(l.audioData),x=Ko(l.audioData);c+=h.byteLength,y.audioBuffer=h,y.audioMimeType=x;}m.push(y);}for(let l of i.photoFrames){let u={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:l.draggable,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isCapturing:l.isCapturing};if(l.capturedImageUrl&&l.capturedImageUrl.startsWith("data:")){let p=so(l.capturedImageUrl),y=Ko(l.capturedImageUrl);c+=p.byteLength,u.buffer=p,u.mimeType=y;}if(l.audioData&&l.audioData.startsWith("data:")){let p=so(l.audioData),y=Ko(l.audioData);c+=p.byteLength,u.audioBuffer=p,u.audioMimeType=y;}f.push(u);}n.push({...i,images:d,videos:m,photoFrames:f});}return {slides:n,totalSize:c}},vL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},yL=e=>{let o=new FormData,t=e.slides.map((a,s)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,mimeType:r.mimeType,fileKey:`slide_${s}_image_${n}`,audioFileKey:r.audioBuffer?`slide_${s}_image_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,isPlaying:r.isPlaying,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isRecorded:r.isRecorded,mimeType:r.mimeType,fileKey:`slide_${s}_video_${n}`,thumbnailFileKey:`slide_${s}_video_${n}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${s}_video_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,rotation:r.rotation,draggable:r.draggable,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isCapturing:r.isCapturing,mimeType:r.mimeType,fileKey:r.buffer?`slide_${s}_photoframe_${n}`:void 0,audioFileKey:r.audioBuffer?`slide_${s}_photoframe_${n}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,s)=>{a.images.forEach((r,n)=>{let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${_o(r.mimeType)}`;if(o.append(`slide_${s}_image_${n}`,c,i),r.audioBuffer&&r.audioMimeType){let d=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${_o(r.audioMimeType)}`;o.append(`slide_${s}_image_${n}_audio`,d,m);}}),a.videos.forEach((r,n)=>{let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${_o(r.mimeType)}`;if(o.append(`slide_${s}_video_${n}`,c,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let d=so(r.thumbnailDataUrl),m=new Blob([d],{type:"image/jpeg"}),f=`${r.id}_thumbnail.jpg`;o.append(`slide_${s}_video_${n}_thumbnail`,m,f);}if(r.audioBuffer&&r.audioMimeType){let d=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${_o(r.audioMimeType)}`;o.append(`slide_${s}_video_${n}_audio`,d,m);}}),a.photoFrames.forEach((r,n)=>{if(r.buffer&&r.mimeType){let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${_o(r.mimeType)}`;o.append(`slide_${s}_photoframe_${n}`,c,i);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${_o(r.audioMimeType)}`;o.append(`slide_${s}_photoframe_${n}_audio`,c,i);}});}),o};var SL=()=>{let e=st(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let s=await $l(),r=Jl(),n=await ed();if(s&&s.length>0){let c=await pf(),i=s.map(m=>{if(m.videos&&m.videos.length>0){let f=m.videos.map(l=>{let u=c.get(l.id);if(u){let p=gf(u.blob);return {...l,objectUrl:p,thumbnailDataUrl:u.thumbnailDataUrl,videoBlob:u.blob}}else return l});return {...m,videos:f}}return m}),d=r&&i.find(m=>m.id===r)?r:i[0].id;e(lo({slides:i,currentSlideId:d}));}e(n?bi({title:n.title,description:n.description}):Ts(!0));}catch(s){console.error("Error loading persisted slides:",s),e(Ts(true));}finally{t(false);}})();},[e]),{isLoading:o}};var lm=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||""})),dm=new WeakSet,um=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await eo(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},IL=()=>{let e=st(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||dm.has(a))return;dm.add(a);let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Cn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let c=r&&s.find(d=>d.id===r)?r:s[0].id,i=lm(s);e(lo({slides:i,currentSlideId:c})),await um(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Cn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let c=r&&s.find(d=>d.id===r)?r:s[0].id,i=lm(s);e(lo({slides:i,currentSlideId:c})),await um(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
6
+ This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:f?"none":"auto"}})}),jsx(Group,{y:C+M+I+k+g+E,children:f&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),x();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),x();},scaleX:u==="reset"?.95:1,scaleY:u==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});xl.displayName="LongAnswer";var mc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(xl,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:c=>r(c,n.id)},n.id))});var Ya=1600,Ja=900,xc=3200,bc=1800,Bb=.4,Ob=1.5,Nb=e=>{let o=0,t=0,a=Ya,s=Ja;if(!e)return {minX:o,minY:t,maxX:a,maxY:s,width:Ya,height:Ja};let r=(i,d,m,f)=>{o=Math.min(o,i),t=Math.min(t,d),a=Math.max(a,i+m),s=Math.max(s,d+f);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let d=i.x||0,m=i.y||0,f=i.scaleX||1,l=i.scaleY||1;for(let u=0;u<i.points.length;u+=2){let p=d+i.points[u]*f,y=m+i.points[u+1]*l;o=Math.min(o,p),t=Math.min(t,y),a=Math.max(a,p),s=Math.max(s,y);}}}),e.images?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>r(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>r(i.x,i.y,i.width,i.height));let n=Math.min(a-o,xc),c=Math.min(s-t,bc);return o=Math.max(o,a-xc),t=Math.max(t,s-bc),{minX:o,minY:t,maxX:a,maxY:s,width:n,height:c}},Vb=(e,o,t={minX:0,minY:0,maxX:Ya,maxY:Ja,width:Ya,height:Ja})=>{let a=Math.max(t.width,Ya),s=Math.max(t.height,Ja),r=e/o,n=a/s,c,i,d,f=0;if(r>n){i=s,c=Math.round(i*r),d=o/i;}else {c=a,i=Math.round(c/r),d=e/c;let l=s*d;f=(o-l)/2;}return d=Math.max(Bb,Math.min(Ob,d)),{scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:c,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},vc=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},qb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:s={enabled:true}}={})=>{let r=st(),n=ze(),c=te(w=>w.toolbar.selectedTool),i=te(he),d=te(mo),f=(i?.videos||[]).find(w=>w.isRecorded&&w.isPlaying),l=!!f,u=useCallback(()=>{f&&r(Na(f.id));},[r,f]),p=i?.editingActivity,y=i?.showMcqForm,h=i?.lines||[],x=useRef(null),v=useRef(null),[b,L]=useState(null),[C,M]=useState(""),k=useRef(null),[g,P]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Ya,stageHeight:Ja,offsetX:0,offsetY:0,baseWidth:Ya,baseHeight:Ja,contentOffsetX:0,contentOffsetY:0}),E=useMemo(()=>Nb(i||null),[d]),[I,B]=useState(null),[G,R]=useState(null),[K,D]=useState(null),[Q,V]=useState(null),[ae,W]=useState(null),[q,Y]=useState(null),[H,U]=useState(null),[J,ee]=useState(false),[j,ue]=useState(null),[ke,Me]=useState(false),Te=useRef(null),Ne=useRef(null),ct=useRef(null),{debouncedGenerateThumbnail:no}=jd(d,x);useEffect(()=>{let w=()=>{if(v.current){let A=v.current.getBoundingClientRect(),O=Vb(A.width,A.height,E);P(O);}};w();let S=new ResizeObserver(w);return v.current&&S.observe(v.current),window.addEventListener("resize",w),()=>{S.disconnect(),window.removeEventListener("resize",w);}},[E]),useEffect(()=>{if(x.current){let w=x.current.container();w&&(w.style.cursor="");}},[c]);let ne=useCallback(()=>{x.current&&requestAnimationFrame(()=>{if(!x.current)return;x.current.getLayers().forEach(O=>O.batchDraw());let S=1/6,A=x.current.toDataURL({pixelRatio:S});M(A),no();});},[no]),Hr=useRef(d);useEffect(()=>{Hr.current!==d&&(Hr.current=d,ne());},[d,ne]);let Ur=useRef(null),Fa=useRef(true);useEffect(()=>{if(!i)return;let w=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),S=Ur.current?.count!==w;!Fa.current&&S&&setTimeout(()=>{ne();},100),Ur.current={slideId:d,count:w},Fa.current=false;},[i,d,ne]),useEffect(()=>{x.current&&e&&e(x);},[e]),useEffect(()=>{ct.current&&a&&a(ct);},[a]);let{startDrawing:zr,draw:Wr,stopDrawing:Gr,setCanvasRef:Kr,tool:kn,color:Mn,strokeWidth:Tn,isSketchMode:An}=yd(ne),Ba=useRef(new Map),{images:F,getLoadedImage:se,imageRefs:ve,handleDragEnd:ge,handleImageTransformEnd:re}=Md(ne),{videos:le,videoRefs:we,handleVideoClick:Ke,handleVideoDragEnd:Ot,handleVideoTransformEnd:ft}=Pd(ne),{multipleChoice:Pe,handleMcqTransform:Ue,mcqRefs:Lt,handleDragEnd:da}=Td(ne),{trueFalse:Pn,handleTrueFalseTransform:Dn,trueFalseRefs:Oa,handleTrueFalseDragEnd:Nt}=Ad(ne),{shortAnswers:ua,saRefs:Vt,handleShortAnswerDragEnd:cm}=Od(ne),{longAnswers:fm,handleLongAnswerDragEnd:mm}=Nd(ne),{fillInTheBlanks:pm,handleFillInTheBlanksDragEnd:hm,fibRefs:_r}=nc(ne),{transformerRef:fe,boundBoxFunc:St}=Wd(),{shapes:gm,shapeRefs:jr,isDragging:od,handleShapeDragEnd:xm,handleShapeResizeEnd:bm}=Ed(ne),{texts:jo,textRefs:ca,handleDragEnd:vm,handleTransformEnd:ym,handleDoubleClick:wm,startEditing:Xr,editingTextId:pe,editingValue:rd,handleEditingChange:sd,finishEditing:Rn}=Bd(ne,Te);useEffect(()=>{t&&t(Xr);},[t,Xr]);let $r=te(w=>w.canvas.editingTextId);useEffect(()=>{$r&&$r!==pe&&Xr($r);},[$r,pe,Xr]);let{flashcards:Lm,flashcardRefs:Yr,handleDragEnd:Sm,handleFlashcardTransformEnd:Im,handleNext:Cm,handlePrevious:km}=qd(ne),{photoFrames:nd,photoFrameRefs:Jr,handleDragEnd:Mm,handlePhotoFrameTransformEnd:Tm,startCamera:Am,capturePhoto:Pm,cameraStreams:Dm}=zd(ne);useEffect(()=>{if(fe.current){if(pe){fe.current.nodes([]),fe.current.getLayer()?.batchDraw();return}if(b&&!le.find(A=>A.id===b)?.isPlaying){let A=Ba.current.get(b)||ve.current.get(b)||we.current.get(b)||jr.current.get(b)||ca.current.get(b)||Lt.current.get(b)||Yr.current.get(b)||Jr.current.get(b)||Vt.current.get(b)||Oa.current.get(b)||_r.current.get(b);if(A){let O=A.attrs?.locked;if(A.visible()&&O!==true){fe.current.nodes([A]),fe.current.getLayer()?.batchDraw();return}}}fe.current.nodes([]),fe.current.getLayer()?.batchDraw();}},[b,pe,le,Ba,ve,we,jr,ca,Yr,Jr,nd,Lt,Oa,_r,fe]);let _e=useCallback(w=>{L(w),o?.(w);},[o]),io=useCallback(()=>{L(null),o?.(null),fe.current&&(fe.current.nodes([]),fe.current.getLayer()?.batchDraw());},[fe,o]),id=useCallback(w=>i?i.lines?.some(S=>S.id===w)?"line":i.images?.some(S=>S.id===w)?"image":i.videos?.some(S=>S.id===w)?"video":i.shapes?.some(S=>S.id===w)?"shape":i.texts?.some(S=>S.id===w)?"text":i.flashcards?.some(S=>S.id===w)?"flashcard":i.photoFrames?.some(S=>S.id===w)?"photoFrame":i.multipleChoices?.some(S=>S.id===w)?"mcq":i.trueFalses?.some(S=>S.id===w)?"trueFalse":i.shortAnswers?.some(S=>S.id===w)?"shortAnswer":i.LongAnswer?.some(S=>S.id===w)?"longAnswer":i.fillInTheBlanks?.some(S=>S.id===w)?"fillInTheBlanks":null:null,[i]),ld=useCallback((w,S)=>{switch(r(ce()),S){case "line":r(Ms(w));break;case "image":r(Qr(w));break;case "video":r(os(w));break;case "shape":r(ns(w));break;case "text":r(is(w));break;case "flashcard":r(ds(w));break;case "photoFrame":r(cs(w));break;case "mcq":r(ms(w));break;case "trueFalse":r(hs(w));break;case "shortAnswer":r(xs(w));break;case "longAnswer":r(vs(w));break;case "fillInTheBlanks":r(ws(w));break}io(),ne();},[r,io,ne]);useEffect(()=>{let w=S=>{if(S.key!=="Delete"||!b||pe)return;let A=document.activeElement;if(A instanceof HTMLInputElement||A instanceof HTMLTextAreaElement||A?.getAttribute("contenteditable")==="true")return;S.preventDefault();let De=id(b);De&&ld(b,De);};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[b,pe,id,ld]),useEffect(()=>{let w=fe.current;return ()=>{w&&w.nodes([]);}},[d]),useEffect(()=>{let w=S=>{pe&&S.target.tagName!=="TEXTAREA"&&Rn();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[pe,Rn]),useEffect(()=>{let w=pe||b;if(!w||b&&pe){R(null);return}let S=ca.current.get(w),A=x.current;if(!S||!A){R(null);return}let O=A.container().getBoundingClientRect(),De=S.absolutePosition(),Le=A.scaleX();R({x:O.left+(De.x+S.width()*Le/2)*Le,y:O.top+De.y*Le});},[b,pe,jo,ca]),useEffect(()=>{if(!pe){D(null);return}let w=ca.current.get(pe),S=x.current;if(!w||!S){D(null);return}let A=S.container().getBoundingClientRect(),O=w.absolutePosition(),De=S.scaleX();D({top:A.top+O.y*De,left:A.left+O.x*De,scale:De});},[pe,jo,ca]);let dd=useCallback(w=>{let S=w.target.getClassName(),A=w.target===w.target.getStage(),O=S==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",De=S==="Image",Le=S==="Text",oe=S==="Group"||w.target.getParent()?.getClassName()==="Group",qt=S==="Circle"||S==="Star"||S==="RegularPolygon"||S==="Ellipse"||S==="Ring"||S==="Wedge"||S==="Arrow"||S==="Line"||S==="Arc"||S==="Rect"&&w.target.attrs.id,Ct=S==="Group";if(A&&!O&&!De&&!Le&&!oe&&!qt&&!Ct&&io(),!(c==="pen"||c==="eraser")&&(De||Le||O||oe||qt||Ct))return;let Ye=w.target.getStage()?.getPointerPosition();if(!Ye)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(c)){let N=vc(Ye,g);zr(N);}},[c,zr,io,g]),ud=useCallback(w=>{if(od)return;let S=w.target.getStage()?.getPointerPosition();if(!S)return;let A=vc(S,g);Wr(A);},[Wr,od,g]),cd=useCallback(()=>{Gr();},[Gr]),Rm=useCallback(w=>{ge(w,ne);},[ge,ne]),Em=useCallback(w=>{Ke(w),_e(w);},[Ke,_e]),It=useCallback((w,S,A)=>{if(w.preventDefault(),!s.enabled)return;let O=w.clientX,De=w.clientY,Le=k.current?.offsetHeight||450,oe=k.current?.offsetWidth||450,qt=window.innerHeight,Ct=window.innerWidth,rt=O,Ye=De;De+Le>qt&&(Ye=De-Le),O+oe>Ct&&(rt=O-oe),B({x:rt,y:Ye,elementId:S,elementType:A}),_e(S);},[_e,s.enabled]),fd=useCallback(w=>{r(Zo(w)),r(pa(true));},[r]),Fm=useCallback(w=>{r(Xo(w)),r(qa(true));},[r]),Bm=useCallback((w,S)=>{if(!I)return;let{elementId:A,elementType:O}=I;switch(w){case "order":if(S){let T=S.target.getBoundingClientRect();V({x:T.right+5,y:T.top,type:"order"});}break;case "lock":if(S){let T=S.target.getBoundingClientRect();V({x:T.right+5,y:T.top,type:"lock"});}break;case "link":if(B(null),O==="line")break;let De=i?O==="image"?i.images.find(T=>T.id===A):i.videos.find(T=>T.id===A):null;W({type:"link",defaultValue:De?.link||""});break;case "voice":if(B(null),O==="line")break;let Le=i?O==="image"?i.images.find(T=>T.id===A):O==="video"?i.videos.find(T=>T.id===A):O==="text"?i.texts.find(T=>T.id===A):O==="flashcard"?i.flashcards.find(T=>T.id===A):O==="photoFrame"?i.photoFrames.find(T=>T.id===A):O==="mcq"?i.multipleChoices.find(T=>T.id===A):O==="fillInTheBlanks"?i.fillInTheBlanks.find(T=>T.id===A):O==="longAnswer"?i.LongAnswer.find(T=>T.id===A):O==="shortAnswer"?i.shortAnswers.find(T=>T.id===A):O==="trueFalse"?i.trueFalses.find(T=>T.id===A):O==="shape"?i.shapes.find(T=>T.id===A):null:null;ue({elementId:A,elementType:O,existingAudio:Le?.audioData});break;case "edit":B(null);let oe=null;O==="mcq"?oe=i?.multipleChoices.find(T=>T.id===A):O==="trueFalse"?oe=i?.trueFalses.find(T=>T.id===A):O==="shortAnswer"?oe=i?.shortAnswers.find(T=>T.id===A):O==="longAnswer"?oe=i?.LongAnswer.find(T=>T.id===A):O==="fillInTheBlanks"&&(oe=i?.fillInTheBlanks.find(T=>T.id===A)),oe&&fd(oe);break;case "editFlashcard":B(null);let qt=i?.flashcards.find(T=>T.id===A);qt&&Fm(qt);break;case "color":B(null);let Ct=i?.shapes.find(T=>T.id===A);Y({elementId:A,elementType:"shape",defaultColor:Ct?.color||"#096B76"});break;case "crop":if(B(null),O==="image"){let T=i?.images.find(zm=>zm.id===A);T&&U({elementId:A,imageSrc:T.src});}break;case "draw":B(null),O==="image"?r(Zn(A)):O==="photoFrame"&&r(ei(A));break;case "duplicate":r(ce()),O==="line"?r(fi(A)):O==="image"?r(es(A)):O==="video"?r(rs(A)):O==="shape"?r(ss(A)):O==="text"?r(ls(A)):O==="flashcard"?r(us(A)):O==="photoFrame"?r(fs(A)):O==="mcq"?r(ps(A)):O==="trueFalse"?r(gs(A)):O==="shortAnswer"?r(bs(A)):O==="fillInTheBlanks"?r(Ls(A)):O==="longAnswer"&&r(ys(A)),ne();break;case "infinite-clone":r(ce());let rt=5;for(let T=0;T<rt;T++)O==="image"?r(es(A)):O==="video"?r(rs(A)):O==="shape"?r(ss(A)):O==="text"?r(ls(A)):O==="flashcard"?r(us(A)):O==="photoFrame"?r(fs(A)):O==="mcq"?r(ps(A)):O==="trueFalse"?r(gs(A)):O==="shortAnswer"?r(bs(A)):O==="fillInTheBlanks"?r(Ls(A)):O==="longAnswer"&&r(ys(A));ne();break;case "make-response":if(B(null),O==="line")break;let Ye=`#response-${A}`;r(ce()),r(Ss({id:A,type:O,link:Ye})),(i?O==="image"?i.images.find(T=>T.id===A):O==="video"?i.videos.find(T=>T.id===A):O==="shape"?i.shapes.find(T=>T.id===A):O==="flashcard"?i.flashcards.find(T=>T.id===A):O==="photoFrame"?i.photoFrames.find(T=>T.id===A):i.multipleChoices.find(T=>T.id===A):null)?.altText||r(Is({id:A,type:O,altText:"Interactive response area"})),ne(),console.log(`Element ${A} marked as interactive response area`);break;case "accessibility":if(B(null),O==="line")break;let N=i?O==="image"?i.images.find(T=>T.id===A):O==="video"?i.videos.find(T=>T.id===A):O==="shape"?i.shapes.find(T=>T.id===A):null:null;W({type:"altText",defaultValue:N?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),B(null),Me(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ce()),O==="line"?r(Ms(A)):O==="image"?r(Qr(A)):O==="video"?r(os(A)):O==="shape"?r(ns(A)):O==="text"?r(is(A)):O==="flashcard"?r(ds(A)):O==="photoFrame"?r(cs(A)):O==="mcq"?r(ms(A)):O==="trueFalse"?r(hs(A)):O==="shortAnswer"?r(xs(A)):O==="longAnswer"?r(vs(A)):O==="fillInTheBlanks"&&r(ws(A)),io(),ne();break}},[I,r,ne,io,i,fd]),Om=useCallback(()=>{B(null),V(null);},[]),En=useCallback(w=>{if(!I)return;let{elementId:S,elementType:A}=I;switch(r(ce()),w){case "bring-to-front":A!=="line"&&r(li({id:S,type:A}));break;case "send-to-back":A!=="line"&&r(di({id:S,type:A}));break;case "lock":case "unlock":A!=="line"&&r(ui({id:S,type:A}));break}ne(),B(null),V(null);},[I,r,ne]),Nm=useCallback(w=>{if(!I||!ae)return;let{elementId:S,elementType:A}=I;r(ce()),ae.type==="link"&&A!=="line"?r(Ss({id:S,type:A,link:w})):ae.type==="altText"&&A!=="line"&&r(Is({id:S,type:A,altText:w})),ne(),W(null);},[I,ae,r,ne]),Vm=useCallback(w=>{if(!j)return;let{elementId:S,elementType:A}=j;r(ce()),r(Cs({id:S,type:A,audioData:w})),ne(),ue(null);},[j,r,ne]),qm=useCallback(()=>{if(!j)return;let{elementId:w,elementType:S}=j;r(ce()),r(Cs({id:w,type:S,audioData:""})),ne();},[j,r,ne]),Hm=useCallback(w=>{if(!q)return;let{elementId:S}=q;r(ce()),r(co({id:S,color:w})),ne(),Y(null);},[q,r,ne]),Um=useCallback(w=>{if(!H)return;let{elementId:S}=H;r(ce()),r(uo({id:S,src:w})),ne(),U(null);},[H,r,ne]);return jsxs("div",{ref:v,className:"fixed inset-0",style:{cursor:c==="pen"?"crosshair":c==="eraser"?"":"default"},children:[c==="pen"&&jsx(Cd,{ref:w=>{if(Ne.current=w,Kr(w),w){let S=w.getCanvasElement();S&&(ct.current=S,a&&a(ct));}},width:g.baseWidth,height:g.baseHeight,tool:kn,color:Mn,strokeWidth:Tn/g.scale,isSketchMode:An,xOffset:g.contentOffsetX,yOffset:g.contentOffsetY-g.offsetY/g.scale,style:{width:g.stageWidth,height:g.stageHeight}}),jsxs(Stage,{ref:x,width:g.stageWidth,height:g.stageHeight,scaleX:g.scaleX,scaleY:g.scaleY,x:g.offsetX,y:0,onMouseDown:dd,onMouseMove:ud,onMouseUp:cd,onTouchStart:dd,onTouchMove:ud,onTouchEnd:cd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:g.baseWidth,height:g.stageHeight/g.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-g.contentOffsetX,y:g.offsetY/g.scale-g.contentOffsetY,children:(()=>{let w=[];return h.forEach((S,A)=>{w.push({type:"line",timestamp:S.timestamp||A,element:{...S,id:S.id??`line-${A}`},index:A});}),gm.forEach(S=>{w.push({type:"shape",timestamp:S.timestamp||0,element:S});}),F.forEach(S=>{w.push({type:"image",timestamp:S.timestamp||0,element:S});}),le.forEach(S=>{w.push({type:"video",timestamp:S.timestamp||0,element:S});}),jo.forEach(S=>{w.push({type:"text",timestamp:S.timestamp||0,element:S});}),Lm.forEach(S=>{w.push({type:"flashcard",timestamp:S.timestamp||0,element:S});}),nd.forEach(S=>{w.push({type:"photoFrame",timestamp:S.timestamp||0,element:S});}),Pe.forEach(S=>{w.push({type:"mcq",timestamp:S.timestamp||0,element:S});}),Pn.forEach(S=>{w.push({type:"trueFalse",timestamp:S.timestamp||0,element:S});}),ua.forEach(S=>{w.push({type:"shortAnswer",timestamp:S.timestamp||0,element:S});}),fm.forEach(S=>{w.push({type:"longAnswer",timestamp:S.timestamp||0,element:S});}),pm.forEach(S=>{w.push({type:"fillInTheBlanks",timestamp:S.timestamp||0,element:S});}),w.sort((S,A)=>S.timestamp-A.timestamp),w.map((S,A)=>{let O=`${S.type}-${"id"in S.element&&S.element.id||S.index||A}`,De="id"in S.element?S.element.id:void 0,Le=De&&b===De;switch(S.type){case "line":let oe=S.element,qt=S.index||0,Ct=oe.tool==="eraser",rt=oe.isSketch&&oe.tool==="pen",Ye=oe.isSketch&&Ct,kt=oe.id||`line-${qt}`;return oe.x===void 0&&(oe.x=0),oe.y===void 0&&(oe.y=0),oe.scaleX===void 0&&(oe.scaleX=1),oe.scaleY===void 0&&(oe.scaleY=1),oe.rotation===void 0&&(oe.rotation=0),c==="eraser"?jsx(Group,{x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,children:jsx(Line,{points:oe.points||[],stroke:rt||Ye?void 0:oe.color,strokeWidth:rt||Ye?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:rt||Ye?Ct?"black":oe.color:void 0,closed:rt||Ye,tension:0,globalCompositeOperation:Ct?"destination-out":"source-over",listening:true,onClick:()=>{r(ce()),r(Zr(qt));},onTap:()=>{r(ce()),r(Zr(qt));},hitStrokeWidth:Math.max(20,(oe.strokeWidth??0)*2),onMouseEnter:N=>{let T=N.target.getStage();T&&(T.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:N=>{let T=N.target.getStage();T&&(T.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:kt,ref:N=>{N?Ba.current.set(kt,N):Ba.current.delete(kt);},x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,draggable:c==="select",listening:c==="select",onClick:()=>{c==="select"&&(console.log("Line clicked:",kt),_e(kt));},onTap:()=>{c==="select"&&(console.log("Line tapped:",kt),_e(kt));},onDragEnd:N=>{r(ce()),r(ks({id:kt,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),ne();},onTransformEnd:N=>{r(ce()),r(ks({id:kt,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),ne();},onMouseEnter:N=>{if(c==="select"){let T=N.target.getStage();T&&(T.container().style.cursor="move");}},onMouseLeave:N=>{if(c==="select"){let T=N.target.getStage();T&&(T.container().style.cursor="default");}},onContextMenu:N=>{let T=N.evt;T.preventDefault(),It(T,kt,"line");},children:jsx(Line,{points:oe.points||[],stroke:rt||Ye?void 0:oe.color,strokeWidth:rt||Ye?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:rt||Ye?Ct?"black":oe.color:void 0,closed:rt||Ye,tension:0,globalCompositeOperation:Ct?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Ba.current.get(b);console.log("Line Transformer - selectedId:",b,"node found:",!!T),T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:St,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(Ri,{onSelect:_e,shapes:[S.element],shapeRefs:jr,handleShapeDragEnd:xm,handleShapeResizeEnd:bm,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=jr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Ti,{images:[S.element],getLoadedImage:se,imageRefs:ve,onDragEnd:Rm,onTransform:re,onSelect:_e,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=ve.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Di,{videos:[S.element],selectedId:b,videoRefs:we,onVideoClick:Em,onDragEnd:Ot,onTransformEnd:ft,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=we.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(ru,{texts:[S.element],textRefs:ca,onDragEnd:vm,onTransformEnd:ym,onSelect:_e,onContextMenu:It,onDoubleClick:wm,editingTextId:pe,editingValue:rd,onEditingChange:sd}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=ca.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Bi,{flashcards:[S.element],flashcardRefs:Yr,selectedId:b,onDragEnd:Sm,onTransform:Im,onSelect:_e,onNext:Cm,onPrevious:km,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Yr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Ui,{photoFrames:[S.element],photoFrameRefs:Jr,selectedId:b,onDragEnd:Mm,onTransform:Tm,onSelect:_e,onStartCamera:Am,onCapture:Pm,cameraStreams:Dm,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Jr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Bu,{handleMcqTransform:Ue,multipleChoice:[S.element],handleSelect:_e,mcqRefs:Lt,handleDragEnd:da,onContextMenu:It}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Lt.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(Vu,{trueFalses:[S.element],handleTrueFalseTransform:Dn,handleSelect:_e,trueFalseRefs:Oa,onContextMenu:It,handleDragEnd:Nt}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Oa.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(sc,{shortAnswers:[S.element],handleSelect:_e,handleTransform:Ue,saRefs:Vt,onContextMenu:It,handleDragEnd:cm}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Vt.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(mc,{longAnswer:[S.element],handleSelect:_e,handleTransform:Ue,saRefs:Vt,onContextMenu:It,handleDragEnd:mm}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Vt.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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(cc,{fillInTheBlanks:[S.element],handleSelect:_e,handleTransform:Ue,onContextMenu:It,handleDragEnd:hm,fibRefs:_r}),Le&&!pe&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=_r.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:St,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}})})()})]}),I&&jsx(xu,{menuRef:k,x:I.x,y:I.y,type:I.elementType,onAction:Bm,onClose:Om,isDrawingMode:I.elementType==="image"?i?.images.find(w=>w.id===I.elementId)?.isDrawingMode:I.elementType==="photoFrame"?i?.photoFrames.find(w=>w.id===I.elementId)?.isDrawingMode:false}),Q&&I&&jsx(bu,{x:Q.x,y:Q.y,items:Q.type==="order"?[{label:"Bring to Front",onClick:()=>En("bring-to-front")},{label:"Send to Back",onClick:()=>En("send-to-back")}]:[{label:i&&(I.elementType==="image"?i.images.find(w=>w.id===I.elementId)?.locked:i.videos.find(w=>w.id===I.elementId)?.locked)?"Unlock":"Lock",onClick:()=>En(i&&(I.elementType==="image"?i.images.find(w=>w.id===I.elementId)?.locked:i.videos.find(w=>w.id===I.elementId)?.locked)?"unlock":"lock")}],onClose:()=>V(null)}),ae&&jsx(wu,{title:ae.type==="link"?"Add Link":"Add Alt Text",label:ae.type==="link"?"URL":"Alternative Text",placeholder:ae.type==="link"?"https://example.com":"Describe this image/video",defaultValue:ae.defaultValue,onSave:Nm,onClose:()=>W(null)}),q&&jsx(Os,{defaultColor:q.defaultColor,onConfirm:Hm,onCancel:()=>Y(null)}),H&&jsx(Cu,{imageSrc:H.imageSrc,onConfirm:Um,onCancel:()=>U(null)}),J&&jsx(dr,{onClose:()=>ee(false),stageRef:x}),j&&jsx(Au,{elementId:j.elementId,elementType:j.elementType,existingAudio:j.existingAudio,onSave:Vm,onDelete:qm,onClose:()=>ue(null)}),ke&&jsx(Ru,{selectedElementId:b||void 0,onClose:()=>Me(false),onSelectElement:w=>{_e(w),Me(false);}}),i?.images.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.videos.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.shapes?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.texts?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.flashcards?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(At,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),y&&jsx($u,{editElement:p}),G&&(()=>{let w=pe||b;if(!w)return null;let S=jo.find(A=>A.id===w);return S?jsx(Qu,{text:S,position:G}):null})(),K&&pe&&(()=>{let w=jo.find(S=>S.id===pe);return w?jsx(tc,{text:w,editingValue:rd,onEditingChange:sd,onFinish:Rn,position:{top:K.top,left:K.left},scale:K.scale,textareaRef:Te},pe):null})(),l&&n&&createPortal(jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,zIndex:99999,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"black"},children:jsx("video",{src:f?.objectUrl,controls:true,autoPlay:true,style:{width:"100%",height:"100%",objectFit:"contain"},onEnded:u})}),jsx("button",{onClick:u,style:{position:"fixed",top:"32px",right:"32px",zIndex:1e5,display:"flex",width:"48px",height:"48px",alignItems:"center",justifyContent:"center",borderRadius:"9999px",backgroundColor:"rgba(255, 255, 255, 0.9)",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",border:"none",cursor:"pointer"},"aria-label":"Close video",children:jsx(X$1,{style:{width:"24px",height:"24px",color:"#111827"},weight:"bold"})})]}),n)]})},Hb=qb;function bl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Ze(e,o,{checkForDefaultPrevented:t=true}={}){return function(s){if(e?.(s),t===false||!s.defaultPrevented)return o?.(s)}}function yc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Dr(...e){return o=>{let t=false,a=e.map(s=>{let r=yc(s,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let s=0;s<a.length;s++){let r=a[s];typeof r=="function"?r():yc(e[s],null);}}}}function Ft(...e){return be.useCallback(Dr(...e),e)}function Ma(e,o=[]){let t=[];function a(r,n){let c=be.createContext(n),i=t.length;t=[...t,n];let d=f=>{let{scope:l,children:u,...p}=f,y=l?.[e]?.[i]||c,h=be.useMemo(()=>p,Object.values(p));return jsx(y.Provider,{value:h,children:u})};d.displayName=r+"Provider";function m(f,l){let u=l?.[e]?.[i]||c,p=be.useContext(u);if(p)return p;if(n!==void 0)return n;throw new Error(`\`${f}\` must be used within \`${r}\``)}return [d,m]}let s=()=>{let r=t.map(n=>be.createContext(n));return function(c){let i=c?.[e]||r;return be.useMemo(()=>({[`__scope${e}`]:{...c,[e]:i}}),[c,i])}};return s.scopeName=e,[a,Wb(s,...o)]}function Wb(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(r){let n=a.reduce((c,{useScope:i,scopeName:d})=>{let f=i(r)[`__scope${d}`];return {...c,...f}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var No=globalThis?.document?be.useLayoutEffect:()=>{};var Gb=be[" useInsertionEffect ".trim().toString()]||No;function aa({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[s,r,n]=Kb({defaultProp:o,onChange:t}),c=e!==void 0,i=c?e:s;{let m=be.useRef(e!==void 0);be.useEffect(()=>{let f=m.current;f!==c&&console.warn(`${a} is changing from ${f?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=c;},[c,a]);}let d=be.useCallback(m=>{if(c){let f=_b(m)?m(e):m;f!==e&&n.current?.(f);}else r(m);},[c,e,r,n]);return [i,d]}function Kb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),s=be.useRef(t),r=be.useRef(o);return Gb(()=>{r.current=o;},[o]),be.useEffect(()=>{s.current!==t&&(r.current?.(t),s.current=t);},[t,s]),[t,a,r]}function _b(e){return typeof e=="function"}var jb=be.createContext(void 0);function Vo(e){let o=be.useContext(jb);return e||o||"ltr"}function Sc(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 Cc(e){let[o,t]=be.useState(void 0);return No(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;let r=s[0],n,c;if("borderBoxSize"in r){let i=r.borderBoxSize,d=Array.isArray(i)?i[0]:i;n=d.inlineSize,c=d.blockSize;}else n=e.offsetWidth,c=e.offsetHeight;t({width:n,height:c});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function Mc(e){let o=Xb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,c=be.Children.toArray(r),i=c.find(Yb);if(i){let d=i.props.children,m=c.map(f=>f===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(d)?be.cloneElement(d,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function Xb(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=Zb(s),c=Jb(r,s.props);return s.type!==be.Fragment&&(c.ref=a?Dr(a,n):n),be.cloneElement(s,c)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var $b=Symbol("radix.slottable");function Yb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$b}function Jb(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...c)=>{let i=r(...c);return s(...c),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function Zb(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 tv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],dt=tv.reduce((e,o)=>{let t=Mc(`Primitive.${o}`),a=be.forwardRef((s,r)=>{let{asChild:n,...c}=s,i=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...c,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function vl(e){let o=av(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,c=be.Children.toArray(r),i=c.find(rv);if(i){let d=i.props.children,m=c.map(f=>f===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(d)?be.cloneElement(d,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function av(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=nv(s),c=sv(r,s.props);return s.type!==be.Fragment&&(c.ref=a?Dr(a,n):n),be.cloneElement(s,c)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var ov=Symbol("radix.slottable");function rv(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ov}function sv(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...c)=>{let i=r(...c);return s(...c),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function nv(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 cn(e){let o=e+"CollectionProvider",[t,a]=Ma(o),[s,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=y=>{let{scope:h,children:x}=y,v=be__default.useRef(null),b=be__default.useRef(new Map).current;return jsx(s,{scope:h,itemMap:b,collectionRef:v,children:x})};n.displayName=o;let c=e+"CollectionSlot",i=vl(c),d=be__default.forwardRef((y,h)=>{let{scope:x,children:v}=y,b=r(c,x),L=Ft(h,b.collectionRef);return jsx(i,{ref:L,children:v})});d.displayName=c;let m=e+"CollectionItemSlot",f="data-radix-collection-item",l=vl(m),u=be__default.forwardRef((y,h)=>{let{scope:x,children:v,...b}=y,L=be__default.useRef(null),C=Ft(h,L),M=r(m,x);return be__default.useEffect(()=>(M.itemMap.set(L,{ref:L,...b}),()=>void M.itemMap.delete(L))),jsx(l,{[f]:"",ref:C,children:v})});u.displayName=m;function p(y){let h=r(e+"CollectionConsumer",y);return be__default.useCallback(()=>{let v=h.collectionRef.current;if(!v)return [];let b=Array.from(v.querySelectorAll(`[${f}]`));return Array.from(h.itemMap.values()).sort((M,k)=>b.indexOf(M.ref.current)-b.indexOf(k.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:n,Slot:d,ItemSlot:u},p,a]}var Pc=["PageUp","PageDown"],Dc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Rc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},qo="Slider",[wl,lv,dv]=cn(qo),[Ec]=Ma(qo,[dv]),[uv,fn]=Ec(qo),Fc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:s=100,step:r=1,orientation:n="horizontal",disabled:c=false,minStepsBetweenThumbs:i=0,defaultValue:d=[a],value:m,onValueChange:f=()=>{},onValueCommit:l=()=>{},inverted:u=false,form:p,...y}=e,h=be.useRef(new Set),x=be.useRef(0),b=n==="horizontal"?cv:fv,[L=[],C]=aa({prop:m,defaultProp:d,onChange:I=>{[...h.current][x.current]?.focus(),f(I);}}),M=be.useRef(L);function k(I){let B=xv(L,I);E(I,B);}function g(I){E(I,x.current);}function P(){let I=M.current[x.current];L[x.current]!==I&&l(L);}function E(I,B,{commit:G}={commit:false}){let R=wv(r),K=Lv(Math.round((I-a)/r)*r+a,R),D=bl(K,[a,s]);C((Q=[])=>{let V=hv(Q,D,B);if(yv(V,i*r)){x.current=V.indexOf(D);let ae=String(V)!==String(Q);return ae&&G&&l(V),ae?V:Q}else return Q});}return jsx(uv,{scope:e.__scopeSlider,name:t,disabled:c,min:a,max:s,valueIndexToChangeRef:x,thumbs:h.current,values:L,orientation:n,form:p,children:jsx(wl.Provider,{scope:e.__scopeSlider,children:jsx(wl.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":c,"data-disabled":c?"":void 0,...y,ref:o,onPointerDown:Ze(y.onPointerDown,()=>{c||(M.current=L);}),min:a,max:s,inverted:u,onSlideStart:c?void 0:k,onSlideMove:c?void 0:g,onSlideEnd:c?void 0:P,onHomeKeyDown:()=>!c&&E(a,0,{commit:true}),onEndKeyDown:()=>!c&&E(s,L.length-1,{commit:true}),onStepKeyDown:({event:I,direction:B})=>{if(!c){let K=Pc.includes(I.key)||I.shiftKey&&Dc.includes(I.key)?10:1,D=x.current,Q=L[D],V=r*K*B;E(Q+V,D,{commit:true});}}})})})})});Fc.displayName=qo;var[Bc,Oc]=Ec(qo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),cv=be.forwardRef((e,o)=>{let{min:t,max:a,dir:s,inverted:r,onSlideStart:n,onSlideMove:c,onSlideEnd:i,onStepKeyDown:d,...m}=e,[f,l]=be.useState(null),u=Ft(o,b=>l(b)),p=be.useRef(void 0),y=Vo(s),h=y==="ltr",x=h&&!r||!h&&r;function v(b){let L=p.current||f.getBoundingClientRect(),C=[0,L.width],k=Il(C,x?[t,a]:[a,t]);return p.current=L,k(b-L.left)}return jsx(Bc,{scope:e.__scopeSlider,startEdge:x?"left":"right",endEdge:x?"right":"left",direction:x?1:-1,size:"width",children:jsx(Nc,{dir:y,"data-orientation":"horizontal",...m,ref:u,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let L=v(b.clientX);n?.(L);},onSlideMove:b=>{let L=v(b.clientX);c?.(L);},onSlideEnd:()=>{p.current=void 0,i?.();},onStepKeyDown:b=>{let C=Rc[x?"from-left":"from-right"].includes(b.key);d?.({event:b,direction:C?-1:1});}})})}),fv=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:s,onSlideStart:r,onSlideMove:n,onSlideEnd:c,onStepKeyDown:i,...d}=e,m=be.useRef(null),f=Ft(o,m),l=be.useRef(void 0),u=!s;function p(y){let h=l.current||m.current.getBoundingClientRect(),x=[0,h.height],b=Il(x,u?[a,t]:[t,a]);return l.current=h,b(y-h.top)}return jsx(Bc,{scope:e.__scopeSlider,startEdge:u?"bottom":"top",endEdge:u?"top":"bottom",size:"height",direction:u?1:-1,children:jsx(Nc,{"data-orientation":"vertical",...d,ref:f,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{let h=p(y.clientY);r?.(h);},onSlideMove:y=>{let h=p(y.clientY);n?.(h);},onSlideEnd:()=>{l.current=void 0,c?.();},onStepKeyDown:y=>{let x=Rc[u?"from-bottom":"from-top"].includes(y.key);i?.({event:y,direction:x?-1:1});}})})}),Nc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:s,onSlideEnd:r,onHomeKeyDown:n,onEndKeyDown:c,onStepKeyDown:i,...d}=e,m=fn(qo,t);return jsx(dt.span,{...d,ref:o,onKeyDown:Ze(e.onKeyDown,f=>{f.key==="Home"?(n(f),f.preventDefault()):f.key==="End"?(c(f),f.preventDefault()):Pc.concat(Dc).includes(f.key)&&(i(f),f.preventDefault());}),onPointerDown:Ze(e.onPointerDown,f=>{let l=f.target;l.setPointerCapture(f.pointerId),f.preventDefault(),m.thumbs.has(l)?l.focus():a(f);}),onPointerMove:Ze(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f);}),onPointerUp:Ze(e.onPointerUp,f=>{let l=f.target;l.hasPointerCapture(f.pointerId)&&(l.releasePointerCapture(f.pointerId),r(f));})})}),Vc="SliderTrack",qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=fn(Vc,t);return jsx(dt.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...a,ref:o})});qc.displayName=Vc;var Ll="SliderRange",Hc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=fn(Ll,t),r=Oc(Ll,t),n=be.useRef(null),c=Ft(o,n),i=s.values.length,d=s.values.map(l=>Wc(l,s.min,s.max)),m=i>1?Math.min(...d):0,f=100-Math.max(...d);return jsx(dt.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...a,ref:c,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:f+"%"}})});Hc.displayName=Ll;var Sl="SliderThumb",Uc=be.forwardRef((e,o)=>{let t=lv(e.__scopeSlider),[a,s]=be.useState(null),r=Ft(o,c=>s(c)),n=be.useMemo(()=>a?t().findIndex(c=>c.ref.current===a):-1,[t,a]);return jsx(mv,{...e,ref:r,index:n})}),mv=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:s,...r}=e,n=fn(Sl,t),c=Oc(Sl,t),[i,d]=be.useState(null),m=Ft(o,v=>d(v)),f=i?n.form||!!i.closest("form"):true,l=Cc(i),u=n.values[a],p=u===void 0?0:Wc(u,n.min,n.max),y=gv(a,n.values.length),h=l?.[c.size],x=h?bv(h,p,c.direction):0;return be.useEffect(()=>{if(i)return n.thumbs.add(i),()=>{n.thumbs.delete(i);}},[i,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[c.startEdge]:`calc(${p}% + ${x}px)`},children:[jsx(wl.ItemSlot,{scope:e.__scopeSlider,children:jsx(dt.span,{role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":n.min,"aria-valuenow":u,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...r,ref:m,style:u===void 0?{display:"none"}:e.style,onFocus:Ze(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),f&&jsx(zc,{name:s??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:u},a)]})});Uc.displayName=Sl;var pv="RadioBubbleInput",zc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let s=be.useRef(null),r=Ft(s,a),n=Sc(o);return be.useEffect(()=>{let c=s.current;if(!c)return;let i=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(i,"value").set;if(n!==o&&m){let f=new Event("input",{bubbles:true});m.call(c,o),c.dispatchEvent(f);}},[n,o]),jsx(dt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});zc.displayName=pv;function hv(e=[],o,t){let a=[...e];return a[t]=o,a.sort((s,r)=>s-r)}function Wc(e,o,t){let r=100/(t-o)*(e-o);return bl(r,[0,100])}function gv(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function xv(e,o){if(e.length===1)return 0;let t=e.map(s=>Math.abs(s-o)),a=Math.min(...t);return t.indexOf(a)}function bv(e,o,t){let a=e/2,r=Il([0,50],[0,a]);return (a-r(o)*t)*t}function vv(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function yv(e,o){if(o>0){let t=vv(e);return Math.min(...t)>=o}return true}function Il(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 wv(e){return (String(e).split(".")[1]||"").length}function Lv(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Gc=Fc,Kc=qc,_c=Hc,jc=Uc;function Xc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(o=0;o<s;o++)e[o]&&(t=Xc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function mn(){for(var e,o,t=0,a="",s=arguments.length;t<s;t++)(e=arguments[t])&&(o=Xc(e))&&(a&&(a+=" "),a+=o);return a}var Iv=(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},Cv=(e,o)=>({classGroupId:e,validator:o}),Qc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var $c=[],kv="arbitrary..",Mv=e=>{let o=Av(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return Tv(n);let c=n.split("-"),i=c[0]===""&&c.length>1?1:0;return ef(c,i,o)},getConflictingClassGroupIds:(n,c)=>{if(c){let i=a[n],d=t[n];return i?d?Iv(d,i):i:d||$c}return t[n]||$c}}},ef=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let s=e[o],r=t.nextPart.get(s);if(r){let d=ef(e,o+1,r);if(d)return d}let n=t.validators;if(n===null)return;let c=o===0?e.join("-"):e.slice(o).join("-"),i=n.length;for(let d=0;d<i;d++){let m=n[d];if(m.validator(c))return m.classGroupId}},Tv=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?kv+a:void 0})(),Av=e=>{let{theme:o,classGroups:t}=e;return Pv(t,o)},Pv=(e,o)=>{let t=Qc();for(let a in e){let s=e[a];Ml(s,t,a,o);}return t},Ml=(e,o,t,a)=>{let s=e.length;for(let r=0;r<s;r++){let n=e[r];Dv(n,o,t,a);}},Dv=(e,o,t,a)=>{if(typeof e=="string"){Rv(e,o,t);return}if(typeof e=="function"){Ev(e,o,t,a);return}Fv(e,o,t,a);},Rv=(e,o,t)=>{let a=e===""?o:tf(o,e);a.classGroupId=t;},Ev=(e,o,t,a)=>{if(Bv(e)){Ml(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Cv(t,e));},Fv=(e,o,t,a)=>{let s=Object.entries(e),r=s.length;for(let n=0;n<r;n++){let[c,i]=s[n];Ml(i,tf(o,c),t,a);}},tf=(e,o)=>{let t=e,a=o.split("-"),s=a.length;for(let r=0;r<s;r++){let n=a[r],c=t.nextPart.get(n);c||(c=Qc(),t.nextPart.set(n,c)),t=c;}return t},Bv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Ov=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),s=(r,n)=>{t[r]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let n=t[r];if(n!==void 0)return n;if((n=a[r])!==void 0)return s(r,n),n},set(r,n){r in t?t[r]=n:s(r,n);}}};var Nv=[],Yc=(e,o,t,a,s)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:s}),Vv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=s=>{let r=[],n=0,c=0,i=0,d,m=s.length;for(let y=0;y<m;y++){let h=s[y];if(n===0&&c===0){if(h===":"){r.push(s.slice(i,y)),i=y+1;continue}if(h==="/"){d=y;continue}}h==="["?n++:h==="]"?n--:h==="("?c++:h===")"&&c--;}let f=r.length===0?s:s.slice(i),l=f,u=false;f.endsWith("!")?(l=f.slice(0,-1),u=true):f.startsWith("!")&&(l=f.slice(1),u=true);let p=d&&d>i?d-i:void 0;return Yc(r,u,l,p)};if(o){let s=o+":",r=a;a=n=>n.startsWith(s)?r(n.slice(s.length)):Yc(Nv,false,n,void 0,true);}if(t){let s=a;a=r=>t({className:r,parseClassName:s});}return a},qv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],s=[];for(let r=0;r<t.length;r++){let n=t[r],c=n[0]==="[",i=o.has(n);c||i?(s.length>0&&(s.sort(),a.push(...s),s=[]),a.push(n)):s.push(n);}return s.length>0&&(s.sort(),a.push(...s)),a}},Hv=e=>({cache:Ov(e.cacheSize),parseClassName:Vv(e),sortModifiers:qv(e),...Mv(e)}),Uv=/\s+/,zv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:s,sortModifiers:r}=o,n=[],c=e.trim().split(Uv),i="";for(let d=c.length-1;d>=0;d-=1){let m=c[d],{isExternal:f,modifiers:l,hasImportantModifier:u,baseClassName:p,maybePostfixModifierPosition:y}=t(m);if(f){i=m+(i.length>0?" "+i:i);continue}let h=!!y,x=a(h?p.substring(0,y):p);if(!x){if(!h){i=m+(i.length>0?" "+i:i);continue}if(x=a(p),!x){i=m+(i.length>0?" "+i:i);continue}h=false;}let v=l.length===0?"":l.length===1?l[0]:r(l).join(":"),b=u?v+"!":v,L=b+x;if(n.indexOf(L)>-1)continue;n.push(L);let C=s(x,h);for(let M=0;M<C.length;++M){let k=C[M];n.push(b+k);}i=m+(i.length>0?" "+i:i);}return i},Wv=(...e)=>{let o=0,t,a,s="";for(;o<e.length;)(t=e[o++])&&(a=af(t))&&(s&&(s+=" "),s+=a);return s},af=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=af(e[a]))&&(t&&(t+=" "),t+=o);return t},Gv=(e,...o)=>{let t,a,s,r,n=i=>{let d=o.reduce((m,f)=>f(m),e());return t=Hv(d),a=t.cache.get,s=t.cache.set,r=c,c(i)},c=i=>{let d=a(i);if(d)return d;let m=zv(i,t);return s(i,m),m};return r=n,(...i)=>r(Wv(...i))},Kv=[],He=e=>{let o=t=>t[e]||Kv;return o.isThemeGetter=true,o},of=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,rf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,_v=/^\d+\/\d+$/,jv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Xv=/\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$/,$v=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Yv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Jv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ho=e=>_v.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ta=e=>!!e&&Number.isInteger(Number(e)),Cl=e=>e.endsWith("%")&&de(e.slice(0,-1)),oa=e=>jv.test(e),Zv=()=>true,Qv=e=>Xv.test(e)&&!$v.test(e),sf=()=>false,ey=e=>Yv.test(e),ty=e=>Jv.test(e),ay=e=>!X(e)&&!$(e),oy=e=>Uo(e,df,sf),X=e=>of.test(e),Qa=e=>Uo(e,uf,Qv),kl=e=>Uo(e,ly,de),Jc=e=>Uo(e,nf,sf),ry=e=>Uo(e,lf,ty),pn=e=>Uo(e,cf,ey),$=e=>rf.test(e),Rr=e=>zo(e,uf),sy=e=>zo(e,dy),Zc=e=>zo(e,nf),ny=e=>zo(e,df),iy=e=>zo(e,lf),hn=e=>zo(e,cf,true),Uo=(e,o,t)=>{let a=of.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},zo=(e,o,t=false)=>{let a=rf.exec(e);return a?a[1]?o(a[1]):t:false},nf=e=>e==="position"||e==="percentage",lf=e=>e==="image"||e==="url",df=e=>e==="length"||e==="size"||e==="bg-size",uf=e=>e==="length",ly=e=>e==="number",dy=e=>e==="family-name",cf=e=>e==="shadow";var uy=()=>{let e=He("color"),o=He("font"),t=He("text"),a=He("font-weight"),s=He("tracking"),r=He("leading"),n=He("breakpoint"),c=He("container"),i=He("spacing"),d=He("radius"),m=He("shadow"),f=He("inset-shadow"),l=He("text-shadow"),u=He("drop-shadow"),p=He("blur"),y=He("perspective"),h=He("aspect"),x=He("ease"),v=He("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],C=()=>[...L(),$,X],M=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],g=()=>[$,X,i],P=()=>[Ho,"full","auto",...g()],E=()=>[Ta,"none","subgrid",$,X],I=()=>["auto",{span:["full",Ta,$,X]},Ta,$,X],B=()=>[Ta,"auto",$,X],G=()=>["auto","min","max","fr",$,X],R=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],K=()=>["start","end","center","stretch","center-safe","end-safe"],D=()=>["auto",...g()],Q=()=>[Ho,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...g()],V=()=>[e,$,X],ae=()=>[...L(),Zc,Jc,{position:[$,X]}],W=()=>["no-repeat",{repeat:["","x","y","space","round"]}],q=()=>["auto","cover","contain",ny,oy,{size:[$,X]}],Y=()=>[Cl,Rr,Qa],H=()=>["","none","full",d,$,X],U=()=>["",de,Rr,Qa],J=()=>["solid","dashed","dotted","double"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],j=()=>[de,Cl,Zc,Jc],ue=()=>["","none",p,$,X],ke=()=>["none",de,$,X],Me=()=>["none",de,$,X],Te=()=>[de,$,X],Ne=()=>[Ho,"full",...g()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[oa],breakpoint:[oa],color:[Zv],container:[oa],"drop-shadow":[oa],ease:["in","out","in-out"],font:[ay],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[oa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[oa],shadow:[oa],spacing:["px",de],text:[oa],"text-shadow":[oa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ho,X,$,h]}],container:["container"],columns:[{columns:[de,X,$,c]}],"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:C()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],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:[Ta,"auto",$,X]}],basis:[{basis:[Ho,"full","auto",c,...g()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Ho,"auto","initial","none",X]}],grow:[{grow:["",de,$,X]}],shrink:[{shrink:["",de,$,X]}],order:[{order:[Ta,"first","last","none",$,X]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:I()}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:I()}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:g()}],"gap-x":[{"gap-x":g()}],"gap-y":[{"gap-y":g()}],"justify-content":[{justify:[...R(),"normal"]}],"justify-items":[{"justify-items":[...K(),"normal"]}],"justify-self":[{"justify-self":["auto",...K()]}],"align-content":[{content:["normal",...R()]}],"align-items":[{items:[...K(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...K(),{baseline:["","last"]}]}],"place-content":[{"place-content":R()}],"place-items":[{"place-items":[...K(),"baseline"]}],"place-self":[{"place-self":["auto",...K()]}],p:[{p:g()}],px:[{px:g()}],py:[{py:g()}],ps:[{ps:g()}],pe:[{pe:g()}],pt:[{pt:g()}],pr:[{pr:g()}],pb:[{pb:g()}],pl:[{pl:g()}],m:[{m:D()}],mx:[{mx:D()}],my:[{my:D()}],ms:[{ms:D()}],me:[{me:D()}],mt:[{mt:D()}],mr:[{mr:D()}],mb:[{mb:D()}],ml:[{ml:D()}],"space-x":[{"space-x":g()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":g()}],"space-y-reverse":["space-y-reverse"],size:[{size:Q()}],w:[{w:[c,"screen",...Q()]}],"min-w":[{"min-w":[c,"screen","none",...Q()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[n]},...Q()]}],h:[{h:["screen","lh",...Q()]}],"min-h":[{"min-h":["screen","lh","none",...Q()]}],"max-h":[{"max-h":["screen","lh",...Q()]}],"font-size":[{text:["base",t,Rr,Qa]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,kl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Cl,X]}],"font-family":[{font:[sy,X,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,$,X]}],"line-clamp":[{"line-clamp":[de,"none",$,kl]}],leading:[{leading:[r,...g()]}],"list-image":[{"list-image":["none",$,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:V()}],"text-color":[{text:V()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",$,Qa]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[de,"auto",$,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:g()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:ae()}],"bg-repeat":[{bg:W()}],"bg-size":[{bg:q()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ta,$,X],radial:["",$,X],conic:[Ta,$,X]},iy,ry]}],"bg-color":[{bg:V()}],"gradient-from-pos":[{from:Y()}],"gradient-via-pos":[{via:Y()}],"gradient-to-pos":[{to:Y()}],"gradient-from":[{from:V()}],"gradient-via":[{via:V()}],"gradient-to":[{to:V()}],rounded:[{rounded:H()}],"rounded-s":[{"rounded-s":H()}],"rounded-e":[{"rounded-e":H()}],"rounded-t":[{"rounded-t":H()}],"rounded-r":[{"rounded-r":H()}],"rounded-b":[{"rounded-b":H()}],"rounded-l":[{"rounded-l":H()}],"rounded-ss":[{"rounded-ss":H()}],"rounded-se":[{"rounded-se":H()}],"rounded-ee":[{"rounded-ee":H()}],"rounded-es":[{"rounded-es":H()}],"rounded-tl":[{"rounded-tl":H()}],"rounded-tr":[{"rounded-tr":H()}],"rounded-br":[{"rounded-br":H()}],"rounded-bl":[{"rounded-bl":H()}],"border-w":[{border:U()}],"border-w-x":[{"border-x":U()}],"border-w-y":[{"border-y":U()}],"border-w-s":[{"border-s":U()}],"border-w-e":[{"border-e":U()}],"border-w-t":[{"border-t":U()}],"border-w-r":[{"border-r":U()}],"border-w-b":[{"border-b":U()}],"border-w-l":[{"border-l":U()}],"divide-x":[{"divide-x":U()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":U()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:V()}],"border-color-x":[{"border-x":V()}],"border-color-y":[{"border-y":V()}],"border-color-s":[{"border-s":V()}],"border-color-e":[{"border-e":V()}],"border-color-t":[{"border-t":V()}],"border-color-r":[{"border-r":V()}],"border-color-b":[{"border-b":V()}],"border-color-l":[{"border-l":V()}],"divide-color":[{divide:V()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,$,X]}],"outline-w":[{outline:["",de,Rr,Qa]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",m,hn,pn]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",f,hn,pn]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:U()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[de,Qa]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":U()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",l,hn,pn]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[de,$,X]}],"mix-blend":[{"mix-blend":[...ee(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ee()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":j()}],"mask-image-linear-to-pos":[{"mask-linear-to":j()}],"mask-image-linear-from-color":[{"mask-linear-from":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"mask-image-t-from-pos":[{"mask-t-from":j()}],"mask-image-t-to-pos":[{"mask-t-to":j()}],"mask-image-t-from-color":[{"mask-t-from":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"mask-image-r-from-pos":[{"mask-r-from":j()}],"mask-image-r-to-pos":[{"mask-r-to":j()}],"mask-image-r-from-color":[{"mask-r-from":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"mask-image-b-from-pos":[{"mask-b-from":j()}],"mask-image-b-to-pos":[{"mask-b-to":j()}],"mask-image-b-from-color":[{"mask-b-from":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"mask-image-l-from-pos":[{"mask-l-from":j()}],"mask-image-l-to-pos":[{"mask-l-to":j()}],"mask-image-l-from-color":[{"mask-l-from":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"mask-image-x-from-pos":[{"mask-x-from":j()}],"mask-image-x-to-pos":[{"mask-x-to":j()}],"mask-image-x-from-color":[{"mask-x-from":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"mask-image-y-from-pos":[{"mask-y-from":j()}],"mask-image-y-to-pos":[{"mask-y-to":j()}],"mask-image-y-from-color":[{"mask-y-from":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[$,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":j()}],"mask-image-radial-to-pos":[{"mask-radial-to":j()}],"mask-image-radial-from-color":[{"mask-radial-from":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":j()}],"mask-image-conic-to-pos":[{"mask-conic-to":j()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:ae()}],"mask-repeat":[{mask:W()}],"mask-size":[{mask:q()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,X]}],filter:[{filter:["","none",$,X]}],blur:[{blur:ue()}],brightness:[{brightness:[de,$,X]}],contrast:[{contrast:[de,$,X]}],"drop-shadow":[{"drop-shadow":["","none",u,hn,pn]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",de,$,X]}],"hue-rotate":[{"hue-rotate":[de,$,X]}],invert:[{invert:["",de,$,X]}],saturate:[{saturate:[de,$,X]}],sepia:[{sepia:["",de,$,X]}],"backdrop-filter":[{"backdrop-filter":["","none",$,X]}],"backdrop-blur":[{"backdrop-blur":ue()}],"backdrop-brightness":[{"backdrop-brightness":[de,$,X]}],"backdrop-contrast":[{"backdrop-contrast":[de,$,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,$,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,$,X]}],"backdrop-invert":[{"backdrop-invert":["",de,$,X]}],"backdrop-opacity":[{"backdrop-opacity":[de,$,X]}],"backdrop-saturate":[{"backdrop-saturate":[de,$,X]}],"backdrop-sepia":[{"backdrop-sepia":["",de,$,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":g()}],"border-spacing-x":[{"border-spacing-x":g()}],"border-spacing-y":[{"border-spacing-y":g()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",$,X]}],ease:[{ease:["linear","initial",x,$,X]}],delay:[{delay:[de,$,X]}],animate:[{animate:["none",v,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,$,X]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:ke()}],"rotate-x":[{"rotate-x":ke()}],"rotate-y":[{"rotate-y":ke()}],"rotate-z":[{"rotate-z":ke()}],scale:[{scale:Me()}],"scale-x":[{"scale-x":Me()}],"scale-y":[{"scale-y":Me()}],"scale-z":[{"scale-z":Me()}],"scale-3d":["scale-3d"],skew:[{skew:Te()}],"skew-x":[{"skew-x":Te()}],"skew-y":[{"skew-y":Te()}],transform:[{transform:[$,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ne()}],"translate-x":[{"translate-x":Ne()}],"translate-y":[{"translate-y":Ne()}],"translate-z":[{"translate-z":Ne()}],"translate-none":["translate-none"],accent:[{accent:V()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:V()}],"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",$,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":g()}],"scroll-mx":[{"scroll-mx":g()}],"scroll-my":[{"scroll-my":g()}],"scroll-ms":[{"scroll-ms":g()}],"scroll-me":[{"scroll-me":g()}],"scroll-mt":[{"scroll-mt":g()}],"scroll-mr":[{"scroll-mr":g()}],"scroll-mb":[{"scroll-mb":g()}],"scroll-ml":[{"scroll-ml":g()}],"scroll-p":[{"scroll-p":g()}],"scroll-px":[{"scroll-px":g()}],"scroll-py":[{"scroll-py":g()}],"scroll-ps":[{"scroll-ps":g()}],"scroll-pe":[{"scroll-pe":g()}],"scroll-pt":[{"scroll-pt":g()}],"scroll-pr":[{"scroll-pr":g()}],"scroll-pb":[{"scroll-pb":g()}],"scroll-pl":[{"scroll-pl":g()}],"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",$,X]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[de,Rr,Qa,kl]}],stroke:[{stroke:["none",...V()]}],"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 ff=Gv(uy);function Aa(...e){return ff(mn(e))}function gn({className:e,defaultValue:o,value:t,min:a=0,max:s=100,rangeClassName:r,trackClassName:n,thumbClassName:c,...i}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,s],[t,o,a,s]);return jsxs(Gc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:s,className:Aa("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[jsx(Kc,{"data-slot":"slider-track",className:Aa("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(_c,{"data-slot":"slider-range",className:Aa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:d.length},(m,f)=>jsx(jc,{"data-slot":"slider-thumb",className:Aa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",c)},f))]})}var fy="SchooplaVideoStorage";var Zt="videos",xn=()=>new Promise((e,o)=>{let t=indexedDB.open(fy,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Zt)||s.createObjectStore(Zt,{keyPath:"id"});};}),eo=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await xn(),r=a.transaction([Zt],"readwrite").objectStore(Zt),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((c,i)=>{let d=r.put(n);d.onsuccess=()=>c(!0),d.onerror=()=>i(d.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var pf=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await xn(),t=e.transaction([Zt],"readonly").objectStore(Zt);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result,c=new Map;n.forEach(i=>{c.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${c.size} video blobs from IndexedDB`),a(c);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Al=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await xn(),a=o.transaction([Zt],"readwrite").objectStore(Zt);await new Promise((s,r)=>{let n=a.delete(e);n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},hf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await xn(),t=e.transaction([Zt],"readwrite").objectStore(Zt);await new Promise((a,s)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>s(r.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},gf=e=>URL.createObjectURL(e);var my=be[" useId ".trim().toString()]||(()=>{}),py=0;function xf(e){let[o,t]=be.useState(my());return No(()=>{t(a=>a??String(py++));},[e]),(o?`radix-${o}`:"")}function bf(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var Dl="rovingFocusGroup.onEntryFocus",hy={bubbles:false,cancelable:true},Er="RovingFocusGroup",[Rl,vf,gy]=cn(Er),[xy,El]=Ma(Er,[gy]),[by,vy]=xy(Er),yf=be.forwardRef((e,o)=>jsx(Rl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Rl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(yy,{...e,ref:o})})}));yf.displayName=Er;var yy=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:s=false,dir:r,currentTabStopId:n,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:i,onEntryFocus:d,preventScrollOnEntryFocus:m=false,...f}=e,l=be.useRef(null),u=Ft(o,l),p=Vo(r),[y,h]=aa({prop:n,defaultProp:c??null,onChange:i,caller:Er}),[x,v]=be.useState(false),b=bf(d),L=vf(t),C=be.useRef(false),[M,k]=be.useState(0);return be.useEffect(()=>{let g=l.current;if(g)return g.addEventListener(Dl,b),()=>g.removeEventListener(Dl,b)},[b]),jsx(by,{scope:t,orientation:a,dir:p,loop:s,currentTabStopId:y,onItemFocus:be.useCallback(g=>h(g),[h]),onItemShiftTab:be.useCallback(()=>v(true),[]),onFocusableItemAdd:be.useCallback(()=>k(g=>g+1),[]),onFocusableItemRemove:be.useCallback(()=>k(g=>g-1),[]),children:jsx(dt.div,{tabIndex:x||M===0?-1:0,"data-orientation":a,...f,ref:u,style:{outline:"none",...e.style},onMouseDown:Ze(e.onMouseDown,()=>{C.current=true;}),onFocus:Ze(e.onFocus,g=>{let P=!C.current;if(g.target===g.currentTarget&&P&&!x){let E=new CustomEvent(Dl,hy);if(g.currentTarget.dispatchEvent(E),!E.defaultPrevented){let I=L().filter(D=>D.focusable),B=I.find(D=>D.active),G=I.find(D=>D.id===y),K=[B,G,...I].filter(Boolean).map(D=>D.ref.current);Sf(K,m);}}C.current=false;}),onBlur:Ze(e.onBlur,()=>v(false))})})}),wf="RovingFocusGroupItem",Lf=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:s=false,tabStopId:r,children:n,...c}=e,i=xf(),d=r||i,m=vy(wf,t),f=m.currentTabStopId===d,l=vf(t),{onFocusableItemAdd:u,onFocusableItemRemove:p,currentTabStopId:y}=m;return be.useEffect(()=>{if(a)return u(),()=>p()},[a,u,p]),jsx(Rl.ItemSlot,{scope:t,id:d,focusable:a,active:s,children:jsx(dt.span,{tabIndex:f?0:-1,"data-orientation":m.orientation,...c,ref:o,onMouseDown:Ze(e.onMouseDown,h=>{a?m.onItemFocus(d):h.preventDefault();}),onFocus:Ze(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:Ze(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){m.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let x=Sy(h,m.orientation,m.dir);if(x!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let b=l().filter(L=>L.focusable).map(L=>L.ref.current);if(x==="last")b.reverse();else if(x==="prev"||x==="next"){x==="prev"&&b.reverse();let L=b.indexOf(h.currentTarget);b=m.loop?Iy(b,L+1):b.slice(L+1);}setTimeout(()=>Sf(b));}}),children:typeof n=="function"?n({isCurrentTabStop:f,hasTabStop:y!=null}):n})})});Lf.displayName=wf;var wy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Ly(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Sy(e,o,t){let a=Ly(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return wy[a]}function Sf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Iy(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var If=yf,Cf=Lf;var Mf="Toggle",Fl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:s,...r}=e,[n,c]=aa({prop:t,onChange:s,defaultProp:a??false,caller:Mf});return jsx(dt.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:Ze(e.onClick,()=>{e.disabled||c(!n);})})});Fl.displayName=Mf;var Pa="ToggleGroup",[Af]=Ma(Pa,[El]),Pf=El(),Bl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(My,{...a,ref:o});if(t==="multiple")return jsx(Ty,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Pa}\``)});Bl.displayName=Pa;var[Df,Rf]=Af(Pa),My=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,c]=aa({prop:t,defaultProp:a??"",onChange:s,caller:Pa});return jsx(Df,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:c,onItemDeactivate:be__default.useCallback(()=>c(""),[c]),children:jsx(Ef,{...r,ref:o})})}),Ty=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,c]=aa({prop:t,defaultProp:a??[],onChange:s,caller:Pa}),i=be__default.useCallback(m=>c((f=[])=>[...f,m]),[c]),d=be__default.useCallback(m=>c((f=[])=>f.filter(l=>l!==m)),[c]);return jsx(Df,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:i,onItemDeactivate:d,children:jsx(Ef,{...r,ref:o})})});Bl.displayName=Pa;var[Ay,Py]=Af(Pa),Ef=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:s=true,orientation:r,dir:n,loop:c=true,...i}=e,d=Pf(t),m=Vo(n),f={role:"group",dir:m,...i};return jsx(Ay,{scope:t,rovingFocus:s,disabled:a,children:s?jsx(If,{asChild:true,...d,orientation:r,dir:m,loop:c,children:jsx(dt.div,{...f,ref:o})}):jsx(dt.div,{...f,ref:o})})}),bn="ToggleGroupItem",Dy=be__default.forwardRef((e,o)=>{let t=Rf(bn,e.__scopeToggleGroup),a=Py(bn,e.__scopeToggleGroup),s=Pf(e.__scopeToggleGroup),r=t.value.includes(e.value),n=a.disabled||e.disabled,c={...e,pressed:r,disabled:n},i=be__default.useRef(null);return a.rovingFocus?jsx(Cf,{asChild:true,...s,focusable:!n,active:r,ref:i,children:jsx(Tf,{...c,ref:o})}):jsx(Tf,{...c,ref:o})});Dy.displayName=bn;var Tf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...s}=e,r=Rf(bn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=r.type==="single"?n:void 0;return jsx(Fl,{...c,...s,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Ff=Bl;var Fy=be.createContext({size:"default",variant:"default",spacing:0});function Da({className:e,variant:o,size:t,spacing:a=1,children:s,...r}){return jsx(Ff,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Aa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Fy.Provider,{value:{variant:o,size:t,spacing:a},children:s})})}var Oy={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},qf=createSlice({name:"toolbar",initialState:Oy,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:_t,setPenColor:Go,setStrokeWidth:Fr,setFontSize:wD,setFontFamily:LD,setFontStyle:SD,setFontWeight:ID,setTextDecoration:CD,setTextColor:kD}=qf.actions,Hf=qf.reducer;var Uf=({onClose:e,onRecordingComplete:o})=>{let t=ze(),[a,s]=useState(false),[r,n]=useState(null),[c,i]=useState(0),[d,m]=useState(null),[f,l]=useState(false),u=useRef(null),p=useRef([]),y=useRef(null),h=useRef(null),x=useRef(null);useEffect(()=>((async()=>{try{let P=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(P),l(!0),x.current&&(x.current.srcObject=P);}catch(P){console.error("Error accessing camera:",P),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{y.current&&clearInterval(y.current),d&&d.getTracks().forEach(P=>P.stop());}),[]);let v=()=>{d&&(d.getTracks().forEach(g=>g.stop()),m(null),l(false));},b=async()=>{try{let g=null,P=null;try{g=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(R){console.error("Error accessing camera for recording:",R),alert("Failed to access camera for recording.");return}try{P=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(R){console.warn("Microphone access denied:",R);}let E=[...g.getVideoTracks()];P&&E.push(...P.getAudioTracks());let I=new MediaStream(E),B="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?B="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?B="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?B="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(B="video/webm;codecs=vp8");let G=new MediaRecorder(I,{mimeType:B,videoBitsPerSecond:25e5});u.current=G,p.current=[],G.ondataavailable=R=>{R.data.size>0&&p.current.push(R.data);},G.onstop=()=>{let R=new Blob(p.current,{type:B}),K=document.createElement("video");K.src=URL.createObjectURL(R),K.muted=!0,K.currentTime=.1,K.onseeked=()=>{let D=document.createElement("canvas");D.width=K.videoWidth,D.height=K.videoHeight;let Q=D.getContext("2d");Q&&(Q.drawImage(K,0,0),h.current=D.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(K.src);},I.getTracks().forEach(D=>D.stop()),g&&g.getTracks().forEach(D=>D.stop()),P&&P.getTracks().forEach(D=>D.stop()),y.current&&clearInterval(y.current),n(R),v();},G.onerror=R=>{console.error("MediaRecorder error:",R);},G.start(1e3),s(!0),i(0),y.current=setInterval(()=>{i(R=>R+1);},1e3);}catch(g){console.error("Error starting camera recording:",g),alert("Failed to start recording. Please check permissions.");}},L=()=>{u.current&&a&&(u.current.state!=="inactive"&&(u.current.requestData(),setTimeout(()=>{u.current&&u.current.state!=="inactive"&&u.current.stop();},100)),s(false));},C=()=>{if(r){let g=URL.createObjectURL(r),P=document.createElement("a");P.href=g,P.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(g);}},M=g=>{let P=Math.floor(g/60),E=g%60;return `${P.toString().padStart(2,"0")}:${E.toString().padStart(2,"0")}`};if(!t)return null;let k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:g=>{g.target===g.currentTarget&&e(),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",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:g=>g.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:x,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:b,disabled:!f,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!f&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:L,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:M(c)})]})]})]}),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: ",M(c)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:C,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&h.current&&(o(r,h.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(k,t)};var ra=40,Wf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,s]=useState(t?.images||[]),[r,n]=useState(t?.order||"sequential"),[c,i]=useState(false),d=useRef(null),m=ze(),f=useRef(null);useEffect(()=>{let b=L=>{L.key==="Escape"&&o();};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[o]);let l=b=>{let L=b.target.files;if(!L||L.length===0)return;let C=ra-a.length;if(C<=0){alert(`You can only upload a maximum of ${ra} images`);return}let M=Array.from(L).slice(0,C);M.length<L.length&&alert(`Only ${C} more images can be added (max ${ra} total)`);let k=M.map(g=>new Promise((P,E)=>{let I=new FileReader;I.onload=B=>{B.target?.result?P(B.target.result):E(new Error("Failed to read file"));},I.onerror=E,I.readAsDataURL(g);}));Promise.all(k).then(g=>{s(P=>[...P,...g]),f.current&&(f.current.value="");});},u=b=>{b.preventDefault(),i(false);let L=Array.from(b.dataTransfer.files).filter(g=>g.type.startsWith("image/"));if(L.length===0)return;let C=ra-a.length;if(C<=0){alert(`You can only upload a maximum of ${ra} images`);return}let M=L.slice(0,C);M.length<L.length&&alert(`Only ${C} more images can be added (max ${ra} total)`);let k=M.map(g=>new Promise((P,E)=>{let I=new FileReader;I.onload=B=>{B.target?.result?P(B.target.result):E(new Error("Failed to read file"));},I.onerror=E,I.readAsDataURL(g);}));Promise.all(k).then(g=>{s(P=>[...P,...g]);});},p=b=>{b.preventDefault(),i(true);},y=()=>{i(false);},h=b=>{s(L=>L.filter((C,M)=>M!==b));},x=b=>{if(b.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!m)return null;let v=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:b=>{b.target===b.currentTarget&&o(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{ref:d,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:b=>b.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:x,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=ra?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ra," images"]}):jsxs("span",{children:[a.length,"/",ra," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:u,onDragOver:p,onDragLeave:y,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${c?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:c?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${r==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((b,L)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:b,alt:`Flashcard ${L+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>h(L),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:L+1})]},L))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(v,m)};var vn={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}},Zy={enabled:true};function ql(e){return e?{tools:{...vn.tools,...e.tools},actions:{...vn.actions,...e.actions}}:vn}var Qy={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}},ew={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 Tw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:s}={})=>{let r=xe(),n=te(F=>F.canvas.slides.find(se=>se.id===F.canvas.currentSlideId)),c=n?.videos||[],i=n?.editingFlashcard,d=te(F=>F.toolbar.selectedTool),m=te(F=>F.toolbar.penColor),f=te(F=>F.toolbar.strokeWidth),l=n?.showMcqForm,u=n?.showFlashcardForm,p=useRef(null),y=useMemo(()=>ql(s),[s]),{tools:h,actions:x}=y,v=c.some(F=>F.isRecorded&&F.isPlaying),b=te(F=>F.toolbar.fontSize),L=te(F=>F.toolbar.fontFamily),C=te(F=>F.toolbar.fontStyle),M=te(F=>F.toolbar.fontWeight),k=te(F=>F.toolbar.textDecoration),g=te(F=>F.toolbar.textColor),[P,E]=useState(false),[I,B]=useState(false),[G,R]=useState(false),[K,D]=useState(false),[Q,V]=useState(false),[ae,W]=useState(false),[q,Y]=useState(false),H=useRef(null),U=useRef(null),J=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),ee=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),j=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],[]),ue=useMemo(()=>J.filter(F=>{let se=h[F.configKey];return typeof se=="boolean"?se:Array.isArray(se)?se.length>0:true}),[h,J]),ke=useMemo(()=>{let F=h.shapes;return F===false?[]:F===true?ee:Array.isArray(F)?ee.filter(se=>F.includes(se.name)):ee},[h.shapes,ee]),Me=useMemo(()=>{let F=h.activities;return F===false?[]:F===true?j:Array.isArray(F)?j.filter(se=>F.includes(se.name)):j},[h.activities,j]),Te=useMemo(()=>{let F=h.media;return F===false?{photoFrame:false,image:false,video:false}:F===true?{photoFrame:true,image:true,video:true}:Array.isArray(F)?{photoFrame:F.includes("photo-frame"),image:F.includes("image"),video:F.includes("video")}:{photoFrame:true,image:true,video:true}},[h.media]),Ne=useMemo(()=>{let F=h.activities;return F===false?false:F===true?true:Array.isArray(F)?F.includes("flashcard"):true},[h.activities]),ct=F=>{let se=F.target.files;!se||se.length===0||(r(_t("select")),r(pt(false)),D(false),Array.from(se).forEach(ve=>{let ge=new FileReader;ge.onload=re=>{let le=new window.Image;le.src=re.target?.result,le.onload=()=>{let we=le.width/le.height,Ke=300,Ot=300,ft=le.width,Pe=le.height;ft>Ke&&(ft=Ke,Pe=ft/we),Pe>Ot&&(Pe=Ot,ft=Pe*we),r(ce());let Ue=960-ft/2,Lt=540-Pe/2;r(Kn({id:v4(),src:le.src,x:Ue,y:Lt,width:ft,height:Pe,draggable:true,rotation:0}));};},ge.readAsDataURL(ve);}),F.target.value="");},no=async F=>{let se=F.target.files;if(!(!se||se.length===0)){console.log("files",F),r(_t("select")),r(pt(false)),D(false);for(let ve of Array.from(se))try{let ge=URL.createObjectURL(ve),re=document.createElement("video");console.log("video",re),re.src=ge,re.muted=!0,re.playsInline=!0,re.preload="auto",re.load(),await new Promise((Nt,ua)=>{let Vt=setTimeout(()=>ua(new Error("Metadata load timeout")),1e4);re.onloadedmetadata=()=>{clearTimeout(Vt),Nt();},re.onerror=()=>{clearTimeout(Vt),ua(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:re.duration,width:re.videoWidth,height:re.videoHeight}),await new Promise((Nt,ua)=>{let Vt=setTimeout(()=>ua(new Error("Video load timeout")),1e4);re.readyState>=2?(clearTimeout(Vt),Nt()):re.onloadeddata=()=>{clearTimeout(Vt),Nt();};});let le=Math.min(.8,re.duration/2);console.log("Seeking to:",le),re.currentTime=le,await new Promise(Nt=>{let ua=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Nt();},5e3);re.onseeked=()=>{clearTimeout(ua),console.log("Seek completed"),Nt();};});let we=document.createElement("canvas"),Ke=re.videoWidth/re.videoHeight,Ot=400,ft=400,Pe=re.videoWidth,Ue=re.videoHeight;Pe>Ot&&(Pe=Ot,Ue=Pe/Ke),Ue>ft&&(Ue=ft,Pe=Ue*Ke),we.width=Pe,we.height=Ue;let Lt=we.getContext("2d",{willReadFrequently:!1});if(!Lt)throw new Error("Failed to get canvas context");if(await new Promise(Nt=>setTimeout(Nt,100)),re.videoWidth===0||re.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Pe,height:Ue}),Lt.drawImage(re,0,0,Pe,Ue);let da=we.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",da.length),r(ce());let Pn=960-Pe/2,Dn=540-Ue/2,Oa=v4();await eo(Oa,ve,da),r(ts({id:Oa,objectUrl:ge,thumbnailDataUrl:da,videoBlob:ve,x:Pn,y:Dn,width:Pe,height:Ue,draggable:!0,isPlaying:!1,rotation:0})),re.src="",re.load(),console.log(`Video uploaded: ${ve.name}`);}catch(ge){console.error("Error processing video:",ge),alert(`Failed to process video: ${ve.name}`);}F.target.value="";}},ne=(F,se,ve)=>{r(ce()),r(_t("select")),r(pt(false));let ge=300,re=300,le=960-ge/2,we=540-re/2;r(ve?fo({id:ve,images:F,order:se,x:le,y:we,width:ge,height:re,rotation:0,draggable:true}):Xn({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:F,currentIndex:0,order:se,x:le,y:we,width:ge,height:re,rotation:0,draggable:true})),r(qa(false));},Hr=()=>{r(ce()),r(_t("select")),r(pt(false));let F=400,se=300,ve=800-F/2,ge=450-se/2;if(t?.current){let re=t.current,le=re.scaleX()||1,we=re.scaleY()||1,Ke=re.width()/le,Ot=re.height()/we;ve=Ke/2-F/2,ge=Ot/2-se/2;}r(Jn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ve,y:ge,width:F,height:se,rotation:0,draggable:true,isCapturing:false})),V(false);},Ur=F=>{let le={};switch(F.name){case "circle":case "ring":case "wedge":case "arc":le.radius=50,(F.name==="ring"||F.name==="arc")&&(le.innerRadius=25,le.outerRadius=50),(F.name==="wedge"||F.name==="arc")&&(le.angle=F.name==="wedge"?60:90);break;case "ellipse":le.radiusX=60,le.radiusY=40;break;case "triangle":le.radius=50,le.sides=3;break;case "polygon":le.radius=50,le.sides=6;break;case "star":le.innerRadius=25,le.outerRadius=50,le.numPoints=5;break;case "arrow":case "line":le.points=[0,0,100,0],F.name==="arrow"&&(le.pointerLength=10,le.pointerWidth=10);break}let we={id:`shape-${Date.now()}`,type:F.name,x:910,y:490,width:100,height:100,rotation:0,color:m,...le};r(ce()),r(pt(false)),r(_t(F.name)),r(_n(we));},Fa=F=>{if(r(_t(F)),F==="select")r(pt(false));else if(F==="text"){r(pt(false)),r(ce());let se=200,ve=50,ge=960-se/2,re=540-ve/2,we=window.innerWidth<768?Math.max(b,32):b,Ke=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(jn({id:Ke,text:"",x:ge,y:re,width:se,height:ve,rotation:0,draggable:true,fontSize:we,fontFamily:L,fontStyle:C,fontWeight:M,textDecoration:k,fill:g,align:"left"})),setTimeout(()=>{r(er(Ke));},100),a&&a(Ke);}else r(pt(true));},zr=()=>{r(mi()),r(_t("select")),r(pt(false));},Wr=()=>{o?o():t?E(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Gr=()=>{B(true);},Kr=async(F,se)=>{try{r(_t("select")),r(pt(!1));let ve=URL.createObjectURL(F),ge=document.createElement("video");ge.src=ve,ge.muted=!0,ge.playsInline=!0,ge.preload="auto",await new Promise((Ue,Lt)=>{let da=setTimeout(()=>Lt(new Error("Metadata load timeout")),1e4);ge.onloadedmetadata=()=>{clearTimeout(da),Ue();},ge.onerror=()=>{clearTimeout(da),Lt(new Error("Failed to load video"));};});let re=640,le=ge.videoWidth/ge.videoHeight,we=re,Ke=we/le;r(ce());let Ot=960-we/2,ft=540-Ke/2,Pe=v4();await eo(Pe,F,se),r(ts({id:Pe,objectUrl:ve,thumbnailDataUrl:se,videoBlob:F,x:Ot,y:ft,width:we,height:Ke,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),E(!1),B(!1);}catch(ve){console.error("Error adding recorded video to canvas:",ve),alert("Failed to add video to canvas. Please try again.");}},kn=F=>{r(_t("select")),r(pt(false)),r(Zo(null)),F&&r(ii(F)),r(pa(!l));},Mn=()=>{r(Xo(null)),r(qa(true)),V(false);},Tn=()=>{R(!G);},An=()=>{D(!K);},Ba=()=>{V(!Q);};return useEffect(()=>{if(!q)return;let F=se=>{p.current&&!p.current.contains(se.target)&&Y(false);};return document.addEventListener("mousedown",F),()=>{document.removeEventListener("mousedown",F);}},[q]),v?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Da,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:ue.map((F,se)=>jsx("div",{title:F.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 ${F.name===d?"bg-primary/10":""}`,onClick:()=>{if(F.name==="image"){An(),R(false),V(false),Fa(F.name);return}else if(F.name==="shapes"){Tn(),D(false),V(false),Fa(F.name);return}else if(F.name==="activities"){Fa(F.name),Ba(),R(false),D(false);return}Fa(F.name),R(false),D(false),V(false);},children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},se))}),G&&jsx(Da,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:ke.map((F,se)=>jsx("div",{title:F.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Ur(F),children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},se))}),K&&jsxs(Da,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Te.photoFrame&&jsx("div",{title:"Photo frame",onClick:Hr,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Te.image&&jsx("div",{title:"Image",onClick:()=>H.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Te.video&&jsx("div",{title:"Video",onClick:()=>U.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),Q&&jsxs(Da,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Ne&&jsx("div",{title:"Flashcard",onClick:()=>Mn(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),Me.map((F,se)=>jsx("div",{title:F.label,onClick:()=>kn(F.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},se))]})]}),(x.undo||x.redo||x.screenRecord||x.cameraRecord||x.clear)&&jsxs(Da,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[x.undo&&jsx("button",{value:"undo",onClick:()=>r(pi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.redo&&jsx("button",{value:"redo",onClick:()=>r(hi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl"})}),x.screenRecord&&jsx("button",{value:"screen-record",onClick:Wr,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6279F8] md:block",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl"})}),jsx("button",{title:"Pen Color",onClick:()=>W(true),className:"relative mx-4 my-2 flex cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-white text-xl md:hidden",style:{borderColor:m},children:jsx("div",{className:"h-5 w-5 rounded-full border-2 border-white shadow-sm",style:{backgroundColor:m}})}),jsxs("div",{ref:p,className:"relative md:hidden",children:[jsx("button",{title:"Pen Size",onClick:()=>Y(!q),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${q?"bg-primary/10":""}`,children:jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border-2 border-[#FFFFFF80] bg-[#000000CC]",children:jsx("span",{className:"text-xs font-semibold text-white",children:f})})}),q&&jsxs("div",{className:"absolute top-1/2 left-full z-50 ml-2 w-48 -translate-y-1/2 rounded-lg border bg-white p-4 shadow-xl",children:[jsx("p",{className:"mb-3 text-xs font-semibold text-black/40",children:"PEN SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 shrink-0 rounded-full bg-black"}),jsx(gn,{defaultValue:[12],max:28,min:6,step:1,className:"w-full",value:[f],rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:F=>r(Fr(F[0]))}),jsx("div",{className:"h-5 w-5 shrink-0 rounded-full bg-black"})]})]})]}),x.cameraRecord&&jsx("button",{value:"camera-record",onClick:Gr,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6BBB93] md:block",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl"})}),x.clear&&jsx("button",{value:"clear",onClick:()=>zr(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl"})})]})]}),jsx("input",{ref:H,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:ct}),jsx("input",{ref:U,type:"file",accept:"video/*",className:"hidden",onChange:no}),!o&&P&&t&&jsx(dr,{onClose:()=>E(false),stageRef:t,onRecordingComplete:Kr}),I&&jsx(Uf,{onClose:()=>B(false),onRecordingComplete:Kr}),u&&jsx(Wf,{editingFlashcard:i,onConfirm:ne,onCancel:()=>r(qa(false))}),ae&&jsx(Os,{defaultColor:m,onConfirm:F=>{r(Go(F)),W(false);},onCancel:()=>W(false)})]})},Aw=Tw;var Gl=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let s=mt(po),r=mt(vi),n=a?r:s,c=mt(tr),m=(mt(v=>v.canvas.slides.find(b=>b.id===v.canvas.currentSlideId))?.videos||[]).some(v=>v.isRecorded&&v.isPlaying),[f,l]=useState(false),[u,p]=useState(null),[y,h]=useState(null),x=async()=>{if(s.length===0){h({type:"error",message:"No slides to publish"});return}if(!e){h({type:"error",message:"No publish handler provided"});return}l(true),h(null);try{let v=await e(n,c,b=>{p(b);});v.success?h({type:"success",message:v.message}):h({type:"error",message:v.message});}catch(v){h({type:"error",message:v instanceof Error?v.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{p(null),h(null);},3e3);}};return m?null:jsxs("button",{onClick:x,disabled:f||s.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var Fw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:s,onDescriptionChange:r,showPublishButton:n=true,showBackButton:c=true,editableTitle:i=true,editableDescription:d=true,className:m="",rightContent:f,leftContent:l,includeInactiveSlides:u=false})=>{let p=st(),y=mt(tr),h=mt(wi),x=e??(h?y.title:"")??"Untitled",v=o??(h?y.description:"")??"Add a description...",[b,L]=useState(false),[C,M]=useState(false),[k,g]=useState(x),[P,E]=useState(v),I=useRef(null),B=useRef(null);useEffect(()=>{g(x);},[x]),useEffect(()=>{E(v);},[v]),useEffect(()=>{b&&I.current&&(I.current.focus(),I.current.select());},[b]),useEffect(()=>{C&&B.current&&(B.current.focus(),B.current.select());},[C]);let G=()=>{i&&L(true);},R=()=>{d&&M(true);},K=()=>{L(false),k.trim()&&k!==x?s?s(k.trim()):p(gi(k.trim())):k.trim()||g(x);},D=()=>{M(false),P.trim()&&P!==v?r?r(P.trim()):p(xi(P.trim())):P.trim()||E(v);},Q=ae=>{ae.key==="Enter"?K():ae.key==="Escape"&&(g(x),L(false));},V=ae=>{ae.key==="Enter"?D():ae.key==="Escape"&&(E(v),M(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${m}`,children:[l||jsxs("div",{className:"flex items-center gap-6",children:[c&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[b?jsx("input",{ref:I,type:"text",value:k,onChange:ae=>g(ae.target.value),onBlur:K,onKeyDown:Q,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:G,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${i?"hover:border-primary cursor-text":""}`,children:k}),C?jsx("input",{ref:B,type:"text",value:P,onChange:ae=>E(ae.target.value),onBlur:D,onKeyDown:V,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:R,title:P,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${d?"hover:border-primary cursor-text":""}`,children:P})]})]}),f||n&&a&&jsx(Gl,{onPublish:a,includeInactiveSlides:u})]})};var Hw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Uw=({colors:e=Hw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:s=""})=>{let[r,n]=useState(true),c=te(he),i=te(l=>l.toolbar.penColor),d=te(l=>l.toolbar.strokeWidth),m=c?.backgroundColor,f=xe();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:r?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:px-8 2xl:py-6 ${s}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(gn,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[d],onValueChange:l=>f(Fr(l[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"COLOR"}),jsxs(Da,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${i===l.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:l.value},onClick:()=>f(Go(l.value))},l.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>f(Go(l.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-xs font-semibold whitespace-nowrap text-[#00000066] 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] lg:h-12 lg:w-12",style:{backgroundColor:m},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>f(Wn(l.target.value))})})]})}),jsx("div",{className:"absolute -top-4 left-1/2 flex flex-col items-center justify-between px-2",children:jsx("button",{onClick:()=>n(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{size:20,weight:"bold",className:"text-gray-600"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>n(true),className:"fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var jf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),zw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),_l=e=>{let o=zw(e);return o.charAt(0).toUpperCase()+o.slice(1)},Sn=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Xf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var $f={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 Jf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:n,...c},i)=>createElement("svg",{ref:i,...$f,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Sn("lucide",s),...!r&&!Xf(c)&&{"aria-hidden":"true"},...c},[...n.map(([d,m])=>createElement(d,m)),...Array.isArray(r)?r:[r]]));var In=(e,o)=>{let t=forwardRef(({className:a,...s},r)=>createElement(Jf,{ref:r,iconNode:o,className:Sn(`lucide-${jf(_l(e))}`,`lucide-${e}`,a),...s}));return t.displayName=_l(e),t};var _w=[["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"}]],Nr=In("copy",_w);var jw=[["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"}]],Vr=In("trash-2",jw);var Qf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:s,onDuplicate:r,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:s,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:c=>{c.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Nr,{size:14})}),!a&&jsx("button",{onClick:c=>{c.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(Vr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var Jw=({softDelete:e=false})=>{let o=st(),t=mt(po),a=mt(mo),s=mt(yi),[r,n]=useState(true),d=(mt(p=>p.canvas.slides.find(y=>y.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),m=()=>{s&&o(Vn());},f=p=>{o(Un(p));},l=p=>{o(Hn(p));},u=p=>{t.length>1&&o(qn({id:p,softDelete:e}));};return d?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((p,y)=>jsx(Qf,{slide:p,index:y,isSelected:p.id===a,isSingleSlide:t.length===1,onSelect:()=>f(p.id),onDuplicate:()=>l(p.id),onDelete:()=>u(p.id)},p.id))}),jsxs("button",{onClick:m,disabled:!s,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${s?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var Zw="SchooplaEditorDB",Qw=1,Ra="slides",Ea="metadata",jl="schoopla_current_slide_id",am="presentation_metadata",qr=()=>new Promise((e,o)=>{let t=indexedDB.open(Zw,Qw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Ra)||s.createObjectStore(Ra,{keyPath:"id"}),s.objectStoreNames.contains(Ea)||s.createObjectStore(Ea,{keyPath:"id"});};}),Xl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await qr(),a=o.transaction([Ra],"readwrite").objectStore(Ra);await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);});for(let s of e)await new Promise((r,n)=>{let c=a.add(s);c.onsuccess=()=>r(!0),c.onerror=()=>n(c.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},$l=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await qr(),t=e.transaction([Ra],"readonly").objectStore(Ra);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(c=>({id:c.id,width:c.width,height:c.height,x:c.x,y:c.y}))),a(n.length>0?n:null);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Cn=async()=>{try{let e=await qr(),o=e.transaction([Ra,Ea],"readwrite"),t=o.objectStore(Ra),a=o.objectStore(Ea);await new Promise((s,r)=>{let n=t.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(jl),localStorage.removeItem("schoopla_presentation_metadata"),await hf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Yl=e=>{try{localStorage.setItem(jl,e);}catch(o){console.error("Error saving current slide ID:",o);}},Jl=()=>{try{return localStorage.getItem(jl)}catch(e){return console.error("Error loading current slide ID:",e),null}},Zl=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Ql=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await qr(),a=o.transaction([Ea],"readwrite").objectStore(Ea);await new Promise((s,r)=>{let n=a.put({id:am,...e});n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},ed=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await qr(),t=e.transaction([Ea],"readonly").objectStore(Ea);return new Promise((a,s)=>{let r=t.get(am);r.onsuccess=()=>{e.close();let n=r.result;if(n){let{id:c,...i}=n;console.log("\u2705 Loaded presentation metadata:",i),a(i);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var eL=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides","canvas/updateSlideThumbnail"],tL=["canvas/clearCanvas"],aL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],oL=Zl((e,o)=>{Xl(e),Yl(o);},500),rL=Zl(e=>{Ql(e);},500),sL=(e,o)=>{Xl(e),Yl(o);},td=false,om=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let s=t.payload;Al(s).catch(r=>{console.error("Error deleting video blob:",r);});}if(t.type==="canvas/deleteSlide"&&t.payload){let s=t.payload,n=e.getState().canvas.slides.find(c=>c.id===s);n&&n.videos&&n.videos.length>0&&n.videos.forEach(c=>{Al(c.id).catch(i=>{console.error("Error deleting video blob:",i);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let s=t.payload,r=e.getState(),c=r.canvas.slides.find(i=>i.id===r.canvas.currentSlideId)?.videos.find(i=>i.id===s);c&&c.videoBlob&&setTimeout(()=>{let i=e.getState(),m=i.canvas.slides.find(f=>f.id===i.canvas.currentSlideId)?.videos.find(f=>f.id!==s&&f.x===c.x+20&&f.y===c.y+20);m&&c.videoBlob&&eo(m.id,c.videoBlob,m.thumbnailDataUrl).catch(f=>{console.error("Error saving duplicated video blob:",f);});},0);}let a=o(t);if(t.type&&tL.includes(t.type)){if(!td){td=true;try{let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;sL(r,n);}finally{setTimeout(()=>{td=false;},0);}}}else if(t.type&&eL.includes(t.type)){let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;oL(r,n);}else if(t.type&&aL.includes(t.type)){let s=e.getState(),{presentationMetadata:r}=s.canvas;rL(r);}return a});new QueryClient;var lL=configureStore({reducer:{toolbar:Hf,canvas:bd},middleware:e=>e({serializableCheck:false}).concat(om)});var dL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2,fileName:r=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",c=e.toDataURL({mimeType:n,quality:a,pixelRatio:s}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=c,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},uL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o;return new Promise((r,n)=>{try{let c=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:c,quality:a,pixelRatio:s});fetch(i).then(d=>d.blob()).then(d=>r(d)).catch(d=>n(d));}catch(c){n(c);}})},cL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:s})};var fL=(e,o,t)=>{let a=t.x-o.x,s=t.y-o.y;if(a===0&&s===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+s*s,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*s)/r)),c=o.x+n*a,i=o.y+n*s;return Math.sqrt(Math.pow(e.x-c,2)+Math.pow(e.y-i,2))},ad=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,s=e[0],r=e[e.length-1];for(let n=1;n<e.length-1;n++){let c=fL(e[n],s,r);c>t&&(t=c,a=n);}if(t>o){let n=ad(e.slice(0,a+1),o),c=ad(e.slice(a),o);return [...n.slice(0,-1),...c]}return [s,r]},mL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},pL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},rm=(e,o=1.5)=>{if(e.length<=4)return e;let t=mL(e),a=ad(t,o);return pL(a)},sm=(e,o=1.5)=>({...e,points:rm(e.points,o)}),hL=(e,o=1.5)=>e.map(t=>sm(t,o)),gL=(e,o)=>{let t=e.length/2,a=o.length/2,s=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${s}%`}};var xL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var nm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:s=.85}=o;return new Promise((r,n)=>{let c=new Image;c.onload=()=>{let{width:i,height:d}=c;if(i>t||d>a){let p=i/d;i>d?(i=Math.min(i,t),d=i/p):(d=Math.min(d,a),i=d*p);}let m=document.createElement("canvas");m.width=i,m.height=d;let f=m.getContext("2d");if(!f){n(new Error("Failed to get canvas context"));return}f.drawImage(c,0,0,i,d);let l=xL(e),u=m.toDataURL(l,s);r(u);},c.onerror=n,c.src=e;})};var so=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return a.buffer},Ko=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",_o=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",bL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:s=1080,imageQuality:r=.85}=o,n=[],c=0;for(let i of e){let d=[],m=[],f=[];for(let l of i.images){let u=l.src;if(t&&u.startsWith("data:"))try{u=await nm(u,{maxWidth:a,maxHeight:s,quality:r});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(u.startsWith("data:")){let p=so(u),y=Ko(u);c+=p.byteLength;let h={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,buffer:p,mimeType:y};if(l.audioData&&l.audioData.startsWith("data:")){let x=so(l.audioData),v=Ko(l.audioData);c+=x.byteLength,h.audioBuffer=x,h.audioMimeType=v;}d.push(h);}}for(let l of i.videos){let u,p;if(l.videoBlob)u=await l.videoBlob.arrayBuffer(),p=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))u=so(l.videoData),p=Ko(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}c+=u.byteLength;let y={id:l.id,thumbnailDataUrl:l.thumbnailDataUrl,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,isPlaying:l.isPlaying,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isRecorded:l.isRecorded,buffer:u,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let h=so(l.audioData),x=Ko(l.audioData);c+=h.byteLength,y.audioBuffer=h,y.audioMimeType=x;}m.push(y);}for(let l of i.photoFrames){let u={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:l.draggable,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isCapturing:l.isCapturing};if(l.capturedImageUrl&&l.capturedImageUrl.startsWith("data:")){let p=so(l.capturedImageUrl),y=Ko(l.capturedImageUrl);c+=p.byteLength,u.buffer=p,u.mimeType=y;}if(l.audioData&&l.audioData.startsWith("data:")){let p=so(l.audioData),y=Ko(l.audioData);c+=p.byteLength,u.audioBuffer=p,u.audioMimeType=y;}f.push(u);}n.push({...i,images:d,videos:m,photoFrames:f});}return {slides:n,totalSize:c}},vL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},yL=e=>{let o=new FormData,t=e.slides.map((a,s)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,mimeType:r.mimeType,fileKey:`slide_${s}_image_${n}`,audioFileKey:r.audioBuffer?`slide_${s}_image_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,isPlaying:r.isPlaying,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isRecorded:r.isRecorded,mimeType:r.mimeType,fileKey:`slide_${s}_video_${n}`,thumbnailFileKey:`slide_${s}_video_${n}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${s}_video_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,rotation:r.rotation,draggable:r.draggable,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isCapturing:r.isCapturing,mimeType:r.mimeType,fileKey:r.buffer?`slide_${s}_photoframe_${n}`:void 0,audioFileKey:r.audioBuffer?`slide_${s}_photoframe_${n}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,s)=>{a.images.forEach((r,n)=>{let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${_o(r.mimeType)}`;if(o.append(`slide_${s}_image_${n}`,c,i),r.audioBuffer&&r.audioMimeType){let d=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${_o(r.audioMimeType)}`;o.append(`slide_${s}_image_${n}_audio`,d,m);}}),a.videos.forEach((r,n)=>{let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${_o(r.mimeType)}`;if(o.append(`slide_${s}_video_${n}`,c,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let d=so(r.thumbnailDataUrl),m=new Blob([d],{type:"image/jpeg"}),f=`${r.id}_thumbnail.jpg`;o.append(`slide_${s}_video_${n}_thumbnail`,m,f);}if(r.audioBuffer&&r.audioMimeType){let d=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${_o(r.audioMimeType)}`;o.append(`slide_${s}_video_${n}_audio`,d,m);}}),a.photoFrames.forEach((r,n)=>{if(r.buffer&&r.mimeType){let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${_o(r.mimeType)}`;o.append(`slide_${s}_photoframe_${n}`,c,i);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${_o(r.audioMimeType)}`;o.append(`slide_${s}_photoframe_${n}_audio`,c,i);}});}),o};var SL=()=>{let e=st(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let s=await $l(),r=Jl(),n=await ed();if(s&&s.length>0){let c=await pf(),i=s.map(m=>{if(m.videos&&m.videos.length>0){let f=m.videos.map(l=>{let u=c.get(l.id);if(u){let p=gf(u.blob);return {...l,objectUrl:p,thumbnailDataUrl:u.thumbnailDataUrl,videoBlob:u.blob}}else return l});return {...m,videos:f}}return m}),d=r&&i.find(m=>m.id===r)?r:i[0].id;e(lo({slides:i,currentSlideId:d}));}e(n?bi({title:n.title,description:n.description}):Ts(!0));}catch(s){console.error("Error loading persisted slides:",s),e(Ts(true));}finally{t(false);}})();},[e]),{isLoading:o}};var lm=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||""})),dm=new WeakSet,um=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await eo(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},IL=()=>{let e=st(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||dm.has(a))return;dm.add(a);let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Cn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let c=r&&s.find(d=>d.id===r)?r:s[0].id,i=lm(s);e(lo({slides:i,currentSlideId:c})),await um(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Cn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let c=r&&s.find(d=>d.id===r)?r:s[0].id,i=lm(s);e(lo({slides:i,currentSlideId:c})),await um(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
7
7
 
8
8
  lucide-react/dist/esm/shared/src/utils.js:
9
9
  lucide-react/dist/esm/defaultAttributes.js: