@turnix-co/konva-editor 3.0.44 → 3.0.47

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,R=r.find(U=>U.id===i)?.fontSize||24,O=M*R*1.2+10;g.width=Math.max(200,x),g.height=Math.max(50,C,O);}else if(v&&s.trim()){let b=v.text(),w=v.width();v.text(s),v.width(void 0);let I=v.width(),k=v.height();v.text(b),v.width(w),g.width=Math.max(200,I+20),g.height=Math.max(50,k+20);}t(Dt(g)),u(null),c(""),t(sr(null)),e();}}}};var _d=e=>{let o=useDispatch(),a=useSelector(he)?.shortAnswers||[],r=useRef(new Map),n=useCallback((i,u)=>{let s=i.target;o(tr({id:u,x:s.x(),y:s.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:n}};var Xd=e=>{let o=useDispatch(),t=useSelector(he),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((n,i)=>{let u=n.target;o(ar({id:i,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var Yd=e=>{let o=xe(),a=te(he)?.flashcards||[],r=useRef(new Map),n=useRef(new Map),i=useCallback((d,l)=>{if(n.current.has(l))return n.current.get(l);let f=new window.Image;return (d.startsWith("http://")||d.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=d,n.current.set(l,f),f},[]),u=useCallback((d,l)=>{let f=d.target,h=f.id();a.find(v=>v.id===h)&&(o(go({id:h,x:f.x(),y:f.y()})),l?.());},[a,o]),s=useCallback((d,l)=>{let f=l.target,h=f.scaleX(),m=f.scaleY(),v=f.rotation(),y=Math.max(50,f.width()*h),g=Math.max(50,f.height()*m);f.scaleX(1),f.scaleY(1),f.width(y),f.height(g),o(go({id:d,width:y,height:g,x:f.x(),y:f.y(),rotation:v})),f.getLayer()?.batchDraw(),e?.();},[o,e]),c=useCallback(d=>{o(si(d)),e?.();},[o,e]),p=useCallback(d=>{o(ii(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:i,flashcardRefs:r,handleDragEnd:u,handleFlashcardTransformEnd:s,handleNext:c,handlePrevious:p}};var Qd=e=>{let o=xe(),a=te(he)?.photoFrames||[],r=useRef(new Map),[n,i]=useState(new Map),u=useCallback((f,h)=>{console.log("handleDragEnd"),o(Wa({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),s=useCallback((f,h)=>{let m=h.target,v=m.scaleX(),y=m.scaleY(),g=m.rotation(),b=a.find(k=>k.id===f);if(!b)return;let w=Math.max(100,b.width*v),I=Math.max(100,b.height*y);m.scaleX(1),m.scaleY(1),o(Wa({id:f,width:w,height:I,x:m.x(),y:m.y(),rotation:g})),m.getLayer()?.batchDraw(),e?.();},[o,e,a]),c=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return i(m=>{let v=new Map(m);return v.set(f,h),v}),o(Wa({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),p=useCallback(f=>{let h=n.get(f);h&&(h.getTracks().forEach(m=>m.stop()),i(m=>{let v=new Map(m);return v.delete(f),v}),o(Wa({id:f,isCapturing:false})),e?.());},[n,o,e]),d=useCallback((f,h)=>{let m=document.createElement("canvas");m.width=h.videoWidth,m.height=h.videoHeight;let v=m.getContext("2d");if(v){v.drawImage(h,0,0,m.width,m.height);let y=m.toDataURL("image/jpeg",.8);return o(Wa({id:f,capturedImageUrl:y,isCapturing:false})),p(f),e?.(),y}return null},[o,p,e]),l=useRef(n);return useEffect(()=>{l.current=n;},[n]),useEffect(()=>()=>{l.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:u,handlePhotoFrameTransformEnd:s,startCamera:c,stopCamera:p,capturePhoto:d,cameraStreams:n}};var eu=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((n,i)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...i,width:Math.max(o.minWidth,Math.min(i.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(i.height,o.maxHeight))}:i,[o]),a=useCallback((n,i,u,s,c,p,d,l=[])=>{if(e.current){if(n&&!l.find(m=>m.id===n)?.isPlaying){let m=i.get(n)||u.get(n)||s.get(n)||c.get(n)||p.get(n)||(d?d.get(n):null);if(m){e.current.boundBoxFunc(t),e.current.nodes([m]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var zp=(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])},ru=(e,o)=>{let t=ut(),a=at(Hn),r=useRef(e);useEffect(()=>{r.current=e;},[e]);let n=useCallback(()=>{if(!(!o.current||a))try{let u=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});u&&u.startsWith("data:")&&t(ei({id:r.current,thumbnail:u}));}catch(u){console.warn("Could not generate thumbnail (likely CORS issue with images):",u);}},[o,t,a]),i=zp(n,500);return {generateThumbnail:n,debouncedGenerateThumbnail:i}};var Gp=e=>e.flatMap(o=>[o[0],o[1]]),Vn=(e,o)=>{let t=Fd(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 Gp(t)};var nu=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,i]=useState(null),u=te(b=>b.toolbar.selectedTool),s=te(b=>b.toolbar.penColor),c=te(b=>b.toolbar.strokeWidth),p=te(b=>b.canvas.isSketchMode),d=te(b=>b.canvas.slides.find(I=>I.id===b.canvas.currentSlideId)?.images.find(I=>I.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,m=d?.height||1,v=useCallback(b=>{if(u!=="pen"&&u!=="eraser")return;t.current=true,a.current=false,r.current=[{x:b.x,y:b.y}];let w=b.x/h,I=b.y/m;i({tool:u,points:[w,I],color:s,strokeWidth:c/h,isSketch:p});},[u,s,c,p,h,m]),y=useCallback(b=>{if(!t.current||!n)return;a.current=true;let w=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-w.x,2)+Math.pow(b.y-w.y,2))<2)return;r.current.push({x:b.x,y:b.y});let k;if(p)k=Vn(r.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,C)=>C%2===0?x/h:x/m);else {let S=b.x/h,x=b.y/m;k=[...n.points,S,x];}i(S=>S?{...S,points:k}:null);},[p,c,n,h,m]),g=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(ui({imageId:e,line:n})),i(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:l,activeLine:n,isDrawingMode:f,startDrawing:v,draw:y,stopDrawing:g,tool:u}};function Oe({onLongPress:e,delay:o=500,moveTolerance:t=10}){let a=useRef(null),r=useRef(null);return {createHandlers:useCallback((i,u)=>({onTouchStart:s=>{let c=s.evt.touches[0];r.current={x:c.clientX,y:c.clientY},a.current=setTimeout(()=>{e(i,u)(s.evt);},o);},onTouchMove:s=>{if(!r.current)return;let c=s.evt.touches[0],p=Math.abs(c.clientX-r.current.x),d=Math.abs(c.clientY-r.current.y);(p>t||d>t)&&a.current&&(clearTimeout(a.current),a.current=null);},onTouchEnd:()=>{a.current&&(clearTimeout(a.current),a.current=null),r.current=null;}}),[e,o,t])}}var uu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:i,onLongPress:u})=>{let{annotations:s,activeLine:c,stopDrawing:l,tool:f}=nu(e.id),{createHandlers:h}=Oe({onLongPress:u});useEffect(()=>{let b=t.current.get(e.id);b&&(b.width()!==e.width||b.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:b.width(),konvaHeight:b.height()}),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let m=false;useEffect(()=>{return;},[l,m]);let v=b=>{{n(e.id);return}},y=b=>{return;},g=b=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="eraser",children:[jsx(Image$1,{id:e.id,ref:b=>{if(b)t.current.set(e.id,b),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw();else {let w=t.current.get(e.id);w?._contextMenuCleanup&&w._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:b=>r(e.id,b),image:o,x:e.x,y:e.y,width:e.width,height:e.height,onContextMenu:b=>{b.evt.preventDefault();let w=b.evt;i(w,e.id,"image");},...f!=="pen"&&f!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onMouseMove:y,onMouseUp:g,...h(e.id,"image")}:{}}),s?.map((b,w)=>{let I=b.points.map((S,x)=>x%2===0?S*e.width+e.x:S*e.height+e.y),k=b.strokeWidth*e.width;return jsx(Line,{points:I,stroke:b.tool==="eraser"?"white":b.color,strokeWidth:k,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},w)}),c&&jsx(Line,{points:c.points.map((b,w)=>w%2===0?b*e.width+e.x:b*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});uu.displayName="ImageWithDrawing";var Hi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:i,onLongPress:u})=>jsx(Fragment,{children:e.map(s=>{let c=o(s);return c?jsx(uu,{img:s,loadedImage:c,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:i,onLongPress:u},s.id):null})}));Hi.displayName="ImageLayer";var ah=({src:e,x:o,id:t,y:a,width:r,height:n,isSelected:i,rotation:u=0,onTransformEnd:s,onDragEnd:c})=>{let p=xe(),d=useRef(null),l=f=>{p(Ua(f));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:n,rotation:u,onDragEnd:c,onTransformEnd:s,children:[jsx(Rect,{width:r,height:n,fill:"black",stroke:i?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${n}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>l(t),onSeeking:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},cu=ah;var uh=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,nodeRef:i})=>{let[u,s]=useState(null),c=useSelector(m=>m.toolbar.selectedTool),p=c==="pen"||c==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let m=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(m.crossOrigin="anonymous"),m.src=e.thumbnailDataUrl,m.onload=()=>{s(m);};}},[e.thumbnailDataUrl]),!u)return null;let d=e.width/2,l=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,80));return jsxs(Group,{draggable:!p,listening:!p,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...p?{}:{onDragEnd:a,onTransformEnd:r},ref:m=>{if(i(m),m){let v=m.getStage()?.container();if(v){let y=g=>{let b=m.getStage()?.getPointerPosition();if(b){let w={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=w.x&&b.x<=w.x+w.width&&b.y>=w.y&&b.y<=w.y+w.height&&n(g);}};v.addEventListener("contextmenu",y),m._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",y);};}}},children:[jsx(Image$1,{image:u,width:e.width,height:e.height,listening:!p,...p?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:d,y:l,radius:h,fill:"white",listening:!p,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...p?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:l,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!p,...p?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:l,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!p,...p?{}:{onClick:t,onTap:t}})]})},mu=uh;var Ui=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:n,onContextMenu:i})=>jsx(Fragment,{children:e.map(u=>jsxs(be__default.Fragment,{children:[jsx(mu,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>a(u.id),onDragEnd:s=>r(u.id,s),onTransformEnd:s=>n(u.id,s),onContextMenu:s=>i(s,u.id,"video"),nodeRef:s=>{s?t.current.set(u.id,s):t.current.delete(u.id);}}),u.isPlaying&&!u.isRecorded&&jsx(cu,{id:u.id,src:u.objectUrl,x:u.x,y:u.y,width:u.width,height:u.height,isSelected:false,rotation:u.rotation,onTransformEnd:s=>n(u.id,s),onDragEnd:s=>r(u.id,s)})]},u.id))}));Ui.displayName="VideoLayer";var Wi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:n,onContextMenu:i,onLongPress:u})=>{let s=useSelector(d=>d.toolbar.selectedTool),c=s==="pen"||s==="eraser",{createHandlers:p}=Oe({onLongPress:u});return jsx(Fragment,{children:e.map((d,l)=>{let f=d.id||l,h={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!c,listening:!c,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},radius:d.radius||d.width/2,width:d.width,height:d.width},f);case "star":return jsx(Star,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},sides:3,radius:d.radius||d.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},sides:d.sides||6,radius:d.radius||d.width/2},f);case "ellipse":return jsx(Ellipse,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},f);case "ring":return jsx(Ring,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "wedge":return jsx(Wedge,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},radius:d.radius||d.width/2,angle:d.angle||60},f);case "arrow":return jsx(Arrow,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "line":return jsx(Line,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...h,draggable:!d.locked&&!c,...c?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),i(m.evt,d.id,"shape");},...p(d.id,"shape")},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},f)}})})});Wi.displayName="ShapeLayer";var gu=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:n,onDoubleClick:i,editingTextId:u,onLongPress:s})=>{let c=useSelector(l=>l.toolbar.selectedTool),p=c==="pen"||c==="eraser",{createHandlers:d}=Oe({onLongPress:s});return jsx(Fragment,{children:e.map(l=>{let f=l.id===u,h=l.fontWeight==="bold",m=h?Math.max(1,l.fontSize/25):0;return jsx(Text,{id:l.id,ref:v=>{v?o.current.set(l.id,v):o.current.delete(l.id);},text:l.text,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:!l.locked&&!f&&!p,listening:!p,fontSize:l.fontSize,fontFamily:l.fontFamily,fontStyle:l.fontStyle,fontWeight:l.fontWeight,textDecoration:l.textDecoration,fill:l.fill,stroke:h?l.fill:void 0,strokeWidth:m,align:l.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...p?{}:{onClick:()=>r(l.id),onTap:()=>r(l.id),onDblClick:()=>i(l.id),onDblTap:()=>i(l.id),onDragEnd:v=>t(v,l.id),onTransformEnd:()=>a(l.id),onContextMenu:v=>{v.evt.preventDefault();let y=v.evt;n(y,l.id,"text");},...d(l.id,"text")}},l.id)})})};var Bh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onNext:i,onPrevious:u,nodeRef:s,touchHandlers:c,currentTool:p})=>{let[d,l]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let g=new window.Image,b=e.images[e.currentIndex];(b.startsWith("http://")||b.startsWith("https://"))&&(g.crossOrigin="anonymous"),g.src=b,g.onload=()=>{l(g);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let f=8,h=2,m=Math.min(e.width,e.height)*.08,v=Math.max(16,Math.min(m,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:r,...c,ref:g=>{if(s(g),g){let b=g.getStage()?.container();if(b){let w=I=>{let k=g.getStage()?.getPointerPosition();if(k){let S={x:e.x,y:e.y,width:e.width,height:e.height};k.x>=S.x&&k.x<=S.x+S.width&&k.y>=S.y&&k.y<=S.y+S.height&&n(I);}};b.addEventListener("contextmenu",w),g._contextMenuCleanup=()=>{b.removeEventListener("contextmenu",w);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,stroke:"#E5E7EB",strokeWidth:h,listening:false}),jsx(Image$1,{x:h+4,y:h+4,image:d,width:e.width-(h+4)*2,height:e.height-(h+4)*2,cornerRadius:f-h,onClick:t,onTap:t}),jsx(Rect,{x:h,y:e.height-50,width:e.width-h*2,height:50,cornerRadius:[0,0,f-h,f-h],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+v,y:e.height/2,onClick:g=>{g.cancelBubble=true,u();},onTap:g=>{g.cancelBubble=true,u();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-y-v,y:e.height/2,onClick:g=>{g.cancelBubble=true,i();},onTap:g=>{g.cancelBubble=true,i();},children:[jsx(Circle,{radius:v,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},vu=Bh;var Gi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onNext:i,onPrevious:u,onContextMenu:s,onLongPress:c})=>{let{createHandlers:p}=Oe({onLongPress:c});return jsx(Fragment,{children:e.map(d=>jsx(vu,{flashcard:d,isSelected:t===d.id,onClick:()=>n(d.id),onDragEnd:a,onTransformEnd:l=>r(d.id,l),onContextMenu:l=>s(l,d.id,"flashcard"),onNext:()=>i(d.id),onPrevious:()=>u(d.id),touchHandlers:p(d.id,"flashcard"),nodeRef:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);}},d.id))})});Gi.displayName="FlashcardLayer";var wu=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,i]=useState(null);te(b=>b.toolbar.selectedTool);let s=te(b=>b.toolbar.penColor),c=te(b=>b.toolbar.strokeWidth),p=te(b=>b.canvas.isSketchMode),d=te(b=>b.canvas.slides.find(I=>I.id===b.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),l=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,m=d?.height||1,v=useCallback(b=>{if(!f)return;t.current=true,a.current=false,r.current=[{x:b.x,y:b.y}];let w=b.x/h,I=b.y/m;i({tool:"pen",points:[w,I],color:s,strokeWidth:c/h,isSketch:p});},[f,s,c,p,h,m]),y=useCallback(b=>{if(!t.current||!n)return;a.current=true;let w=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-w.x,2)+Math.pow(b.y-w.y,2))<2)return;r.current.push({x:b.x,y:b.y});let k;if(p)k=Vn(r.current,{size:c*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,C)=>C%2===0?x/h:x/m);else {let S=b.x/h,x=b.y/m;k=[...n.points,S,x];}i(S=>S?{...S,points:k}:null);},[p,c,n,h,m]),g=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(fi({frameId:e,line:n})),i(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:l,activeLine:n,isDrawingMode:f,startDrawing:v,draw:y,stopDrawing:g}};var zh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onStartCamera:i,onCapture:u,cameraStream:s,nodeRef:c,touchHandlers:p})=>{let[d,l]=useState(null),[f,h]=useState(null),m=useRef(null),v=useRef(null),y=useRef(null),g=useRef(null),b=useRef(0),w=33,I=useSelector(V=>V.toolbar.selectedTool),k=I==="pen"||I==="eraser",{annotations:S,activeLine:x,isDrawingMode:C,startDrawing:M,draw:P,stopDrawing:R}=wu(e.id);useEffect(()=>{if(!C)return;let V=()=>{R();},j=()=>{R();};return window.addEventListener("mouseup",V),window.addEventListener("touchend",j),()=>{window.removeEventListener("mouseup",V),window.removeEventListener("touchend",j);}},[R,C]),useEffect(()=>{if(e.capturedImageUrl){let V=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(V.crossOrigin="anonymous"),V.src=e.capturedImageUrl,V.onload=()=>{l(V);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&s){m.current||(m.current=document.createElement("video"),m.current.autoplay=true,m.current.playsInline=true),v.current||(v.current=document.createElement("canvas"));let V=m.current,j=v.current;V.srcObject=s;let Y=()=>{j.width=V.videoWidth||640,j.height=V.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",j.width,j.height);let Z=oe=>{if(oe-b.current<w){y.current=requestAnimationFrame(Z);return}b.current=oe;let J=j.getContext("2d");if(J&&V.readyState===V.HAVE_ENOUGH_DATA){J.drawImage(V,0,0,j.width,j.height);let fe=j.toDataURL("image/jpeg",.6),we=new window.Image;we.onload=()=>{h(we);},we.src=fe;}y.current=requestAnimationFrame(Z);};y.current=requestAnimationFrame(Z);};return V.onloadedmetadata=Y,V.readyState>=V.HAVE_METADATA&&Y(),V.play().catch(Z=>console.error("Error playing video:",Z)),()=>{y.current&&(cancelAnimationFrame(y.current),y.current=null);}}return ()=>{h(null),g.current&&(g.current.src="");}},[e.isCapturing,s]);let W=()=>{m.current&&e.isCapturing&&u(m.current);},O=V=>{if(e.capturedImageUrl){if(!C){t();return}let j=V.currentTarget,Y=j.getAbsoluteTransform().copy(),oe=j.getStage()?.getPointerPosition();if(oe){Y.invert();let J=Y.point(oe);M(J);}V.cancelBubble=true;}else t();},U=V=>{if(!C||!e.capturedImageUrl)return;let j=V.currentTarget,Y=j.getAbsoluteTransform().copy(),oe=j.getStage()?.getPointerPosition();if(oe){Y.invert();let J=Y.point(oe);P(J);}},N=()=>{!C||!e.capturedImageUrl||R();},q=e.isCapturing?f:d,F=Math.min(e.width,e.height)*.12,z=Math.max(25,Math.min(F,50)),$=e.width/2,re=e.height/2;return jsxs(Group,{id:e.id,draggable:!C&&!k,listening:true,x:e.x,y:e.y,...p,...k?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:V=>{if(c(V),V){let j=V.getStage()?.container();if(j){let Y=Z=>{let oe=V.getStage()?.getPointerPosition();if(oe){let J={x:e.x,y:e.y,width:e.width,height:e.height};oe.x>=J.x&&oe.x<=J.x+J.width&&oe.y>=J.y&&oe.y<=J.y+J.height&&n(Z);}};j.addEventListener("contextmenu",Y),V._contextMenuCleanup=()=>{j.removeEventListener("contextmenu",Y);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:q?"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}}),q&&jsx(Image$1,{image:q,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:O,onTap:O,onMouseDown:O,onTouchStart:O,onMouseMove:U,onTouchMove:U,onMouseUp:N,onTouchEnd:N,...k?{}:{onDragEnd:a,onTransformEnd:r}}),S?.map((V,j)=>{let Y=V.points.map((oe,J)=>J%2===0?oe*e.width:oe*e.height),Z=V.strokeWidth*e.width;return jsx(Line,{points:Y,stroke:V.tool==="eraser"?"white":V.color,strokeWidth:Z,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},j)}),x&&jsx(Line,{points:x.points.map((V,j)=>j%2===0?V*e.width:V*e.height),stroke:x.tool==="eraser"?"white":x.color,strokeWidth:x.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},"active"),!q&&!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:re-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:$-z+6,y:re-60,width:z*1.6,height:z*1.6,radius:z,fill:"white",cornerRadius:8,listening:true,onClick:V=>{V.cancelBubble=true,e.isCapturing?W():i();},onTap:V=>{V.cancelBubble=true,e.isCapturing?W():i();}}),jsx(Html,{groupProps:{x:$-12,y:re-40,width:z*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:V=>{V.stopPropagation(),e.isCapturing?W():i();}})})]}),jsx(Text,{x:0,y:re,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:re+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:$-24,y:re+104,width:z*1.6,height:z*1.6,radius:z,fill:"#096B76",cornerRadius:z,listening:true,onClick:V=>{V.cancelBubble=true,e.isCapturing?W():i();},onTap:V=>{V.cancelBubble=true,e.isCapturing?W():i();}}),jsx(Html,{groupProps:{x:$-8,y:re+120,width:z*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:V=>{V.stopPropagation(),e.isCapturing?W():i();}})})]}),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:$-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:V=>{V.stopPropagation(),W();},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})})})})]})]})},Cu=zh;var Zi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onStartCamera:i,onCapture:u,cameraStreams:s,onContextMenu:c,onLongPress:p})=>{let{createHandlers:d}=Oe({onLongPress:p});return jsx(Fragment,{children:e.map(l=>jsx(Cu,{photoFrame:l,isSelected:t===l.id,onClick:()=>n(l.id),onDragEnd:f=>a(f,l.id),onTransformEnd:f=>r(l.id,f),onContextMenu:f=>c(f,l.id,"photoFrame"),onStartCamera:()=>i(l.id),onCapture:f=>u(l.id,f),cameraStream:s.get(l.id),touchHandlers:d(l.id,"photoFrame"),nodeRef:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);}},l.id))})});Zi.displayName="PhotoFrameLayer";var Au=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:n="",isDrawingMode:i,menuRef:u})=>{useEffect(()=>{let d=f=>{u?.current&&!u.current.contains(f.target)&&a();},l=f=>{f.key==="Escape"&&a();};return document.addEventListener("mousedown",d),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",l);}},[a]);let s=useMemo(()=>[{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"draw",label:i?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line","video"]},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(l=>!(l.showForTypes&&!l.showForTypes.includes(r)||l.hideForTypes&&l.hideForTypes.includes(r))),[r,i]),c=(d,l)=>{d==="order"||d==="lock"?t(d,l):(t(d),a());},p=jsx("div",{ref:u,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:s.map((d,l)=>jsxs("button",{onClick:f=>c(d.action,f),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${d.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[d.icon,jsx("span",{className:`font-medium ${d.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:d.label})]}),d.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},l))})});return createPortal(p,document.body)};var Pu=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let n=i=>{r.current&&!r.current.contains(i.target)&&a();};return document.addEventListener("mousedown",n),()=>{document.removeEventListener("mousedown",n);}},[a]),jsx("div",{ref:r,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((n,i)=>jsx("button",{onClick:()=>{n.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:n.label})},i))})})};var Du=createContext(null),Ji=()=>useContext(Du);function dg({children:e,className:o="",style:t}){let a=useRef(null),[r,n]=useState(null);return useEffect(()=>{a.current&&n(a.current);},[]),jsx(Du.Provider,{value:r,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function Ne(){let e=Ji();return typeof document>"u"?null:e||document.body}var Ru=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:n})=>{let[i,u]=useState(a),s=useRef(null),c=Ne();useEffect(()=>{s.current?.focus();},[]);let p=()=>{r(i),n();},d=f=>{f.key==="Enter"?p():f.key==="Escape"&&n();};return c?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:n,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:s,type:"text",value:i,onChange:f=>u(f.target.value),onKeyDown:d,placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:n,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:p,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),c):null};var jn=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),n=useRef(null),i=Ne();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let u=d=>{d.preventDefault(),o(a);},s=(d,l,f)=>{f/=100;let h=l*Math.min(f,1-f)/100,m=v=>{let y=(v+d/30)%12,g=f-h*Math.max(Math.min(y-3,9-y,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return `#${m(0)}${m(8)}${m(4)}`},c=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!i)return null;let p=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:n,className:"max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:u,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:d=>r(d.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:d=>r(d.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:d=>{let l=parseInt(d.target.value),f=s(l,100,50);r(f);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:c.map(d=>jsx("button",{type:"button",onClick:()=>r(d),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===d.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:d},title:d},d))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(p,i)};var Mg=({imageSrc:e,onCrop:o})=>{let[t]=Ou(e),a=useRef(null),r=useRef(null),n=useRef(null),i=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),u=useMemo(()=>{let l=i.width*.5,f=i.height*.5,h=(i.width-l)/2,m=(i.height-f)/2;return {x:h,y:m,width:l,height:f}},[i]),[s,c]=useState(u);useEffect(()=>{c(u);},[u]),useEffect(()=>{n.current&&r.current&&(n.current.nodes([r.current]),n.current.getLayer()?.batchDraw());},[s]),useEffect(()=>{o(s.x,s.y,s.width,s.height);},[s,o]);let p=()=>{let l=r.current;if(!l)return;let f=l.scaleX(),h=l.scaleY();l.scaleX(1),l.scaleY(1),c({x:l.x(),y:l.y(),width:Math.max(20,l.width()*f),height:Math.max(20,l.height()*h)});},d=()=>{let l=r.current;l&&c({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:i.width,height:i.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:i.width,height:i.height}),jsx(Rect,{x:0,y:0,width:i.width,height:i.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:s.x,y:s.y,width:s.width,height:s.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:s.x,y:s.y,width:s.width,height:s.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:p,dragBoundFunc:l=>{let f=Math.max(0,Math.min(l.x,i.width-s.width)),h=Math.max(0,Math.min(l.y,i.height-s.height));return {x:f,y:h}}}),jsx(Transformer,{ref:n,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(l,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>i.width||f.y+f.height>i.height?l:f})]})})},Nu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,n]=useState({x:0,y:0,width:0,height:0}),[i]=Ou(e),u=Ne();useEffect(()=>{let d=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);let s=(d,l,f,h)=>{n({x:d,y:l,width:f,height:h});},c=()=>{if(!i)return;let f=Math.min(600/i.width,400/i.height),h=r.x/f,m=r.y/f,v=r.width/f,y=r.height/f,g=document.createElement("canvas");g.width=v,g.height=y;let b=g.getContext("2d");if(!b)return;b.drawImage(i,h,m,v,y,0,0,v,y);let w=g.toDataURL("image/png");o(w);};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:d=>d.stopPropagation(),onMouseUp:d=>d.stopPropagation(),onMouseMove:d=>d.stopPropagation(),onTouchStart:d=>d.stopPropagation(),onTouchMove:d=>d.stopPropagation(),onTouchEnd:d=>d.stopPropagation(),children:jsxs("div",{ref:a,className:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:d=>d.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$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(Mg,{imageSrc:e,onCrop:s})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:c,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),u):null};var hr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let r=Ne(),[n,i]=useState(false),[u,s]=useState(null),[c,p]=useState(0),[d,l]=useState(true),f=useRef(null),h=useRef([]),m=useRef(null),v=useRef(null),y=useRef(null),g=useRef(null),b=useRef(null),w=useRef(null);useEffect(()=>()=>{y.current&&cancelAnimationFrame(y.current),m.current&&clearInterval(m.current),v.current&&v.current.getTracks().forEach(M=>M.stop());},[]);let I=async()=>{try{let M,P=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let N=o.current.getLayers();console.log("Konva layers:",N.length),N.forEach((Y,Z)=>{let oe=Y.getChildren();console.log(`Layer ${Z} children count:`,oe.length);});let q=document.createElement("canvas");q.width=o.current.width(),q.height=o.current.height();let F=q.getContext("2d",{willReadFrequently:!1});if(!F){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 z=()=>{if(F.clearRect(0,0,q.width,q.height),N.forEach(Y=>{let Z=Y.getCanvas()._canvas;Z&&F.drawImage(Z,0,0);}),a?.current){let Y=a.current;F.drawImage(Y,0,0);}};w.current=z,o.current.draw(),z(),await new Promise(Y=>setTimeout(Y,100)),console.log("Creating captureStream..."),M=q.captureStream(30),console.log("Canvas stream created, tracks:",M.getTracks().length);let re=M.getVideoTracks()[0];re&&console.log("Video track:",re.label,"state:",re.readyState);let V=0,j=()=>{z(),o?.current&&(o.current.getLayers().forEach(Z=>{Z.batchDraw();}),V++,V%60===0&&console.log("Drawing frame:",V)),y.current=requestAnimationFrame(j);};j();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(d)try{P=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(N){console.warn("Microphone access denied:",N);}let R=[...M.getVideoTracks()];P&&R.push(...P.getAudioTracks());let W=new MediaStream(R);v.current=W;let O="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?O="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?O="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?O="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(O="video/webm;codecs=vp8"),console.log("Using mimeType:",O);let U=new MediaRecorder(W,{mimeType:O,videoBitsPerSecond:25e5});f.current=U,h.current=[],U.ondataavailable=N=>{console.log("Data available, size:",N.data.size),N.data.size>0&&h.current.push(N.data);},U.onstop=()=>{console.log("Recording stopped, chunks:",h.current.length);let N=new Blob(h.current,{type:O});console.log("Final blob size:",N.size),o?.current&&w.current&&b.current&&(o.current.draw(),o.current.getLayers().forEach(F=>{F.batchDraw();}),w.current(),g.current=b.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",g.current.length)),W.getTracks().forEach(q=>q.stop()),m.current&&clearInterval(m.current),y.current&&(cancelAnimationFrame(y.current),y.current=null),s(N);},U.onerror=N=>{console.error("MediaRecorder error:",N);},console.log("Starting recording..."),U.start(1e3),i(!0),p(0),m.current=setInterval(()=>{p(N=>N+1);},1e3);}catch(M){console.error("Error starting screen recording:",M),alert("Failed to start recording. Please ensure you granted permission.");}},k=()=>{f.current&&n&&(console.log("Stopping recording, state:",f.current.state),f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),i(false));},S=()=>{if(u){let M=URL.createObjectURL(u),P=document.createElement("a");P.href=M,P.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(M);}},x=M=>{let P=Math.floor(M/60),R=M%60;return `${P.toString().padStart(2,"0")}:${R.toString().padStart(2,"0")}`};if(!r)return null;if(n){let M=jsxs("div",{className:"fixed top-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:x(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:k,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(M,r)}let C=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!u&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>l(!d),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${d?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:d?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:I,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),u&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(u),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",x(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&u&&g.current&&(t(u,g.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:S,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:()=>{s(null),p(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})});return createPortal(C,r)};var Uu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let n=Ne(),[i,u]=useState(false),[s,c]=useState(null),[p,d]=useState(false),[l,f]=useState(0),h=useRef(null),m=useRef([]),v=useRef(null),y=useRef(null);useEffect(()=>{o&&!s&&fetch(o).then(M=>M.blob()).then(M=>c(M)).catch(M=>console.error("Error loading audio:",M));},[o,s]);let g=async()=>{try{let M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),P=new MediaRecorder(M);h.current=P,m.current=[],P.ondataavailable=R=>{R.data.size>0&&m.current.push(R.data);},P.onstop=()=>{let R=new Blob(m.current,{type:"audio/webm"});c(R),M.getTracks().forEach(W=>W.stop()),v.current&&clearInterval(v.current);},P.start(),u(!0),f(0),v.current=setInterval(()=>{f(R=>R+1);},1e3);}catch(M){console.error("Error starting audio recording:",M),alert("Failed to start recording. Please allow microphone access.");}},b=()=>{h.current&&i&&(h.current.stop(),u(false));},w=()=>{if(s){let M=URL.createObjectURL(s),P=new Audio(M);y.current=P,P.onended=()=>{d(false),URL.revokeObjectURL(M);},P.play(),d(true);}},I=()=>{y.current&&(y.current.pause(),y.current.currentTime=0,d(false));},k=async()=>{if(s){let M=new FileReader;M.onloadend=()=>{let P=M.result;t(P),r();},M.readAsDataURL(s);}},S=()=>{c(null),a();},x=M=>{let P=Math.floor(M/60),R=M%60;return `${P.toString().padStart(2,"0")}:${R.toString().padStart(2,"0")}`};if(!n)return null;if(i){let M=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:x(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick: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(M,n)}let C=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:[!s&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:g,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),s&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:p?I:w,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),p?"Playing...":"Play Audio"]}),jsx("button",{onClick:S,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:k,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:r,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})});return createPortal(C,n)};var Ft=({audioData:e,x:o,y:t,width:a,scale:r=1,offsetX:n=0,offsetY:i=0,containerTop:u=90,containerRight:s=320})=>{let[c,p]=useState(false),d=useRef(null),l=m=>{if(m.stopPropagation(),c&&d.current)d.current.pause(),d.current.currentTime=0,p(false);else {let v=new Audio(e);d.current=v,v.onended=()=>{p(false);},v.onerror=()=>{console.error("Error playing audio"),p(false);},v.play(),p(true);}},f=(o+a)*r+n-15,h=t*r+i+u-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${c?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${f}px`,top:`${h}px`,width:"30px",height:"30px",zIndex:99},title:c?"Stop Audio":"Play Audio",children:c?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var Ku=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=te(he),n=Ne(),i=useMemo(()=>{if(!r)return [];let y=[];return r.images?.forEach(g=>{y.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),r.videos?.forEach(g=>{y.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),r.shapes?.forEach(g=>{y.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),r.texts?.forEach(g=>{y.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),r.flashcards?.forEach(g=>{y.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),r.photoFrames?.forEach(g=>{y.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),r.multipleChoices?.forEach(g=>{y.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),r.trueFalses?.forEach(g=>{y.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),r.shortAnswers?.forEach(g=>{y.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),r.LongAnswer?.forEach(g=>{y.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),r.fillInTheBlanks?.forEach(g=>{y.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),r.lines?.forEach(g=>{g.id&&y.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),y.sort((g,b)=>b.timestamp-g.timestamp)},[r]),[u,s]=useState(i),[c,p]=useState(false);useEffect(()=>{c||s(i);},[i]);let d=y=>{let g="h-5 w-5";switch(y){case "image":return jsx(Image$3,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes$1,{className:g});case "text":return jsx(TextT,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners,{className:g});case "line":return jsx(Pen,{className:g});default:return jsx(Question,{className:g})}},h=y=>{p(true),s(y);},m=()=>{p(false);let y=Date.now();u.forEach((g,b)=>{let w=y-b;a(nr({id:g.id,type:g.type,newTimestamp:w}));});};if(!n)return null;let v=jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-50 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-50 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$2,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:u.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:u,onReorder:h,className:"space-y-1",children:u.map(y=>{let g=y.id===e;return jsxs(Reorder.Item,{value:y,onDragEnd:m,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${g?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(y.id,y.type),className:`font-medium ${g?"text-[#096B76]":"text-[#00000099]"}`,children:y.name})}),jsx("div",{className:`${g?"text-[#096B76]":"text-[#00000099]"}`,children:d(y.type)})]},y.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[u.length," Layers"]})]})]})]});return createPortal(v,n)};var Jn=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o*1.2;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let p=s?`${s} ${c}`:c;n.measureText(p).width>t&&s!==""?(u.push(s),s=c):s=p;}),s&&u.push(s),u.length*o*1.2},Gu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n,touchHandlers:i})=>{let u=useSelector(P=>P.toolbar.selectedTool),s=u==="pen"||u==="eraser",[c,p]=useState(new Set),[d,l]=useState(false),[f,h]=useState(null),m=useRef(null);useEffect(()=>{let P=m.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id]);let v=new Set(e.data.responseOptions.correctIndex),y=v.size>1,g=P=>{d||p(y?R=>{let W=new Set(R);return W.has(P)?W.delete(P):W.add(P),W}:new Set([P]));},b=()=>{c.size>0&&l(true);},w=()=>{l(false),p(new Set);},I=c.size===v.size&&Array.from(c).every(P=>v.has(P)),k=Array.from(c).filter(P=>v.has(P)),S=y&&k.length>0&&!I,x=()=>I?"\u2713 Correct! Great job! \u{1F389}":S?`\u26A0 Partially correct (${k.length}/${v.size})`:"\u2717 Try again!",C=()=>I?{bg:"#dcfce7",text:"#166534"}:S?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},M=useMemo(()=>{let F=e.data.feedbackMode==="practice"?48:0,z=12,$=e.width-48,re=$-80,V=Math.max(60,Jn(e.data.question,20,$,"bold")+20),j=`Select ${v.size} answers (${c.size}/${v.size} selected)`,Y=y&&!d&&e.data.feedbackMode==="practice"?Jn(j,14,$)+10:0,Z=d&&e.data.feedbackMode==="practice"?Math.max(60,Jn(x(),16,$-40)+30):0,oe=e.data.responseOptions.options.map(Le=>{let Ie=Jn(Le,16,re);return Math.max(55,Ie+20)}),J=V+Y+Z,fe=oe.reduce((Le,Ie)=>Le+Ie+8,-8),we=J+fe+z+F+24;return {padding:24,questionHeight:V,instructionHeight:Y,feedbackHeight:Z,optionsStartY:J,optionHeights:oe,totalHeight:we,questionFontSize:20,optionFontSize:16,instructionFontSize:14,feedbackFontSize:16,optionGap:8,buttonHeight:F,buttonTopMargin:z,availableWidth:$,optionTextWidth:re}},[e.width,e.data.question,e.data.responseOptions.options,e.data.feedbackMode,d,c.size,v.size,y,x]);return jsxs(Group,{ref:m,name:"mcq-element",draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:M.totalHeight,...i,...s?{}:{onDragEnd:r,onClick:P=>t&&t(e.id),onTap:P=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:M.totalHeight,width:e.width,onTransformEnd:P=>o(e.id,P),onContextMenu:P=>{P.cancelBubble=true,n(P.evt,e.id,"mcq");}}),jsx(Text,{x:M.padding+8,y:M.padding,text:e.data.question,fontSize:M.questionFontSize,fontStyle:"bold",fill:"#111827",width:M.availableWidth,height:M.questionHeight-M.padding,wrap:"word",ellipsis:true,listening:false}),M.instructionHeight>0&&jsx(Text,{x:M.padding,y:M.questionHeight,text:`Select ${v.size} answers (${c.size}/${v.size} selected)`,fontSize:M.instructionFontSize,fill:"#6b7280",width:M.availableWidth,wrap:"word",listening:false}),d&&e.data.feedbackMode==="practice"&&jsxs(Fragment,{children:[jsx(Rect,{x:M.padding+24,y:M.questionHeight+M.instructionHeight+10,width:M.availableWidth-40,height:M.feedbackHeight-20,fill:C().bg,cornerRadius:8}),jsx(Text,{x:M.padding+24,y:M.questionHeight+M.instructionHeight+10,width:M.availableWidth-40,height:M.feedbackHeight-20,text:x(),fontSize:M.feedbackFontSize,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.responseOptions.options.map((P,R)=>{let W=v.has(R),O=c.has(R),U=M.optionsStartY;for(let $=0;$<R;$++)U+=M.optionHeights[$]+M.optionGap;let N=M.optionHeights[R],q="#e5e7eb",F="#ffffff",z="#111827";return d&&W?(q="#22c55e",F="#dcfce7",z="#1B9D2C"):d&&O&&!W?(q="#ef4444",F="#fee2e2",z="#ef4444"):O&&(q="#096B76",F="#ECFFF8",z="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:M.padding+12,y:U+(N-20)/2,width:20,height:20,fill:O?"#096B76":"white",stroke:O?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:y?4:10,onClick:$=>{$.cancelBubble=true,g(R);},onTap:$=>{$.cancelBubble=true,g(R);}}),O&&jsx(Text,{x:M.padding+12,y:U+(N-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:M.padding+44,y:U,width:M.availableWidth-60,height:N,fill:F,stroke:q,strokeWidth:2,cornerRadius:8,onClick:$=>{$.cancelBubble=true,g(R);},onTap:$=>{$.cancelBubble=true,g(R);}}),jsx(Text,{x:M.padding+60,y:U+10,width:M.optionTextWidth,height:N-20,text:P,fontSize:M.optionFontSize,fill:z,verticalAlign:"middle",wrap:"word",ellipsis:false,listening:false})]},R)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:M.optionsStartY+M.optionHeights.reduce((P,R)=>P+R+M.optionGap,-M.optionGap)+M.buttonTopMargin,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,h("check");},onMouseUp:P=>{P.cancelBubble=true,h(null),b();},onMouseLeave:P=>{P.cancelBubble=true,h(null);},onTouchStart:P=>{P.cancelBubble=true,h("check");},onTouchEnd:P=>{P.cancelBubble=true,h(null),b();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:M.padding+14,width:(M.availableWidth-24)/(d?2:1),height:M.buttonHeight,fill:c.size===0||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:M.padding+14,width:(M.availableWidth-24)/(d?2:1),height:M.buttonHeight,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-M.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),w();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),w();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:M.padding,width:(M.availableWidth-8)/2,height:M.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:M.padding,width:(M.availableWidth-8)/2,height:M.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Gu.displayName="MultipleChoice";var ju=Gu;var bx=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let p=s?`${s} ${c}`:c;n.measureText(p).width>t&&s!==""?(u.push(s),s=c):s=p;}),s&&u.push(s),u.length*o*1.2},al=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:r,touchHandlers:n})=>{let i=useDispatch(),u=useSelector(q=>q.toolbar.selectedTool),s=u==="pen"||u==="eraser",[c,p]=useState(false),[d,l]=useState(new Set),[f,h]=useState(false),[m,v]=useState(false),[y,g]=useState(0),b=new Set(e.data.responseOptions.correctIndex),w=Array.from(d).filter(q=>b.has(q)),I=d.size===b.size&&Array.from(d).every(q=>b.has(q)),k=w.length>0&&!I,S=()=>I?"\u2713 Correct! Great job!":k?`\u26A0 Partially correct (${w.length}/${b.size})`:"\u2717 Try again!",x=useMemo(()=>{let z=window.innerWidth*.4,$=20,re=18,V=28,j=40,Y=50,Z=20,oe=60,J=z-40,fe=Math.max(60,bx(e.data.question,$,J,"bold")+20),we=340+Z,Le=100+fe+20,Ie=z-Z*2,ze=Math.max(150,window.innerHeight*.3),Mt=e.data.feedbackMode==="practice",At=fe+50+ze+(f?oe+18:0)+(Mt?j+(f?Y:0)+20:0),ma=At+100;return {screenX:340,screenY:100,screenWidth:z,screenHeight:ma,dropZoneX:we,dropZoneY:Le,dropZoneWidth:Ie,dropZoneHeight:ze,questionFontSize:$,questionHeight:fe,feedbackFontSize:re,feedbackHeight:oe,dropHereFontSize:V,buttonHeight:j,buttonGap:Y,padding:Z,contentWidth:J,totalContentHeight:At,isPracticeMode:Mt}},[e.data.question,e.data.feedbackMode,f,d.size]),C=useRef(null);useEffect(()=>{let q=C.current;if(q)return r.current.set(e.id,q),()=>{r.current.delete(e.id);}},[e.id]);let M=q=>{i(ba({id:e.id,x:q.target.x(),y:q.target.y()}));},P=q=>{let F=q.target,z=F.x(),$=F.y(),re=window.innerWidth*.2,j=z+re>x.dropZoneX&&z<x.dropZoneX+x.dropZoneWidth&&$+50>x.dropZoneY&&$<x.dropZoneY+x.dropZoneHeight;p(j);},R=(q,F)=>{let z=F.target,$=z.x(),re=z.y(),V=window.innerWidth*.2,Y=$+V>x.dropZoneX&&$<x.dropZoneX+x.dropZoneWidth&&re+50>x.dropZoneY&&re<x.dropZoneY+x.dropZoneHeight;l(Y?Z=>new Set(Z).add(q):Z=>{let oe=new Set(Z);return oe.delete(q),oe}),p(false);},W=()=>{h(true);},O=()=>{h(false),l(new Set),g(q=>q+1);},U=()=>I?{bg:"#dcfce7",text:"#166534"}:k?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},N=()=>f?I?"#4CAF50":k?"#f59e0b":"#ef4444":c?"#4CAF50":"#075560";return jsxs(Group,{ref:C,name:"mcq-element",width:x.screenWidth,height:x.screenHeight,draggable:!s,listening:!s,...n,...s?{}:{onClick:q=>a&&a(e.id),onTap:q=>a&&a(e.id),onContextMenu:q=>{q.evt.preventDefault(),o(q.evt,e.id,"mcq");}},children:[jsxs(Group,{x:x.screenX,y:x.screenY,rotation:e.rotation,onDragEnd:M,children:[jsx(Rect,{fill:"white",stroke:c?"#4CAF50":"#e5e7eb",strokeWidth:c?4:2,cornerRadius:12,height:x.totalContentHeight,width:x.screenWidth,shadowColor:c?"#4CAF50":"transparent",shadowBlur:c?20:0,shadowOpacity:.5}),jsx(Text,{x:x.padding,y:x.padding,width:x.contentWidth,height:x.questionHeight-x.padding,text:e.data.question,fontSize:x.questionFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",wrap:"word"}),jsx(Rect,{x:x.padding,y:x.questionHeight+20,width:x.dropZoneWidth,height:x.dropZoneHeight,fill:"#EBF6F7",stroke:N(),strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:x.padding+3,y:x.questionHeight+20+x.dropZoneHeight+18,width:x.dropZoneWidth-5,height:x.feedbackHeight,fill:U().bg,cornerRadius:8}),jsx(Text,{x:x.padding,y:x.questionHeight+20+x.dropZoneHeight+20,width:x.dropZoneWidth,height:x.feedbackHeight,text:S(),fontSize:x.feedbackFontSize,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle",wrap:"word"})]}),d.size===0&&!f&&jsx(Text,{x:x.padding,y:x.questionHeight+20,width:x.dropZoneWidth,height:x.dropZoneHeight,text:b.size>1?`Drop ${b.size} Correct Answers Here`:"Drop Here",fontSize:x.dropHereFontSize,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),x.isPracticeMode?jsxs(Group,{x:x.padding,y:x.questionHeight+20+x.dropZoneHeight+(f?x.feedbackHeight+18:0)+20,children:[jsxs(Group,{onMouseDown:()=>{v(true),W();},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),W();},onTouchEnd:()=>v(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:x.buttonHeight,width:x.dropZoneWidth}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:x.dropZoneWidth,height:x.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:x.buttonGap,onMouseDown:O,onTouchStart:O,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:x.buttonHeight,width:x.dropZoneWidth}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:x.dropZoneWidth,height:x.buttonHeight,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((q,F)=>{let z=F%2,$=Math.floor(F/2),re=window.innerWidth*.2,V=50,j=10,Y=d.has(F),Z=b.has(F),oe=f&&Y,J="transparent";return oe?J=Z?"#4CAF50":"#ef4444":Y&&(J="#4CAF50"),jsxs(Group,{x:340+z*(re+j),y:x.screenY+x.totalContentHeight+$*(V+j)+20,draggable:!f,onDragMove:P,onDragEnd:fe=>R(F,fe),opacity:f&&!Y?.5:1,children:[jsx(Rect,{width:re-20,height:V,fill:"white",stroke:J,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:re-20,height:V,text:q,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${F}-${y}`)})]})};al.displayName="MultipleChoiceDragAndDrop";var _u=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n,onLongPress:i})=>{let{createHandlers:u}=Oe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(ju,{multipleChoice:s,handleMcqTransform:o,mcqRefs:a,handleDragEnd:c=>r(c,s.id),onContextMenu:n,touchHandlers:u(s.id,"mcq")},s.id):jsx(al,{multipleChoice:s,handleMcqTransform:o,mcqRefs:a,onContextMenu:n,touchHandlers:u(s.id,"mcq")},s.id))})};var Xu=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o*1.2;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let p=s?`${s} ${c}`:c;n.measureText(p).width>t&&s!==""?(u.push(s),s=c):s=p;}),s&&u.push(s),u.length*o*1.2},$u=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i})=>{let u=useSelector(x=>x.toolbar.selectedTool),s=u==="pen"||u==="eraser",[c,p]=useState(null),[d,l]=useState(false),[f,h]=useState(null),m=useRef(null);useEffect(()=>{let x=m.current;if(x)return a.current.set(e.id,x),()=>{a.current.delete(e.id);}},[e.id]);let v=()=>{c!==null&&l(true);},y=()=>{l(false),p(null);},g=e.data.responseOptions.correctAnswer,b=c===g,w=x=>{d||p(x);},I=()=>b?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",k=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},S=useMemo(()=>{let O=e.data.feedbackMode==="practice"?48:0,U=12,N=e.width-48,q=Math.max(60,Xu(e.data.question,20,N,"bold")+20),F=d&&e.data.feedbackMode==="practice"?Math.max(60,Xu(I(),16,N-40)+30):0,z=q+F,$=164,re=z+$+U+O+24;return {padding:24,questionHeight:q,feedbackHeight:F,optionsStartY:z,optionsHeight:$,totalHeight:re,questionFontSize:20,feedbackFontSize:16,optionLabelFontSize:18,optionHeight:70,optionGap:12,buttonHeight:O,buttonTopMargin:U,availableWidth:N}},[e.width,e.data.question,e.data.feedbackMode,d,I]);return jsxs(Group,{ref:m,name:"trueFalse-element",draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:S.totalHeight,...i,...s?{}:{onDragEnd:x=>n(x,e.id),onClick:x=>t&&t(e.id),onTap:x=>t&&t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:S.totalHeight,width:e.width,onTransformEnd:x=>o(e.id,x),onContextMenu:x=>{x.cancelBubble=true,r(x.evt,e.id,"trueFalse");}}),jsx(Text,{x:S.padding+8,y:S.padding,text:e.data.question,fontSize:S.questionFontSize,fontStyle:"bold",fill:"#111827",width:S.availableWidth,height:S.questionHeight-S.padding,wrap:"word",ellipsis:true,listening:false}),d&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:S.padding+24,y:S.questionHeight+10,width:S.availableWidth-40,height:S.feedbackHeight-20,fill:k().bg,cornerRadius:8}),jsx(Text,{x:S.padding+24,y:S.questionHeight+10,width:S.availableWidth-40,height:S.feedbackHeight-20,text:I(),fontSize:S.feedbackFontSize,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((x,C)=>{let M=g===x.value,P=c===x.value,R=(e.width-S.padding*3)/2,W=S.padding+C*(R+S.padding),O=S.optionsStartY,U=x.value===true,N=U?"#10b981":"#ef4444",q="#ffffff",F="#ffffff",z="#e5e7eb";return d&&(M?(F=U?"#f0fdf4":"#fef2f2",z=U?"#86efac":"#fecaca"):P&&!M&&(F="#fee2e2",z="#ef4444")),P&&!d&&(z="#096B76",F="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:W,y:O,width:R,height:S.optionHeight+50,fill:F,stroke:z,strokeWidth:2,cornerRadius:12,onClick:$=>{$.cancelBubble=true,w(x.value);},onTap:$=>{$.cancelBubble=true,w(x.value);}}),jsx(Circle,{x:W+R/2,y:O+40,radius:28,fill:N,listening:false}),U?jsx(Text,{x:W+R/2-14,y:O+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:q,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:W+R/2-14,y:O+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:q,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:W,y:O+85,width:R,height:30,text:x.label,fontSize:S.optionLabelFontSize,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},x.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:S.optionsStartY+2*(S.optionHeight+S.optionGap)+S.buttonTopMargin,children:[jsxs(Group,{onMouseDown:x=>{x.cancelBubble=true,h("check");},onMouseUp:x=>{x.cancelBubble=true,h(null),v();},onMouseLeave:x=>{x.cancelBubble=true,h(null);},onTouchStart:x=>{x.cancelBubble=true,h("check");},onTouchEnd:x=>{x.cancelBubble=true,h(null),v();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:S.padding+14,width:(S.availableWidth-24)/(d?2:1),height:S.buttonHeight,fill:c===null||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:x=>x.cancelBubble=true,onTap:x=>x.cancelBubble=true}),jsx(Text,{x:S.padding+14,width:(S.availableWidth-24)/(d?2:1),height:S.buttonHeight,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-S.padding*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),y();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),y();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:S.padding,width:(S.availableWidth-8)/2,height:S.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:x=>x.cancelBubble=true,onTap:x=>x.cancelBubble=true}),jsx(Text,{x:S.padding,width:(S.availableWidth-8)/2,height:S.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});$u.displayName="TrueFalse";var Yu=$u;var Ex="#FFFFFF",nl=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t,touchHandlers:a})=>{let r=useDispatch(),n=useSelector(Z=>Z.toolbar.selectedTool),i=n==="pen"||n==="eraser",[u,s]=useState(false),[c,p]=useState(null),[d,l]=useState(false),[f,h]=useState(false),[m,v]=useState(0),[y,g]=useState(false),b=340,w=100,I=window.innerWidth*.4,k=window.innerHeight*.5,S=I-40,x=k-300,C=20,M=60,P=S,R=x,W=I*.2-40,O=50,U=useRef(null),N=Z=>{r(va({id:e.id,x:Z.target.x(),y:Z.target.y()}));},q=Z=>{let oe=Z.target,J=oe.x(),fe=oe.y(),we=Math.max(0,Math.min(J+W,C+P)-Math.max(J,C)),Le=Math.max(0,Math.min(fe+O,M+R)-Math.max(fe,M)),Ie=we*Le,ze=W*O;s(Ie/ze>=.5);},F=(Z,oe)=>{let J=oe.target,fe=J.x(),we=J.y(),Le=Math.max(0,Math.min(fe+W,C+P)-Math.max(fe,C)),Ie=Math.max(0,Math.min(we+O,M+R)-Math.max(we,M)),ze=Le*Ie,Mt=W*O;if(ze/Mt>=.5)p(Z);else return;s(false);},z=()=>{l(true);},$=()=>{l(false),p(null),v(Z=>Z+1);},re=e.data.responseOptions.correctAnswer,V=c===re,j=()=>V?"\u2713 Correct! Great job!":"\u2717 Try again!",Y=()=>V?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:U,name:"trueFalse-element",width:I,height:k,draggable:!i,listening:!i,...a,...i?{}:{onContextMenu:Z=>{Z.evt.preventDefault(),o(Z.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:w,rotation:e.rotation,onDragEnd:N,children:[jsx(Rect,{fill:"white",stroke:u?"#4CAF50":"#e5e7eb",strokeWidth:u?4:2,cornerRadius:12,height:d?k:e.data.feedbackMode==="practice"?k-50:k-100,width:I,shadowColor:u?"#4CAF50":"transparent",shadowBlur:u?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:I-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:S,height:x,fill:"transparent",stroke:u?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:S,height:60,fill:Y().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:S,height:60,text:j(),fontSize:18,fontStyle:"bold",fill:Y().text,align:"center",verticalAlign:"middle"})]}),c===null&&!d&&jsx(Text,{x:20,y:60,width:S,height:x-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:k-100,children:[jsxs(Group,{onMouseDown:()=>{c!==null&&(h(true),z());},onMouseUp:()=>h(false),onMouseLeave:()=>h(false),onTouchStart:()=>{c!==null&&(h(true),z());},onTouchEnd:()=>h(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:c===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{y:50,onMouseDown:$,onTouchStart:$,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((Z,oe)=>{let J=window.innerWidth*.2,fe=50,we=10,Le=c===Z.value,Ie=re===Z.value,ze=d&&Le,Mt="transparent";return ze?Mt=Ie?"#4CAF50":"#ef4444":Le&&(Mt="#4CAF50"),jsxs(Group,{x:16+oe*(J+we),y:w+k-300,draggable:!d,onDragMove:q,onDragEnd:At=>F(Z.value,At),opacity:d&&!Le?.5:1,children:[jsx(Rect,{width:J-40,height:fe,fill:"#075560",stroke:Mt,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:J-40,height:fe,text:Z.label,fontSize:18,fontStyle:"bold",fill:Ex,align:"center",verticalAlign:"middle",listening:false})]},`${Z.value}-${m}`)})]})})};nl.displayName="TrueFalseDragAndDrop";var Zu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:n,onLongPress:i})=>{let{createHandlers:u}=Oe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(Yu,{trueFalse:s,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r,touchHandlers:u(s.id,"trueFalse")},s.id):jsx(nl,{trueFalse:s,handleTrueFalseTransform:o,trueFalseRefs:a,onContextMenu:n,touchHandlers:u(s.id,"trueFalse")},s.id))})};var Ia=new WeakMap,Eo=new WeakMap,wr={current:[]},il=false,yr=0,vr=new Set,Qn=new Map;function Ju(e){let o=Array.from(e).sort((t,a)=>t instanceof Gt&&t.options.deps.includes(a)?1:a instanceof Gt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(wr.current.includes(t))continue;wr.current.push(t),t.recompute();let a=Eo.get(t);if(a)for(let r of a){let n=Ia.get(r);n&&Ju(n);}}}function Fx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Bx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function es(e){if(yr>0&&!Qn.has(e)&&Qn.set(e,e.prevState),vr.add(e),!(yr>0)&&!il)try{for(il=!0;vr.size>0;){let o=Array.from(vr);vr.clear();for(let t of o){let a=Qn.get(t)??t.prevState;t.prevState=a,Fx(t);}for(let t of o){let a=Ia.get(t);a&&(wr.current.push(t),Ju(a));}for(let t of o){let a=Ia.get(t);if(a)for(let r of a)Bx(r);}}}finally{il=false,wr.current=[],Qn.clear();}}function St(e){yr++;try{e();}finally{if(yr--,yr===0){let o=vr.values().next().value;o&&es(o);}}}function Qu(e){return typeof e=="function"}var Jt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,n;this.listeners.add(a);let i=(n=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:n.call(r,a,this);return ()=>{this.listeners.delete(a),i?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,r;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):Qu(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),es(this);}};var Gt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),r=new Array(t);for(let n=0;n<t;n++){let i=this.options.deps[n];a[n]=i.prevState,r[n]=i.state;}return this.lastSeenDepValues=r,{prevDepVals:a,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let n of this.options.deps)n instanceof e&&n.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let n=0;n<r.length;n++)if(r[n]!==a[n]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,r;this.listeners.add(t);let n=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),n?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof Jt){let a=Ia.get(t);a||(a=new Set,Ia.set(t,a)),a.add(this);let r=Eo.get(this);r||(r=new Set,Eo.set(this,r)),r.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof Jt){let a=Ia.get(t);a&&a.delete(this);let r=Eo.get(this);r&&r.delete(t);}}};function Ox(e){return typeof e=="function"}function ll(e,...o){return Ox(e)?e(...o):e}function ec(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var Ca,mt,nt,Sr,ka,_a,oa,Do,Lr,ts,Ir,Ro,Xa=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){De(this,Ca,true);De(this,mt);De(this,nt);De(this,Sr);De(this,ka);De(this,_a);De(this,oa);De(this,Do);De(this,Lr,0);De(this,ts,5);De(this,Ir,()=>{this.debugLog("Connected to event bus"),Me(this,_a,true),this.debugLog("Emitting queued events",G(this,ka)),G(this,ka).forEach(o=>this.emitEventToBus(o)),Me(this,ka,[]),this.stopConnectLoop(),G(this,nt).call(this).removeEventListener("tanstack-connect-success",G(this,Ir));});De(this,Ro,()=>{if(G(this,nt).call(this).addEventListener("tanstack-connect-success",G(this,Ir)),G(this,Lr)<G(this,ts)){Td(this,Lr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}G(this,nt).call(this).removeEventListener("tanstack-connect",G(this,Ro)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Me(this,mt,o),Me(this,Ca,a),Me(this,nt,this.getGlobalTarget),Me(this,Sr,t),this.debugLog(" Initializing event subscription for plugin",G(this,mt)),Me(this,ka,[]),Me(this,_a,false),Me(this,oa,null),Me(this,Do,r);}startConnectLoop(){G(this,oa)!==null||G(this,_a)||(this.debugLog(`Starting connect loop (every ${G(this,Do)}ms)`),Me(this,oa,setInterval(G(this,Ro),G(this,Do))));}stopConnectLoop(){G(this,oa)!==null&&(clearInterval(G(this,oa)),Me(this,oa,null),this.debugLog("Stopped connect loop"));}debugLog(...o){G(this,Sr)&&console.log(`\u{1F334} [tanstack-devtools:${G(this,mt)}-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 G(this,mt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});G(this,nt).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{G(this,nt).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!G(this,Ca)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!G(this,_a)){this.debugLog("Bus not available, will be pushed as soon as connected"),G(this,ka).push({type:`${G(this,mt)}:${o}`,payload:t,pluginId:G(this,mt)}),typeof CustomEvent<"u"&&(G(this,Ro).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${G(this,mt)}:${o}`,payload:t,pluginId:G(this,mt)})}on(o,t){let a=`${G(this,mt)}:${o}`;if(!G(this,Ca))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=n=>{this.debugLog("Received event from bus",n.detail),t(n.detail);};return G(this,nt).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{G(this,nt).call(this).removeEventListener(a,r);}}onAll(o){if(!G(this,Ca))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return G(this,nt).call(this).addEventListener("tanstack-devtools-global",t),()=>G(this,nt).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!G(this,Ca))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;G(this,mt)&&r.pluginId!==G(this,mt)||o(r);};return G(this,nt).call(this).addEventListener("tanstack-devtools-global",t),()=>G(this,nt).call(this).removeEventListener("tanstack-devtools-global",t)}};Ca=new WeakMap,mt=new WeakMap,nt=new WeakMap,Sr=new WeakMap,ka=new WeakMap,_a=new WeakMap,oa=new WeakMap,Do=new WeakMap,Lr=new WeakMap,ts=new WeakMap,Ir=new WeakMap,Ro=new WeakMap;var dl=class extends Xa{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},tc=(e,o)=>{ul.emit(e,o);},ul=new dl;function ac(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Nx={enabled:true,leading:true,trailing:true,wait:0},Ta,Lt,$a,Ya,Za,Fo,as=class{constructor(o,t){De(this,Ta);De(this,Lt);De(this,$a);De(this,Ya);De(this,Za);De(this,Fo);this.fn=o,this.store=new Jt(ac()),this.setOptions=a=>{this.options={...this.options,...a},G(this,$a).call(this)||this.cancel();},Me(this,Lt,a=>{this.store.setState(r=>{let n={...r,...a},{isPending:i}=n;return {...n,status:G(this,$a).call(this)?i?"pending":"idle":"disabled"}}),tc("Throttler",this);}),Me(this,$a,()=>!!ll(this.options.enabled,this)),Me(this,Ya,()=>ll(this.options.wait,this)),this.maybeExecute=(...a)=>{G(this,Lt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),n=r-this.store.state.lastExecutionTime,i=G(this,Ya).call(this);if(this.options.leading&&n>=i)G(this,Za).call(this,...a);else if(G(this,Lt).call(this,{lastArgs:a}),!G(this,Ta)&&this.options.trailing){let u=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,s=i-u;G(this,Lt).call(this,{isPending:true}),Me(this,Ta,setTimeout(()=>{let{lastArgs:c}=this.store.state;c!==void 0&&G(this,Za).call(this,...c);},s));}},Me(this,Za,(...a)=>{if(!G(this,$a).call(this))return;this.fn(...a);let r=Date.now(),n=r+G(this,Ya).call(this);G(this,Fo).call(this),G(this,Lt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:n,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||G(this,Lt).call(this,{nextExecutionTime:void 0});},G(this,Ya).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&G(this,Za).call(this,...this.store.state.lastArgs);},Me(this,Fo,()=>{G(this,Ta)&&(clearTimeout(G(this,Ta)),Me(this,Ta,void 0));}),this.cancel=()=>{G(this,Fo).call(this),G(this,Lt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{G(this,Lt).call(this,ac());},this.key=ec(t.key),this.options={...Nx,...t},G(this,Lt).call(this,this.options.initialState??{}),ul.on("d-Throttler",a=>{a.payload.key===this.key&&(G(this,Lt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};Ta=new WeakMap,Lt=new WeakMap,$a=new WeakMap,Ya=new WeakMap,Za=new WeakMap,Fo=new WeakMap;function cl(e,o){return new as(e,o).maybeExecute}function Ma(e,o){return typeof e=="function"?e(o):e}function Aa(e,o){return ss(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function Bo(e,o,t){let a=ss(o);function r(n){if(!a.length)return Ma(t,n);let i=a.shift();if(typeof i=="string"||typeof i=="number"&&!Array.isArray(n))return typeof n=="object"?(n===null&&(n={}),{...n,[i]:r(n[i])}):{[i]:r()};if(Array.isArray(n)&&typeof i=="number"){let u=n.slice(0,i);return [...u.length?u:new Array(i),r(n[i]),...n.slice(i+1)]}return [...new Array(i),r()]}return r(e)}function ml(e,o){let t=ss(o);function a(r){if(!r)return;if(t.length===1){let i=t[0];if(Array.isArray(r)&&typeof i=="number")return r.filter((c,p)=>p!==i);let{[i]:u,...s}=r;return s}let n=t.shift();if(typeof n=="string"&&typeof r=="object")return {...r,[n]:a(r[n])};if(typeof n=="number"&&Array.isArray(r)){if(n>=r.length)return r;let i=r.slice(0,n);return [...i.length?i:new Array(n),a(r[n]),...r.slice(n+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var Hx=/^(\d+)$/gm,qx=/\.(\d+)(?=\.)/gm,Vx=/^(\d+)\./gm,Ux=/\.(\d+$)/gm,Wx=/\.{2,}/gm,fl="__int__",os=`${fl}$1`;function ss(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(Hx,os).replace(qx,`.${os}.`).replace(Vx,`${os}.`).replace(Ux,`.${os}`).replace(Wx,".").split(".").map(o=>{if(o.startsWith(fl)){let t=o.substring(fl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function pl(e){return !(Array.isArray(e)&&e.length===0)}function Oo(e,o){let t=a=>a.validators.filter(Boolean).map(r=>({cause:r.cause,validate:r.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function No(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:n}=o.validators||{},i=t??0,u=s=>s.validators.filter(Boolean).map(c=>{let p=c?.cause||e,d=i;switch(p){case "change":d=r??i;break;case "blur":d=a??i;break;case "dynamic":d=n??i;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:p,validate:c.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var Cr=e=>!!e&&typeof e=="object"&&"fields"in e;function Pa(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[r,n]of e)if(!o.has(r)||!Object.is(n,o.get(r)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let r of e)if(!o.has(r))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let r of t)if(!a.includes(r)||!Pa(e[r],o[r]))return false;return true}var is=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},ls=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function _e(e,o){return e==null?o:{...e,...o}}var Ja=256,ns=[],rs;for(;Ja--;)ns[Ja]=(Ja+256).toString(16).substring(1);function hl(){let e=0,o,t="";if(!rs||Ja+16>256){for(rs=new Array(256),e=256;e--;)rs[e]=256*Math.random()|0;e=0,Ja=0;}for(;e<16;e++)o=rs[Ja+e],e===6?t+=ns[o&15|64]:e===8?t+=ns[o&63|128]:t+=ns[o],e&1&&e>1&&e<11&&(t+="-");return Ja++,t}var Ea=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},n={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},i=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,r,n,i],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,i],form:e.form});case "change":return e.runValidation({validators:[a,i],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function zx(e,o){let t=new Map;for(let a of e){let r=a.path??[],n=o,i="";for(let u=0;u<r.length;u++){let s=r[u];if(s===void 0)continue;let c=typeof s=="object"?s.key:s,p=Number(c);Array.isArray(n)&&!Number.isNaN(p)?i+=`[${p}]`:i+=(u>0?".":"")+String(c),typeof n=="object"&&n!==null?n=n[c]:n=void 0;}t.set(i,(t.get(i)??[]).concat(a));}return Object.fromEntries(t)}var oc=(e,o)=>{let t=zx(e,o);return {form:t,fields:t}},Da={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:oc(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:oc(a.issues,e)}},ds=e=>!!e&&"~standard"in e;var Ho={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function kr(e){function o(d,l,f,h){let m=a(d,l,f,h);({insert:()=>u(m,d,l),remove:()=>s(m),swap:()=>h!==void 0&&p(m,d,l,h),move:()=>h!==void 0&&c(m,d,l,h)})[f]();}function t(d,l){return `${d}[${l}]`}function a(d,l,f,h){let m=[t(d,l)];if(f==="swap")m.push(t(d,h));else if(f==="move"){let[v,y]=[Math.min(l,h),Math.max(l,h)];for(let g=v;g<=y;g++)m.push(t(d,g));}else {let v=e.getFieldValue(d),y=Array.isArray(v)?v.length:0;for(let g=l+1;g<y;g++)m.push(t(d,g));}return Object.keys(e.fieldInfo).filter(v=>m.some(y=>v.startsWith(y)))}function r(d,l){return d.replace(/\[(\d+)\]/,(f,h)=>{let m=parseInt(h,10);return `[${l==="up"?m+1:Math.max(0,m-1)}]`})}function n(d,l){(l==="up"?d:[...d].reverse()).forEach(h=>{let m=r(h.toString(),l),v=e.getFieldMeta(m);v?e.setFieldMeta(h,v):e.setFieldMeta(h,i());});}let i=()=>Ho,u=(d,l,f)=>{n(d,"down"),d.forEach(h=>{h.toString().startsWith(t(l,f))&&e.setFieldMeta(h,i());});},s=d=>{n(d,"up");},c=(d,l,f,h)=>{let m=new Map(Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,f))).map(v=>[v,e.getFieldMeta(v)]));n(d,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(v=>v.startsWith(t(l,h))).forEach(v=>{let y=v.replace(t(l,h),t(l,f)),g=m.get(y);g&&e.setFieldMeta(v,g);});},p=(d,l,f,h)=>{d.forEach(m=>{if(!m.toString().startsWith(t(l,f)))return;let v=m.toString().replace(t(l,f),t(l,h)),[y,g]=[e.getFieldMeta(m),e.getFieldMeta(v)];y&&e.setFieldMeta(v,y),g&&e.setFieldMeta(m,g);});};return {handleArrayFieldMetaShift:o}}var gl=class extends Xa{constructor(){super({pluginId:"form-devtools"});}},It=new gl;function xl(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 Mr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),n=()=>{a(),r(),It.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:i}=this.options.validators||{};return It.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),i&&this.validateSync("mount"),n},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let n=!!a.transform?.deps?.some((s,c)=>s!==this.prevTransformArray[c]),i=a.defaultValues&&!Pa(a.defaultValues,r.defaultValues)&&!this.state.isTouched,u=!Pa(a.defaultState,r.defaultState)&&!this.state.isTouched;!i&&!u&&!n||(St(()=>{this.baseStore.setState(()=>xl(Object.assign({},this.state,u?a.defaultState:{},i?{values:a.defaultValues}:{},n?{_force_re_eval:!this.state._force_re_eval}:{})));}),It.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:n}=this.state,i=this.resetFieldMeta(n);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>xl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:i}));},this.validateAllFields=async a=>{let r=[];return St(()=>{Object.values(this.fieldInfo).forEach(i=>{if(!i.instance)return;let u=i.instance;r.push(Promise.resolve().then(()=>u.validate(a,{skipFormValidation:!0}))),i.instance.state.meta.isTouched||i.instance.setMeta(s=>({...s,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,n)=>{let i=this.getFieldValue(a),u=Array.isArray(i)?Math.max(i.length-1,0):null,s=[`${a}[${r}]`];for(let l=r+1;l<=(u??0);l++)s.push(`${a}[${l}]`);let c=Object.keys(this.fieldInfo).filter(l=>s.some(f=>l.startsWith(f))),p=[];return St(()=>{c.forEach(l=>{p.push(Promise.resolve().then(()=>this.validateField(l,n)));});}),(await Promise.all(p)).flat()},this.validateField=(a,r)=>{let n=this.fieldInfo[a]?.instance;return n?(n.state.meta.isTouched||n.setMeta(i=>({...i,isTouched:true})),n.validate(r)):[]},this.validateSync=a=>{let r=Oo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ea}),n=false,i={};return St(()=>{for(let c of r){if(!c.validate)continue;let p=this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:l}=us(p),f=Tr(c.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let m=this.getFieldMeta(h);if(!m)continue;let{errorMap:v,errorSourceMap:y}=m,g=l?.[h],{newErrorValue:b,newSource:w}=is({newFormValidatorError:g,isPreviousErrorFromFormValidator:y?.[f]==="form",previousErrorValue:v?.[f]});w==="form"&&(i[h]={...i[h],[f]:g}),v?.[f]!==b&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[f]:b},errorSourceMap:{...I.errorSourceMap,[f]:w}}));}this.state.errorMap?.[f]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:d}})),(d||l)&&(n=!0);}let u=Tr("submit");this.state.errorMap?.[u]&&a!=="submit"&&!n&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[u]:void 0}}));let s=Tr("server");this.state.errorMap?.[s]&&a!=="server"&&!n&&this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[s]:void 0}}));}),{hasErrored:n,fieldsErrorMap:i}},this.validateAsync=async a=>{let r=No(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ea});this.state.isFormValidating||this.baseStore.setState(c=>({...c,isFormValidating:true}));let n=[],i;for(let c of r){if(!c.validate)continue;let p=Tr(c.cause);this.state.validationMetaMap[p]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[p]={lastAbortController:l},n.push(new Promise(async f=>{let h;try{h=await new Promise((g,b)=>{setTimeout(async()=>{if(l.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:c.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(w){b(w);}},c.debounceMs);});}catch(g){h=g;}let{formError:m,fieldErrors:v}=us(h);v&&(i=i?{...i,...v}:v);let y=Tr(c.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let b=this.getFieldMeta(g);if(!b)continue;let{errorMap:w,errorSourceMap:I}=b,k=i?.[g],{newErrorValue:S,newSource:x}=is({newFormValidatorError:k,isPreviousErrorFromFormValidator:I?.[y]==="form",previousErrorValue:w?.[y]});w?.[y]!==S&&this.setFieldMeta(g,C=>({...C,errorMap:{...C.errorMap,[y]:S},errorSourceMap:{...C.errorSourceMap,[y]:x}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[y]:m}})),f(i?{fieldErrors:i,errorMapKey:y}:void 0);}));}let u=[],s={};if(n.length){u=await Promise.all(n);for(let c of u)if(c?.fieldErrors){let{errorMapKey:p}=c;for(let[d,l]of Object.entries(c.fieldErrors)){let h={...s[d]||{},[p]:l};s[d]=h;}}}return this.baseStore.setState(c=>({...c,isFormValidating:false})),s},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:n}=this.validateSync(a);return r&&!this.options.asyncAlways?n:this.validateAsync(a)},this.getFieldValue=a=>Aa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var r;return (r=this.fieldInfo)[a]||(r[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,r)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:Ma(r,n.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,n)=>{let i=n;return r[i]=Ho,r},{}),this.setFieldValue=(a,r,n)=>{let i=n?.dontUpdateMeta??false,u=n?.dontRunListeners??false,s=n?.dontValidate??false;St(()=>{i||this.setFieldMeta(a,c=>({...c,isTouched:!0,isDirty:!0,errorMap:{...c?.errorMap,onMount:void 0}})),this.baseStore.setState(c=>({...c,values:Bo(c.values,a,r)}));}),u||this.getFieldInfo(a).instance?.triggerOnChangeListener(),s||this.validateField(a,"change");},this.deleteField=a=>{let n=[...Object.keys(this.fieldInfo).filter(i=>{let u=a.toString();return i!==u&&i.startsWith(u)}),a];this.baseStore.setState(i=>{let u={...i};return n.forEach(s=>{u.values=ml(u.values,s),delete this.fieldInfo[s],delete u.fieldMetaBase[s];}),u});},this.pushFieldValue=(a,r,n)=>{this.setFieldValue(a,i=>[...Array.isArray(i)?i:[],r],n);},this.insertFieldValue=async(a,r,n,i)=>{this.setFieldValue(a,s=>[...s.slice(0,r),n,...s.slice(r)],_e(i,{dontValidate:true}));let u=i?.dontValidate??false;u||await this.validateField(a,"change"),kr(this).handleArrayFieldMetaShift(a,r,"insert"),u||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,n,i)=>{this.setFieldValue(a,s=>s.map((c,p)=>p===r?n:c),_e(i,{dontValidate:true})),(i?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,n)=>{let i=this.getFieldValue(a),u=Array.isArray(i)?Math.max(i.length-1,0):null;if(this.setFieldValue(a,c=>c.filter((p,d)=>d!==r),_e(n,{dontValidate:true})),kr(this).handleArrayFieldMetaShift(a,r,"remove"),u!==null){let c=`${a}[${u}]`;this.deleteField(c);}(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,n,i)=>{this.setFieldValue(a,s=>{let c=s[r],p=s[n];return Bo(Bo(s,`${r}`,p),`${n}`,c)},_e(i,{dontValidate:true})),kr(this).handleArrayFieldMetaShift(a,r,"swap",n),(i?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.moveFieldValues=(a,r,n,i)=>{this.setFieldValue(a,s=>{let c=[...s];return c.splice(n,0,c.splice(r,1)[0]),c},_e(i,{dontValidate:true})),kr(this).handleArrayFieldMetaShift(a,r,"move",n),(i?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.clearFieldValues=(a,r)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,[],_e(r,{dontValidate:true})),i!==null)for(let s=0;s<=i;s++){let c=`${a}[${s}]`;this.deleteField(c);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Ho},values:this.options.defaultValues?Bo(r.values,a,Aa(this.options.defaultValues,a)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[r,n])=>(Object.keys(n).length&&n.errors.length&&(a[r]={errors:n.errors,errorMap:n.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Da.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Da.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??hl(),this._devtoolsSubmissionOverride=false,this.baseStore=new Jt(xl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Gt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let i=n,u=a?.[0],s=r[0],c=0,p={};for(let d of Object.keys(s.fieldMetaBase)){let l=s.fieldMetaBase[d],f=u?.fieldMetaBase[d],h=i?.[d],m=Aa(s.values,d),v=h?.errors;if(!f||l.errorMap!==f.errorMap){v=Object.values(l.errorMap??{}).filter(I=>I!==void 0);let w=this.getFieldInfo(d)?.instance;w&&!w.options.disableErrorFlat&&(v=v?.flat(1));}let y=!pl(v??[]),g=!l.isDirty,b=Pa(m,Aa(this.options.defaultValues,d))||Pa(m,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===y&&h.isDefaultValue===b&&h.errors===v&&l===f){p[d]=h,c++;continue}p[d]={...l,errors:v,isPristine:g,isValid:y,isDefaultValue:b};}return Object.keys(s.fieldMetaBase).length&&i&&c===Object.keys(s.fieldMetaBase).length?i:p}}),this.store=new Gt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let i=n,u=a?.[0],s=r[0],c=r[1],p=Object.values(c).filter(Boolean),d=p.some(O=>O.isValidating),l=p.every(O=>O.isValid),f=p.some(O=>O.isTouched),h=p.some(O=>O.isBlurred),m=p.every(O=>O.isDefaultValue),v=f&&s.errorMap?.onMount,y=p.some(O=>O.isDirty),g=!y,b=!!(s.errorMap?.onMount||p.some(O=>O?.errorMap?.onMount)),w=!!d,I=i?.errors??[];(!u||s.errorMap!==u.errorMap)&&(I=Object.values(s.errorMap).reduce((O,U)=>U===void 0?O:U&&Cr(U)?(O.push(U.form),O):(O.push(U),O),[]));let k=I.length===0,S=l&&k,x=this.options.canSubmitWhenInvalid??false,C=s.submissionAttempts===0&&!f&&!b||!w&&!s.isSubmitting&&S||x,M=s.errorMap;if(v&&(I=I.filter(O=>O!==s.errorMap.onMount),M=Object.assign(M,{onMount:void 0})),i&&u&&i.errorMap===M&&i.fieldMeta===this.fieldMetaDerived.state&&i.errors===I&&i.isFieldsValidating===d&&i.isFieldsValid===l&&i.isFormValid===k&&i.isValid===S&&i.canSubmit===C&&i.isTouched===f&&i.isBlurred===h&&i.isPristine===g&&i.isDefaultValue===m&&i.isDirty===y&&Pa(u,s))return i;let P={...s,errorMap:M,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:l,isFormValid:k,isValid:S,canSubmit:C,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:m,isDirty:y},R=this.options.transform?.deps??[];if(R.length!==this.prevTransformArray.length||R.some((O,U)=>O!==this.prevTransformArray[U])){let O=Object.assign({},this,{state:P});this.options.transform?.fn(O),P=O.state,this.prevTransformArray=R;}return P}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=cl(a=>It.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),It.on("request-form-state",a=>{a.payload.id===this._formId&&It.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),It.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),It.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 ds(o.validate)?Da[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(r=>({...r,isSubmitted:false,submissionAttempts:r.submissionAttempts+1,isSubmitSuccessful:false})),St(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(n=>({...n,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(r=>({...r,isSubmitting:true}));let a=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),It.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(r=>r.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),It.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}St(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance?.options.listeners?.onSubmit?.({value:r.instance.state.value,fieldApi:r.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),St(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),It.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(n=>({...n,isSubmitSuccessful:false})),It.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){St(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(Cr(a)){let{formError:n,fieldErrors:i}=us(a);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,c=>({...c,errorMap:{...c.errorMap,[r]:i?.[u]},errorSourceMap:{...c.errorSourceMap,[r]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[r]:n}}));}else this.baseStore.setState(n=>({...n,errorMap:{...n.errorMap,[r]:a}}));});});}};function us(e){if(e){if(Cr(e)){let o=us(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function Tr(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 Ar=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let n=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});n&&this.setMeta(i=>({...i,errorMap:{...i?.errorMap,onMount:n},errorSourceMap:{...i?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let r=Aa(t.form.options.defaultValues,t.name),n=t.defaultValue??r;a?this.setValue(i=>i||n,{dontUpdateMeta:true}):n!==void 0&&this.setValue(n,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,_e(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,_e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,_e(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,_e(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,_e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,_e(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,_e(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,_e(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),r=[];for(let n of a){if(!n.instance)continue;let{onChangeListenTo:i,onBlurListenTo:u}=n.instance.options.validators||{};t==="change"&&i?.includes(this.name)&&r.push(n.instance),t==="blur"&&u?.includes(this.name)&&r.push(n.instance);}return r},this.validateSync=(t,a)=>{let r=Oo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ea}),i=this.getLinkedFields(t).reduce((c,p)=>{let d=Oo(t,{...p.options,form:p.form,validationLogic:p.form.options.validationLogic||Ea});return d.forEach(l=>{l.field=p;}),c.concat(d)},[]),u=false;St(()=>{let c=(p,d)=>{let l=cs(d.cause),f=d.validate?rc(p.runValidator({validate:d.validate,value:{value:p.store.state.value,validationSource:"field",fieldApi:p},type:"validate"})):void 0,h=a[l],{newErrorValue:m,newSource:v}=ls({formLevelError:h,fieldLevelError:f});p.state.meta.errorMap?.[l]!==m&&p.setMeta(y=>({...y,errorMap:{...y.errorMap,[l]:m},errorSourceMap:{...y.errorSourceMap,[l]:v}})),m&&(u=!0);};for(let p of r)c(this,p);for(let p of i)p.validate&&c(p.field,p);});let s=cs("submit");return this.state.meta.errorMap?.[s]&&t!=="submit"&&!u&&this.setMeta(c=>({...c,errorMap:{...c.errorMap,[s]:void 0},errorSourceMap:{...c.errorSourceMap,[s]:void 0}})),{hasErrored:u}},this.validateAsync=async(t,a)=>{let r=No(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ea}),n=await a,i=this.getLinkedFields(t),u=i.reduce((l,f)=>{let h=No(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||Ea});return h.forEach(m=>{m.field=f;}),l.concat(h)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of i)l.setMeta(f=>({...f,isValidating:true}));let s=[],c=[],p=(l,f,h)=>{let m=cs(f.cause);l.getInfo().validationMetaMap[m]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[m]={lastAbortController:y},h.push(new Promise(async g=>{let b;try{b=await new Promise((x,C)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(y.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:f.validate,value:{value:l.store.state.value,fieldApi:l,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(M){C(M);}},f.debounceMs);});}catch(x){b=x;}if(y.signal.aborted)return g(void 0);let w=rc(b),I=n[this.name]?.[m],{newErrorValue:k,newSource:S}=ls({formLevelError:I,fieldLevelError:w});l.setMeta(x=>({...x,errorMap:{...x?.errorMap,[m]:k},errorSourceMap:{...x.errorSourceMap,[m]:S}})),g(k);}));};for(let l of r)l.validate&&p(this,l,s);for(let l of u)l.validate&&p(l.field,l,c);let d=[];(s.length||c.length)&&(d=await Promise.all(s),await Promise.all(c)),this.setMeta(l=>({...l,isValidating:false}));for(let l of i)l.setMeta(f=>({...f,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:n}=this.validateSync(t,r[this.name]??{});if(n&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[cs(t)]?.lastAbortController.abort(),this.state.meta.errors;let i=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,i)},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=>Da.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Da.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Gt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Ho,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return ds(o.validate)?Da[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 rc(e){if(e)return e}function cs(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 fs(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Gx)}function Gx(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,r]of e)if(!o.has(a)||!Object.is(r,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=nc(e);if(t.length!==nc(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 nc(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var qo=typeof window<"u"?useLayoutEffect:useEffect;function Jx(e){let[o]=useState(()=>{let a=new Ar({...e,form:e.form,name:e.name});return a.Field=bl,a});return qo(o.mount,[o]),qo(()=>{o.update(e);}),fs(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var bl=(({children:e,...o})=>{let t=Jx(o),a=useMemo(()=>Ma(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function tb({form:e,selector:o,children:t}){let a=fs(e.store,o);return Ma(t,a)}function vl(e){let o=useId(),[t]=useState(()=>{let a=new Mr({...e,formId:o}),r=a;return r.Field=function(i){return jsx(bl,{...i,form:a})},r.Subscribe=function(i){return jsx(tb,{form:a,selector:i.selector,children:i.children})},r});return qo(t.mount,[]),qo(()=>{t.update(e);}),t}function yl({field:e}){return jsxs(Fragment,{children:[e.state.meta.isTouched&&!e.state.meta.isValid?jsx("em",{children:e.state.meta.errors.join(", ")}):null,e.state.meta.isValidating?"Validating...":null]})}var cb=({editElement:e})=>{let o=useDispatch(),t=useSelector(he),a=useRef(null),r=Ne(),n=!!e,i=e?.data.questionType||t?.activityType||"multiple-choice",[u,s]=useState(i),c=vl({defaultValues:{questionType:i,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:l})=>{if(l.questionType==="true-false"){let f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:300,rotation:n?e.rotation:0};o(n?va(f):pi(f));}else if(l.questionType==="multiple-choice"){let f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:575,height:n?e.height:400,rotation:n?e.rotation:0};o(n?ba(f):mi(f));}else if(l.questionType==="short-answer"){let f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:400,rotation:n?e.rotation:0};o(n?tr(f):hi(f));}else if(l.questionType==="fill-in-the-blank"){let f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:400,rotation:n?e.rotation:0};o(n?or(f):xi(f));}else if(l.questionType==="long-answer"){let f={id:n?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:n?e.x:500,y:n?e.y:200,width:n?e.width:400,height:n?e.height:400,rotation:n?e.rotation:0};o(n?ar(f):gi(f));}o(ya(false));}}),p=()=>{o(ya(false));};if(!r)return null;let d=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:l=>{l.preventDefault(),l.stopPropagation(),c.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:n?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{p();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(c.Field,{name:"questionType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:f=>{l.handleChange(f.target.value),s(f.target.value);},disabled:n,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 ${n?"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"})})})]}),n&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(yl,{field:l})]})}),u&&!["short-answer","fill-in-the-blank","long-answer"].includes(u)&&jsx(c.Field,{name:"responseType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:f=>l.handleChange(f.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(yl,{field:l})]})})]}),jsx(c.Field,{name:"feedbackMode",children:l=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${u==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>l.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:u==="long-answer",onClick:()=>l.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),u==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(yl,{field:l})]})}),jsx(c.Field,{name:"question",validators:{onChange:({value:l})=>l?void 0:"A question is required"},children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:l.state.value,onChange:f=>l.handleChange(f.target.value),onBlur:l.handleBlur,placeholder:"Enter Your Question"})}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),u==="true-false"&&jsx(c.Field,{name:"responseOptions.correctAnswer",children:l=>{let f=l.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>l.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${f===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),f===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>l.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${f===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),f===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),u==="multiple-choice"&&jsx(c.Field,{name:"responseOptions",validators:{onChange:({value:l})=>{if(l.options.filter(h=>!h.trim()).length>0)return "All options must have text";if(!l.correctIndex||l.correctIndex.length===0)return "Please select at least one correct answer"}},children:l=>{let f=(y,g)=>{let b=[...l.state.value.options];b[y]=g,l.handleChange({...l.state.value,options:b});},h=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},m=y=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let g=l.state.value.options.filter((w,I)=>I!==y),b=l.state.value.correctIndex?.filter(w=>w!==y).map(w=>w>y?w-1:w);l.handleChange({...l.state.value,options:g,correctIndex:b});},v=y=>{let g=l.state.value.correctIndex||[];if(g.includes(y))l.handleChange({...l.state.value,correctIndex:g.filter(w=>w!==y)});else {if(g.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...g,y]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:l.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:l.state.value.options.map((y,g)=>{let b=!y.trim(),w=l.state.value.correctIndex?.includes(g),I=l.state.meta.isTouched&&b;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>v(g),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${w?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:w&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${I?"border-red-500 bg-red-50":w?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${g+1}`,value:y,onChange:k=>f(g,k.target.value),onBlur:l.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),l.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>m(g),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},g)})}),jsx("button",{type:"button",onClick:h,disabled:l.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),l.state.value.correctIndex.length===0||l.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:l.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(u==="short-answer"||u==="fill-in-the-blank")&&jsx(c.Field,{name:"responseOptions.correctShortAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:l.state.value,onChange:f=>{l.handleChange(f.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),u==="long-answer"&&jsx(c.Field,{name:"responseOptions.correctLongAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:l.state.value,onChange:f=>{l.handleChange(f.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),jsx(c.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,f])=>jsx("button",{type:"submit",disabled:!l,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:f?"Saving...":n?"Update Question":"Save Question"})})]})})});return createPortal(d,r)},lc=cb;var fc=({text:e,position:o})=>{let t=xe(),a=c=>{t(ue()),t(Dt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+c))}));},r=c=>{t(ue()),t(Dt({id:e.id,fill:c}));},n=()=>{t(ue()),t(Dt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},i=()=>{t(ue()),t(Dt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},u=()=>{t(ue()),t(Dt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},s=c=>{t(ue()),t(Dt({id:e.id,fontFamily:c}));};return jsxs("div",{className:"absolute z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:`${o.x}px`,top:`${Math.max(60,o.y-60)}px`,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:c=>c.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:c=>s(c.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:n,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:i,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:u,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:[jsx(TextUnderline,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextUnderline,{size:16,weight:"bold",className:"hidden sm:block"})]})]}),jsx("div",{className:"border-l border-gray-200 pl-1",children:jsx("input",{type:"color",value:e.fill,onChange:c=>r(c.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var pc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:n,textareaRef:i})=>{let u=useRef(null),s=useMemo(()=>({fontSize:`${e.fontSize*n}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,n]),c=useCallback(p=>{p.style.height="auto",p.style.height=`${p.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(p).font,d.style.fontSize=p.style.fontSize,d.style.fontFamily=p.style.fontFamily,d.style.fontWeight=p.style.fontWeight,d.style.fontStyle=p.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let l=p.value.split(`
4
4
  `),f=0;document.body.appendChild(d);for(let m of l){d.textContent=m||" ";let v=d.offsetWidth;v>f&&(f=v);}document.body.removeChild(d);let h=10;p.style.width=`${Math.max(200,f+h+20)}px`;},[]);return useEffect(()=>{let p=u.current;p&&(p.style.fontSize=`${e.fontSize*n}px`,p.style.fontFamily=e.fontFamily,p.style.fontStyle=e.fontStyle,p.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",p.style.textDecoration=e.textDecoration,p.style.color=e.fill,c(p));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,n,c]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:p=>{if(u.current=p,i.current=p,p){p.focus();let d=p.value.length;p.setSelectionRange(d,d),c(p);}},value:o,onChange:p=>{t(p.target.value);},onKeyDown:p=>{p.key==="Escape"&&a();},style:s},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var hc=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let p=s?`${s} ${c}`:c;n.measureText(p).width>t&&s!==""?(u.push(s),s=c):s=p;}),s&&u.push(s),u.length*o*1.2},gc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,touchHandlers:i})=>{let u=useSelector(S=>S.toolbar.selectedTool),s=u==="pen"||u==="eraser",c=useRef(null),[p,d]=useState(""),[l,f]=useState(false),[h,m]=useState(null);useEffect(()=>{let S=c.current;if(S)return a.current.set(e.id,S),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",y=l&&p.trim().toLowerCase()===v,g=()=>{f(false),d("");},b=()=>y?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",w=()=>y?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},I=e.data.feedbackMode==="practice",k=useMemo(()=>{let R=I?48:0,W=12,O=30,U=e.width-48,N=Math.max(60,hc(e.data.question,18,U,"bold")+20),q=l?Math.max(40,hc(b(),12,U/2)+20):0,F=l?54:20,z=N+q+O+50+12+W+R+24;return {padding:24,questionHeight:N,questionFontSize:18,feedbackHeight:q,feedbackFontSize:12,inputY:F,inputHeight:50,inputMargin:12,buttonHeight:R,buttonTopMargin:W,placeholderHeight:O,contentWidth:U,totalHeight:z}},[e.width,e.data.question,l,y,I,b]);return jsxs(Group,{ref:c,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:k.totalHeight,name:"sa-element",...i,...s?{}:{onDragEnd:n,onClick:()=>o&&o(e.id),onTap:()=>o&&o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:k.totalHeight,onTransformEnd:S=>t(e.id,S),onContextMenu:S=>{S.cancelBubble=true,r(S.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:k.padding+8,y:k.padding,fontSize:k.questionFontSize,fontStyle:"bold",fill:"#111827",width:k.contentWidth,height:k.questionHeight-k.padding,wrap:"word",listening:false}),jsx(Rect,{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight-k.inputY,width:k.contentWidth+4,height:k.inputHeight+6,fill:"#ffffff",stroke:y?"#22c55e":l?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:k.padding,y:k.questionHeight+k.feedbackHeight+k.placeholderHeight-k.inputY},divProps:{style:{width:`${k.contentWidth-4}px`,height:`${k.inputHeight}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:p,onChange:S=>d(S.target.value),disabled:l,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:l?"none":"auto"}})}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:k.padding,y:k.questionHeight+80,width:e.width/2+24,height:k.feedbackHeight,fill:w().bg,cornerRadius:8}),jsx(Text,{x:36,y:k.questionHeight+80,width:k.contentWidth,height:k.feedbackHeight,text:b(),fontSize:k.feedbackFontSize,fontStyle:"bold",fill:w().text,verticalAlign:"middle",wrap:"word",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:k.questionHeight+k.feedbackHeight+k.placeholderHeight+k.inputHeight+k.inputMargin+k.buttonTopMargin,children:[jsxs(Group,{onMouseDown:S=>{S.cancelBubble=true,m("check");},onMouseUp:S=>{S.cancelBubble=true,m(null),p.length>0&&f(true);},onMouseLeave:S=>{S.cancelBubble=true,m(null);},onTouchStart:S=>{S.cancelBubble=true,m("check");},onTouchEnd:S=>{S.cancelBubble=true,m(null),p.length>0&&f(true);},scaleX:h==="check"?.95:1,scaleY:h==="check"?.95:1,children:[jsx(Rect,{x:k.padding+14,width:(k.contentWidth-24)/(l?2:1),height:k.buttonHeight,fill:p.length===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:S=>S.cancelBubble=true,onTap:S=>S.cancelBubble=true}),jsx(Text,{x:k.padding+14,width:(k.contentWidth-24)/(l?2:1),height:k.buttonHeight,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-k.padding*2)/2+8,onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),g();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:k.padding,width:(k.contentWidth-8)/2,height:k.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:S=>S.cancelBubble=true,onTap:S=>S.cancelBubble=true}),jsx(Text,{x:k.padding,width:(k.contentWidth-8)/2,height:k.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});gc.displayName="ShortAnswer";var xc=gc;var vc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,onLongPress:i})=>{let{createHandlers:u}=Oe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>jsx(xc,{shortAnswer:s,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id),touchHandlers:u(s.id,"shortAnswer")},s.id))})};var yc=e=>{let o=useDispatch(),a=useSelector(he)?.fillInTheBlanks||[],r=useRef(new Map),n=useCallback((i,u)=>{let s=i.target;o(or({id:u,x:s.x(),y:s.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:n}};var Ll=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let p=s?`${s} ${c}`:c;n.measureText(p).width>t&&s!==""?(u.push(s),s=c):s=p;}),s&&u.push(s),u.length*o*1.2},wc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:n,touchHandlers:i})=>{let u=useSelector(S=>S.toolbar.selectedTool),s=u==="pen"||u==="eraser",c=useRef(null),[p,d]=useState(""),[l,f]=useState(false),[h,m]=useState(null);useEffect(()=>{let S=c.current;if(S)return n.current.set(e.id,S),()=>{n.current.delete(e.id);}},[e.id,n]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",y=l&&p.trim().toLowerCase()===v,g=()=>{f(false),d("");},b=()=>{p.length>0&&f(true);},w=e.data.feedbackMode==="practice",I=useMemo(()=>{let O=e.width-48,U=(O-15)/2,N=24,q=N,F=Math.max(60,Ll(e.data.question.replace("_____","________"),24,O,"bold")+20);N+=F;let z=N,$=Math.max(35,Ll("Enter your answer in the blank.",16,O)+10);N+=$;let re=N;N+=67;let V=N,j=l?Math.max(32,Ll(y?"Right Answer, Great Job!":"Wrong Answer",14,O-40)+16):0;l&&(N+=j+16);let Y=N;return w&&(N+=64),N+=24,{padding:24,questionY:q,questionHeight:F,questionFontSize:24,helperTextY:z,helperTextHeight:$,helperTextFontSize:16,inputY:re,inputHeight:51,feedbackY:V,feedbackHeight:j,feedbackFontSize:14,buttonsY:Y,buttonHeight:64,buttonGap:15,buttonWidth:U,contentWidth:O,totalHeight:N}},[e.width,e.data.question,l,y,w]),k=()=>l?y?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:c,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...i,...s?{}:{onDragEnd:S=>a(S,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:I.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:S=>t(e.id,S),onContextMenu:S=>{S.cancelBubble=true,r?.(S.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:I.padding,y:I.questionY,fontSize:I.questionFontSize,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:I.contentWidth,wrap:"word",lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:I.padding,y:I.helperTextY,fontSize:I.helperTextFontSize,fill:"rgba(0,0,0,0.4)",width:I.contentWidth,height:I.helperTextHeight-10,wrap:"word",listening:false}),jsx(Rect,{x:I.padding,y:I.inputY,width:I.contentWidth,height:I.inputHeight,fill:"#ffffff",stroke:k(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:I.padding,y:I.inputY},divProps:{style:{width:`${I.contentWidth}px`,height:`${I.inputHeight}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:p,onChange:S=>d(S.target.value),disabled:l,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),l&&jsxs(Group,{y:I.feedbackY,children:[jsx(Rect,{x:I.padding,width:y?206:140,height:I.feedbackHeight,fill:y?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:y?"\u2713":"\u2717",x:I.padding+10,y:0,width:16,height:I.feedbackHeight,fontSize:I.feedbackFontSize,fill:y?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:y?"Right Answer, Great Job!":"Wrong Answer",x:I.padding+30,y:0,height:I.feedbackHeight,fontSize:I.feedbackFontSize,fontStyle:"600",fill:y?"#1b9d2c":"#ef4444",verticalAlign:"middle",wrap:"word",listening:false})]}),w&&jsxs(Group,{y:I.buttonsY,children:[jsxs(Group,{x:I.padding,onMouseDown:S=>{S.cancelBubble=true,m("reset");},onMouseUp:S=>{S.cancelBubble=true,m(null),g();},onMouseLeave:S=>{S.cancelBubble=true,m(null);},onTouchStart:S=>{S.cancelBubble=true,m("reset");},onTouchEnd:S=>{S.cancelBubble=true,m(null),g();},scaleX:h==="reset"?.98:1,scaleY:h==="reset"?.98:1,children:[jsx(Rect,{width:I.buttonWidth,height:I.buttonHeight,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:I.buttonWidth,height:I.buttonHeight,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:I.padding+I.buttonWidth+I.buttonGap,onMouseDown:S=>{S.cancelBubble=true,m("submit");},onMouseUp:S=>{S.cancelBubble=true,m(null),b();},onMouseLeave:S=>{S.cancelBubble=true,m(null);},onTouchStart:S=>{S.cancelBubble=true,m("submit");},onTouchEnd:S=>{S.cancelBubble=true,m(null),b();},scaleX:h==="submit"?.98:1,scaleY:h==="submit"?.98:1,children:[jsx(Rect,{width:I.buttonWidth,height:I.buttonHeight,fill:p.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:I.buttonWidth,height:I.buttonHeight,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});wc.displayName="FillInTheBlanks";var Sc=wc;var Ic=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,onLongPress:n,fibRefs:i})=>{let{createHandlers:u}=Oe({onLongPress:n});return jsx(Fragment,{children:e.map(s=>jsx(Sc,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:i,touchHandlers:u(s.id,"fillInTheBlanks")},s.id))})};var kl=(e,o,t,a)=>{let n=document.createElement("canvas").getContext("2d");if(!n)return o;n.font=`${a||""} ${o}px Arial, sans-serif`;let i=e.split(" "),u=[],s="";return i.forEach(c=>{let p=s?`${s} ${c}`:c;n.measureText(p).width>t&&s!==""?(u.push(s),s=c):s=p;}),s&&u.push(s),u.length*o*1.2},Ml=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,touchHandlers:n,handleDragEnd:i})=>{let u=useSelector(k=>k.toolbar.selectedTool),s=u==="pen"||u==="eraser",c=useRef(null),[p,d]=useState(""),[l,f]=useState(false),[h,m]=useState(null);useEffect(()=>{let k=c.current;if(k)return a.current.set(e.id,k),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",y=l&&p.trim().toLowerCase()===v,g=()=>{f(false),d("");},b=()=>y?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",w=()=>y?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},I=useMemo(()=>{let O=e.width-48,U=Math.max(60,kl(e.data.question,20,O,"bold")+20),N=l?Math.max(60,kl(b(),14,O)+30):0,F=Math.max(30,kl("Answer (Extended response):",14,O)+10),z=U+N+F+120+12+12+48+24;return {padding:24,questionHeight:U,questionFontSize:20,feedbackHeight:N,feedbackFontSize:14,placeholderHeight:F,placeholderFontSize:14,textareaHeight:120,textareaMargin:12,buttonHeight:48,buttonTopMargin:12,contentWidth:O,totalHeight:z}},[e.width,e.data.question,l,y,b]);return jsxs(Group,{ref:c,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:I.totalHeight,...n,name:"la-element",...s?{}:{onDragEnd:i,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:k=>{let S=c.current?.getStage()?.getPointerPosition();if(!S||!r)return;let x={x:e.x,y:e.y,width:e.width,height:I.totalHeight};S.x>=x.x&&S.x<=x.x+x.width&&S.y>=x.y&&S.y<=x.y+x.height&&r(k.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:I.totalHeight,onTransformEnd:k=>t(e.id,k)}),jsx(Text,{text:e.data.question,x:I.padding+8,y:I.padding,fontSize:I.questionFontSize,fontStyle:"bold",fill:"#111827",width:I.contentWidth,height:I.questionHeight-I.padding,wrap:"word",listening:false}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:I.padding,y:I.questionHeight,width:I.contentWidth,height:I.feedbackHeight,fill:w().bg,cornerRadius:8}),jsx(Text,{x:I.padding,y:I.questionHeight,width:I.contentWidth,height:I.feedbackHeight,text:b(),fontSize:I.feedbackFontSize,fontStyle:"bold",fill:w().text,align:"center",verticalAlign:"middle",wrap:"word",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:I.padding,y:I.questionHeight+I.feedbackHeight+I.textareaMargin,fontSize:I.placeholderFontSize,fill:"#6b7280",width:I.contentWidth,wrap:"word",listening:false}),jsx(Rect,{x:I.padding,y:I.questionHeight+I.feedbackHeight+I.placeholderHeight,width:I.contentWidth,height:I.textareaHeight,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:I.padding,y:I.questionHeight+I.feedbackHeight+I.placeholderHeight},divProps:{style:{width:`${I.contentWidth}px`,height:`${I.textareaHeight}px`,pointerEvents:l?"none":"auto"}},children:jsx("textarea",{value:p,onChange:k=>d(k.target.value),disabled:l,placeholder:`Type your extended answer here...\r
5
5
  \r
6
- This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:l?"none":"auto"}})}),jsx(Group,{y:I.questionHeight+I.feedbackHeight+I.placeholderHeight+I.textareaHeight+I.textareaMargin+I.buttonTopMargin,children:l&&jsxs(Group,{onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),g();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:I.padding,width:I.contentWidth,height:I.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:k=>k.cancelBubble=true,onTap:k=>k.cancelBubble=true}),jsx(Text,{x:I.padding,width:I.contentWidth,height:I.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Ml.displayName="LongAnswer";var kc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,onLongPress:i})=>{let{createHandlers:u}=Oe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>jsx(Ml,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id),touchHandlers:u(s.id,"longAnswer")},s.id))})};var eo=1600,to=900,Pc=3200,Ec=1800,$b=e=>{let o=0,t=0,a=eo,r=to;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:eo,height:to};let n=(s,c,p,d)=>{o=Math.min(o,s),t=Math.min(t,c),a=Math.max(a,s+p),r=Math.max(r,c+d);};e.lines?.forEach(s=>{if(s.points&&s.points.length>=2){let c=s.x||0,p=s.y||0,d=s.scaleX||1,l=s.scaleY||1;for(let f=0;f<s.points.length;f+=2){let h=c+s.points[f]*d,m=p+s.points[f+1]*l;o=Math.min(o,h),t=Math.min(t,m),a=Math.max(a,h),r=Math.max(r,m);}}}),e.images?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.videos?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.shapes?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.texts?.forEach(s=>n(s.x,s.y,s.width||200,s.height||s.fontSize||24)),e.flashcards?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.photoFrames?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.multipleChoices?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.trueFalses?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.shortAnswers?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.LongAnswer?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.fillInTheBlanks?.forEach(s=>n(s.x,s.y,s.width,s.height));let i=Math.min(a-o,Pc),u=Math.min(r-t,Ec);return o=Math.max(o,a-Pc),t=Math.max(t,r-Ec),{minX:o,minY:t,maxX:a,maxY:r,width:i,height:u}},Yb=(e,o,t={minX:0,minY:0,maxX:eo,maxY:to,width:eo,height:to})=>{let a=Math.max(t.width,eo),r=Math.max(t.height,to),n=e/o,i=a/r,u,s,c,d=0;if(n>i){s=r,u=Math.round(s*n),c=o/s;}else {u=a,s=Math.round(u/n),c=e/u;let l=r*c;d=(o-l)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:d,baseWidth:u,baseHeight:s,contentOffsetX:t.minX,contentOffsetY:t.minY}},Dc=(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}},Zb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r={enabled:true}}={})=>{let n=ut(),i=Ne(),u=te(L=>L.toolbar.selectedTool),s=te(he),c=te(xo),p=te(Hn),l=(s?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),f=!!l,h=useCallback(()=>{l&&n(Ua(l.id));},[n,l]),m=s?.editingActivity,v=s?.showMcqForm,y=s?.lines||[],g=useRef(null),b=useRef(null),[w,I]=useState(null),[k,S]=useState(""),x=useRef(null),[C,M]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:eo,stageHeight:to,offsetX:0,offsetY:0,baseWidth:eo,baseHeight:to,contentOffsetX:0,contentOffsetY:0}),P=useMemo(()=>$b(s||null),[c]),[R,W]=useState(null),[O,U]=useState(null),[N,q]=useState(null),[F,z]=useState(null),[$,re]=useState(null),[V,j]=useState(null),[Y,Z]=useState(null),[oe,J]=useState(false),[fe,we]=useState(null),[Le,Ie]=useState(false),ze=useRef(null),Mt=useRef(null),At=useRef(null),{debouncedGenerateThumbnail:ma}=ru(c,g);useEffect(()=>{let L=()=>{if(b.current){let E=b.current.getBoundingClientRect(),B=Yb(E.width,E.height,P);M(B);}};L();let T=new ResizeObserver(L);return b.current&&T.observe(b.current),window.addEventListener("resize",L),()=>{T.disconnect(),window.removeEventListener("resize",L);}},[P]),useEffect(()=>{if(g.current){let L=g.current.container();L&&(L.style.cursor="");}},[u]);let se=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(T=>T.batchDraw()),!p)try{let E=g.current.toDataURL({pixelRatio:.16666666666666666});S(E),ma();}catch(T){console.warn("Preview generation failed (CORS):",T);}});},[ma,p]),Gr=useRef(c);useEffect(()=>{Gr.current!==c&&(Gr.current=c,se());},[c,se]);let jr=useRef(null),_r=useRef(true);useEffect(()=>{if(!s)return;let L=(s.lines?.length||0)+(s.images?.length||0)+(s.videos?.length||0)+(s.shapes?.length||0)+(s.texts?.length||0)+(s.flashcards?.length||0)+(s.photoFrames?.length||0)+(s.multipleChoices?.length||0)+(s.trueFalses?.length||0)+(s.shortAnswers?.length||0)+(s.LongAnswer?.length||0)+(s.fillInTheBlanks?.length||0),T=jr.current?.count!==L;!_r.current&&T&&setTimeout(()=>{se();},100),jr.current={slideId:c,count:L},_r.current=false;},[s,c,se]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{At.current&&a&&a(At);},[a]);let{startDrawing:Xr,draw:$r,stopDrawing:pa,setCanvasRef:Bs,tool:Os,color:Ns,strokeWidth:Hs,isSketchMode:Yr}=Ed(se),ha=useRef(new Map),{images:qs,getLoadedImage:Vs,imageRefs:uo,handleDragEnd:Zr,handleImageTransformEnd:Us}=Hd(se),{videos:Yo,videoRefs:co,handleVideoClick:A,handleVideoDragEnd:ee,handleVideoTransformEnd:Te}=Ud(se),{multipleChoice:ve,handleMcqTransform:ie,mcqRefs:le,handleDragEnd:Be}=qd(se),{trueFalse:it,handleTrueFalseTransform:aa,trueFalseRefs:$e,handleTrueFalseDragEnd:Ee}=Vd(se),{shortAnswers:tt,saRefs:xt,handleShortAnswerDragEnd:ga}=_d(se),{longAnswers:Ws,handleLongAnswerDragEnd:zs}=Xd(se),{fillInTheBlanks:Jr,handleFillInTheBlanksDragEnd:Ut,fibRefs:Wt}=yc(se),{transformerRef:ne,boundBoxFunc:Pt}=eu(),{shapes:km,shapeRefs:Qr,isDragging:hd,handleShapeDragEnd:Tm,handleShapeResizeEnd:Mm}=Kd(se),{texts:Zo,textRefs:xa,handleDragEnd:Am,handleTransformEnd:Pm,handleDoubleClick:Em,startEditing:en,editingTextId:pe,editingValue:gd,handleEditingChange:xd,finishEditing:Ks}=jd(se,ze);useEffect(()=>{t&&t(en);},[t,en]);let tn=te(L=>L.canvas.editingTextId);useEffect(()=>{tn&&tn!==pe&&en(tn);},[tn,pe,en]);let{flashcards:Dm,flashcardRefs:an,handleDragEnd:Rm,handleFlashcardTransformEnd:Fm,handleNext:Bm,handlePrevious:Om}=Yd(se),{photoFrames:bd,photoFrameRefs:on,handleDragEnd:Nm,handlePhotoFrameTransformEnd:Hm,startCamera:qm,capturePhoto:Vm,cameraStreams:Um}=Qd(se);useEffect(()=>{if(ne.current){if(pe){ne.current.nodes([]),ne.current.getLayer()?.batchDraw();return}if(w&&!Yo.find(E=>E.id===w)?.isPlaying){let E=ha.current.get(w)||uo.current.get(w)||co.current.get(w)||Qr.current.get(w)||xa.current.get(w)||le.current.get(w)||an.current.get(w)||on.current.get(w)||xt.current.get(w)||$e.current.get(w)||Wt.current.get(w);if(E){let B=E.attrs?.locked;if(E.visible()&&B!==true){ne.current.nodes([E]),ne.current.getLayer()?.batchDraw();return}}}ne.current.nodes([]),ne.current.getLayer()?.batchDraw();}},[w,pe,Yo,ha,uo,co,Qr,xa,an,on,bd,le,$e,Wt,ne]);let He=useCallback(L=>{I(L),o?.(L);},[o]),fo=useCallback(()=>{I(null),o?.(null),ne.current&&(ne.current.nodes([]),ne.current.getLayer()?.batchDraw());},[ne,o]),vd=useCallback(L=>s?s.lines?.some(T=>T.id===L)?"line":s.images?.some(T=>T.id===L)?"image":s.videos?.some(T=>T.id===L)?"video":s.shapes?.some(T=>T.id===L)?"shape":s.texts?.some(T=>T.id===L)?"text":s.flashcards?.some(T=>T.id===L)?"flashcard":s.photoFrames?.some(T=>T.id===L)?"photoFrame":s.multipleChoices?.some(T=>T.id===L)?"mcq":s.trueFalses?.some(T=>T.id===L)?"trueFalse":s.shortAnswers?.some(T=>T.id===L)?"shortAnswer":s.LongAnswer?.some(T=>T.id===L)?"longAnswer":s.fillInTheBlanks?.some(T=>T.id===L)?"fillInTheBlanks":null:null,[s]),yd=useCallback((L,T)=>{switch(n(ue()),T){case "line":n(Fn(L));break;case "image":n(nn(L));break;case "video":n(un(L));break;case "shape":n(mn(L));break;case "text":n(pn(L));break;case "flashcard":n(gn(L));break;case "photoFrame":n(bn(L));break;case "mcq":n(yn(L));break;case "trueFalse":n(Sn(L));break;case "shortAnswer":n(In(L));break;case "longAnswer":n(kn(L));break;case "fillInTheBlanks":n(Mn(L));break}fo(),se();},[n,fo,se]);useEffect(()=>{let L=T=>{if(T.key!=="Delete"||!w||pe)return;let E=document.activeElement;if(E instanceof HTMLInputElement||E instanceof HTMLTextAreaElement||E?.getAttribute("contenteditable")==="true")return;T.preventDefault();let ye=vd(w);ye&&yd(w,ye);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[w,pe,vd,yd]),useEffect(()=>{let L=ne.current;return ()=>{L&&L.nodes([]);}},[c]),useEffect(()=>{let L=T=>{pe&&T.target.tagName!=="TEXTAREA"&&Ks();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[pe,Ks]),useEffect(()=>{let L=pe||w;if(!L||w&&pe){U(null);return}let T=xa.current.get(L),E=g.current;if(!T||!E){U(null);return}let B=E.container().getBoundingClientRect(),ye=T.absolutePosition(),ge=E.scaleX();U({x:B.left+(ye.x+T.width()*ge/2)*ge+C.offsetX,y:B.top+ye.y*ge+C.offsetY-70});},[w,pe,Zo,xa,C.offsetX,C.offsetY]),useEffect(()=>{if(!pe){q(null);return}let L=xa.current.get(pe),T=g.current;if(!L||!T){q(null);return}let E=T.container().getBoundingClientRect(),B=L.absolutePosition(),ye=T.scaleX();q({top:E.top+B.y*ye+C.offsetY,left:E.left+B.x*ye+C.offsetX,scale:ye});},[pe,Zo,xa,C.offsetY,C.offsetX]);let wd=useCallback(L=>{let T=L.target.getClassName(),E=L.target===L.target.getStage(),B=T==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",ye=T==="Image",ge=T==="Text",ae=T==="Group"||L.target.getParent()?.getClassName()==="Group",lt=T==="Circle"||T==="Star"||T==="RegularPolygon"||T==="Ellipse"||T==="Ring"||T==="Wedge"||T==="Arrow"||T==="Line"||T==="Arc"||T==="Rect"&&L.target.attrs.id,dt=T==="Group";if(E&&!B&&!ye&&!ge&&!ae&&!lt&&!dt&&fo(),!(u==="pen"||u==="eraser")&&(ye||ge||B||ae||lt||dt))return;let qe=L.target.getStage()?.getPointerPosition();if(!qe)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let H=Dc(qe,C);Xr(H);}},[u,Xr,fo,C]),Sd=useCallback(L=>{if(hd)return;let T=L.target.getStage()?.getPointerPosition();if(!T)return;let E=Dc(T,C);$r(E);},[$r,hd,C]),Ld=useCallback(()=>{pa();},[pa]),Wm=useCallback(L=>{Zr(L,se);},[Zr,se]),zm=useCallback(L=>{A(L),He(L);},[A,He]),Et=useCallback((L,T,E)=>{if(L.preventDefault(),!r.enabled)return;let B=L.clientX,ye=L.clientY,ge=x.current?.offsetHeight||450,ae=x.current?.offsetWidth||450,lt=window.innerHeight,dt=window.innerWidth,Ye=B,qe=ye;ye+ge>lt&&(qe=ye-ge),B+ae>dt&&(Ye=B-ae),He(T),W({x:Ye,y:qe,elementId:T,elementType:E});},[He,r.enabled]),Va=useRef(null),Jo=useRef(null),bt=useCallback((L,T)=>E=>{if(!r.enabled)return;E.preventDefault();let B=E.changedTouches[0];if(!B)return;let ye=B.clientX,ge=B.clientY,ae=x.current?.offsetHeight||200,lt=x.current?.offsetWidth||200,dt=window.innerHeight,Ye=window.innerWidth,qe=ye,Ze=ge;ge+ae>dt&&(Ze=ge-ae),ye+lt>Ye&&(qe=ye-lt),He(L),W({x:qe,y:Ze,elementId:L,elementType:T});},[He,r.enabled]),Km=useCallback((L,T)=>({onTouchStart:E=>{let B=E.evt.touches[0];Jo.current={x:B.clientX,y:B.clientY},Va.current=setTimeout(()=>{bt(L,T)(E.evt);},500);},onTouchMove:E=>{if(!Jo.current)return;let B=E.evt.touches[0],ye=Math.abs(B.clientX-Jo.current.x),ge=Math.abs(B.clientY-Jo.current.y);(ye>10||ge>10)&&Va.current&&(clearTimeout(Va.current),Va.current=null);},onTouchEnd:()=>{Va.current&&(clearTimeout(Va.current),Va.current=null),Jo.current=null;}}),[bt]),Id=useCallback(L=>{n(rr(L)),n(ya(true));},[n]),Gm=useCallback(L=>{n(er(L)),n(za(true));},[n]),jm=useCallback((L,T)=>{if(!R)return;let{elementId:E,elementType:B}=R;switch(L){case "order":if(T){let D=T.target.getBoundingClientRect();z({x:D.right+5,y:D.top,type:"order"});}break;case "lock":if(T){let D=T.target.getBoundingClientRect();z({x:D.right+5,y:D.top,type:"lock"});}break;case "link":if(W(null),B==="line")break;let ye=s?B==="image"?s.images.find(D=>D.id===E):s.videos.find(D=>D.id===E):null;re({type:"link",defaultValue:ye?.link||""});break;case "voice":if(W(null),B==="line")break;let ge=s?B==="image"?s.images.find(D=>D.id===E):B==="video"?s.videos.find(D=>D.id===E):B==="text"?s.texts.find(D=>D.id===E):B==="flashcard"?s.flashcards.find(D=>D.id===E):B==="photoFrame"?s.photoFrames.find(D=>D.id===E):B==="mcq"?s.multipleChoices.find(D=>D.id===E):B==="fillInTheBlanks"?s.fillInTheBlanks.find(D=>D.id===E):B==="longAnswer"?s.LongAnswer.find(D=>D.id===E):B==="shortAnswer"?s.shortAnswers.find(D=>D.id===E):B==="trueFalse"?s.trueFalses.find(D=>D.id===E):B==="shape"?s.shapes.find(D=>D.id===E):null:null;we({elementId:E,elementType:B,existingAudio:ge?.audioData});break;case "edit":W(null);let ae=null;B==="mcq"?ae=s?.multipleChoices.find(D=>D.id===E):B==="trueFalse"?ae=s?.trueFalses.find(D=>D.id===E):B==="shortAnswer"?ae=s?.shortAnswers.find(D=>D.id===E):B==="longAnswer"?ae=s?.LongAnswer.find(D=>D.id===E):B==="fillInTheBlanks"&&(ae=s?.fillInTheBlanks.find(D=>D.id===E)),ae&&Id(ae);break;case "editFlashcard":W(null);let lt=s?.flashcards.find(D=>D.id===E);lt&&Gm(lt);break;case "color":W(null);let dt=s?.shapes.find(D=>D.id===E);j({elementId:E,elementType:"shape",defaultColor:dt?.color||"#096B76"});break;case "crop":if(W(null),B==="image"){let D=s?.images.find(Qm=>Qm.id===E);D&&Z({elementId:E,imageSrc:D.src});}break;case "draw":W(null),B==="image"?n(di(E)):B==="photoFrame"&&n(ci(E));break;case "duplicate":n(ue()),B==="line"?n(Li(E)):B==="image"?n(sn(E)):B==="video"?n(cn(E)):B==="shape"?n(fn(E)):B==="text"?n(hn(E)):B==="flashcard"?n(xn(E)):B==="photoFrame"?n(vn(E)):B==="mcq"?n(wn(E)):B==="trueFalse"?n(Ln(E)):B==="shortAnswer"?n(Cn(E)):B==="fillInTheBlanks"?n(An(E)):B==="longAnswer"&&n(Tn(E)),se();break;case "infinite-clone":n(ue());let Ye=5;for(let D=0;D<Ye;D++)B==="image"?n(sn(E)):B==="video"?n(cn(E)):B==="shape"?n(fn(E)):B==="text"?n(hn(E)):B==="flashcard"?n(xn(E)):B==="photoFrame"?n(vn(E)):B==="mcq"?n(wn(E)):B==="trueFalse"?n(Ln(E)):B==="shortAnswer"?n(Cn(E)):B==="fillInTheBlanks"?n(An(E)):B==="longAnswer"&&n(Tn(E));se();break;case "make-response":if(W(null),B==="line")break;let qe=`#response-${E}`;n(ue()),n(Pn({id:E,type:B,link:qe})),(s?B==="image"?s.images.find(D=>D.id===E):B==="video"?s.videos.find(D=>D.id===E):B==="shape"?s.shapes.find(D=>D.id===E):B==="flashcard"?s.flashcards.find(D=>D.id===E):B==="photoFrame"?s.photoFrames.find(D=>D.id===E):s.multipleChoices.find(D=>D.id===E):null)?.altText||n(En({id:E,type:B,altText:"Interactive response area"})),se(),console.log(`Element ${E} marked as interactive response area`);break;case "accessibility":if(W(null),B==="line")break;let H=s?B==="image"?s.images.find(D=>D.id===E):B==="video"?s.videos.find(D=>D.id===E):B==="shape"?s.shapes.find(D=>D.id===E):null:null;re({type:"altText",defaultValue:H?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),W(null),Ie(true),console.log("showLayersPanel state set to:",true);break;case "delete":n(ue()),B==="line"?n(Fn(E)):B==="image"?n(nn(E)):B==="video"?n(un(E)):B==="shape"?n(mn(E)):B==="text"?n(pn(E)):B==="flashcard"?n(gn(E)):B==="photoFrame"?n(bn(E)):B==="mcq"?n(yn(E)):B==="trueFalse"?n(Sn(E)):B==="shortAnswer"?n(In(E)):B==="longAnswer"?n(kn(E)):B==="fillInTheBlanks"&&n(Mn(E)),fo(),se();break}},[R,n,se,fo,s,Id]),_m=useCallback(()=>{W(null),z(null);},[]),Gs=useCallback(L=>{if(!R)return;let{elementId:T,elementType:E}=R;switch(n(ue()),L){case "bring-to-front":E!=="line"&&n(vi({id:T,type:E}));break;case "send-to-back":E!=="line"&&n(yi({id:T,type:E}));break;case "lock":case "unlock":E!=="line"&&n(wi({id:T,type:E}));break}se(),W(null),z(null);},[R,n,se]),Xm=useCallback(L=>{if(!R||!$)return;let{elementId:T,elementType:E}=R;n(ue()),$.type==="link"&&E!=="line"?n(Pn({id:T,type:E,link:L})):$.type==="altText"&&E!=="line"&&n(En({id:T,type:E,altText:L})),se(),re(null);},[R,$,n,se]),$m=useCallback(L=>{if(!fe)return;let{elementId:T,elementType:E}=fe;n(ue()),n(Dn({id:T,type:E,audioData:L})),se(),we(null);},[fe,n,se]),Ym=useCallback(()=>{if(!fe)return;let{elementId:L,elementType:T}=fe;n(ue()),n(Dn({id:L,type:T,audioData:""})),se();},[fe,n,se]),Zm=useCallback(L=>{if(!V)return;let{elementId:T}=V;n(ue()),n(ho({id:T,color:L})),se(),j(null);},[V,n,se]),Jm=useCallback(L=>{if(!Y)return;let{elementId:T}=Y;n(ue()),n(po({id:T,src:L})),se(),Z(null);},[Y,n,se]);return jsxs("div",{ref:b,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Od,{ref:L=>{if(Mt.current=L,Bs(L),L){let T=L.getCanvasElement();T&&(At.current=T,a&&a(At));}},width:C.baseWidth,height:C.baseHeight,tool:Os,color:Ns,strokeWidth:Hs/C.scale,isSketchMode:Yr,xOffset:C.contentOffsetX,yOffset:C.contentOffsetY-C.offsetY/C.scale,style:{width:C.stageWidth,height:C.stageHeight}}),jsxs(Stage,{ref:g,width:C.stageWidth,height:C.stageHeight,scaleX:C.scaleX,scaleY:C.scaleY,x:C.offsetX,y:0,onMouseDown:wd,onMouseMove:Sd,onMouseUp:Ld,onTouchStart:wd,onTouchMove:Sd,onTouchEnd:Ld,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:C.baseWidth,height:C.stageHeight/C.scale,fill:s?.backgroundColor||"white"})}),jsx(Layer,{x:-C.contentOffsetX,y:C.offsetY/C.scale-C.contentOffsetY,children:(()=>{let L=[];return y.forEach((T,E)=>{L.push({type:"line",timestamp:T.timestamp||E,element:{...T,id:T.id??`line-${E}`},index:E});}),km.forEach(T=>{L.push({type:"shape",timestamp:T.timestamp||0,element:T});}),qs.forEach(T=>{L.push({type:"image",timestamp:T.timestamp||0,element:T});}),Yo.forEach(T=>{L.push({type:"video",timestamp:T.timestamp||0,element:T});}),Zo.forEach(T=>{L.push({type:"text",timestamp:T.timestamp||0,element:T});}),Dm.forEach(T=>{L.push({type:"flashcard",timestamp:T.timestamp||0,element:T});}),bd.forEach(T=>{L.push({type:"photoFrame",timestamp:T.timestamp||0,element:T});}),ve.forEach(T=>{L.push({type:"mcq",timestamp:T.timestamp||0,element:T});}),it.forEach(T=>{L.push({type:"trueFalse",timestamp:T.timestamp||0,element:T});}),tt.forEach(T=>{L.push({type:"shortAnswer",timestamp:T.timestamp||0,element:T});}),Ws.forEach(T=>{L.push({type:"longAnswer",timestamp:T.timestamp||0,element:T});}),Jr.forEach(T=>{L.push({type:"fillInTheBlanks",timestamp:T.timestamp||0,element:T});}),L.sort((T,E)=>T.timestamp-E.timestamp),L.map((T,E)=>{let B=`${T.type}-${"id"in T.element&&T.element.id||T.index||E}`,ye="id"in T.element?T.element.id:void 0,ge=ye&&w===ye;switch(T.type){case "line":let ae=T.element,lt=T.index||0,dt=ae.tool==="eraser",Ye=ae.isSketch&&ae.tool==="pen",qe=ae.isSketch&&dt,Ze=ae.id||`line-${lt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),u==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:Ye||qe?void 0:ae.color,strokeWidth:Ye||qe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ye||qe?dt?"black":ae.color:void 0,closed:Ye||qe,tension:0,globalCompositeOperation:dt?"destination-out":"source-over",listening:true,onClick:()=>{n(ue()),n(rn(lt));},onTap:()=>{n(ue()),n(rn(lt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:H=>{let D=H.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:H=>{let D=H.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},B):jsxs(be__default.Fragment,{children:[jsx(Group,{id:Ze,ref:H=>{H?ha.current.set(Ze,H):ha.current.delete(Ze);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",Ze),He(Ze));},onTap:()=>{u==="select"&&(console.log("Line tapped:",Ze),He(Ze));},onDragEnd:H=>{n(ue()),n(Rn({id:Ze,x:H.target.x(),y:H.target.y(),scaleX:H.target.scaleX(),scaleY:H.target.scaleY(),rotation:H.target.rotation()})),se();},onTransformEnd:H=>{n(ue()),n(Rn({id:Ze,x:H.target.x(),y:H.target.y(),scaleX:H.target.scaleX(),scaleY:H.target.scaleY(),rotation:H.target.rotation()})),se();},onMouseEnter:H=>{if(u==="select"){let D=H.target.getStage();D&&(D.container().style.cursor="move");}},onMouseLeave:H=>{if(u==="select"){let D=H.target.getStage();D&&(D.container().style.cursor="default");}},onContextMenu:H=>{let D=H.evt;D.preventDefault(),Et(D,Ze,"line");},...Km(Ze,"line"),children:jsx(Line,{points:ae.points||[],stroke:Ye||qe?void 0:ae.color,strokeWidth:Ye||qe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ye||qe?dt?"black":ae.color:void 0,closed:Ye||qe,tension:0,globalCompositeOperation:dt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=ha.current.get(w);console.log("Line Transformer - selectedId:",w,"node found:",!!D),D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "shape":return jsxs(be__default.Fragment,{children:[jsx(Wi,{onSelect:He,shapes:[T.element],shapeRefs:Qr,handleShapeDragEnd:Tm,handleShapeResizeEnd:Mm,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=Qr.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "image":return jsxs(be__default.Fragment,{children:[jsx(Hi,{images:[T.element],getLoadedImage:Vs,imageRefs:uo,onDragEnd:Wm,onTransform:Us,onSelect:He,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=uo.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "video":return jsxs(be__default.Fragment,{children:[jsx(Ui,{videos:[T.element],selectedId:w,videoRefs:co,onVideoClick:zm,onDragEnd:ee,onTransformEnd:Te,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=co.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "text":return jsxs(be__default.Fragment,{children:[jsx(gu,{texts:[T.element],textRefs:xa,onDragEnd:Am,onTransformEnd:Pm,onSelect:He,onContextMenu:Et,onLongPress:bt,onDoubleClick:Em,editingTextId:pe,editingValue:gd,onEditingChange:xd}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=xa.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Gi,{flashcards:[T.element],flashcardRefs:an,selectedId:w,onDragEnd:Rm,onTransform:Fm,onSelect:He,onNext:Bm,onPrevious:Om,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=an.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Zi,{photoFrames:[T.element],photoFrameRefs:on,selectedId:w,onDragEnd:Nm,onTransform:Hm,onSelect:He,onStartCamera:qm,onCapture:Vm,cameraStreams:Um,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=on.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(_u,{handleMcqTransform:ie,multipleChoice:[T.element],handleSelect:He,mcqRefs:le,handleDragEnd:Be,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=le.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Zu,{trueFalses:[T.element],handleTrueFalseTransform:aa,handleSelect:He,trueFalseRefs:$e,onContextMenu:Et,onLongPress:bt,handleDragEnd:Ee}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=$e.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(vc,{shortAnswers:[T.element],handleSelect:He,handleTransform:ie,saRefs:xt,onContextMenu:Et,onLongPress:bt,handleDragEnd:ga}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=xt.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(kc,{longAnswer:[T.element],handleSelect:He,handleTransform:ie,saRefs:xt,onContextMenu:Et,onLongPress:bt,handleDragEnd:zs}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=xt.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Ic,{fillInTheBlanks:[T.element],handleSelect:He,handleTransform:ie,onContextMenu:Et,onLongPress:bt,handleDragEnd:Ut,fibRefs:Wt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=Wt.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);default:return null}})})()})]}),R&&jsx(Au,{menuRef:x,x:R.x,y:R.y,type:R.elementType,onAction:jm,onClose:_m,isDrawingMode:R.elementType==="image"?s?.images.find(L=>L.id===R.elementId)?.isDrawingMode:R.elementType==="photoFrame"?s?.photoFrames.find(L=>L.id===R.elementId)?.isDrawingMode:false}),F&&R&&jsx(Pu,{x:F.x,y:F.y,items:F.type==="order"?[{label:"Bring to Front",onClick:()=>Gs("bring-to-front")},{label:"Send to Back",onClick:()=>Gs("send-to-back")}]:[{label:s&&(R.elementType==="image"?s.images.find(L=>L.id===R.elementId)?.locked:s.videos.find(L=>L.id===R.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Gs(s&&(R.elementType==="image"?s.images.find(L=>L.id===R.elementId)?.locked:s.videos.find(L=>L.id===R.elementId)?.locked)?"unlock":"lock")}],onClose:()=>z(null)}),$&&jsx(Ru,{title:$.type==="link"?"Add Link":"Add Alt Text",label:$.type==="link"?"URL":"Alternative Text",placeholder:$.type==="link"?"https://example.com":"Describe this image/video",defaultValue:$.defaultValue,onSave:Xm,onClose:()=>re(null)}),V&&jsx(jn,{defaultColor:V.defaultColor,onConfirm:Zm,onCancel:()=>j(null)}),Y&&jsx(Nu,{imageSrc:Y.imageSrc,onConfirm:Jm,onCancel:()=>Z(null)}),oe&&jsx(hr,{onClose:()=>J(false),stageRef:g}),fe&&jsx(Uu,{elementId:fe.elementId,elementType:fe.elementType,existingAudio:fe.existingAudio,onSave:$m,onDelete:Ym,onClose:()=>we(null)}),Le&&jsx(Ku,{selectedElementId:w||void 0,onClose:()=>Ie(false),onSelectElement:L=>{He(L),Ie(false);}}),s?.images.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.videos.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.shapes?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.texts?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),v&&jsx(lc,{editElement:m}),O&&(()=>{let L=pe||w;if(!L)return null;let T=Zo.find(E=>E.id===L);return T?jsx(fc,{text:T,position:O}):null})(),N&&pe&&(()=>{let L=Zo.find(T=>T.id===pe);return L?jsx(pc,{text:L,editingValue:gd,onEditingChange:xd,onFinish:Ks,position:{top:N.top,left:N.left},scale:N.scale,textareaRef:ze},pe):null})(),f&&i&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:l?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:h})}),jsx("button",{onClick:h,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X$1,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),i)]})},Jb=Zb;var ev="SchooplaVideoStorage";var Qt="videos",xs=()=>new Promise((e,o)=>{let t=indexedDB.open(ev,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Qt)||r.createObjectStore(Qt,{keyPath:"id"});};}),ao=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await xs(),n=a.transaction([Qt],"readwrite").objectStore(Qt),i={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,s)=>{let c=n.put(i);c.onsuccess=()=>u(!0),c.onerror=()=>s(c.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var Rc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await xs(),t=e.transaction([Qt],"readonly").objectStore(Qt);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let i=n.result,u=new Map;i.forEach(s=>{u.set(s.id,{blob:s.blob,thumbnailDataUrl:s.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),a(u);},n.onerror=()=>{e.close(),r(n.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 xs(),a=o.transaction([Qt],"readwrite").objectStore(Qt);await new Promise((r,n)=>{let i=a.delete(e);i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Fc=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await xs(),t=e.transaction([Qt],"readwrite").objectStore(Qt);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Bc=e=>URL.createObjectURL(e);function Ra(e,o=[]){let t=[];function a(n,i){let u=be.createContext(i),s=t.length;t=[...t,i];let c=d=>{let{scope:l,children:f,...h}=d,m=l?.[e]?.[s]||u,v=be.useMemo(()=>h,Object.values(h));return jsx(m.Provider,{value:v,children:f})};c.displayName=n+"Provider";function p(d,l){let f=l?.[e]?.[s]||u,h=be.useContext(f);if(h)return h;if(i!==void 0)return i;throw new Error(`\`${d}\` must be used within \`${n}\``)}return [c,p]}let r=()=>{let n=t.map(i=>be.createContext(i));return function(u){let s=u?.[e]||n;return be.useMemo(()=>({[`__scope${e}`]:{...u,[e]:s}}),[u,s])}};return r.scopeName=e,[a,av(r,...o)]}function av(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(n){let i=a.reduce((u,{useScope:s,scopeName:c})=>{let d=s(n)[`__scope${c}`];return {...u,...d}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:i}),[i])}};return t.scopeName=o.scopeName,t}function Oc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Or(...e){return o=>{let t=false,a=e.map(r=>{let n=Oc(r,o);return !t&&typeof n=="function"&&(t=true),n});if(t)return ()=>{for(let r=0;r<a.length;r++){let n=a[r];typeof n=="function"?n():Oc(e[r],null);}}}}function qt(...e){return be.useCallback(Or(...e),e)}function qc(e){let o=ov(e),t=be.forwardRef((a,r)=>{let{children:n,...i}=a,u=be.Children.toArray(n),s=u.find(nv);if(s){let c=s.props.children,p=u.map(d=>d===s?be.Children.count(c)>1?be.Children.only(null):be.isValidElement(c)?c.props.children:null:d);return jsx(o,{...i,ref:r,children:be.isValidElement(c)?be.cloneElement(c,void 0,p):null})}return jsx(o,{...i,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function ov(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let i=iv(r),u=sv(n,r.props);return r.type!==be.Fragment&&(u.ref=a?Or(a,i):i),be.cloneElement(r,u)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var rv=Symbol("radix.slottable");function nv(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rv}function sv(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...u)=>{let s=n(...u);return r(...u),s}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function iv(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 uv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ht=uv.reduce((e,o)=>{let t=qc(`Primitive.${o}`),a=be.forwardRef((r,n)=>{let{asChild:i,...u}=r,s=i?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(s,{...u,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function Qe(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function Pl(e){let o=cv(e),t=be.forwardRef((a,r)=>{let{children:n,...i}=a,u=be.Children.toArray(n),s=u.find(mv);if(s){let c=s.props.children,p=u.map(d=>d===s?be.Children.count(c)>1?be.Children.only(null):be.isValidElement(c)?c.props.children:null:d);return jsx(o,{...i,ref:r,children:be.isValidElement(c)?be.cloneElement(c,void 0,p):null})}return jsx(o,{...i,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function cv(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let i=hv(r),u=pv(n,r.props);return r.type!==be.Fragment&&(u.ref=a?Or(a,i):i),be.cloneElement(r,u)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var fv=Symbol("radix.slottable");function mv(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===fv}function pv(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...u)=>{let s=n(...u);return r(...u),s}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function hv(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 bs(e){let o=e+"CollectionProvider",[t,a]=Ra(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),i=m=>{let{scope:v,children:y}=m,g=be__default.useRef(null),b=be__default.useRef(new Map).current;return jsx(r,{scope:v,itemMap:b,collectionRef:g,children:y})};i.displayName=o;let u=e+"CollectionSlot",s=Pl(u),c=be__default.forwardRef((m,v)=>{let{scope:y,children:g}=m,b=n(u,y),w=qt(v,b.collectionRef);return jsx(s,{ref:w,children:g})});c.displayName=u;let p=e+"CollectionItemSlot",d="data-radix-collection-item",l=Pl(p),f=be__default.forwardRef((m,v)=>{let{scope:y,children:g,...b}=m,w=be__default.useRef(null),I=qt(v,w),k=n(p,y);return be__default.useEffect(()=>(k.itemMap.set(w,{ref:w,...b}),()=>void k.itemMap.delete(w))),jsx(l,{[d]:"",ref:I,children:g})});f.displayName=p;function h(m){let v=n(e+"CollectionConsumer",m);return be__default.useCallback(()=>{let g=v.collectionRef.current;if(!g)return [];let b=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(v.itemMap.values()).sort((k,S)=>b.indexOf(k.ref.current)-b.indexOf(S.ref.current))},[v.collectionRef,v.itemMap])}return [{Provider:i,Slot:c,ItemSlot:f},h,a]}var Uo=globalThis?.document?be.useLayoutEffect:()=>{};var gv=be[" useId ".trim().toString()]||(()=>{}),xv=0;function zc(e){let[o,t]=be.useState(gv());return Uo(()=>{t(a=>a??String(xv++));},[e]),(o?`radix-${o}`:"")}function Kc(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var bv=be[" useInsertionEffect ".trim().toString()]||Uo;function na({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,i]=vv({defaultProp:o,onChange:t}),u=e!==void 0,s=u?e:r;{let p=be.useRef(e!==void 0);be.useEffect(()=>{let d=p.current;d!==u&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${u?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),p.current=u;},[u,a]);}let c=be.useCallback(p=>{if(u){let d=yv(p)?p(e):p;d!==e&&i.current?.(d);}else n(p);},[u,e,n,i]);return [s,c]}function vv({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),n=be.useRef(o);return bv(()=>{n.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function yv(e){return typeof e=="function"}var wv=be.createContext(void 0);function zo(e){let o=be.useContext(wv);return e||o||"ltr"}var Rl="rovingFocusGroup.onEntryFocus",Sv={bubbles:false,cancelable:true},Nr="RovingFocusGroup",[Fl,Gc,Lv]=bs(Nr),[Iv,Bl]=Ra(Nr,[Lv]),[Cv,kv]=Iv(Nr),jc=be.forwardRef((e,o)=>jsx(Fl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Fl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Tv,{...e,ref:o})})}));jc.displayName=Nr;var Tv=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:i,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:s,onEntryFocus:c,preventScrollOnEntryFocus:p=false,...d}=e,l=be.useRef(null),f=qt(o,l),h=zo(n),[m,v]=na({prop:i,defaultProp:u??null,onChange:s,caller:Nr}),[y,g]=be.useState(false),b=Kc(c),w=Gc(t),I=be.useRef(false),[k,S]=be.useState(0);return be.useEffect(()=>{let x=l.current;if(x)return x.addEventListener(Rl,b),()=>x.removeEventListener(Rl,b)},[b]),jsx(Cv,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:m,onItemFocus:be.useCallback(x=>v(x),[v]),onItemShiftTab:be.useCallback(()=>g(true),[]),onFocusableItemAdd:be.useCallback(()=>S(x=>x+1),[]),onFocusableItemRemove:be.useCallback(()=>S(x=>x-1),[]),children:jsx(ht.div,{tabIndex:y||k===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:Qe(e.onMouseDown,()=>{I.current=true;}),onFocus:Qe(e.onFocus,x=>{let C=!I.current;if(x.target===x.currentTarget&&C&&!y){let M=new CustomEvent(Rl,Sv);if(x.currentTarget.dispatchEvent(M),!M.defaultPrevented){let P=w().filter(N=>N.focusable),R=P.find(N=>N.active),W=P.find(N=>N.id===m),U=[R,W,...P].filter(Boolean).map(N=>N.ref.current);$c(U,p);}}I.current=false;}),onBlur:Qe(e.onBlur,()=>g(false))})})}),_c="RovingFocusGroupItem",Xc=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:i,...u}=e,s=zc(),c=n||s,p=kv(_c,t),d=p.currentTabStopId===c,l=Gc(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:m}=p;return be.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(Fl.ItemSlot,{scope:t,id:c,focusable:a,active:r,children:jsx(ht.span,{tabIndex:d?0:-1,"data-orientation":p.orientation,...u,ref:o,onMouseDown:Qe(e.onMouseDown,v=>{a?p.onItemFocus(c):v.preventDefault();}),onFocus:Qe(e.onFocus,()=>p.onItemFocus(c)),onKeyDown:Qe(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){p.onItemShiftTab();return}if(v.target!==v.currentTarget)return;let y=Pv(v,p.orientation,p.dir);if(y!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let b=l().filter(w=>w.focusable).map(w=>w.ref.current);if(y==="last")b.reverse();else if(y==="prev"||y==="next"){y==="prev"&&b.reverse();let w=b.indexOf(v.currentTarget);b=p.loop?Ev(b,w+1):b.slice(w+1);}setTimeout(()=>$c(b));}}),children:typeof i=="function"?i({isCurrentTabStop:d,hasTabStop:m!=null}):i})})});Xc.displayName=_c;var Mv={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Av(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Pv(e,o,t){let a=Av(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Mv[a]}function $c(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Ev(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Yc=jc,Zc=Xc;var Qc="Toggle",Ol=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[i,u]=na({prop:t,onChange:r,defaultProp:a??false,caller:Qc});return jsx(ht.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:Qe(e.onClick,()=>{e.disabled||u(!i);})})});Ol.displayName=Qc;var Fa="ToggleGroup",[tf]=Ra(Fa,[Bl]),af=Bl(),Nl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Fv,{...a,ref:o});if(t==="multiple")return jsx(Bv,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Fa}\``)});Nl.displayName=Fa;var[of,rf]=tf(Fa),Fv=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[i,u]=na({prop:t,defaultProp:a??"",onChange:r,caller:Fa});return jsx(of,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>i?[i]:[],[i]),onItemActivate:u,onItemDeactivate:be__default.useCallback(()=>u(""),[u]),children:jsx(nf,{...n,ref:o})})}),Bv=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[i,u]=na({prop:t,defaultProp:a??[],onChange:r,caller:Fa}),s=be__default.useCallback(p=>u((d=[])=>[...d,p]),[u]),c=be__default.useCallback(p=>u((d=[])=>d.filter(l=>l!==p)),[u]);return jsx(of,{scope:e.__scopeToggleGroup,type:"multiple",value:i,onItemActivate:s,onItemDeactivate:c,children:jsx(nf,{...n,ref:o})})});Nl.displayName=Fa;var[Ov,Nv]=tf(Fa),nf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:i,loop:u=true,...s}=e,c=af(t),p=zo(i),d={role:"group",dir:p,...s};return jsx(Ov,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(Yc,{asChild:true,...c,orientation:n,dir:p,loop:u,children:jsx(ht.div,{...d,ref:o})}):jsx(ht.div,{...d,ref:o})})}),ws="ToggleGroupItem",Hv=be__default.forwardRef((e,o)=>{let t=rf(ws,e.__scopeToggleGroup),a=Nv(ws,e.__scopeToggleGroup),r=af(e.__scopeToggleGroup),n=t.value.includes(e.value),i=a.disabled||e.disabled,u={...e,pressed:n,disabled:i},s=be__default.useRef(null);return a.rovingFocus?jsx(Zc,{asChild:true,...r,focusable:!i,active:n,ref:s,children:jsx(ef,{...u,ref:o})}):jsx(ef,{...u,ref:o})});Hv.displayName=ws;var ef=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=rf(ws,t),i={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=n.type==="single"?i:void 0;return jsx(Ol,{...u,...r,ref:o,onPressedChange:s=>{s?n.onItemActivate(a):n.onItemDeactivate(a);}})}),sf=Nl;function lf(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(o=0;o<r;o++)e[o]&&(t=lf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Ss(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=lf(e))&&(a&&(a+=" "),a+=o);return a}var Vv=(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},Uv=(e,o)=>({classGroupId:e,validator:o}),mf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var df=[],Wv="arbitrary..",zv=e=>{let o=Gv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return Kv(i);let u=i.split("-"),s=u[0]===""&&u.length>1?1:0;return pf(u,s,o)},getConflictingClassGroupIds:(i,u)=>{if(u){let s=a[i],c=t[i];return s?c?Vv(c,s):s:c||df}return t[i]||df}}},pf=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let c=pf(e,o+1,n);if(c)return c}let i=t.validators;if(i===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),s=i.length;for(let c=0;c<s;c++){let p=i[c];if(p.validator(u))return p.classGroupId}},Kv=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?Wv+a:void 0})(),Gv=e=>{let{theme:o,classGroups:t}=e;return jv(t,o)},jv=(e,o)=>{let t=mf();for(let a in e){let r=e[a];Vl(r,t,a,o);}return t},Vl=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let i=e[n];_v(i,o,t,a);}},_v=(e,o,t,a)=>{if(typeof e=="string"){Xv(e,o,t);return}if(typeof e=="function"){$v(e,o,t,a);return}Yv(e,o,t,a);},Xv=(e,o,t)=>{let a=e===""?o:hf(o,e);a.classGroupId=t;},$v=(e,o,t,a)=>{if(Zv(e)){Vl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Uv(t,e));},Yv=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let i=0;i<n;i++){let[u,s]=r[i];Vl(s,hf(o,u),t,a);}},hf=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let n=0;n<r;n++){let i=a[n],u=t.nextPart.get(i);u||(u=mf(),t.nextPart.set(i,u)),t=u;}return t},Zv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Jv=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(n,i)=>{t[n]=i,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(n){let i=t[n];if(i!==void 0)return i;if((i=a[n])!==void 0)return r(n,i),i},set(n,i){n in t?t[n]=i:r(n,i);}}};var Qv=[],uf=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),ey=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],i=0,u=0,s=0,c,p=r.length;for(let m=0;m<p;m++){let v=r[m];if(i===0&&u===0){if(v===":"){n.push(r.slice(s,m)),s=m+1;continue}if(v==="/"){c=m;continue}}v==="["?i++:v==="]"?i--:v==="("?u++:v===")"&&u--;}let d=n.length===0?r:r.slice(s),l=d,f=false;d.endsWith("!")?(l=d.slice(0,-1),f=true):d.startsWith("!")&&(l=d.slice(1),f=true);let h=c&&c>s?c-s:void 0;return uf(n,f,l,h)};if(o){let r=o+":",n=a;a=i=>i.startsWith(r)?n(i.slice(r.length)):uf(Qv,false,i,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},ty=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let n=0;n<t.length;n++){let i=t[n],u=i[0]==="[",s=o.has(i);u||s?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(i)):r.push(i);}return r.length>0&&(r.sort(),a.push(...r)),a}},ay=e=>({cache:Jv(e.cacheSize),parseClassName:ey(e),sortModifiers:ty(e),...zv(e)}),oy=/\s+/,ry=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,i=[],u=e.trim().split(oy),s="";for(let c=u.length-1;c>=0;c-=1){let p=u[c],{isExternal:d,modifiers:l,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:m}=t(p);if(d){s=p+(s.length>0?" "+s:s);continue}let v=!!m,y=a(v?h.substring(0,m):h);if(!y){if(!v){s=p+(s.length>0?" "+s:s);continue}if(y=a(h),!y){s=p+(s.length>0?" "+s:s);continue}v=false;}let g=l.length===0?"":l.length===1?l[0]:n(l).join(":"),b=f?g+"!":g,w=b+y;if(i.indexOf(w)>-1)continue;i.push(w);let I=r(y,v);for(let k=0;k<I.length;++k){let S=I[k];i.push(b+S);}s=p+(s.length>0?" "+s:s);}return s},ny=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=gf(t))&&(r&&(r+=" "),r+=a);return r},gf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=gf(e[a]))&&(t&&(t+=" "),t+=o);return t},sy=(e,...o)=>{let t,a,r,n,i=s=>{let c=o.reduce((p,d)=>d(p),e());return t=ay(c),a=t.cache.get,r=t.cache.set,n=u,u(s)},u=s=>{let c=a(s);if(c)return c;let p=ry(s,t);return r(s,p),p};return n=i,(...s)=>n(ny(...s))},iy=[],We=e=>{let o=t=>t[e]||iy;return o.isThemeGetter=true,o},xf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,bf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,ly=/^\d+\/\d+$/,dy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,uy=/\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$/,cy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,fy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,my=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ko=e=>ly.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ba=e=>!!e&&Number.isInteger(Number(e)),Hl=e=>e.endsWith("%")&&de(e.slice(0,-1)),sa=e=>dy.test(e),py=()=>true,hy=e=>uy.test(e)&&!cy.test(e),vf=()=>false,gy=e=>fy.test(e),xy=e=>my.test(e),by=e=>!_(e)&&!X(e),vy=e=>Go(e,Sf,vf),_=e=>xf.test(e),no=e=>Go(e,Lf,hy),ql=e=>Go(e,Iy,de),cf=e=>Go(e,yf,vf),yy=e=>Go(e,wf,xy),Ls=e=>Go(e,If,gy),X=e=>bf.test(e),Hr=e=>jo(e,Lf),wy=e=>jo(e,Cy),ff=e=>jo(e,yf),Sy=e=>jo(e,Sf),Ly=e=>jo(e,wf),Is=e=>jo(e,If,true),Go=(e,o,t)=>{let a=xf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},jo=(e,o,t=false)=>{let a=bf.exec(e);return a?a[1]?o(a[1]):t:false},yf=e=>e==="position"||e==="percentage",wf=e=>e==="image"||e==="url",Sf=e=>e==="length"||e==="size"||e==="bg-size",Lf=e=>e==="length",Iy=e=>e==="number",Cy=e=>e==="family-name",If=e=>e==="shadow";var ky=()=>{let e=We("color"),o=We("font"),t=We("text"),a=We("font-weight"),r=We("tracking"),n=We("leading"),i=We("breakpoint"),u=We("container"),s=We("spacing"),c=We("radius"),p=We("shadow"),d=We("inset-shadow"),l=We("text-shadow"),f=We("drop-shadow"),h=We("blur"),m=We("perspective"),v=We("aspect"),y=We("ease"),g=We("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],w=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...w(),X,_],k=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],x=()=>[X,_,s],C=()=>[Ko,"full","auto",...x()],M=()=>[Ba,"none","subgrid",X,_],P=()=>["auto",{span:["full",Ba,X,_]},Ba,X,_],R=()=>[Ba,"auto",X,_],W=()=>["auto","min","max","fr",X,_],O=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],N=()=>["auto",...x()],q=()=>[Ko,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...x()],F=()=>[e,X,_],z=()=>[...w(),ff,cf,{position:[X,_]}],$=()=>["no-repeat",{repeat:["","x","y","space","round"]}],re=()=>["auto","cover","contain",Sy,vy,{size:[X,_]}],V=()=>[Hl,Hr,no],j=()=>["","none","full",c,X,_],Y=()=>["",de,Hr,no],Z=()=>["solid","dashed","dotted","double"],oe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[de,Hl,ff,cf],fe=()=>["","none",h,X,_],we=()=>["none",de,X,_],Le=()=>["none",de,X,_],Ie=()=>[de,X,_],ze=()=>[Ko,"full",...x()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[sa],breakpoint:[sa],color:[py],container:[sa],"drop-shadow":[sa],ease:["in","out","in-out"],font:[by],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[sa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[sa],shadow:[sa],spacing:["px",de],text:[sa],"text-shadow":[sa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ko,_,X,v]}],container:["container"],columns:[{columns:[de,_,X,u]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:I()}],overflow:[{overflow:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:C()}],"inset-x":[{"inset-x":C()}],"inset-y":[{"inset-y":C()}],start:[{start:C()}],end:[{end:C()}],top:[{top:C()}],right:[{right:C()}],bottom:[{bottom:C()}],left:[{left:C()}],visibility:["visible","invisible","collapse"],z:[{z:[Ba,"auto",X,_]}],basis:[{basis:[Ko,"full","auto",u,...x()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Ko,"auto","initial","none",_]}],grow:[{grow:["",de,X,_]}],shrink:[{shrink:["",de,X,_]}],order:[{order:[Ba,"first","last","none",X,_]}],"grid-cols":[{"grid-cols":M()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":M()}],"row-start-end":[{row:P()}],"row-start":[{"row-start":R()}],"row-end":[{"row-end":R()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":W()}],"auto-rows":[{"auto-rows":W()}],gap:[{gap:x()}],"gap-x":[{"gap-x":x()}],"gap-y":[{"gap-y":x()}],"justify-content":[{justify:[...O(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...O()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":O()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:x()}],px:[{px:x()}],py:[{py:x()}],ps:[{ps:x()}],pe:[{pe:x()}],pt:[{pt:x()}],pr:[{pr:x()}],pb:[{pb:x()}],pl:[{pl:x()}],m:[{m:N()}],mx:[{mx:N()}],my:[{my:N()}],ms:[{ms:N()}],me:[{me:N()}],mt:[{mt:N()}],mr:[{mr:N()}],mb:[{mb:N()}],ml:[{ml:N()}],"space-x":[{"space-x":x()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":x()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],w:[{w:[u,"screen",...q()]}],"min-w":[{"min-w":[u,"screen","none",...q()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[i]},...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,Hr,no]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,X,ql]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Hl,_]}],"font-family":[{font:[wy,_,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,X,_]}],"line-clamp":[{"line-clamp":[de,"none",X,ql]}],leading:[{leading:[n,...x()]}],"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:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Z(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",X,no]}],"text-decoration-color":[{decoration:F()}],"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:x()}],"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:z()}],"bg-repeat":[{bg:$()}],"bg-size":[{bg:re()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ba,X,_],radial:["",X,_],conic:[Ba,X,_]},Ly,yy]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:V()}],"gradient-via-pos":[{via:V()}],"gradient-to-pos":[{to:V()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:j()}],"rounded-s":[{"rounded-s":j()}],"rounded-e":[{"rounded-e":j()}],"rounded-t":[{"rounded-t":j()}],"rounded-r":[{"rounded-r":j()}],"rounded-b":[{"rounded-b":j()}],"rounded-l":[{"rounded-l":j()}],"rounded-ss":[{"rounded-ss":j()}],"rounded-se":[{"rounded-se":j()}],"rounded-ee":[{"rounded-ee":j()}],"rounded-es":[{"rounded-es":j()}],"rounded-tl":[{"rounded-tl":j()}],"rounded-tr":[{"rounded-tr":j()}],"rounded-br":[{"rounded-br":j()}],"rounded-bl":[{"rounded-bl":j()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Z(),"hidden","none"]}],"divide-style":[{divide:[...Z(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...Z(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,X,_]}],"outline-w":[{outline:["",de,Hr,no]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",p,Is,Ls]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",d,Is,Ls]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[de,no]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",l,Is,Ls]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[de,X,_]}],"mix-blend":[{"mix-blend":[...oe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":oe()}],"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":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"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":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"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":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"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":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"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":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"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":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"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":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"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":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":w()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:$()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",X,_]}],filter:[{filter:["","none",X,_]}],blur:[{blur:fe()}],brightness:[{brightness:[de,X,_]}],contrast:[{contrast:[de,X,_]}],"drop-shadow":[{"drop-shadow":["","none",f,Is,Ls]}],"drop-shadow-color":[{"drop-shadow":F()}],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":fe()}],"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":x()}],"border-spacing-x":[{"border-spacing-x":x()}],"border-spacing-y":[{"border-spacing-y":x()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",X,_]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",X,_]}],ease:[{ease:["linear","initial",y,X,_]}],delay:[{delay:[de,X,_]}],animate:[{animate:["none",g,X,_]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[m,X,_]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:we()}],"rotate-x":[{"rotate-x":we()}],"rotate-y":[{"rotate-y":we()}],"rotate-z":[{"rotate-z":we()}],scale:[{scale:Le()}],"scale-x":[{"scale-x":Le()}],"scale-y":[{"scale-y":Le()}],"scale-z":[{"scale-z":Le()}],"scale-3d":["scale-3d"],skew:[{skew:Ie()}],"skew-x":[{"skew-x":Ie()}],"skew-y":[{"skew-y":Ie()}],transform:[{transform:[X,_,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ze()}],"translate-x":[{"translate-x":ze()}],"translate-y":[{"translate-y":ze()}],"translate-z":[{"translate-z":ze()}],"translate-none":["translate-none"],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"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":x()}],"scroll-mx":[{"scroll-mx":x()}],"scroll-my":[{"scroll-my":x()}],"scroll-ms":[{"scroll-ms":x()}],"scroll-me":[{"scroll-me":x()}],"scroll-mt":[{"scroll-mt":x()}],"scroll-mr":[{"scroll-mr":x()}],"scroll-mb":[{"scroll-mb":x()}],"scroll-ml":[{"scroll-ml":x()}],"scroll-p":[{"scroll-p":x()}],"scroll-px":[{"scroll-px":x()}],"scroll-py":[{"scroll-py":x()}],"scroll-ps":[{"scroll-ps":x()}],"scroll-pe":[{"scroll-pe":x()}],"scroll-pt":[{"scroll-pt":x()}],"scroll-pr":[{"scroll-pr":x()}],"scroll-pb":[{"scroll-pb":x()}],"scroll-pl":[{"scroll-pl":x()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",X,_]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[de,Hr,no,ql]}],stroke:[{stroke:["none",...F()]}],"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 Cf=sy(ky);function Oa(...e){return Cf(Ss(e))}var My=be.createContext({size:"default",variant:"default",spacing:0});function Na({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(sf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Oa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(My.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var Py={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Pf=createSlice({name:"toolbar",initialState:Py,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:ea,setPenColor:ia,setStrokeWidth:qr,setFontSize:PE,setFontFamily:EE,setFontStyle:DE,setFontWeight:RE,setTextDecoration:FE,setTextColor:BE}=Pf.actions,Wl=Pf.reducer;var Ef=({onClose:e,onRecordingComplete:o})=>{let t=Ne(),[a,r]=useState(false),[n,i]=useState(null),[u,s]=useState(0),[c,p]=useState(null),[d,l]=useState(false),f=useRef(null),h=useRef([]),m=useRef(null),v=useRef(null),y=useRef(null);useEffect(()=>((async()=>{try{let C=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});p(C),l(!0),y.current&&(y.current.srcObject=C);}catch(C){console.error("Error accessing camera:",C),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{m.current&&clearInterval(m.current),c&&c.getTracks().forEach(C=>C.stop());}),[]);let g=()=>{c&&(c.getTracks().forEach(x=>x.stop()),p(null),l(false));},b=async()=>{try{let x=null,C=null;try{x=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(O){console.error("Error accessing camera for recording:",O),alert("Failed to access camera for recording.");return}try{C=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(O){console.warn("Microphone access denied:",O);}let M=[...x.getVideoTracks()];C&&M.push(...C.getAudioTracks());let P=new MediaStream(M),R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8");let W=new MediaRecorder(P,{mimeType:R,videoBitsPerSecond:25e5});f.current=W,h.current=[],W.ondataavailable=O=>{O.data.size>0&&h.current.push(O.data);},W.onstop=()=>{let O=new Blob(h.current,{type:R}),U=document.createElement("video");U.src=URL.createObjectURL(O),U.muted=!0,U.currentTime=.1,U.onseeked=()=>{let N=document.createElement("canvas");N.width=U.videoWidth,N.height=U.videoHeight;let q=N.getContext("2d");q&&(q.drawImage(U,0,0),v.current=N.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(U.src);},P.getTracks().forEach(N=>N.stop()),x&&x.getTracks().forEach(N=>N.stop()),C&&C.getTracks().forEach(N=>N.stop()),m.current&&clearInterval(m.current),i(O),g();},W.onerror=O=>{console.error("MediaRecorder error:",O);},W.start(1e3),r(!0),s(0),m.current=setInterval(()=>{s(O=>O+1);},1e3);}catch(x){console.error("Error starting camera recording:",x),alert("Failed to start recording. Please check permissions.");}},w=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),r(false));},I=()=>{if(n){let x=URL.createObjectURL(n),C=document.createElement("a");C.href=x,C.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(x);}},k=x=>{let C=Math.floor(x/60),M=x%60;return `${C.toString().padStart(2,"0")}:${M.toString().padStart(2,"0")}`};if(!t)return null;let S=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:x=>{x.target===x.currentTarget&&e(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:x=>x.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!n&&jsxs(Fragment,{children:[jsx("video",{ref:y,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:b,disabled:!d,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!d&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:w,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:k(u)})]})]})]}),n&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(n),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: ",k(u)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{i(null),s(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&n&&v.current&&(o(n,v.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(S,t)};var la=40,Rf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,i]=useState(t?.order||"sequential"),[u,s]=useState(false),c=useRef(null),p=Ne(),d=useRef(null);useEffect(()=>{let b=w=>{w.key==="Escape"&&o();};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[o]);let l=b=>{let w=b.target.files;if(!w||w.length===0)return;let I=la-a.length;if(I<=0){alert(`You can only upload a maximum of ${la} images`);return}let k=Array.from(w).slice(0,I);k.length<w.length&&alert(`Only ${I} more images can be added (max ${la} total)`);let S=k.map(x=>new Promise((C,M)=>{let P=new FileReader;P.onload=R=>{R.target?.result?C(R.target.result):M(new Error("Failed to read file"));},P.onerror=M,P.readAsDataURL(x);}));Promise.all(S).then(x=>{r(C=>[...C,...x]),d.current&&(d.current.value="");});},f=b=>{b.preventDefault(),s(false);let w=Array.from(b.dataTransfer.files).filter(x=>x.type.startsWith("image/"));if(w.length===0)return;let I=la-a.length;if(I<=0){alert(`You can only upload a maximum of ${la} images`);return}let k=w.slice(0,I);k.length<w.length&&alert(`Only ${I} more images can be added (max ${la} total)`);let S=k.map(x=>new Promise((C,M)=>{let P=new FileReader;P.onload=R=>{R.target?.result?C(R.target.result):M(new Error("Failed to read file"));},P.onerror=M,P.readAsDataURL(x);}));Promise.all(S).then(x=>{r(C=>[...C,...x]);});},h=b=>{b.preventDefault(),s(true);},m=()=>{s(false);},v=b=>{r(w=>w.filter((I,k)=>k!==b));},y=b=>{if(b.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,n,t?.id);};if(!p)return null;let g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:b=>{b.target===b.currentTarget&&o(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:b=>b.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$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:y,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=la?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",la," images"]}):jsxs("span",{children:[a.length,"/",la," images"]})})]}),jsx("input",{ref:d,type:"file",accept:"image/*",multiple:true,onChange:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:f,onDragOver:h,onDragLeave:m,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>i("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>i("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((b,w)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:b,alt:`Flashcard ${w+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(w),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:w+1})]},w))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(g,p)};var Cs={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},jy={enabled:true};function Gl(e){return e?{tools:{...Cs.tools,...e.tools},actions:{...Cs.actions,...e.actions}}:Cs}var _y={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Xy={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};function jl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Ff(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 Of(e){let[o,t]=be.useState(void 0);return Uo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let n=r[0],i,u;if("borderBoxSize"in n){let s=n.borderBoxSize,c=Array.isArray(s)?s[0]:s;i=c.inlineSize,u=c.blockSize;}else i=e.offsetWidth,u=e.offsetHeight;t({width:i,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var Nf=["PageUp","PageDown"],Hf=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],qf={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},_o="Slider",[_l,Yy,Zy]=bs(_o),[Vf]=Ra(_o,[Zy]),[Jy,Ts]=Vf(_o),Uf=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:i="horizontal",disabled:u=false,minStepsBetweenThumbs:s=0,defaultValue:c=[a],value:p,onValueChange:d=()=>{},onValueCommit:l=()=>{},inverted:f=false,form:h,...m}=e,v=be.useRef(new Set),y=be.useRef(0),b=i==="horizontal"?Qy:ew,[w=[],I]=na({prop:p,defaultProp:c,onChange:P=>{[...v.current][y.current]?.focus(),d(P);}}),k=be.useRef(w);function S(P){let R=nw(w,P);M(P,R);}function x(P){M(P,y.current);}function C(){let P=k.current[y.current];w[y.current]!==P&&l(w);}function M(P,R,{commit:W}={commit:false}){let O=dw(n),U=uw(Math.round((P-a)/n)*n+a,O),N=jl(U,[a,r]);I((q=[])=>{let F=ow(q,N,R);if(lw(F,s*n)){y.current=F.indexOf(N);let z=String(F)!==String(q);return z&&W&&l(F),z?F:q}else return q});}return jsx(Jy,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:r,valueIndexToChangeRef:y,thumbs:v.current,values:w,orientation:i,form:h,children:jsx(_l.Provider,{scope:e.__scopeSlider,children:jsx(_l.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":u,"data-disabled":u?"":void 0,...m,ref:o,onPointerDown:Qe(m.onPointerDown,()=>{u||(k.current=w);}),min:a,max:r,inverted:f,onSlideStart:u?void 0:S,onSlideMove:u?void 0:x,onSlideEnd:u?void 0:C,onHomeKeyDown:()=>!u&&M(a,0,{commit:true}),onEndKeyDown:()=>!u&&M(r,w.length-1,{commit:true}),onStepKeyDown:({event:P,direction:R})=>{if(!u){let U=Nf.includes(P.key)||P.shiftKey&&Hf.includes(P.key)?10:1,N=y.current,q=w[N],F=n*U*R;M(q+F,N,{commit:true});}}})})})})});Uf.displayName=_o;var[Wf,zf]=Vf(_o,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Qy=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:i,onSlideMove:u,onSlideEnd:s,onStepKeyDown:c,...p}=e,[d,l]=be.useState(null),f=qt(o,b=>l(b)),h=be.useRef(void 0),m=zo(r),v=m==="ltr",y=v&&!n||!v&&n;function g(b){let w=h.current||d.getBoundingClientRect(),I=[0,w.width],S=Yl(I,y?[t,a]:[a,t]);return h.current=w,S(b-w.left)}return jsx(Wf,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx(Kf,{dir:m,"data-orientation":"horizontal",...p,ref:f,style:{...p.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let w=g(b.clientX);i?.(w);},onSlideMove:b=>{let w=g(b.clientX);u?.(w);},onSlideEnd:()=>{h.current=void 0,s?.();},onStepKeyDown:b=>{let I=qf[y?"from-left":"from-right"].includes(b.key);c?.({event:b,direction:I?-1:1});}})})}),ew=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:i,onSlideEnd:u,onStepKeyDown:s,...c}=e,p=be.useRef(null),d=qt(o,p),l=be.useRef(void 0),f=!r;function h(m){let v=l.current||p.current.getBoundingClientRect(),y=[0,v.height],b=Yl(y,f?[a,t]:[t,a]);return l.current=v,b(m-v.top)}return jsx(Wf,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(Kf,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:m=>{let v=h(m.clientY);n?.(v);},onSlideMove:m=>{let v=h(m.clientY);i?.(v);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:m=>{let y=qf[f?"from-bottom":"from-top"].includes(m.key);s?.({event:m,direction:y?-1:1});}})})}),Kf=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:i,onEndKeyDown:u,onStepKeyDown:s,...c}=e,p=Ts(_o,t);return jsx(ht.span,{...c,ref:o,onKeyDown:Qe(e.onKeyDown,d=>{d.key==="Home"?(i(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):Nf.concat(Hf).includes(d.key)&&(s(d),d.preventDefault());}),onPointerDown:Qe(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),p.thumbs.has(l)?l.focus():a(d);}),onPointerMove:Qe(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d);}),onPointerUp:Qe(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),n(d));})})}),Gf="SliderTrack",jf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=Ts(Gf,t);return jsx(ht.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});jf.displayName=Gf;var Xl="SliderRange",_f=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=Ts(Xl,t),n=zf(Xl,t),i=be.useRef(null),u=qt(o,i),s=r.values.length,c=r.values.map(l=>Yf(l,r.min,r.max)),p=s>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(ht.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:u,style:{...e.style,[n.startEdge]:p+"%",[n.endEdge]:d+"%"}})});_f.displayName=Xl;var $l="SliderThumb",Xf=be.forwardRef((e,o)=>{let t=Yy(e.__scopeSlider),[a,r]=be.useState(null),n=qt(o,u=>r(u)),i=be.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(tw,{...e,ref:n,index:i})}),tw=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,i=Ts($l,t),u=zf($l,t),[s,c]=be.useState(null),p=qt(o,g=>c(g)),d=s?i.form||!!s.closest("form"):true,l=Of(s),f=i.values[a],h=f===void 0?0:Yf(f,i.min,i.max),m=rw(a,i.values.length),v=l?.[u.size],y=v?sw(v,h,u.direction):0;return be.useEffect(()=>{if(s)return i.thumbs.add(s),()=>{i.thumbs.delete(s);}},[s,i.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${y}px)`},children:[jsx(_l.ItemSlot,{scope:e.__scopeSlider,children:jsx(ht.span,{role:"slider","aria-label":e["aria-label"]||m,"aria-valuemin":i.min,"aria-valuenow":f,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...n,ref:p,style:f===void 0?{display:"none"}:e.style,onFocus:Qe(e.onFocus,()=>{i.valueIndexToChangeRef.current=a;})})}),d&&jsx($f,{name:r??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:f},a)]})});Xf.displayName=$l;var aw="RadioBubbleInput",$f=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),n=qt(r,a),i=Ff(o);return be.useEffect(()=>{let u=r.current;if(!u)return;let s=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(s,"value").set;if(i!==o&&p){let d=new Event("input",{bubbles:true});p.call(u,o),u.dispatchEvent(d);}},[i,o]),jsx(ht.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});$f.displayName=aw;function ow(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function Yf(e,o,t){let n=100/(t-o)*(e-o);return jl(n,[0,100])}function rw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function nw(e,o){if(e.length===1)return 0;let t=e.map(r=>Math.abs(r-o)),a=Math.min(...t);return t.indexOf(a)}function sw(e,o,t){let a=e/2,n=Yl([0,50],[0,a]);return (a-n(o)*t)*t}function iw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function lw(e,o){if(o>0){let t=iw(e);return Math.min(...t)>=o}return true}function Yl(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 dw(e){return (String(e).split(".")[1]||"").length}function uw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Zf=Uf,Jf=jf,Qf=_f,em=Xf;function Ms({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:i,thumbClassName:u,...s}){let c=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(Zf,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Oa("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),...s,children:[jsx(Jf,{"data-slot":"slider-track",className:Oa("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",i),children:jsx(Qf,{"data-slot":"slider-range",className:Oa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:c.length},(p,d)=>jsx(em,{"data-slot":"slider-thumb",className:Oa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",u)},d))]})}var Hw=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a}={})=>{let r=xe(),n=te(A=>A.canvas.slides.find(ee=>ee.id===A.canvas.currentSlideId)),i=n?.videos||[],u=n?.editingFlashcard,s=te(A=>A.toolbar.selectedTool),c=te(A=>A.toolbar.penColor),p=te(A=>A.toolbar.strokeWidth),d=n?.showMcqForm,l=n?.showFlashcardForm,f=useRef(null);useEffect(()=>{let A=ee=>{(ee.ctrlKey||ee.metaKey)&&ee.key==="z"&&!ee.shiftKey&&(ee.preventDefault(),r(Bn())),(ee.ctrlKey&&ee.shiftKey&&ee.key==="Z"||ee.ctrlKey&&ee.key==="y")&&(ee.preventDefault(),r(On()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[r]);let h=useMemo(()=>Gl(a),[a]),{tools:m,actions:v}=h,y=i.some(A=>A.isRecorded&&A.isPlaying),g=te(A=>A.toolbar.fontSize),b=te(A=>A.toolbar.fontFamily),w=te(A=>A.toolbar.fontStyle),I=te(A=>A.toolbar.fontWeight),k=te(A=>A.toolbar.textDecoration),S=te(A=>A.toolbar.textColor),[x,C]=useState(false),[M,P]=useState(false),[R,W]=useState(false),[O,U]=useState(false),[N,q]=useState(false),[F,z]=useState(false),[$,re]=useState(false),[V,j]=useState(false),[Y,Z]=useState(true),oe=useRef(null),J=useRef(null),fe=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],we=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"style",icon:Palette,label:"Style",configKey:"style"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),Le=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"}],[]),Ie=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),ze=useMemo(()=>we.filter(A=>{let ee=m[A.configKey];return typeof ee=="boolean"?ee:Array.isArray(ee)?ee.length>0:true}),[m,we]),Mt=useMemo(()=>{let A=m.shapes;return A===false?[]:A===true?Le:Array.isArray(A)?Le.filter(ee=>A.includes(ee.name)):Le},[m.shapes,Le]),At=useMemo(()=>{let A=m.activities;return A===false?[]:A===true?Ie:Array.isArray(A)?Ie.filter(ee=>A.includes(ee.name)):Ie},[m.activities,Ie]),ma=useMemo(()=>{let A=m.media;return A===false?{photoFrame:false,image:false,video:false}:A===true?{photoFrame:true,image:true,video:true}:Array.isArray(A)?{photoFrame:A.includes("photo-frame"),image:A.includes("image"),video:A.includes("video")}:{photoFrame:true,image:true,video:true}},[m.media]),se=useMemo(()=>{let A=m.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[m.activities]),Gr=A=>{let ee=A.target.files;!ee||ee.length===0||(r(ea("select")),r(vt(false)),U(false),Array.from(ee).forEach(Te=>{let ve=new FileReader;ve.onload=ie=>{let le=new window.Image;le.src=ie.target?.result,le.onload=()=>{let Be=le.width/le.height,it=300,aa=300,$e=le.width,Ee=le.height;$e>it&&($e=it,Ee=$e/Be),Ee>aa&&(Ee=aa,$e=Ee*Be),r(ue());let tt=800-$e/2,xt=450-Ee/2;r(ai({id:v4(),src:le.src,x:tt,y:xt,width:$e,height:Ee,draggable:true,rotation:0}));};},ve.readAsDataURL(Te);}),A.target.value="");},jr=async A=>{let ee=A.target.files;if(!(!ee||ee.length===0)){console.log("files",A),r(ea("select")),r(vt(false)),U(false);for(let Te of Array.from(ee))try{let ve=URL.createObjectURL(Te),ie=document.createElement("video");console.log("video",ie),ie.src=ve,ie.muted=!0,ie.playsInline=!0,ie.preload="auto",ie.load(),await new Promise((Ut,Wt)=>{let ne=setTimeout(()=>Wt(new Error("Metadata load timeout")),1e4);ie.onloadedmetadata=()=>{clearTimeout(ne),Ut();},ie.onerror=()=>{clearTimeout(ne),Wt(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ie.duration,width:ie.videoWidth,height:ie.videoHeight}),await new Promise((Ut,Wt)=>{let ne=setTimeout(()=>Wt(new Error("Video load timeout")),1e4);ie.readyState>=2?(clearTimeout(ne),Ut()):ie.onloadeddata=()=>{clearTimeout(ne),Ut();};});let le=Math.min(.8,ie.duration/2);console.log("Seeking to:",le),ie.currentTime=le,await new Promise(Ut=>{let Wt=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ut();},5e3);ie.onseeked=()=>{clearTimeout(Wt),console.log("Seek completed"),Ut();};});let Be=document.createElement("canvas"),it=ie.videoWidth/ie.videoHeight,aa=400,$e=400,Ee=ie.videoWidth,tt=ie.videoHeight;Ee>aa&&(Ee=aa,tt=Ee/it),tt>$e&&(tt=$e,Ee=tt*it),Be.width=Ee,Be.height=tt;let xt=Be.getContext("2d",{willReadFrequently:!1});if(!xt)throw new Error("Failed to get canvas context");if(await new Promise(Ut=>setTimeout(Ut,100)),ie.videoWidth===0||ie.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ee,height:tt}),xt.drawImage(ie,0,0,Ee,tt);let ga=Be.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",ga.length),r(ue());let Ws=800-Ee/2,zs=450-tt/2,Jr=v4();await ao(Jr,Te,ga),r(ln({id:Jr,objectUrl:ve,thumbnailDataUrl:ga,videoBlob:Te,x:Ws,y:zs,width:Ee,height:tt,draggable:!0,isPlaying:!1,rotation:0})),ie.src="",ie.load(),console.log(`Video uploaded: ${Te.name}`);}catch(ve){console.error("Error processing video:",ve),alert(`Failed to process video: ${Te.name}`);}A.target.value="";}},_r=(A,ee,Te)=>{r(ue()),r(ea("select")),r(vt(false));let ve=300,ie=300,le=800-ve/2,Be=450-ie/2;r(Te?go({id:Te,images:A,order:ee,x:le,y:Be,width:ve,height:ie,rotation:0,draggable:true}):ni({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:ee,x:le,y:Be,width:ve,height:ie,rotation:0,draggable:true})),r(za(false));},Xr=()=>{r(ue()),r(ea("select")),r(vt(false));let A=400,ee=300,Te=800-A/2,ve=450-ee/2;r(li({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Te,y:ve,width:A,height:ee,rotation:0,draggable:true,isCapturing:false})),U(false);},$r=A=>{let le={};switch(A.name){case "circle":case "ring":case "wedge":case "arc":le.radius=50,(A.name==="ring"||A.name==="arc")&&(le.innerRadius=25,le.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(le.angle=A.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],A.name==="arrow"&&(le.pointerLength=10,le.pointerWidth=10);break}let Be={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:c,...le};r(ue()),r(vt(false)),r(ea(A.name)),r(oi(Be)),W(false);},pa=A=>{if(r(ea(A)),A==="select")r(vt(false));else if(A==="text"){r(vt(false)),r(ue());let ee=200,Te=50,ve=800-ee/2,ie=450-Te/2,Be=window.innerWidth<768?Math.max(g,32):g,it=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(ri({id:it,text:"",x:ve,y:ie,width:ee,height:Te,rotation:0,draggable:true,fontSize:Be,fontFamily:b,fontStyle:w,fontWeight:I,textDecoration:k,fill:S,align:"left"})),setTimeout(()=>{r(sr(it));},100),t&&t(it);}else r(vt(true));},Bs=()=>{r(Ii()),r(vt(false));},Os=()=>{e?e():o?C(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Ns=()=>{P(true);},Hs=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:Xr,enabled:ma.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>oe.current?.click(),enabled:ma.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>J.current?.click(),enabled:ma.video}],Yr=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Bn()),enabled:v.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(On()),enabled:v.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:Os,enabled:v.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:Ns,enabled:v.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:Bs,enabled:v.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],ha=async(A,ee)=>{try{r(ea("select")),r(vt(!1));let Te=URL.createObjectURL(A),ve=document.createElement("video");ve.src=Te,ve.muted=!0,ve.playsInline=!0,ve.preload="auto",await new Promise((tt,xt)=>{let ga=setTimeout(()=>xt(new Error("Metadata load timeout")),1e4);ve.onloadedmetadata=()=>{clearTimeout(ga),tt();},ve.onerror=()=>{clearTimeout(ga),xt(new Error("Failed to load video"));};});let ie=640,le=ve.videoWidth/ve.videoHeight,Be=ie,it=Be/le;r(ue());let aa=800-Be/2,$e=450-it/2,Ee=v4();await ao(Ee,A,ee),r(ln({id:Ee,objectUrl:Te,thumbnailDataUrl:ee,videoBlob:A,x:aa,y:$e,width:Be,height:it,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),C(!1),P(!1);}catch(Te){console.error("Error adding recorded video to canvas:",Te),alert("Failed to add video to canvas. Please try again.");}},qs=A=>{r(ea("select")),r(vt(false)),r(rr(null)),A&&r(bi(A)),r(ya(!d));},Vs=()=>{r(er(null)),r(za(true)),q(false);},uo=()=>{W(!R);},Zr=()=>{U(!O);},Us=()=>{q(!N);},Yo=()=>{z(!F);},co=()=>{Z(A=>{let ee=!A;return ee||(W(false),U(false),q(false),z(false),j(false),re(false)),ee});};return useEffect(()=>{if(!V)return;let A=ee=>{f.current&&!f.current.contains(ee.target)&&j(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[V]),y?null:jsxs(Fragment,{children:[jsx("button",{type:"button",onClick:co,className:"fixed top-28 left-4 z-50 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:Y?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),Y&&jsxs("div",{className:"fixed top-46 left-4 z-50 flex flex-col gap-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(Na,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:ze.map((A,ee)=>jsx("div",{title:A.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.name===s?"bg-primary/10":A.name==="style"?"md:hidden":""}`,onClick:()=>{A.name==="image"?(Zr(),W(false),q(false),z(false),pa(A.name)):A.name==="shapes"?(uo(),U(false),q(false),z(false),pa(A.name)):A.name==="activities"?(pa(A.name),Us(),W(false),U(false),z(false)):A.name==="style"?(Yo(),W(false),U(false),q(false),pa(A.name)):(pa(A.name),W(false),U(false),q(false),z(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ee))}),R&&jsx(Na,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:Mt.map((A,ee)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>$r(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ee))}),O&&jsx(Na,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:Hs.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),N&&jsxs(Na,{type:"single",className:"mx-1 mt-auto mb-10 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl lg:mb-11",children:[se&&jsx("div",{title:"Flashcard",onClick:()=>Vs(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),At.map((A,ee)=>jsx("div",{title:A.label,onClick:()=>qs(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},ee))]}),F&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Ms,{value:[p],onValueChange:A=>{r(qr(A[0]));},max:28,min:6,step:1,className:"w-28",rangeClassName:"bg-gray-300",thumbClassName:"bg-gray-600 border-none h-4 w-4"}),jsx("div",{className:"h-5 w-5 rounded-full bg-gray-800"})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"COLOR"}),jsxs("div",{className:"flex flex-wrap gap-1",children:[fe.map(A=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${c===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{r(ia(A.value)),z(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:c,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>r(ia(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:c,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{r(Qo(A.target.value)),z(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),Yr.some(A=>A.enabled)&&jsx(Na,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:Yr.filter(A=>A.enabled).map(A=>jsx("button",{onClick:A.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.colorClass}`,title:A.title,children:jsx(A.icon,{weight:A.iconWeight,className:"text-primary text-lg md:text-xl"})},A.key))})]}),jsx("input",{ref:oe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:Gr}),jsx("input",{ref:J,type:"file",accept:"video/*",className:"hidden",onChange:jr}),!e&&x&&o&&jsx(hr,{onClose:()=>C(false),stageRef:o,onRecordingComplete:ha}),M&&jsx(Ef,{onClose:()=>P(false),onRecordingComplete:ha}),l&&jsx(Rf,{editingFlashcard:u,onConfirm:_r,onCancel:()=>r(za(false))}),$&&jsx(jn,{defaultColor:c,onConfirm:A=>{r(ia(A)),re(false);},onCancel:()=>re(false)})]})},qw=Hw;var ad=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let r=at(bo),n=at(Mi),i=a?n:r,u=at(ir),p=(at(g=>g.canvas.slides.find(b=>b.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[d,l]=useState(false),[f,h]=useState(null),[m,v]=useState(null),y=async()=>{if(r.length===0){v({type:"error",message:"No slides to publish"});return}if(!e){v({type:"error",message:"No publish handler provided"});return}l(true),v(null);try{let g=await e(i,u,b=>{h(b);});console.log(g," ",i," ",u),g.success?v({type:"success",message:g.message}):v({type:"error",message:g.message});}catch(g){v({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),v(null);},3e3);}};return p?null:jsxs("button",{onClick:y,disabled:d||r.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 Gw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:r,onDescriptionChange:n,showPublishButton:i=true,showBackButton:u=true,editableTitle:s=true,editableDescription:c=true,className:p="",rightContent:d,leftContent:l,includeInactiveSlides:f=false})=>{let h=ut(),m=at(ir),v=at(Pi),y=e??(v?m.title:"")??"Untitled",g=o??(v?m.description:"")??"Add a description...",[b,w]=useState(false),[I,k]=useState(false),[S,x]=useState(y),[C,M]=useState(g),P=useRef(null),R=useRef(null);useEffect(()=>{x(y);},[y]),useEffect(()=>{M(g);},[g]),useEffect(()=>{b&&P.current&&(P.current.focus(),P.current.select());},[b]),useEffect(()=>{I&&R.current&&(R.current.focus(),R.current.select());},[I]);let W=()=>{s&&w(true);},O=()=>{c&&k(true);},U=()=>{w(false),S.trim()&&S!==y?r?r(S.trim()):h(Ci(S.trim())):S.trim()||x(y);},N=()=>{k(false),C.trim()&&C!==g?n?n(C.trim()):h(ki(C.trim())):C.trim()||M(g);},q=z=>{z.key==="Enter"?U():z.key==="Escape"&&(x(y),w(false));},F=z=>{z.key==="Enter"?N():z.key==="Escape"&&(M(g),k(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${p}`,children:[l||jsxs("div",{className:"flex items-center gap-4",children:[u&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[b?jsx("input",{ref:P,type:"text",value:S,onChange:z=>x(z.target.value),onBlur:U,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:W,title:S,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${s?"hover:border-primary cursor-text":""}`,children:S}),I?jsx("input",{ref:R,type:"text",value:C,onChange:z=>M(z.target.value),onBlur:N,onKeyDown:F,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:O,title:C,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${c?"hover:border-primary cursor-text":""}`,children:C})]})]}),d||i&&a&&jsx(ad,{onPublish:a,includeInactiveSlides:f})]})};var Zw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Jw=({colors:e=Zw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let[n,i]=useState(true),u=te(he),s=te(l=>l.toolbar.penColor),c=te(l=>l.toolbar.strokeWidth),p=u?.backgroundColor,d=xe();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:n?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-16 left-1/2 z-50 hidden w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-3 shadow-2xl md:bottom-6 md:flex md:p-5 2xl:px-8 2xl:py-6 ${r}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-black md:h-3 md:w-3"}),jsx(Ms,{defaultValue:[12],max:28,min:6,step:1,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:l=>d(qr(l[0]))}),jsx("div",{className:"h-5 w-5 rounded-full bg-black md:h-7 md:w-7 lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"COLOR"}),jsxs(Na,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${s===l.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:l.value},onClick:()=>d(ia(l.value))},l.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>d(ia("#2D2F50"))}),jsxs("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] md:h-10 md:w-10 lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(ia(l.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:p},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(Qo(l.target.value))})})]})}),jsx("div",{className:"absolute -top-6 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2 md:-top-4",children:jsx("button",{onClick:()=>i(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{weight:"bold",className:"text-gray-600 md:text-xl"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>i(true),className:"fixed bottom-20 left-1/2 z-50 hidden -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl md:bottom-3 md:flex","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var im=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Qw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),rd=e=>{let o=Qw(e);return o.charAt(0).toUpperCase()+o.slice(1)},Ds=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),lm=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var dm={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 cm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:i,...u},s)=>createElement("svg",{ref:s,...dm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Ds("lucide",r),...!n&&!lm(u)&&{"aria-hidden":"true"},...u},[...i.map(([c,p])=>createElement(c,p)),...Array.isArray(n)?n:[n]]));var Rs=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(cm,{ref:n,iconNode:o,className:Ds(`lucide-${im(rd(e))}`,`lucide-${e}`,a),...r}));return t.displayName=rd(e),t};var oS=[["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"}]],Wr=Rs("copy",oS);var rS=[["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"}]],zr=Rs("trash-2",rS);var mm=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:i})=>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:r,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:u=>{u.stopPropagation(),n();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Wr,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),i();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(zr,{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 lS=({softDelete:e=false})=>{let o=ut(),t=at(bo),a=at(xo),r=at(Ai),[n,i]=useState(true),c=(at(h=>h.canvas.slides.find(m=>m.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),p=()=>{r&&o(Ys());},d=h=>{o(Qs(h));},l=h=>{o(Js(h));},f=h=>{t.length>1&&o(Zs({id:h,softDelete:e}));};return c?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:n?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:()=>i(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((h,m)=>jsx(mm,{slide:h,index:m,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>l(h.id),onDelete:()=>f(h.id)},h.id))}),jsxs("button",{onClick:p,disabled:!r,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${r?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!n&&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:()=>i(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 dS="SchooplaEditorDB",uS=1,Ha="slides",qa="metadata",nd="schoopla_current_slide_id",gm="presentation_metadata",Kr=()=>new Promise((e,o)=>{let t=indexedDB.open(dS,uS);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Ha)||r.createObjectStore(Ha,{keyPath:"id"}),r.objectStoreNames.contains(qa)||r.createObjectStore(qa,{keyPath:"id"});};}),sd=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Kr(),a=o.transaction([Ha],"readwrite").objectStore(Ha);await new Promise((r,n)=>{let i=a.clear();i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);});for(let r of e)await new Promise((n,i)=>{let u=a.add(r);u.onsuccess=()=>n(!0),u.onerror=()=>i(u.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},id=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Kr(),t=e.transaction([Ha],"readonly").objectStore(Ha);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let i=n.result;console.log("\u2705 Loaded from IndexedDB:",i.length,"slides"),i.length>0&&i[0].images&&console.log("First slide images:",i[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(i.length>0?i:null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Fs=async()=>{try{let e=await Kr(),o=e.transaction([Ha,qa],"readwrite"),t=o.objectStore(Ha),a=o.objectStore(qa);await new Promise((r,n)=>{let i=t.clear();i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);}),await new Promise((r,n)=>{let i=a.clear();i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(nd),localStorage.removeItem("schoopla_presentation_metadata"),await Fc(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},ld=e=>{try{localStorage.setItem(nd,e);}catch(o){console.error("Error saving current slide ID:",o);}},dd=()=>{try{return localStorage.getItem(nd)}catch(e){return console.error("Error loading current slide ID:",e),null}},ud=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},cd=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await Kr(),a=o.transaction([qa],"readwrite").objectStore(qa);await new Promise((r,n)=>{let i=a.put({id:gm,...e});i.onsuccess=()=>r(!0),i.onerror=()=>n(i.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);}}},fd=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await Kr(),t=e.transaction([qa],"readonly").objectStore(qa);return new Promise((a,r)=>{let n=t.get(gm);n.onsuccess=()=>{e.close();let i=n.result;if(i){let{id:u,...s}=i;console.log("\u2705 Loaded presentation metadata:",s),a(s);}else console.log("No presentation metadata found"),a(null);},n.onerror=()=>{e.close(),r(n.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 cS=["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"],fS=["canvas/clearCanvas"],mS=["canvas/setPresentationTitle","canvas/setPresentationDescription"],pS=ud((e,o)=>{sd(e),ld(o);},500),hS=ud(e=>{cd(e);},500),gS=(e,o)=>{sd(e),ld(o);},md=false,xm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let n=t.payload;Al(n).catch(i=>{console.error("Error deleting video blob:",i);});}if(t.type==="canvas/deleteSlide"&&t.payload){let n=t.payload,u=e.getState().canvas.slides.find(s=>s.id===n);u&&u.videos&&u.videos.length>0&&u.videos.forEach(s=>{Al(s.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let n=t.payload,i=e.getState(),s=i.canvas.slides.find(c=>c.id===i.canvas.currentSlideId)?.videos.find(c=>c.id===n);s&&s.videoBlob&&setTimeout(()=>{let c=e.getState(),d=c.canvas.slides.find(l=>l.id===c.canvas.currentSlideId)?.videos.find(l=>l.id!==n&&l.x===s.x+20&&l.y===s.y+20);d&&s.videoBlob&&ao(d.id,s.videoBlob,d.thumbnailDataUrl).catch(l=>{console.error("Error saving duplicated video blob:",l);});},0);}let a=o(t),r=e.getState();if(r.canvas.viewerMode)return a;if(t.type&&fS.includes(t.type)){if(!md){md=true;try{let{slides:n,currentSlideId:i}=r.canvas;gS(n,i);}finally{setTimeout(()=>{md=false;},0);}}}else if(t.type&&cS.includes(t.type)){let{slides:n,currentSlideId:i}=r.canvas;pS(n,i);}else if(t.type&&mS.includes(t.type)){let{presentationMetadata:n}=r.canvas;hS(n);}return a});new QueryClient;var bS=configureStore({reducer:{toolbar:Wl,canvas:Ei},middleware:e=>e({serializableCheck:false}).concat(xm)}),vS=()=>configureStore({reducer:{toolbar:Wl,canvas:Ei},middleware:e=>e({serializableCheck:false})});var yS=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:n=`slide-${Date.now()}`}=o;try{let i=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:i,quality:a,pixelRatio:r}),s=document.createElement("a");s.download=`${n}.${t}`,s.href=u,document.body.appendChild(s),s.click(),document.body.removeChild(s);}catch(i){throw console.error("Error exporting slide:",i),new Error("Failed to export slide")}},wS=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((n,i)=>{try{let u=t==="png"?"image/png":"image/jpeg",s=e.toDataURL({mimeType:u,quality:a,pixelRatio:r});fetch(s).then(c=>c.blob()).then(c=>n(c)).catch(c=>i(c));}catch(u){i(u);}})},SS=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,n=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:n,quality:a,pixelRatio:r})};var LS=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let n=a*a+r*r,i=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/n)),u=o.x+i*a,s=o.y+i*r;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-s,2))},pd=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],n=e[e.length-1];for(let i=1;i<e.length-1;i++){let u=LS(e[i],r,n);u>t&&(t=u,a=i);}if(t>o){let i=pd(e.slice(0,a+1),o),u=pd(e.slice(a),o);return [...i.slice(0,-1),...u]}return [r,n]},IS=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},CS=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},vm=(e,o=1.5)=>{if(e.length<=4)return e;let t=IS(e),a=pd(t,o);return CS(a)},ym=(e,o=1.5)=>({...e,points:vm(e.points,o)}),kS=(e,o=1.5)=>e.map(t=>ym(t,o)),TS=(e,o)=>{let t=e.length/2,a=o.length/2,r=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${r}%`}};var MS=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var wm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((n,i)=>{let u=new Image;u.onload=()=>{let{width:s,height:c}=u;if(s>t||c>a){let h=s/c;s>c?(s=Math.min(s,t),c=s/h):(c=Math.min(c,a),s=c*h);}let p=document.createElement("canvas");p.width=s,p.height=c;let d=p.getContext("2d");if(!d){i(new Error("Failed to get canvas context"));return}d.drawImage(u,0,0,s,c);let l=MS(e),f=p.toDataURL(l,r);n(f);},u.onerror=i,u.src=e;})};var lo=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return a.buffer},Xo=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",AS=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,i=[],u=0;for(let s of e){let c=[],p=[],d=[];for(let l of s.images){let f=l.src;if(t&&f.startsWith("data:"))try{f=await wm(f,{maxWidth:a,maxHeight:r,quality:n});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=lo(f),m=Xo(f);u+=h.byteLength;let v={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,buffer:h,mimeType:m};if(l.audioData&&l.audioData.startsWith("data:")){let y=lo(l.audioData),g=Xo(l.audioData);u+=y.byteLength,v.audioBuffer=y,v.audioMimeType=g;}c.push(v);}}for(let l of s.videos){let f,h;if(l.videoBlob)f=await l.videoBlob.arrayBuffer(),h=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))f=lo(l.videoData),h=Xo(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}u+=f.byteLength;let m={id:l.id,thumbnailDataUrl:l.thumbnailDataUrl,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,isPlaying:l.isPlaying,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isRecorded:l.isRecorded,buffer:f,mimeType:h};if(l.audioData&&l.audioData.startsWith("data:")){let v=lo(l.audioData),y=Xo(l.audioData);u+=v.byteLength,m.audioBuffer=v,m.audioMimeType=y;}p.push(m);}for(let l of s.photoFrames){let f={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:l.draggable,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isCapturing:l.isCapturing};if(l.capturedImageUrl&&l.capturedImageUrl.startsWith("data:")){let h=lo(l.capturedImageUrl),m=Xo(l.capturedImageUrl);u+=h.byteLength,f.buffer=h,f.mimeType=m;}if(l.audioData&&l.audioData.startsWith("data:")){let h=lo(l.audioData),m=Xo(l.audioData);u+=h.byteLength,f.audioBuffer=h,f.audioMimeType=m;}d.push(f);}i.push({...s,images:c,videos:p,photoFrames:d});}return {slides:i,totalSize:u}},PS=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},ES=e=>{let o=new FormData,t=e.slides.map((a,r)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((n,i)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,mimeType:n.mimeType,fileKey:`slide_${r}_image_${i}`,audioFileKey:n.audioBuffer?`slide_${r}_image_${i}_audio`:void 0,audioMimeType:n.audioMimeType})),videos:a.videos.map((n,i)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,isPlaying:n.isPlaying,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isRecorded:n.isRecorded,mimeType:n.mimeType,fileKey:`slide_${r}_video_${i}`,thumbnailFileKey:`slide_${r}_video_${i}_thumbnail`,audioFileKey:n.audioBuffer?`slide_${r}_video_${i}_audio`:void 0,audioMimeType:n.audioMimeType})),photoFrames:a.photoFrames.map((n,i)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,draggable:n.draggable,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isCapturing:n.isCapturing,mimeType:n.mimeType,fileKey:n.buffer?`slide_${r}_photoframe_${i}`:void 0,audioFileKey:n.audioBuffer?`slide_${r}_photoframe_${i}_audio`:void 0,audioMimeType:n.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((n,i)=>{let u=new Blob([n.buffer],{type:n.mimeType}),s=`${n.id}.${$o(n.mimeType)}`;if(o.append(`slide_${r}_image_${i}`,u,s),n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),p=`${n.id}_audio.${$o(n.audioMimeType)}`;o.append(`slide_${r}_image_${i}_audio`,c,p);}}),a.videos.forEach((n,i)=>{let u=new Blob([n.buffer],{type:n.mimeType}),s=`${n.id}.${$o(n.mimeType)}`;if(o.append(`slide_${r}_video_${i}`,u,s),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let c=lo(n.thumbnailDataUrl),p=new Blob([c],{type:"image/jpeg"}),d=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${i}_thumbnail`,p,d);}if(n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),p=`${n.id}_audio.${$o(n.audioMimeType)}`;o.append(`slide_${r}_video_${i}_audio`,c,p);}}),a.photoFrames.forEach((n,i)=>{if(n.buffer&&n.mimeType){let u=new Blob([n.buffer],{type:n.mimeType}),s=`${n.id}.${$o(n.mimeType)}`;o.append(`slide_${r}_photoframe_${i}`,u,s);}if(n.audioBuffer&&n.audioMimeType){let u=new Blob([n.audioBuffer],{type:n.audioMimeType}),s=`${n.id}_audio.${$o(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${i}_audio`,u,s);}});}),o};var FS=()=>{let e=ut(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let r=await id(),n=dd(),i=await fd();if(r&&r.length>0){let u=await Rc(),s=r.map(p=>{if(p.videos&&p.videos.length>0){let d=p.videos.map(l=>{let f=u.get(l.id);if(f){let h=Bc(f.blob);return {...l,objectUrl:h,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return l});return {...p,videos:d}}return p}),c=n&&s.find(p=>p.id===n)?n:s[0].id;e(mo({slides:s,currentSlideId:c}));}e(i?Ti({title:i.title,description:i.description}):Nn(!0));}catch(r){console.error("Error loading persisted slides:",r),e(Nn(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||""})),Im=new WeakSet,Cm=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await ao(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},BS=()=>{let e=ut(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Im.has(a))return;Im.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:i=true}=a;if(i)try{await Fs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(c){console.error("Error clearing local data:",c);}let u=n&&r.find(c=>c.id===n)?n:r[0].id,s=Lm(r);e(mo({slides:s,currentSlideId:u})),await Cm(s);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:i=true}=a;if(i)try{await Fs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=n&&r.find(c=>c.id===n)?n:r[0].id,s=Lm(r);e(mo({slides:s,currentSlideId:u})),await Cm(s);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
6
+ This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:l?"none":"auto"}})}),jsx(Group,{y:I.questionHeight+I.feedbackHeight+I.placeholderHeight+I.textareaHeight+I.textareaMargin+I.buttonTopMargin,children:l&&jsxs(Group,{onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),g();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),g();},scaleX:h==="reset"?.95:1,scaleY:h==="reset"?.95:1,children:[jsx(Rect,{x:I.padding,width:I.contentWidth,height:I.buttonHeight,fill:"#ef4444",cornerRadius:8,onClick:k=>k.cancelBubble=true,onTap:k=>k.cancelBubble=true}),jsx(Text,{x:I.padding,width:I.contentWidth,height:I.buttonHeight,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Ml.displayName="LongAnswer";var kc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n,onLongPress:i})=>{let{createHandlers:u}=Oe({onLongPress:i});return jsx(Fragment,{children:e.map(s=>jsx(Ml,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id),touchHandlers:u(s.id,"longAnswer")},s.id))})};var eo=1600,to=900,Pc=3200,Ec=1800,$b=e=>{let o=0,t=0,a=eo,r=to;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:eo,height:to};let n=(s,c,p,d)=>{o=Math.min(o,s),t=Math.min(t,c),a=Math.max(a,s+p),r=Math.max(r,c+d);};e.lines?.forEach(s=>{if(s.points&&s.points.length>=2){let c=s.x||0,p=s.y||0,d=s.scaleX||1,l=s.scaleY||1;for(let f=0;f<s.points.length;f+=2){let h=c+s.points[f]*d,m=p+s.points[f+1]*l;o=Math.min(o,h),t=Math.min(t,m),a=Math.max(a,h),r=Math.max(r,m);}}}),e.images?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.videos?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.shapes?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.texts?.forEach(s=>n(s.x,s.y,s.width||200,s.height||s.fontSize||24)),e.flashcards?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.photoFrames?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.multipleChoices?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.trueFalses?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.shortAnswers?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.LongAnswer?.forEach(s=>n(s.x,s.y,s.width,s.height)),e.fillInTheBlanks?.forEach(s=>n(s.x,s.y,s.width,s.height));let i=Math.min(a-o,Pc),u=Math.min(r-t,Ec);return o=Math.max(o,a-Pc),t=Math.max(t,r-Ec),{minX:o,minY:t,maxX:a,maxY:r,width:i,height:u}},Yb=(e,o,t={minX:0,minY:0,maxX:eo,maxY:to,width:eo,height:to})=>{let a=Math.max(t.width,eo),r=Math.max(t.height,to),n=e/o,i=a/r,u,s,c,d=0;if(n>i){s=r,u=Math.round(s*n),c=o/s;}else {u=a,s=Math.round(u/n),c=e/u;let l=r*c;d=(o-l)/2;}return {scale:c,scaleX:c,scaleY:c,stageWidth:e,stageHeight:o,offsetX:0,offsetY:d,baseWidth:u,baseHeight:s,contentOffsetX:t.minX,contentOffsetY:t.minY}},Dc=(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}},Zb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r={enabled:true}}={})=>{let n=ut(),i=Ne(),u=te(L=>L.toolbar.selectedTool),s=te(he),c=te(xo),p=te(Hn),l=(s?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),f=!!l,h=useCallback(()=>{l&&n(Ua(l.id));},[n,l]),m=s?.editingActivity,v=s?.showMcqForm,y=s?.lines||[],g=useRef(null),b=useRef(null),[w,I]=useState(null),[k,S]=useState(""),x=useRef(null),[C,M]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:eo,stageHeight:to,offsetX:0,offsetY:0,baseWidth:eo,baseHeight:to,contentOffsetX:0,contentOffsetY:0}),P=useMemo(()=>$b(s||null),[c]),[R,W]=useState(null),[O,U]=useState(null),[N,q]=useState(null),[F,z]=useState(null),[$,re]=useState(null),[V,j]=useState(null),[Y,Z]=useState(null),[oe,J]=useState(false),[fe,we]=useState(null),[Le,Ie]=useState(false),ze=useRef(null),Mt=useRef(null),At=useRef(null),{debouncedGenerateThumbnail:ma}=ru(c,g);useEffect(()=>{let L=()=>{if(b.current){let E=b.current.getBoundingClientRect(),B=Yb(E.width,E.height,P);M(B);}};L();let T=new ResizeObserver(L);return b.current&&T.observe(b.current),window.addEventListener("resize",L),()=>{T.disconnect(),window.removeEventListener("resize",L);}},[P]),useEffect(()=>{if(g.current){let L=g.current.container();L&&(L.style.cursor="");}},[u]);let se=useCallback(()=>{g.current&&requestAnimationFrame(()=>{if(!g.current)return;if(g.current.getLayers().forEach(T=>T.batchDraw()),!p)try{let E=g.current.toDataURL({pixelRatio:.16666666666666666});S(E),ma();}catch(T){console.warn("Preview generation failed (CORS):",T);}});},[ma,p]),Gr=useRef(c);useEffect(()=>{Gr.current!==c&&(Gr.current=c,se());},[c,se]);let jr=useRef(null),_r=useRef(true);useEffect(()=>{if(!s)return;let L=(s.lines?.length||0)+(s.images?.length||0)+(s.videos?.length||0)+(s.shapes?.length||0)+(s.texts?.length||0)+(s.flashcards?.length||0)+(s.photoFrames?.length||0)+(s.multipleChoices?.length||0)+(s.trueFalses?.length||0)+(s.shortAnswers?.length||0)+(s.LongAnswer?.length||0)+(s.fillInTheBlanks?.length||0),T=jr.current?.count!==L;!_r.current&&T&&setTimeout(()=>{se();},100),jr.current={slideId:c,count:L},_r.current=false;},[s,c,se]),useEffect(()=>{g.current&&e&&e(g);},[e]),useEffect(()=>{At.current&&a&&a(At);},[a]);let{startDrawing:Xr,draw:$r,stopDrawing:pa,setCanvasRef:Bs,tool:Os,color:Ns,strokeWidth:Hs,isSketchMode:Yr}=Ed(se),ha=useRef(new Map),{images:qs,getLoadedImage:Vs,imageRefs:uo,handleDragEnd:Zr,handleImageTransformEnd:Us}=Hd(se),{videos:Yo,videoRefs:co,handleVideoClick:A,handleVideoDragEnd:ee,handleVideoTransformEnd:Te}=Ud(se),{multipleChoice:ve,handleMcqTransform:ie,mcqRefs:le,handleDragEnd:Be}=qd(se),{trueFalse:it,handleTrueFalseTransform:aa,trueFalseRefs:$e,handleTrueFalseDragEnd:Ee}=Vd(se),{shortAnswers:tt,saRefs:xt,handleShortAnswerDragEnd:ga}=_d(se),{longAnswers:Ws,handleLongAnswerDragEnd:zs}=Xd(se),{fillInTheBlanks:Jr,handleFillInTheBlanksDragEnd:Ut,fibRefs:Wt}=yc(se),{transformerRef:ne,boundBoxFunc:Pt}=eu(),{shapes:km,shapeRefs:Qr,isDragging:hd,handleShapeDragEnd:Tm,handleShapeResizeEnd:Mm}=Kd(se),{texts:Zo,textRefs:xa,handleDragEnd:Am,handleTransformEnd:Pm,handleDoubleClick:Em,startEditing:en,editingTextId:pe,editingValue:gd,handleEditingChange:xd,finishEditing:Ks}=jd(se,ze);useEffect(()=>{t&&t(en);},[t,en]);let tn=te(L=>L.canvas.editingTextId);useEffect(()=>{tn&&tn!==pe&&en(tn);},[tn,pe,en]);let{flashcards:Dm,flashcardRefs:an,handleDragEnd:Rm,handleFlashcardTransformEnd:Fm,handleNext:Bm,handlePrevious:Om}=Yd(se),{photoFrames:bd,photoFrameRefs:on,handleDragEnd:Nm,handlePhotoFrameTransformEnd:Hm,startCamera:qm,capturePhoto:Vm,cameraStreams:Um}=Qd(se);useEffect(()=>{if(ne.current){if(pe){ne.current.nodes([]),ne.current.getLayer()?.batchDraw();return}if(w&&!Yo.find(E=>E.id===w)?.isPlaying){let E=ha.current.get(w)||uo.current.get(w)||co.current.get(w)||Qr.current.get(w)||xa.current.get(w)||le.current.get(w)||an.current.get(w)||on.current.get(w)||xt.current.get(w)||$e.current.get(w)||Wt.current.get(w);if(E){let B=E.attrs?.locked;if(E.visible()&&B!==true){ne.current.nodes([E]),ne.current.getLayer()?.batchDraw();return}}}ne.current.nodes([]),ne.current.getLayer()?.batchDraw();}},[w,pe,Yo,ha,uo,co,Qr,xa,an,on,bd,le,$e,Wt,ne]);let He=useCallback(L=>{I(L),o?.(L);},[o]),fo=useCallback(()=>{I(null),o?.(null),ne.current&&(ne.current.nodes([]),ne.current.getLayer()?.batchDraw());},[ne,o]),vd=useCallback(L=>s?s.lines?.some(T=>T.id===L)?"line":s.images?.some(T=>T.id===L)?"image":s.videos?.some(T=>T.id===L)?"video":s.shapes?.some(T=>T.id===L)?"shape":s.texts?.some(T=>T.id===L)?"text":s.flashcards?.some(T=>T.id===L)?"flashcard":s.photoFrames?.some(T=>T.id===L)?"photoFrame":s.multipleChoices?.some(T=>T.id===L)?"mcq":s.trueFalses?.some(T=>T.id===L)?"trueFalse":s.shortAnswers?.some(T=>T.id===L)?"shortAnswer":s.LongAnswer?.some(T=>T.id===L)?"longAnswer":s.fillInTheBlanks?.some(T=>T.id===L)?"fillInTheBlanks":null:null,[s]),yd=useCallback((L,T)=>{switch(n(ue()),T){case "line":n(Fn(L));break;case "image":n(nn(L));break;case "video":n(un(L));break;case "shape":n(mn(L));break;case "text":n(pn(L));break;case "flashcard":n(gn(L));break;case "photoFrame":n(bn(L));break;case "mcq":n(yn(L));break;case "trueFalse":n(Sn(L));break;case "shortAnswer":n(In(L));break;case "longAnswer":n(kn(L));break;case "fillInTheBlanks":n(Mn(L));break}fo(),se();},[n,fo,se]);useEffect(()=>{let L=T=>{if(T.key!=="Delete"||!w||pe)return;let E=document.activeElement;if(E instanceof HTMLInputElement||E instanceof HTMLTextAreaElement||E?.getAttribute("contenteditable")==="true")return;T.preventDefault();let ye=vd(w);ye&&yd(w,ye);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[w,pe,vd,yd]),useEffect(()=>{let L=ne.current;return ()=>{L&&L.nodes([]);}},[c]),useEffect(()=>{let L=T=>{pe&&T.target.tagName!=="TEXTAREA"&&Ks();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[pe,Ks]),useEffect(()=>{let L=pe||w;if(!L||w&&pe){U(null);return}let T=xa.current.get(L),E=g.current;if(!T||!E){U(null);return}let B=E.container().getBoundingClientRect(),ye=T.absolutePosition(),ge=E.scaleX();U({x:B.left+(ye.x+T.width()*ge/2)*ge+C.offsetX,y:B.top+ye.y*ge+C.offsetY-70});},[w,pe,Zo,xa,C.offsetX,C.offsetY]),useEffect(()=>{if(!pe){q(null);return}let L=xa.current.get(pe),T=g.current;if(!L||!T){q(null);return}let E=T.container().getBoundingClientRect(),B=L.absolutePosition(),ye=T.scaleX();q({top:E.top+B.y*ye+C.offsetY,left:E.left+B.x*ye+C.offsetX,scale:ye});},[pe,Zo,xa,C.offsetY,C.offsetX]);let wd=useCallback(L=>{let T=L.target.getClassName(),E=L.target===L.target.getStage(),B=T==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",ye=T==="Image",ge=T==="Text",ae=T==="Group"||L.target.getParent()?.getClassName()==="Group",lt=T==="Circle"||T==="Star"||T==="RegularPolygon"||T==="Ellipse"||T==="Ring"||T==="Wedge"||T==="Arrow"||T==="Line"||T==="Arc"||T==="Rect"&&L.target.attrs.id,dt=T==="Group";if(E&&!B&&!ye&&!ge&&!ae&&!lt&&!dt&&fo(),!(u==="pen"||u==="eraser")&&(ye||ge||B||ae||lt||dt))return;let qe=L.target.getStage()?.getPointerPosition();if(!qe)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)){let H=Dc(qe,C);Xr(H);}},[u,Xr,fo,C]),Sd=useCallback(L=>{if(hd)return;let T=L.target.getStage()?.getPointerPosition();if(!T)return;let E=Dc(T,C);$r(E);},[$r,hd,C]),Ld=useCallback(()=>{pa();},[pa]),Wm=useCallback(L=>{Zr(L,se);},[Zr,se]),zm=useCallback(L=>{A(L),He(L);},[A,He]),Et=useCallback((L,T,E)=>{if(L.preventDefault(),!r.enabled)return;let B=L.clientX,ye=L.clientY,ge=x.current?.offsetHeight||450,ae=x.current?.offsetWidth||450,lt=window.innerHeight,dt=window.innerWidth,Ye=B,qe=ye;ye+ge>lt&&(qe=ye-ge),B+ae>dt&&(Ye=B-ae),He(T),W({x:Ye,y:qe,elementId:T,elementType:E});},[He,r.enabled]),Va=useRef(null),Jo=useRef(null),bt=useCallback((L,T)=>E=>{if(!r.enabled)return;E.preventDefault();let B=E.changedTouches[0];if(!B)return;let ye=B.clientX,ge=B.clientY,ae=x.current?.offsetHeight||200,lt=x.current?.offsetWidth||200,dt=window.innerHeight,Ye=window.innerWidth,qe=ye,Ze=ge;ge+ae>dt&&(Ze=ge-ae),ye+lt>Ye&&(qe=ye-lt),He(L),W({x:qe,y:Ze,elementId:L,elementType:T});},[He,r.enabled]),Km=useCallback((L,T)=>({onTouchStart:E=>{let B=E.evt.touches[0];Jo.current={x:B.clientX,y:B.clientY},Va.current=setTimeout(()=>{bt(L,T)(E.evt);},500);},onTouchMove:E=>{if(!Jo.current)return;let B=E.evt.touches[0],ye=Math.abs(B.clientX-Jo.current.x),ge=Math.abs(B.clientY-Jo.current.y);(ye>10||ge>10)&&Va.current&&(clearTimeout(Va.current),Va.current=null);},onTouchEnd:()=>{Va.current&&(clearTimeout(Va.current),Va.current=null),Jo.current=null;}}),[bt]),Id=useCallback(L=>{n(rr(L)),n(ya(true));},[n]),Gm=useCallback(L=>{n(er(L)),n(za(true));},[n]),jm=useCallback((L,T)=>{if(!R)return;let{elementId:E,elementType:B}=R;switch(L){case "order":if(T){let D=T.target.getBoundingClientRect();z({x:D.right+5,y:D.top,type:"order"});}break;case "lock":if(T){let D=T.target.getBoundingClientRect();z({x:D.right+5,y:D.top,type:"lock"});}break;case "link":if(W(null),B==="line")break;let ye=s?B==="image"?s.images.find(D=>D.id===E):s.videos.find(D=>D.id===E):null;re({type:"link",defaultValue:ye?.link||""});break;case "voice":if(W(null),B==="line")break;let ge=s?B==="image"?s.images.find(D=>D.id===E):B==="video"?s.videos.find(D=>D.id===E):B==="text"?s.texts.find(D=>D.id===E):B==="flashcard"?s.flashcards.find(D=>D.id===E):B==="photoFrame"?s.photoFrames.find(D=>D.id===E):B==="mcq"?s.multipleChoices.find(D=>D.id===E):B==="fillInTheBlanks"?s.fillInTheBlanks.find(D=>D.id===E):B==="longAnswer"?s.LongAnswer.find(D=>D.id===E):B==="shortAnswer"?s.shortAnswers.find(D=>D.id===E):B==="trueFalse"?s.trueFalses.find(D=>D.id===E):B==="shape"?s.shapes.find(D=>D.id===E):null:null;we({elementId:E,elementType:B,existingAudio:ge?.audioData});break;case "edit":W(null);let ae=null;B==="mcq"?ae=s?.multipleChoices.find(D=>D.id===E):B==="trueFalse"?ae=s?.trueFalses.find(D=>D.id===E):B==="shortAnswer"?ae=s?.shortAnswers.find(D=>D.id===E):B==="longAnswer"?ae=s?.LongAnswer.find(D=>D.id===E):B==="fillInTheBlanks"&&(ae=s?.fillInTheBlanks.find(D=>D.id===E)),ae&&Id(ae);break;case "editFlashcard":W(null);let lt=s?.flashcards.find(D=>D.id===E);lt&&Gm(lt);break;case "color":W(null);let dt=s?.shapes.find(D=>D.id===E);j({elementId:E,elementType:"shape",defaultColor:dt?.color||"#096B76"});break;case "crop":if(W(null),B==="image"){let D=s?.images.find(Qm=>Qm.id===E);D&&Z({elementId:E,imageSrc:D.src});}break;case "draw":W(null),B==="image"?n(di(E)):B==="photoFrame"&&n(ci(E));break;case "duplicate":n(ue()),B==="line"?n(Li(E)):B==="image"?n(sn(E)):B==="video"?n(cn(E)):B==="shape"?n(fn(E)):B==="text"?n(hn(E)):B==="flashcard"?n(xn(E)):B==="photoFrame"?n(vn(E)):B==="mcq"?n(wn(E)):B==="trueFalse"?n(Ln(E)):B==="shortAnswer"?n(Cn(E)):B==="fillInTheBlanks"?n(An(E)):B==="longAnswer"&&n(Tn(E)),se();break;case "infinite-clone":n(ue());let Ye=5;for(let D=0;D<Ye;D++)B==="image"?n(sn(E)):B==="video"?n(cn(E)):B==="shape"?n(fn(E)):B==="text"?n(hn(E)):B==="flashcard"?n(xn(E)):B==="photoFrame"?n(vn(E)):B==="mcq"?n(wn(E)):B==="trueFalse"?n(Ln(E)):B==="shortAnswer"?n(Cn(E)):B==="fillInTheBlanks"?n(An(E)):B==="longAnswer"&&n(Tn(E));se();break;case "make-response":if(W(null),B==="line")break;let qe=`#response-${E}`;n(ue()),n(Pn({id:E,type:B,link:qe})),(s?B==="image"?s.images.find(D=>D.id===E):B==="video"?s.videos.find(D=>D.id===E):B==="shape"?s.shapes.find(D=>D.id===E):B==="flashcard"?s.flashcards.find(D=>D.id===E):B==="photoFrame"?s.photoFrames.find(D=>D.id===E):s.multipleChoices.find(D=>D.id===E):null)?.altText||n(En({id:E,type:B,altText:"Interactive response area"})),se(),console.log(`Element ${E} marked as interactive response area`);break;case "accessibility":if(W(null),B==="line")break;let H=s?B==="image"?s.images.find(D=>D.id===E):B==="video"?s.videos.find(D=>D.id===E):B==="shape"?s.shapes.find(D=>D.id===E):null:null;re({type:"altText",defaultValue:H?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),W(null),Ie(true),console.log("showLayersPanel state set to:",true);break;case "delete":n(ue()),B==="line"?n(Fn(E)):B==="image"?n(nn(E)):B==="video"?n(un(E)):B==="shape"?n(mn(E)):B==="text"?n(pn(E)):B==="flashcard"?n(gn(E)):B==="photoFrame"?n(bn(E)):B==="mcq"?n(yn(E)):B==="trueFalse"?n(Sn(E)):B==="shortAnswer"?n(In(E)):B==="longAnswer"?n(kn(E)):B==="fillInTheBlanks"&&n(Mn(E)),fo(),se();break}},[R,n,se,fo,s,Id]),_m=useCallback(()=>{W(null),z(null);},[]),Gs=useCallback(L=>{if(!R)return;let{elementId:T,elementType:E}=R;switch(n(ue()),L){case "bring-to-front":E!=="line"&&n(vi({id:T,type:E}));break;case "send-to-back":E!=="line"&&n(yi({id:T,type:E}));break;case "lock":case "unlock":E!=="line"&&n(wi({id:T,type:E}));break}se(),W(null),z(null);},[R,n,se]),Xm=useCallback(L=>{if(!R||!$)return;let{elementId:T,elementType:E}=R;n(ue()),$.type==="link"&&E!=="line"?n(Pn({id:T,type:E,link:L})):$.type==="altText"&&E!=="line"&&n(En({id:T,type:E,altText:L})),se(),re(null);},[R,$,n,se]),$m=useCallback(L=>{if(!fe)return;let{elementId:T,elementType:E}=fe;n(ue()),n(Dn({id:T,type:E,audioData:L})),se(),we(null);},[fe,n,se]),Ym=useCallback(()=>{if(!fe)return;let{elementId:L,elementType:T}=fe;n(ue()),n(Dn({id:L,type:T,audioData:""})),se();},[fe,n,se]),Zm=useCallback(L=>{if(!V)return;let{elementId:T}=V;n(ue()),n(ho({id:T,color:L})),se(),j(null);},[V,n,se]),Jm=useCallback(L=>{if(!Y)return;let{elementId:T}=Y;n(ue()),n(po({id:T,src:L})),se(),Z(null);},[Y,n,se]);return jsxs("div",{ref:b,className:"fixed inset-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default"},children:[u==="pen"&&jsx(Od,{ref:L=>{if(Mt.current=L,Bs(L),L){let T=L.getCanvasElement();T&&(At.current=T,a&&a(At));}},width:C.baseWidth,height:C.baseHeight,tool:Os,color:Ns,strokeWidth:Hs/C.scale,isSketchMode:Yr,xOffset:C.contentOffsetX,yOffset:C.contentOffsetY-C.offsetY/C.scale,style:{width:C.stageWidth,height:C.stageHeight}}),jsxs(Stage,{ref:g,width:C.stageWidth,height:C.stageHeight,scaleX:C.scaleX,scaleY:C.scaleY,x:C.offsetX,y:0,onMouseDown:wd,onMouseMove:Sd,onMouseUp:Ld,onTouchStart:wd,onTouchMove:Sd,onTouchEnd:Ld,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:C.baseWidth,height:C.stageHeight/C.scale,fill:s?.backgroundColor||"white"})}),jsx(Layer,{x:-C.contentOffsetX,y:C.offsetY/C.scale-C.contentOffsetY,children:(()=>{let L=[];return y.forEach((T,E)=>{L.push({type:"line",timestamp:T.timestamp||E,element:{...T,id:T.id??`line-${E}`},index:E});}),km.forEach(T=>{L.push({type:"shape",timestamp:T.timestamp||0,element:T});}),qs.forEach(T=>{L.push({type:"image",timestamp:T.timestamp||0,element:T});}),Yo.forEach(T=>{L.push({type:"video",timestamp:T.timestamp||0,element:T});}),Zo.forEach(T=>{L.push({type:"text",timestamp:T.timestamp||0,element:T});}),Dm.forEach(T=>{L.push({type:"flashcard",timestamp:T.timestamp||0,element:T});}),bd.forEach(T=>{L.push({type:"photoFrame",timestamp:T.timestamp||0,element:T});}),ve.forEach(T=>{L.push({type:"mcq",timestamp:T.timestamp||0,element:T});}),it.forEach(T=>{L.push({type:"trueFalse",timestamp:T.timestamp||0,element:T});}),tt.forEach(T=>{L.push({type:"shortAnswer",timestamp:T.timestamp||0,element:T});}),Ws.forEach(T=>{L.push({type:"longAnswer",timestamp:T.timestamp||0,element:T});}),Jr.forEach(T=>{L.push({type:"fillInTheBlanks",timestamp:T.timestamp||0,element:T});}),L.sort((T,E)=>T.timestamp-E.timestamp),L.map((T,E)=>{let B=`${T.type}-${"id"in T.element&&T.element.id||T.index||E}`,ye="id"in T.element?T.element.id:void 0,ge=ye&&w===ye;switch(T.type){case "line":let ae=T.element,lt=T.index||0,dt=ae.tool==="eraser",Ye=ae.isSketch&&ae.tool==="pen",qe=ae.isSketch&&dt,Ze=ae.id||`line-${lt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),u==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:Ye||qe?void 0:ae.color,strokeWidth:Ye||qe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ye||qe?dt?"black":ae.color:void 0,closed:Ye||qe,tension:0,globalCompositeOperation:dt?"destination-out":"source-over",listening:true,onClick:()=>{n(ue()),n(rn(lt));},onTap:()=>{n(ue()),n(rn(lt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:H=>{let D=H.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:H=>{let D=H.target.getStage();D&&(D.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},B):jsxs(be__default.Fragment,{children:[jsx(Group,{id:Ze,ref:H=>{H?ha.current.set(Ze,H):ha.current.delete(Ze);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",Ze),He(Ze));},onTap:()=>{u==="select"&&(console.log("Line tapped:",Ze),He(Ze));},onDragEnd:H=>{n(ue()),n(Rn({id:Ze,x:H.target.x(),y:H.target.y(),scaleX:H.target.scaleX(),scaleY:H.target.scaleY(),rotation:H.target.rotation()})),se();},onTransformEnd:H=>{n(ue()),n(Rn({id:Ze,x:H.target.x(),y:H.target.y(),scaleX:H.target.scaleX(),scaleY:H.target.scaleY(),rotation:H.target.rotation()})),se();},onMouseEnter:H=>{if(u==="select"){let D=H.target.getStage();D&&(D.container().style.cursor="move");}},onMouseLeave:H=>{if(u==="select"){let D=H.target.getStage();D&&(D.container().style.cursor="default");}},onContextMenu:H=>{let D=H.evt;D.preventDefault(),Et(D,Ze,"line");},...Km(Ze,"line"),children:jsx(Line,{points:ae.points||[],stroke:Ye||qe?void 0:ae.color,strokeWidth:Ye||qe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ye||qe?dt?"black":ae.color:void 0,closed:Ye||qe,tension:0,globalCompositeOperation:dt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=ha.current.get(w);console.log("Line Transformer - selectedId:",w,"node found:",!!D),D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "shape":return jsxs(be__default.Fragment,{children:[jsx(Wi,{onSelect:He,shapes:[T.element],shapeRefs:Qr,handleShapeDragEnd:Tm,handleShapeResizeEnd:Mm,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=Qr.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "image":return jsxs(be__default.Fragment,{children:[jsx(Hi,{images:[T.element],getLoadedImage:Vs,imageRefs:uo,onDragEnd:Wm,onTransform:Us,onSelect:He,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=uo.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "video":return jsxs(be__default.Fragment,{children:[jsx(Ui,{videos:[T.element],selectedId:w,videoRefs:co,onVideoClick:zm,onDragEnd:ee,onTransformEnd:Te,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=co.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "text":return jsxs(be__default.Fragment,{children:[jsx(gu,{texts:[T.element],textRefs:xa,onDragEnd:Am,onTransformEnd:Pm,onSelect:He,onContextMenu:Et,onLongPress:bt,onDoubleClick:Em,editingTextId:pe,editingValue:gd,onEditingChange:xd}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=xa.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Gi,{flashcards:[T.element],flashcardRefs:an,selectedId:w,onDragEnd:Rm,onTransform:Fm,onSelect:He,onNext:Bm,onPrevious:Om,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=an.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Zi,{photoFrames:[T.element],photoFrameRefs:on,selectedId:w,onDragEnd:Nm,onTransform:Hm,onSelect:He,onStartCamera:qm,onCapture:Vm,cameraStreams:Um,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=on.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(_u,{handleMcqTransform:ie,multipleChoice:[T.element],handleSelect:He,mcqRefs:le,handleDragEnd:Be,onContextMenu:Et,onLongPress:bt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=le.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Zu,{trueFalses:[T.element],handleTrueFalseTransform:aa,handleSelect:He,trueFalseRefs:$e,onContextMenu:Et,onLongPress:bt,handleDragEnd:Ee}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=$e.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(vc,{shortAnswers:[T.element],handleSelect:He,handleTransform:ie,saRefs:xt,onContextMenu:Et,onLongPress:bt,handleDragEnd:ga}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=xt.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(kc,{longAnswer:[T.element],handleSelect:He,handleTransform:ie,saRefs:xt,onContextMenu:Et,onLongPress:bt,handleDragEnd:zs}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=xt.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Ic,{fillInTheBlanks:[T.element],handleSelect:He,handleTransform:ie,onContextMenu:Et,onLongPress:bt,handleDragEnd:Ut,fibRefs:Wt}),ge&&!pe&&w&&jsx(Transformer,{ref:H=>{if(H&&ne.current!==H){ne.current=H;let D=Wt.current.get(w);D&&D.visible()&&(H.nodes([D]),H.getLayer()?.batchDraw());}},boundBoxFunc:Pt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);default:return null}})})()})]}),R&&jsx(Au,{menuRef:x,x:R.x,y:R.y,type:R.elementType,onAction:jm,onClose:_m,isDrawingMode:R.elementType==="image"?s?.images.find(L=>L.id===R.elementId)?.isDrawingMode:R.elementType==="photoFrame"?s?.photoFrames.find(L=>L.id===R.elementId)?.isDrawingMode:false}),F&&R&&jsx(Pu,{x:F.x,y:F.y,items:F.type==="order"?[{label:"Bring to Front",onClick:()=>Gs("bring-to-front")},{label:"Send to Back",onClick:()=>Gs("send-to-back")}]:[{label:s&&(R.elementType==="image"?s.images.find(L=>L.id===R.elementId)?.locked:s.videos.find(L=>L.id===R.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Gs(s&&(R.elementType==="image"?s.images.find(L=>L.id===R.elementId)?.locked:s.videos.find(L=>L.id===R.elementId)?.locked)?"unlock":"lock")}],onClose:()=>z(null)}),$&&jsx(Ru,{title:$.type==="link"?"Add Link":"Add Alt Text",label:$.type==="link"?"URL":"Alternative Text",placeholder:$.type==="link"?"https://example.com":"Describe this image/video",defaultValue:$.defaultValue,onSave:Xm,onClose:()=>re(null)}),V&&jsx(jn,{defaultColor:V.defaultColor,onConfirm:Zm,onCancel:()=>j(null)}),Y&&jsx(Nu,{imageSrc:Y.imageSrc,onConfirm:Jm,onCancel:()=>Z(null)}),oe&&jsx(hr,{onClose:()=>J(false),stageRef:g}),fe&&jsx(Uu,{elementId:fe.elementId,elementType:fe.elementType,existingAudio:fe.existingAudio,onSave:$m,onDelete:Ym,onClose:()=>we(null)}),Le&&jsx(Ku,{selectedElementId:w||void 0,onClose:()=>Ie(false),onSelectElement:L=>{He(L),Ie(false);}}),s?.images.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.videos.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.shapes?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.texts?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),s?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Ft,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:C.scale,offsetX:C.offsetX,offsetY:C.offsetY},`audio-${L.id}`)),v&&jsx(lc,{editElement:m}),O&&(()=>{let L=pe||w;if(!L)return null;let T=Zo.find(E=>E.id===L);return T?jsx(fc,{text:T,position:O}):null})(),N&&pe&&(()=>{let L=Zo.find(T=>T.id===pe);return L?jsx(pc,{text:L,editingValue:gd,onEditingChange:xd,onFinish:Ks,position:{top:N.top,left:N.left},scale:N.scale,textareaRef:ze},pe):null})(),f&&i&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:l?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:h})}),jsx("button",{onClick:h,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X$1,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),i)]})},Jb=Zb;var ev="SchooplaVideoStorage";var Qt="videos",xs=()=>new Promise((e,o)=>{let t=indexedDB.open(ev,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Qt)||r.createObjectStore(Qt,{keyPath:"id"});};}),ao=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await xs(),n=a.transaction([Qt],"readwrite").objectStore(Qt),i={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((u,s)=>{let c=n.put(i);c.onsuccess=()=>u(!0),c.onerror=()=>s(c.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var Rc=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await xs(),t=e.transaction([Qt],"readonly").objectStore(Qt);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let i=n.result,u=new Map;i.forEach(s=>{u.set(s.id,{blob:s.blob,thumbnailDataUrl:s.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),a(u);},n.onerror=()=>{e.close(),r(n.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 xs(),a=o.transaction([Qt],"readwrite").objectStore(Qt);await new Promise((r,n)=>{let i=a.delete(e);i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Fc=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await xs(),t=e.transaction([Qt],"readwrite").objectStore(Qt);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Bc=e=>URL.createObjectURL(e);function Ra(e,o=[]){let t=[];function a(n,i){let u=be.createContext(i),s=t.length;t=[...t,i];let c=d=>{let{scope:l,children:f,...h}=d,m=l?.[e]?.[s]||u,v=be.useMemo(()=>h,Object.values(h));return jsx(m.Provider,{value:v,children:f})};c.displayName=n+"Provider";function p(d,l){let f=l?.[e]?.[s]||u,h=be.useContext(f);if(h)return h;if(i!==void 0)return i;throw new Error(`\`${d}\` must be used within \`${n}\``)}return [c,p]}let r=()=>{let n=t.map(i=>be.createContext(i));return function(u){let s=u?.[e]||n;return be.useMemo(()=>({[`__scope${e}`]:{...u,[e]:s}}),[u,s])}};return r.scopeName=e,[a,av(r,...o)]}function av(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(n){let i=a.reduce((u,{useScope:s,scopeName:c})=>{let d=s(n)[`__scope${c}`];return {...u,...d}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:i}),[i])}};return t.scopeName=o.scopeName,t}function Oc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Or(...e){return o=>{let t=false,a=e.map(r=>{let n=Oc(r,o);return !t&&typeof n=="function"&&(t=true),n});if(t)return ()=>{for(let r=0;r<a.length;r++){let n=a[r];typeof n=="function"?n():Oc(e[r],null);}}}}function qt(...e){return be.useCallback(Or(...e),e)}function qc(e){let o=ov(e),t=be.forwardRef((a,r)=>{let{children:n,...i}=a,u=be.Children.toArray(n),s=u.find(nv);if(s){let c=s.props.children,p=u.map(d=>d===s?be.Children.count(c)>1?be.Children.only(null):be.isValidElement(c)?c.props.children:null:d);return jsx(o,{...i,ref:r,children:be.isValidElement(c)?be.cloneElement(c,void 0,p):null})}return jsx(o,{...i,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function ov(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let i=iv(r),u=sv(n,r.props);return r.type!==be.Fragment&&(u.ref=a?Or(a,i):i),be.cloneElement(r,u)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var rv=Symbol("radix.slottable");function nv(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rv}function sv(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...u)=>{let s=n(...u);return r(...u),s}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function iv(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 uv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ht=uv.reduce((e,o)=>{let t=qc(`Primitive.${o}`),a=be.forwardRef((r,n)=>{let{asChild:i,...u}=r,s=i?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(s,{...u,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function Qe(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function Pl(e){let o=cv(e),t=be.forwardRef((a,r)=>{let{children:n,...i}=a,u=be.Children.toArray(n),s=u.find(mv);if(s){let c=s.props.children,p=u.map(d=>d===s?be.Children.count(c)>1?be.Children.only(null):be.isValidElement(c)?c.props.children:null:d);return jsx(o,{...i,ref:r,children:be.isValidElement(c)?be.cloneElement(c,void 0,p):null})}return jsx(o,{...i,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function cv(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let i=hv(r),u=pv(n,r.props);return r.type!==be.Fragment&&(u.ref=a?Or(a,i):i),be.cloneElement(r,u)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var fv=Symbol("radix.slottable");function mv(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===fv}function pv(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...u)=>{let s=n(...u);return r(...u),s}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function hv(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 bs(e){let o=e+"CollectionProvider",[t,a]=Ra(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),i=m=>{let{scope:v,children:y}=m,g=be__default.useRef(null),b=be__default.useRef(new Map).current;return jsx(r,{scope:v,itemMap:b,collectionRef:g,children:y})};i.displayName=o;let u=e+"CollectionSlot",s=Pl(u),c=be__default.forwardRef((m,v)=>{let{scope:y,children:g}=m,b=n(u,y),w=qt(v,b.collectionRef);return jsx(s,{ref:w,children:g})});c.displayName=u;let p=e+"CollectionItemSlot",d="data-radix-collection-item",l=Pl(p),f=be__default.forwardRef((m,v)=>{let{scope:y,children:g,...b}=m,w=be__default.useRef(null),I=qt(v,w),k=n(p,y);return be__default.useEffect(()=>(k.itemMap.set(w,{ref:w,...b}),()=>void k.itemMap.delete(w))),jsx(l,{[d]:"",ref:I,children:g})});f.displayName=p;function h(m){let v=n(e+"CollectionConsumer",m);return be__default.useCallback(()=>{let g=v.collectionRef.current;if(!g)return [];let b=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(v.itemMap.values()).sort((k,S)=>b.indexOf(k.ref.current)-b.indexOf(S.ref.current))},[v.collectionRef,v.itemMap])}return [{Provider:i,Slot:c,ItemSlot:f},h,a]}var Uo=globalThis?.document?be.useLayoutEffect:()=>{};var gv=be[" useId ".trim().toString()]||(()=>{}),xv=0;function zc(e){let[o,t]=be.useState(gv());return Uo(()=>{t(a=>a??String(xv++));},[e]),(o?`radix-${o}`:"")}function Kc(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var bv=be[" useInsertionEffect ".trim().toString()]||Uo;function na({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,i]=vv({defaultProp:o,onChange:t}),u=e!==void 0,s=u?e:r;{let p=be.useRef(e!==void 0);be.useEffect(()=>{let d=p.current;d!==u&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${u?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),p.current=u;},[u,a]);}let c=be.useCallback(p=>{if(u){let d=yv(p)?p(e):p;d!==e&&i.current?.(d);}else n(p);},[u,e,n,i]);return [s,c]}function vv({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),n=be.useRef(o);return bv(()=>{n.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function yv(e){return typeof e=="function"}var wv=be.createContext(void 0);function zo(e){let o=be.useContext(wv);return e||o||"ltr"}var Rl="rovingFocusGroup.onEntryFocus",Sv={bubbles:false,cancelable:true},Nr="RovingFocusGroup",[Fl,Gc,Lv]=bs(Nr),[Iv,Bl]=Ra(Nr,[Lv]),[Cv,kv]=Iv(Nr),jc=be.forwardRef((e,o)=>jsx(Fl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Fl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Tv,{...e,ref:o})})}));jc.displayName=Nr;var Tv=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:i,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:s,onEntryFocus:c,preventScrollOnEntryFocus:p=false,...d}=e,l=be.useRef(null),f=qt(o,l),h=zo(n),[m,v]=na({prop:i,defaultProp:u??null,onChange:s,caller:Nr}),[y,g]=be.useState(false),b=Kc(c),w=Gc(t),I=be.useRef(false),[k,S]=be.useState(0);return be.useEffect(()=>{let x=l.current;if(x)return x.addEventListener(Rl,b),()=>x.removeEventListener(Rl,b)},[b]),jsx(Cv,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:m,onItemFocus:be.useCallback(x=>v(x),[v]),onItemShiftTab:be.useCallback(()=>g(true),[]),onFocusableItemAdd:be.useCallback(()=>S(x=>x+1),[]),onFocusableItemRemove:be.useCallback(()=>S(x=>x-1),[]),children:jsx(ht.div,{tabIndex:y||k===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:Qe(e.onMouseDown,()=>{I.current=true;}),onFocus:Qe(e.onFocus,x=>{let C=!I.current;if(x.target===x.currentTarget&&C&&!y){let M=new CustomEvent(Rl,Sv);if(x.currentTarget.dispatchEvent(M),!M.defaultPrevented){let P=w().filter(N=>N.focusable),R=P.find(N=>N.active),W=P.find(N=>N.id===m),U=[R,W,...P].filter(Boolean).map(N=>N.ref.current);$c(U,p);}}I.current=false;}),onBlur:Qe(e.onBlur,()=>g(false))})})}),_c="RovingFocusGroupItem",Xc=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:i,...u}=e,s=zc(),c=n||s,p=kv(_c,t),d=p.currentTabStopId===c,l=Gc(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:m}=p;return be.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(Fl.ItemSlot,{scope:t,id:c,focusable:a,active:r,children:jsx(ht.span,{tabIndex:d?0:-1,"data-orientation":p.orientation,...u,ref:o,onMouseDown:Qe(e.onMouseDown,v=>{a?p.onItemFocus(c):v.preventDefault();}),onFocus:Qe(e.onFocus,()=>p.onItemFocus(c)),onKeyDown:Qe(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){p.onItemShiftTab();return}if(v.target!==v.currentTarget)return;let y=Pv(v,p.orientation,p.dir);if(y!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let b=l().filter(w=>w.focusable).map(w=>w.ref.current);if(y==="last")b.reverse();else if(y==="prev"||y==="next"){y==="prev"&&b.reverse();let w=b.indexOf(v.currentTarget);b=p.loop?Ev(b,w+1):b.slice(w+1);}setTimeout(()=>$c(b));}}),children:typeof i=="function"?i({isCurrentTabStop:d,hasTabStop:m!=null}):i})})});Xc.displayName=_c;var Mv={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Av(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Pv(e,o,t){let a=Av(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Mv[a]}function $c(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Ev(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Yc=jc,Zc=Xc;var Qc="Toggle",Ol=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[i,u]=na({prop:t,onChange:r,defaultProp:a??false,caller:Qc});return jsx(ht.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:Qe(e.onClick,()=>{e.disabled||u(!i);})})});Ol.displayName=Qc;var Fa="ToggleGroup",[tf]=Ra(Fa,[Bl]),af=Bl(),Nl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Fv,{...a,ref:o});if(t==="multiple")return jsx(Bv,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Fa}\``)});Nl.displayName=Fa;var[of,rf]=tf(Fa),Fv=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[i,u]=na({prop:t,defaultProp:a??"",onChange:r,caller:Fa});return jsx(of,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>i?[i]:[],[i]),onItemActivate:u,onItemDeactivate:be__default.useCallback(()=>u(""),[u]),children:jsx(nf,{...n,ref:o})})}),Bv=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[i,u]=na({prop:t,defaultProp:a??[],onChange:r,caller:Fa}),s=be__default.useCallback(p=>u((d=[])=>[...d,p]),[u]),c=be__default.useCallback(p=>u((d=[])=>d.filter(l=>l!==p)),[u]);return jsx(of,{scope:e.__scopeToggleGroup,type:"multiple",value:i,onItemActivate:s,onItemDeactivate:c,children:jsx(nf,{...n,ref:o})})});Nl.displayName=Fa;var[Ov,Nv]=tf(Fa),nf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:i,loop:u=true,...s}=e,c=af(t),p=zo(i),d={role:"group",dir:p,...s};return jsx(Ov,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(Yc,{asChild:true,...c,orientation:n,dir:p,loop:u,children:jsx(ht.div,{...d,ref:o})}):jsx(ht.div,{...d,ref:o})})}),ws="ToggleGroupItem",Hv=be__default.forwardRef((e,o)=>{let t=rf(ws,e.__scopeToggleGroup),a=Nv(ws,e.__scopeToggleGroup),r=af(e.__scopeToggleGroup),n=t.value.includes(e.value),i=a.disabled||e.disabled,u={...e,pressed:n,disabled:i},s=be__default.useRef(null);return a.rovingFocus?jsx(Zc,{asChild:true,...r,focusable:!i,active:n,ref:s,children:jsx(ef,{...u,ref:o})}):jsx(ef,{...u,ref:o})});Hv.displayName=ws;var ef=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=rf(ws,t),i={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},u=n.type==="single"?i:void 0;return jsx(Ol,{...u,...r,ref:o,onPressedChange:s=>{s?n.onItemActivate(a):n.onItemDeactivate(a);}})}),sf=Nl;function lf(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(o=0;o<r;o++)e[o]&&(t=lf(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function Ss(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=lf(e))&&(a&&(a+=" "),a+=o);return a}var Vv=(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},Uv=(e,o)=>({classGroupId:e,validator:o}),mf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var df=[],Wv="arbitrary..",zv=e=>{let o=Gv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return Kv(i);let u=i.split("-"),s=u[0]===""&&u.length>1?1:0;return pf(u,s,o)},getConflictingClassGroupIds:(i,u)=>{if(u){let s=a[i],c=t[i];return s?c?Vv(c,s):s:c||df}return t[i]||df}}},pf=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let c=pf(e,o+1,n);if(c)return c}let i=t.validators;if(i===null)return;let u=o===0?e.join("-"):e.slice(o).join("-"),s=i.length;for(let c=0;c<s;c++){let p=i[c];if(p.validator(u))return p.classGroupId}},Kv=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?Wv+a:void 0})(),Gv=e=>{let{theme:o,classGroups:t}=e;return jv(t,o)},jv=(e,o)=>{let t=mf();for(let a in e){let r=e[a];Vl(r,t,a,o);}return t},Vl=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let i=e[n];_v(i,o,t,a);}},_v=(e,o,t,a)=>{if(typeof e=="string"){Xv(e,o,t);return}if(typeof e=="function"){$v(e,o,t,a);return}Yv(e,o,t,a);},Xv=(e,o,t)=>{let a=e===""?o:hf(o,e);a.classGroupId=t;},$v=(e,o,t,a)=>{if(Zv(e)){Vl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Uv(t,e));},Yv=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let i=0;i<n;i++){let[u,s]=r[i];Vl(s,hf(o,u),t,a);}},hf=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let n=0;n<r;n++){let i=a[n],u=t.nextPart.get(i);u||(u=mf(),t.nextPart.set(i,u)),t=u;}return t},Zv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Jv=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(n,i)=>{t[n]=i,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(n){let i=t[n];if(i!==void 0)return i;if((i=a[n])!==void 0)return r(n,i),i},set(n,i){n in t?t[n]=i:r(n,i);}}};var Qv=[],uf=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),ey=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],i=0,u=0,s=0,c,p=r.length;for(let m=0;m<p;m++){let v=r[m];if(i===0&&u===0){if(v===":"){n.push(r.slice(s,m)),s=m+1;continue}if(v==="/"){c=m;continue}}v==="["?i++:v==="]"?i--:v==="("?u++:v===")"&&u--;}let d=n.length===0?r:r.slice(s),l=d,f=false;d.endsWith("!")?(l=d.slice(0,-1),f=true):d.startsWith("!")&&(l=d.slice(1),f=true);let h=c&&c>s?c-s:void 0;return uf(n,f,l,h)};if(o){let r=o+":",n=a;a=i=>i.startsWith(r)?n(i.slice(r.length)):uf(Qv,false,i,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},ty=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let n=0;n<t.length;n++){let i=t[n],u=i[0]==="[",s=o.has(i);u||s?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(i)):r.push(i);}return r.length>0&&(r.sort(),a.push(...r)),a}},ay=e=>({cache:Jv(e.cacheSize),parseClassName:ey(e),sortModifiers:ty(e),...zv(e)}),oy=/\s+/,ry=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,i=[],u=e.trim().split(oy),s="";for(let c=u.length-1;c>=0;c-=1){let p=u[c],{isExternal:d,modifiers:l,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:m}=t(p);if(d){s=p+(s.length>0?" "+s:s);continue}let v=!!m,y=a(v?h.substring(0,m):h);if(!y){if(!v){s=p+(s.length>0?" "+s:s);continue}if(y=a(h),!y){s=p+(s.length>0?" "+s:s);continue}v=false;}let g=l.length===0?"":l.length===1?l[0]:n(l).join(":"),b=f?g+"!":g,w=b+y;if(i.indexOf(w)>-1)continue;i.push(w);let I=r(y,v);for(let k=0;k<I.length;++k){let S=I[k];i.push(b+S);}s=p+(s.length>0?" "+s:s);}return s},ny=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=gf(t))&&(r&&(r+=" "),r+=a);return r},gf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=gf(e[a]))&&(t&&(t+=" "),t+=o);return t},sy=(e,...o)=>{let t,a,r,n,i=s=>{let c=o.reduce((p,d)=>d(p),e());return t=ay(c),a=t.cache.get,r=t.cache.set,n=u,u(s)},u=s=>{let c=a(s);if(c)return c;let p=ry(s,t);return r(s,p),p};return n=i,(...s)=>n(ny(...s))},iy=[],We=e=>{let o=t=>t[e]||iy;return o.isThemeGetter=true,o},xf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,bf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,ly=/^\d+\/\d+$/,dy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,uy=/\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$/,cy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,fy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,my=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ko=e=>ly.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ba=e=>!!e&&Number.isInteger(Number(e)),Hl=e=>e.endsWith("%")&&de(e.slice(0,-1)),sa=e=>dy.test(e),py=()=>true,hy=e=>uy.test(e)&&!cy.test(e),vf=()=>false,gy=e=>fy.test(e),xy=e=>my.test(e),by=e=>!_(e)&&!X(e),vy=e=>Go(e,Sf,vf),_=e=>xf.test(e),no=e=>Go(e,Lf,hy),ql=e=>Go(e,Iy,de),cf=e=>Go(e,yf,vf),yy=e=>Go(e,wf,xy),Ls=e=>Go(e,If,gy),X=e=>bf.test(e),Hr=e=>jo(e,Lf),wy=e=>jo(e,Cy),ff=e=>jo(e,yf),Sy=e=>jo(e,Sf),Ly=e=>jo(e,wf),Is=e=>jo(e,If,true),Go=(e,o,t)=>{let a=xf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},jo=(e,o,t=false)=>{let a=bf.exec(e);return a?a[1]?o(a[1]):t:false},yf=e=>e==="position"||e==="percentage",wf=e=>e==="image"||e==="url",Sf=e=>e==="length"||e==="size"||e==="bg-size",Lf=e=>e==="length",Iy=e=>e==="number",Cy=e=>e==="family-name",If=e=>e==="shadow";var ky=()=>{let e=We("color"),o=We("font"),t=We("text"),a=We("font-weight"),r=We("tracking"),n=We("leading"),i=We("breakpoint"),u=We("container"),s=We("spacing"),c=We("radius"),p=We("shadow"),d=We("inset-shadow"),l=We("text-shadow"),f=We("drop-shadow"),h=We("blur"),m=We("perspective"),v=We("aspect"),y=We("ease"),g=We("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],w=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...w(),X,_],k=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],x=()=>[X,_,s],C=()=>[Ko,"full","auto",...x()],M=()=>[Ba,"none","subgrid",X,_],P=()=>["auto",{span:["full",Ba,X,_]},Ba,X,_],R=()=>[Ba,"auto",X,_],W=()=>["auto","min","max","fr",X,_],O=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],N=()=>["auto",...x()],q=()=>[Ko,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...x()],F=()=>[e,X,_],z=()=>[...w(),ff,cf,{position:[X,_]}],$=()=>["no-repeat",{repeat:["","x","y","space","round"]}],re=()=>["auto","cover","contain",Sy,vy,{size:[X,_]}],V=()=>[Hl,Hr,no],j=()=>["","none","full",c,X,_],Y=()=>["",de,Hr,no],Z=()=>["solid","dashed","dotted","double"],oe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[de,Hl,ff,cf],fe=()=>["","none",h,X,_],we=()=>["none",de,X,_],Le=()=>["none",de,X,_],Ie=()=>[de,X,_],ze=()=>[Ko,"full",...x()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[sa],breakpoint:[sa],color:[py],container:[sa],"drop-shadow":[sa],ease:["in","out","in-out"],font:[by],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[sa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[sa],shadow:[sa],spacing:["px",de],text:[sa],"text-shadow":[sa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ko,_,X,v]}],container:["container"],columns:[{columns:[de,_,X,u]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:I()}],overflow:[{overflow:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:C()}],"inset-x":[{"inset-x":C()}],"inset-y":[{"inset-y":C()}],start:[{start:C()}],end:[{end:C()}],top:[{top:C()}],right:[{right:C()}],bottom:[{bottom:C()}],left:[{left:C()}],visibility:["visible","invisible","collapse"],z:[{z:[Ba,"auto",X,_]}],basis:[{basis:[Ko,"full","auto",u,...x()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Ko,"auto","initial","none",_]}],grow:[{grow:["",de,X,_]}],shrink:[{shrink:["",de,X,_]}],order:[{order:[Ba,"first","last","none",X,_]}],"grid-cols":[{"grid-cols":M()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":M()}],"row-start-end":[{row:P()}],"row-start":[{"row-start":R()}],"row-end":[{"row-end":R()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":W()}],"auto-rows":[{"auto-rows":W()}],gap:[{gap:x()}],"gap-x":[{"gap-x":x()}],"gap-y":[{"gap-y":x()}],"justify-content":[{justify:[...O(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...O()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":O()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:x()}],px:[{px:x()}],py:[{py:x()}],ps:[{ps:x()}],pe:[{pe:x()}],pt:[{pt:x()}],pr:[{pr:x()}],pb:[{pb:x()}],pl:[{pl:x()}],m:[{m:N()}],mx:[{mx:N()}],my:[{my:N()}],ms:[{ms:N()}],me:[{me:N()}],mt:[{mt:N()}],mr:[{mr:N()}],mb:[{mb:N()}],ml:[{ml:N()}],"space-x":[{"space-x":x()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":x()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],w:[{w:[u,"screen",...q()]}],"min-w":[{"min-w":[u,"screen","none",...q()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[i]},...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,Hr,no]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,X,ql]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Hl,_]}],"font-family":[{font:[wy,_,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,X,_]}],"line-clamp":[{"line-clamp":[de,"none",X,ql]}],leading:[{leading:[n,...x()]}],"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:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Z(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",X,no]}],"text-decoration-color":[{decoration:F()}],"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:x()}],"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:z()}],"bg-repeat":[{bg:$()}],"bg-size":[{bg:re()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ba,X,_],radial:["",X,_],conic:[Ba,X,_]},Ly,yy]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:V()}],"gradient-via-pos":[{via:V()}],"gradient-to-pos":[{to:V()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:j()}],"rounded-s":[{"rounded-s":j()}],"rounded-e":[{"rounded-e":j()}],"rounded-t":[{"rounded-t":j()}],"rounded-r":[{"rounded-r":j()}],"rounded-b":[{"rounded-b":j()}],"rounded-l":[{"rounded-l":j()}],"rounded-ss":[{"rounded-ss":j()}],"rounded-se":[{"rounded-se":j()}],"rounded-ee":[{"rounded-ee":j()}],"rounded-es":[{"rounded-es":j()}],"rounded-tl":[{"rounded-tl":j()}],"rounded-tr":[{"rounded-tr":j()}],"rounded-br":[{"rounded-br":j()}],"rounded-bl":[{"rounded-bl":j()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Z(),"hidden","none"]}],"divide-style":[{divide:[...Z(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...Z(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,X,_]}],"outline-w":[{outline:["",de,Hr,no]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",p,Is,Ls]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",d,Is,Ls]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[de,no]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",l,Is,Ls]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[de,X,_]}],"mix-blend":[{"mix-blend":[...oe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":oe()}],"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":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"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":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"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":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"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":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"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":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"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":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"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":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"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":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":w()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:$()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",X,_]}],filter:[{filter:["","none",X,_]}],blur:[{blur:fe()}],brightness:[{brightness:[de,X,_]}],contrast:[{contrast:[de,X,_]}],"drop-shadow":[{"drop-shadow":["","none",f,Is,Ls]}],"drop-shadow-color":[{"drop-shadow":F()}],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":fe()}],"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":x()}],"border-spacing-x":[{"border-spacing-x":x()}],"border-spacing-y":[{"border-spacing-y":x()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",X,_]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",X,_]}],ease:[{ease:["linear","initial",y,X,_]}],delay:[{delay:[de,X,_]}],animate:[{animate:["none",g,X,_]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[m,X,_]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:we()}],"rotate-x":[{"rotate-x":we()}],"rotate-y":[{"rotate-y":we()}],"rotate-z":[{"rotate-z":we()}],scale:[{scale:Le()}],"scale-x":[{"scale-x":Le()}],"scale-y":[{"scale-y":Le()}],"scale-z":[{"scale-z":Le()}],"scale-3d":["scale-3d"],skew:[{skew:Ie()}],"skew-x":[{"skew-x":Ie()}],"skew-y":[{"skew-y":Ie()}],transform:[{transform:[X,_,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ze()}],"translate-x":[{"translate-x":ze()}],"translate-y":[{"translate-y":ze()}],"translate-z":[{"translate-z":ze()}],"translate-none":["translate-none"],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"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":x()}],"scroll-mx":[{"scroll-mx":x()}],"scroll-my":[{"scroll-my":x()}],"scroll-ms":[{"scroll-ms":x()}],"scroll-me":[{"scroll-me":x()}],"scroll-mt":[{"scroll-mt":x()}],"scroll-mr":[{"scroll-mr":x()}],"scroll-mb":[{"scroll-mb":x()}],"scroll-ml":[{"scroll-ml":x()}],"scroll-p":[{"scroll-p":x()}],"scroll-px":[{"scroll-px":x()}],"scroll-py":[{"scroll-py":x()}],"scroll-ps":[{"scroll-ps":x()}],"scroll-pe":[{"scroll-pe":x()}],"scroll-pt":[{"scroll-pt":x()}],"scroll-pr":[{"scroll-pr":x()}],"scroll-pb":[{"scroll-pb":x()}],"scroll-pl":[{"scroll-pl":x()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",X,_]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[de,Hr,no,ql]}],stroke:[{stroke:["none",...F()]}],"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 Cf=sy(ky);function Oa(...e){return Cf(Ss(e))}var My=be.createContext({size:"default",variant:"default",spacing:0});function Na({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(sf,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Oa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(My.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var Py={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Pf=createSlice({name:"toolbar",initialState:Py,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:ea,setPenColor:ia,setStrokeWidth:qr,setFontSize:AE,setFontFamily:PE,setFontStyle:EE,setFontWeight:DE,setTextDecoration:RE,setTextColor:FE}=Pf.actions,Wl=Pf.reducer;var Ef=({onClose:e,onRecordingComplete:o})=>{let t=Ne(),[a,r]=useState(false),[n,i]=useState(null),[u,s]=useState(0),[c,p]=useState(null),[d,l]=useState(false),f=useRef(null),h=useRef([]),m=useRef(null),v=useRef(null),y=useRef(null);useEffect(()=>((async()=>{try{let C=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});p(C),l(!0),y.current&&(y.current.srcObject=C);}catch(C){console.error("Error accessing camera:",C),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{m.current&&clearInterval(m.current),c&&c.getTracks().forEach(C=>C.stop());}),[]);let g=()=>{c&&(c.getTracks().forEach(x=>x.stop()),p(null),l(false));},b=async()=>{try{let x=null,C=null;try{x=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(O){console.error("Error accessing camera for recording:",O),alert("Failed to access camera for recording.");return}try{C=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(O){console.warn("Microphone access denied:",O);}let M=[...x.getVideoTracks()];C&&M.push(...C.getAudioTracks());let P=new MediaStream(M),R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8");let W=new MediaRecorder(P,{mimeType:R,videoBitsPerSecond:25e5});f.current=W,h.current=[],W.ondataavailable=O=>{O.data.size>0&&h.current.push(O.data);},W.onstop=()=>{let O=new Blob(h.current,{type:R}),U=document.createElement("video");U.src=URL.createObjectURL(O),U.muted=!0,U.currentTime=.1,U.onseeked=()=>{let N=document.createElement("canvas");N.width=U.videoWidth,N.height=U.videoHeight;let q=N.getContext("2d");q&&(q.drawImage(U,0,0),v.current=N.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(U.src);},P.getTracks().forEach(N=>N.stop()),x&&x.getTracks().forEach(N=>N.stop()),C&&C.getTracks().forEach(N=>N.stop()),m.current&&clearInterval(m.current),i(O),g();},W.onerror=O=>{console.error("MediaRecorder error:",O);},W.start(1e3),r(!0),s(0),m.current=setInterval(()=>{s(O=>O+1);},1e3);}catch(x){console.error("Error starting camera recording:",x),alert("Failed to start recording. Please check permissions.");}},w=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),r(false));},I=()=>{if(n){let x=URL.createObjectURL(n),C=document.createElement("a");C.href=x,C.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(x);}},k=x=>{let C=Math.floor(x/60),M=x%60;return `${C.toString().padStart(2,"0")}:${M.toString().padStart(2,"0")}`};if(!t)return null;let S=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:x=>{x.target===x.currentTarget&&e(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:x=>x.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!n&&jsxs(Fragment,{children:[jsx("video",{ref:y,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:b,disabled:!d,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!d&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:w,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:k(u)})]})]})]}),n&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(n),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: ",k(u)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{i(null),s(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&n&&v.current&&(o(n,v.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(S,t)};var la=40,Rf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,i]=useState(t?.order||"sequential"),[u,s]=useState(false),c=useRef(null),p=Ne(),d=useRef(null);useEffect(()=>{let b=w=>{w.key==="Escape"&&o();};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[o]);let l=b=>{let w=b.target.files;if(!w||w.length===0)return;let I=la-a.length;if(I<=0){alert(`You can only upload a maximum of ${la} images`);return}let k=Array.from(w).slice(0,I);k.length<w.length&&alert(`Only ${I} more images can be added (max ${la} total)`);let S=k.map(x=>new Promise((C,M)=>{let P=new FileReader;P.onload=R=>{R.target?.result?C(R.target.result):M(new Error("Failed to read file"));},P.onerror=M,P.readAsDataURL(x);}));Promise.all(S).then(x=>{r(C=>[...C,...x]),d.current&&(d.current.value="");});},f=b=>{b.preventDefault(),s(false);let w=Array.from(b.dataTransfer.files).filter(x=>x.type.startsWith("image/"));if(w.length===0)return;let I=la-a.length;if(I<=0){alert(`You can only upload a maximum of ${la} images`);return}let k=w.slice(0,I);k.length<w.length&&alert(`Only ${I} more images can be added (max ${la} total)`);let S=k.map(x=>new Promise((C,M)=>{let P=new FileReader;P.onload=R=>{R.target?.result?C(R.target.result):M(new Error("Failed to read file"));},P.onerror=M,P.readAsDataURL(x);}));Promise.all(S).then(x=>{r(C=>[...C,...x]);});},h=b=>{b.preventDefault(),s(true);},m=()=>{s(false);},v=b=>{r(w=>w.filter((I,k)=>k!==b));},y=b=>{if(b.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,n,t?.id);};if(!p)return null;let g=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:b=>{b.target===b.currentTarget&&o(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{ref:c,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:b=>b.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$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:y,className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=la?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",la," images"]}):jsxs("span",{children:[a.length,"/",la," images"]})})]}),jsx("input",{ref:d,type:"file",accept:"image/*",multiple:true,onChange:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:f,onDragOver:h,onDragLeave:m,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>i("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>i("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((b,w)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:b,alt:`Flashcard ${w+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>v(w),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:w+1})]},w))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(g,p)};var Cs={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},jy={enabled:true};function Gl(e){return e?{tools:{...Cs.tools,...e.tools},actions:{...Cs.actions,...e.actions}}:Cs}var _y={tools:{select:true,pen:false,style:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Xy={tools:{select:true,pen:true,style:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};function jl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Ff(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 Of(e){let[o,t]=be.useState(void 0);return Uo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let n=r[0],i,u;if("borderBoxSize"in n){let s=n.borderBoxSize,c=Array.isArray(s)?s[0]:s;i=c.inlineSize,u=c.blockSize;}else i=e.offsetWidth,u=e.offsetHeight;t({width:i,height:u});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var Nf=["PageUp","PageDown"],Hf=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],qf={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},_o="Slider",[_l,Yy,Zy]=bs(_o),[Vf]=Ra(_o,[Zy]),[Jy,Ts]=Vf(_o),Uf=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:i="horizontal",disabled:u=false,minStepsBetweenThumbs:s=0,defaultValue:c=[a],value:p,onValueChange:d=()=>{},onValueCommit:l=()=>{},inverted:f=false,form:h,...m}=e,v=be.useRef(new Set),y=be.useRef(0),b=i==="horizontal"?Qy:ew,[w=[],I]=na({prop:p,defaultProp:c,onChange:P=>{[...v.current][y.current]?.focus(),d(P);}}),k=be.useRef(w);function S(P){let R=nw(w,P);M(P,R);}function x(P){M(P,y.current);}function C(){let P=k.current[y.current];w[y.current]!==P&&l(w);}function M(P,R,{commit:W}={commit:false}){let O=dw(n),U=uw(Math.round((P-a)/n)*n+a,O),N=jl(U,[a,r]);I((q=[])=>{let F=ow(q,N,R);if(lw(F,s*n)){y.current=F.indexOf(N);let z=String(F)!==String(q);return z&&W&&l(F),z?F:q}else return q});}return jsx(Jy,{scope:e.__scopeSlider,name:t,disabled:u,min:a,max:r,valueIndexToChangeRef:y,thumbs:v.current,values:w,orientation:i,form:h,children:jsx(_l.Provider,{scope:e.__scopeSlider,children:jsx(_l.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":u,"data-disabled":u?"":void 0,...m,ref:o,onPointerDown:Qe(m.onPointerDown,()=>{u||(k.current=w);}),min:a,max:r,inverted:f,onSlideStart:u?void 0:S,onSlideMove:u?void 0:x,onSlideEnd:u?void 0:C,onHomeKeyDown:()=>!u&&M(a,0,{commit:true}),onEndKeyDown:()=>!u&&M(r,w.length-1,{commit:true}),onStepKeyDown:({event:P,direction:R})=>{if(!u){let U=Nf.includes(P.key)||P.shiftKey&&Hf.includes(P.key)?10:1,N=y.current,q=w[N],F=n*U*R;M(q+F,N,{commit:true});}}})})})})});Uf.displayName=_o;var[Wf,zf]=Vf(_o,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Qy=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:i,onSlideMove:u,onSlideEnd:s,onStepKeyDown:c,...p}=e,[d,l]=be.useState(null),f=qt(o,b=>l(b)),h=be.useRef(void 0),m=zo(r),v=m==="ltr",y=v&&!n||!v&&n;function g(b){let w=h.current||d.getBoundingClientRect(),I=[0,w.width],S=Yl(I,y?[t,a]:[a,t]);return h.current=w,S(b-w.left)}return jsx(Wf,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx(Kf,{dir:m,"data-orientation":"horizontal",...p,ref:f,style:{...p.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let w=g(b.clientX);i?.(w);},onSlideMove:b=>{let w=g(b.clientX);u?.(w);},onSlideEnd:()=>{h.current=void 0,s?.();},onStepKeyDown:b=>{let I=qf[y?"from-left":"from-right"].includes(b.key);c?.({event:b,direction:I?-1:1});}})})}),ew=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:i,onSlideEnd:u,onStepKeyDown:s,...c}=e,p=be.useRef(null),d=qt(o,p),l=be.useRef(void 0),f=!r;function h(m){let v=l.current||p.current.getBoundingClientRect(),y=[0,v.height],b=Yl(y,f?[a,t]:[t,a]);return l.current=v,b(m-v.top)}return jsx(Wf,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(Kf,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:m=>{let v=h(m.clientY);n?.(v);},onSlideMove:m=>{let v=h(m.clientY);i?.(v);},onSlideEnd:()=>{l.current=void 0,u?.();},onStepKeyDown:m=>{let y=qf[f?"from-bottom":"from-top"].includes(m.key);s?.({event:m,direction:y?-1:1});}})})}),Kf=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:i,onEndKeyDown:u,onStepKeyDown:s,...c}=e,p=Ts(_o,t);return jsx(ht.span,{...c,ref:o,onKeyDown:Qe(e.onKeyDown,d=>{d.key==="Home"?(i(d),d.preventDefault()):d.key==="End"?(u(d),d.preventDefault()):Nf.concat(Hf).includes(d.key)&&(s(d),d.preventDefault());}),onPointerDown:Qe(e.onPointerDown,d=>{let l=d.target;l.setPointerCapture(d.pointerId),d.preventDefault(),p.thumbs.has(l)?l.focus():a(d);}),onPointerMove:Qe(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d);}),onPointerUp:Qe(e.onPointerUp,d=>{let l=d.target;l.hasPointerCapture(d.pointerId)&&(l.releasePointerCapture(d.pointerId),n(d));})})}),Gf="SliderTrack",jf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=Ts(Gf,t);return jsx(ht.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});jf.displayName=Gf;var Xl="SliderRange",_f=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=Ts(Xl,t),n=zf(Xl,t),i=be.useRef(null),u=qt(o,i),s=r.values.length,c=r.values.map(l=>Yf(l,r.min,r.max)),p=s>1?Math.min(...c):0,d=100-Math.max(...c);return jsx(ht.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:u,style:{...e.style,[n.startEdge]:p+"%",[n.endEdge]:d+"%"}})});_f.displayName=Xl;var $l="SliderThumb",Xf=be.forwardRef((e,o)=>{let t=Yy(e.__scopeSlider),[a,r]=be.useState(null),n=qt(o,u=>r(u)),i=be.useMemo(()=>a?t().findIndex(u=>u.ref.current===a):-1,[t,a]);return jsx(tw,{...e,ref:n,index:i})}),tw=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,i=Ts($l,t),u=zf($l,t),[s,c]=be.useState(null),p=qt(o,g=>c(g)),d=s?i.form||!!s.closest("form"):true,l=Of(s),f=i.values[a],h=f===void 0?0:Yf(f,i.min,i.max),m=rw(a,i.values.length),v=l?.[u.size],y=v?sw(v,h,u.direction):0;return be.useEffect(()=>{if(s)return i.thumbs.add(s),()=>{i.thumbs.delete(s);}},[s,i.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[u.startEdge]:`calc(${h}% + ${y}px)`},children:[jsx(_l.ItemSlot,{scope:e.__scopeSlider,children:jsx(ht.span,{role:"slider","aria-label":e["aria-label"]||m,"aria-valuemin":i.min,"aria-valuenow":f,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...n,ref:p,style:f===void 0?{display:"none"}:e.style,onFocus:Qe(e.onFocus,()=>{i.valueIndexToChangeRef.current=a;})})}),d&&jsx($f,{name:r??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:f},a)]})});Xf.displayName=$l;var aw="RadioBubbleInput",$f=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),n=qt(r,a),i=Ff(o);return be.useEffect(()=>{let u=r.current;if(!u)return;let s=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(s,"value").set;if(i!==o&&p){let d=new Event("input",{bubbles:true});p.call(u,o),u.dispatchEvent(d);}},[i,o]),jsx(ht.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});$f.displayName=aw;function ow(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function Yf(e,o,t){let n=100/(t-o)*(e-o);return jl(n,[0,100])}function rw(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function nw(e,o){if(e.length===1)return 0;let t=e.map(r=>Math.abs(r-o)),a=Math.min(...t);return t.indexOf(a)}function sw(e,o,t){let a=e/2,n=Yl([0,50],[0,a]);return (a-n(o)*t)*t}function iw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function lw(e,o){if(o>0){let t=iw(e);return Math.min(...t)>=o}return true}function Yl(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 dw(e){return (String(e).split(".")[1]||"").length}function uw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Zf=Uf,Jf=jf,Qf=_f,em=Xf;function Ms({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:i,thumbClassName:u,...s}){let c=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(Zf,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Oa("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),...s,children:[jsx(Jf,{"data-slot":"slider-track",className:Oa("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",i),children:jsx(Qf,{"data-slot":"slider-range",className:Oa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:c.length},(p,d)=>jsx(em,{"data-slot":"slider-thumb",className:Oa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",u)},d))]})}var Hw=({onScreenRecord:e,stageRef:o,onTextAdded:t,config:a}={})=>{let r=xe(),n=te(A=>A.canvas.slides.find(ee=>ee.id===A.canvas.currentSlideId)),i=n?.videos||[],u=n?.editingFlashcard,s=te(A=>A.toolbar.selectedTool),c=te(A=>A.toolbar.penColor),p=te(A=>A.toolbar.strokeWidth),d=n?.showMcqForm,l=n?.showFlashcardForm,f=useRef(null);useEffect(()=>{let A=ee=>{(ee.ctrlKey||ee.metaKey)&&ee.key==="z"&&!ee.shiftKey&&(ee.preventDefault(),r(Bn())),(ee.ctrlKey&&ee.shiftKey&&ee.key==="Z"||ee.ctrlKey&&ee.key==="y")&&(ee.preventDefault(),r(On()));};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A);}},[r]);let h=useMemo(()=>Gl(a),[a]),{tools:m,actions:v}=h,y=i.some(A=>A.isRecorded&&A.isPlaying),g=te(A=>A.toolbar.fontSize),b=te(A=>A.toolbar.fontFamily),w=te(A=>A.toolbar.fontStyle),I=te(A=>A.toolbar.fontWeight),k=te(A=>A.toolbar.textDecoration),S=te(A=>A.toolbar.textColor),[x,C]=useState(false),[M,P]=useState(false),[R,W]=useState(false),[O,U]=useState(false),[N,q]=useState(false),[F,z]=useState(false),[$,re]=useState(false),[V,j]=useState(false),[Y,Z]=useState(true),oe=useRef(null),J=useRef(null),fe=[{name:"black",value:"#2D2F50"},{name:"blue",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"green",value:"#60C75E"},{name:"yellow",value:"#FFE056"}],we=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"style",icon:Palette,label:"Style",configKey:"style"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),Le=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"}],[]),Ie=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"}],[]),ze=useMemo(()=>we.filter(A=>{let ee=m[A.configKey];return typeof ee=="boolean"?ee:Array.isArray(ee)?ee.length>0:true}),[m,we]),Mt=useMemo(()=>{let A=m.shapes;return A===false?[]:A===true?Le:Array.isArray(A)?Le.filter(ee=>A.includes(ee.name)):Le},[m.shapes,Le]),At=useMemo(()=>{let A=m.activities;return A===false?[]:A===true?Ie:Array.isArray(A)?Ie.filter(ee=>A.includes(ee.name)):Ie},[m.activities,Ie]),ma=useMemo(()=>{let A=m.media;return A===false?{photoFrame:false,image:false,video:false}:A===true?{photoFrame:true,image:true,video:true}:Array.isArray(A)?{photoFrame:A.includes("photo-frame"),image:A.includes("image"),video:A.includes("video")}:{photoFrame:true,image:true,video:true}},[m.media]),se=useMemo(()=>{let A=m.activities;return A===false?false:A===true?true:Array.isArray(A)?A.includes("flashcard"):true},[m.activities]),Gr=A=>{let ee=A.target.files;!ee||ee.length===0||(r(ea("select")),r(vt(false)),U(false),Array.from(ee).forEach(Te=>{let ve=new FileReader;ve.onload=ie=>{let le=new window.Image;le.src=ie.target?.result,le.onload=()=>{let Be=le.width/le.height,it=300,aa=300,$e=le.width,Ee=le.height;$e>it&&($e=it,Ee=$e/Be),Ee>aa&&(Ee=aa,$e=Ee*Be),r(ue());let tt=800-$e/2,xt=450-Ee/2;r(ai({id:v4(),src:le.src,x:tt,y:xt,width:$e,height:Ee,draggable:true,rotation:0}));};},ve.readAsDataURL(Te);}),A.target.value="");},jr=async A=>{let ee=A.target.files;if(!(!ee||ee.length===0)){console.log("files",A),r(ea("select")),r(vt(false)),U(false);for(let Te of Array.from(ee))try{let ve=URL.createObjectURL(Te),ie=document.createElement("video");console.log("video",ie),ie.src=ve,ie.muted=!0,ie.playsInline=!0,ie.preload="auto",ie.load(),await new Promise((Ut,Wt)=>{let ne=setTimeout(()=>Wt(new Error("Metadata load timeout")),1e4);ie.onloadedmetadata=()=>{clearTimeout(ne),Ut();},ie.onerror=()=>{clearTimeout(ne),Wt(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ie.duration,width:ie.videoWidth,height:ie.videoHeight}),await new Promise((Ut,Wt)=>{let ne=setTimeout(()=>Wt(new Error("Video load timeout")),1e4);ie.readyState>=2?(clearTimeout(ne),Ut()):ie.onloadeddata=()=>{clearTimeout(ne),Ut();};});let le=Math.min(.8,ie.duration/2);console.log("Seeking to:",le),ie.currentTime=le,await new Promise(Ut=>{let Wt=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ut();},5e3);ie.onseeked=()=>{clearTimeout(Wt),console.log("Seek completed"),Ut();};});let Be=document.createElement("canvas"),it=ie.videoWidth/ie.videoHeight,aa=400,$e=400,Ee=ie.videoWidth,tt=ie.videoHeight;Ee>aa&&(Ee=aa,tt=Ee/it),tt>$e&&(tt=$e,Ee=tt*it),Be.width=Ee,Be.height=tt;let xt=Be.getContext("2d",{willReadFrequently:!1});if(!xt)throw new Error("Failed to get canvas context");if(await new Promise(Ut=>setTimeout(Ut,100)),ie.videoWidth===0||ie.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ee,height:tt}),xt.drawImage(ie,0,0,Ee,tt);let ga=Be.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",ga.length),r(ue());let Ws=800-Ee/2,zs=450-tt/2,Jr=v4();await ao(Jr,Te,ga),r(ln({id:Jr,objectUrl:ve,thumbnailDataUrl:ga,videoBlob:Te,x:Ws,y:zs,width:Ee,height:tt,draggable:!0,isPlaying:!1,rotation:0})),ie.src="",ie.load(),console.log(`Video uploaded: ${Te.name}`);}catch(ve){console.error("Error processing video:",ve),alert(`Failed to process video: ${Te.name}`);}A.target.value="";}},_r=(A,ee,Te)=>{r(ue()),r(ea("select")),r(vt(false));let ve=300,ie=300,le=800-ve/2,Be=450-ie/2;r(Te?go({id:Te,images:A,order:ee,x:le,y:Be,width:ve,height:ie,rotation:0,draggable:true}):ni({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:A,currentIndex:0,order:ee,x:le,y:Be,width:ve,height:ie,rotation:0,draggable:true})),r(za(false));},Xr=()=>{r(ue()),r(ea("select")),r(vt(false));let A=400,ee=300,Te=800-A/2,ve=450-ee/2;r(li({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Te,y:ve,width:A,height:ee,rotation:0,draggable:true,isCapturing:false})),U(false);},$r=A=>{let le={};switch(A.name){case "circle":case "ring":case "wedge":case "arc":le.radius=50,(A.name==="ring"||A.name==="arc")&&(le.innerRadius=25,le.outerRadius=50),(A.name==="wedge"||A.name==="arc")&&(le.angle=A.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],A.name==="arrow"&&(le.pointerLength=10,le.pointerWidth=10);break}let Be={id:`shape-${Date.now()}`,type:A.name,x:750,y:400,width:100,height:100,rotation:0,color:c,...le};r(ue()),r(vt(false)),r(ea(A.name)),r(oi(Be)),W(false);},pa=A=>{if(r(ea(A)),A==="select")r(vt(false));else if(A==="text"){r(vt(false)),r(ue());let ee=200,Te=50,ve=800-ee/2,ie=450-Te/2,Be=window.innerWidth<768?Math.max(g,32):g,it=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(ri({id:it,text:"",x:ve,y:ie,width:ee,height:Te,rotation:0,draggable:true,fontSize:Be,fontFamily:b,fontStyle:w,fontWeight:I,textDecoration:k,fill:S,align:"left"})),setTimeout(()=>{r(sr(it));},100),t&&t(it);}else r(vt(true));},Bs=()=>{r(Ii()),r(vt(false));},Os=()=>{e?e():o?C(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Ns=()=>{P(true);},Hs=[{key:"photoFrame",title:"Photo frame",icon:CameraPlus,onClick:Xr,enabled:ma.photoFrame},{key:"image",title:"Image",icon:Image$2,onClick:()=>oe.current?.click(),enabled:ma.image},{key:"video",title:"Video",icon:MonitorPlay,onClick:()=>J.current?.click(),enabled:ma.video}],Yr=[{key:"undo",title:"Undo",icon:ArrowCounterClockwise,onClick:()=>r(Bn()),enabled:v.undo,iconWeight:"bold",colorClass:"text-primary"},{key:"redo",title:"Redo",icon:ArrowClockwise,onClick:()=>r(On()),enabled:v.redo,iconWeight:"bold",colorClass:"text-primary"},{key:"screenRecord",title:"Screen Record",icon:Record,onClick:Os,enabled:v.screenRecord,iconWeight:"fill",colorClass:"text-[#6279F8]"},{key:"cameraRecord",title:"Camera Record",icon:Camera,onClick:Ns,enabled:v.cameraRecord,iconWeight:"fill",colorClass:"text-[#6BBB93]"},{key:"clear",title:"Clear",icon:Trash,onClick:Bs,enabled:v.clear,iconWeight:"fill",colorClass:"text-[#E92222]"}],ha=async(A,ee)=>{try{r(ea("select")),r(vt(!1));let Te=URL.createObjectURL(A),ve=document.createElement("video");ve.src=Te,ve.muted=!0,ve.playsInline=!0,ve.preload="auto",await new Promise((tt,xt)=>{let ga=setTimeout(()=>xt(new Error("Metadata load timeout")),1e4);ve.onloadedmetadata=()=>{clearTimeout(ga),tt();},ve.onerror=()=>{clearTimeout(ga),xt(new Error("Failed to load video"));};});let ie=640,le=ve.videoWidth/ve.videoHeight,Be=ie,it=Be/le;r(ue());let aa=800-Be/2,$e=450-it/2,Ee=v4();await ao(Ee,A,ee),r(ln({id:Ee,objectUrl:Te,thumbnailDataUrl:ee,videoBlob:A,x:aa,y:$e,width:Be,height:it,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),C(!1),P(!1);}catch(Te){console.error("Error adding recorded video to canvas:",Te),alert("Failed to add video to canvas. Please try again.");}},qs=A=>{r(ea("select")),r(vt(false)),r(rr(null)),A&&r(bi(A)),r(ya(!d));},Vs=()=>{r(er(null)),r(za(true)),q(false);},uo=()=>{W(!R);},Zr=()=>{U(!O);},Us=()=>{q(!N);},Yo=()=>{z(!F);},co=()=>{Z(A=>{let ee=!A;return ee||(W(false),U(false),q(false),z(false),j(false),re(false)),ee});};return useEffect(()=>{if(!V)return;let A=ee=>{f.current&&!f.current.contains(ee.target)&&j(false);};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("mousedown",A);}},[V]),y?null:jsxs("div",{className:"fixed top-[90px] right-0 bottom-0 z-40 items-start md:flex",children:[jsx("button",{type:"button",onClick:co,className:"fixed top-[100px] left-4 z-40 cursor-pointer rounded-md border bg-white p-4 shadow-xl xl:p-5",title:Y?"Hide toolbar":"Show toolbar",children:jsx(List,{weight:"bold",className:"text-primary text-lg md:text-xl"})}),Y&&jsxs("div",{className:"fixed top-[168px] left-4 z-50 flex flex-col gap-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(Na,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:ze.map((A,ee)=>jsx("div",{title:A.label,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.name===s?"bg-primary/10":A.name==="style"?"md:hidden":""}`,onClick:()=>{A.name==="image"?(Zr(),W(false),q(false),z(false),pa(A.name)):A.name==="shapes"?(uo(),U(false),q(false),z(false),pa(A.name)):A.name==="activities"?(pa(A.name),Us(),W(false),U(false),z(false)):A.name==="style"?(Yo(),W(false),U(false),q(false),pa(A.name)):(pa(A.name),W(false),U(false),q(false),z(false));},children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ee))}),R&&jsx(Na,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-2 shadow-xl",children:Mt.map((A,ee)=>jsx("div",{title:A.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>$r(A),children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg md:text-xl"})},ee))}),O&&jsx(Na,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 border bg-white p-2 shadow-2xl",children:Hs.filter(A=>A.enabled).map(A=>jsx("div",{title:A.title,onClick:A.onClick,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},A.key))}),N&&jsxs(Na,{type:"single",className:"mx-1 mt-auto mb-10 grid grid-cols-2 gap-2 border bg-white p-2 shadow-2xl lg:mb-11",children:[se&&jsx("div",{title:"Flashcard",onClick:()=>Vs(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-lg lg:text-xl"})}),At.map((A,ee)=>jsx("div",{title:A.label,onClick:()=>qs(A.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(A.icon,{weight:"fill",className:"text-primary text-lg lg:text-xl"})},ee))]}),F&&jsxs("div",{className:"mx-1 flex flex-col gap-4 rounded-md border bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-gray-800"}),jsx(Ms,{value:[p],onValueChange:A=>{r(qr(A[0]));},max:28,min:6,step:1,className:"w-28",rangeClassName:"bg-gray-300",thumbClassName:"bg-gray-600 border-none h-4 w-4"}),jsx("div",{className:"h-5 w-5 rounded-full bg-gray-800"})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"COLOR"}),jsxs("div",{className:"flex flex-wrap gap-1",children:[fe.map(A=>jsx("button",{className:`h-6 w-6 rounded-full border-2 transition-all hover:scale-110 ${c===A.value?"ring-2 ring-gray-400 ring-offset-1":"border-gray-300"}`,style:{backgroundColor:A.value},onClick:()=>{r(ia(A.value)),z(false);},title:A.name},A.value)),jsxs("label",{className:"relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 bg-white transition-all hover:scale-110",children:[jsx("input",{type:"color",value:c,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>r(ia(A.target.value))}),jsx(Plus,{size:16,className:"text-gray-600",weight:"bold"})]})]})]}),jsx("div",{className:"h-px bg-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("p",{className:"text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsxs("label",{className:"relative flex h-8 cursor-pointer items-center justify-center rounded-md border-2 border-gray-300 bg-white transition-all hover:border-gray-400",children:[jsx("input",{type:"color",value:c,className:"absolute inset-0 cursor-pointer opacity-0",onChange:A=>{r(Qo(A.target.value)),z(false);}}),jsxs("div",{className:"flex items-center gap-2 px-3",children:[jsx(Plus,{}),jsx("span",{className:"text-xs font-medium text-gray-600",children:"Pick Color"})]})]})]})]})]}),Yr.some(A=>A.enabled)&&jsx(Na,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:Yr.filter(A=>A.enabled).map(A=>jsx("button",{onClick:A.onClick,className:`hover:bg-primary/10 cursor-pointer rounded-md p-3 xl:p-4 ${A.colorClass}`,title:A.title,children:jsx(A.icon,{weight:A.iconWeight,className:"text-primary text-lg md:text-xl"})},A.key))})]}),jsx("input",{ref:oe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:Gr}),jsx("input",{ref:J,type:"file",accept:"video/*",className:"hidden",onChange:jr}),!e&&x&&o&&jsx(hr,{onClose:()=>C(false),stageRef:o,onRecordingComplete:ha}),M&&jsx(Ef,{onClose:()=>P(false),onRecordingComplete:ha}),l&&jsx(Rf,{editingFlashcard:u,onConfirm:_r,onCancel:()=>r(za(false))}),$&&jsx(jn,{defaultColor:c,onConfirm:A=>{r(ia(A)),re(false);},onCancel:()=>re(false)})]})},qw=Hw;var ad=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let r=at(bo),n=at(Mi),i=a?n:r,u=at(ir),p=(at(g=>g.canvas.slides.find(b=>b.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[d,l]=useState(false),[f,h]=useState(null),[m,v]=useState(null),y=async()=>{if(r.length===0){v({type:"error",message:"No slides to publish"});return}if(!e){v({type:"error",message:"No publish handler provided"});return}l(true),v(null);try{let g=await e(i,u,b=>{h(b);});console.log(g," ",i," ",u),g.success?v({type:"success",message:g.message}):v({type:"error",message:g.message});}catch(g){v({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{h(null),v(null);},3e3);}};return p?null:jsxs("button",{onClick:y,disabled:d||r.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 Kw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:r,onDescriptionChange:n,showPublishButton:i=true,showBackButton:u=true,editableTitle:s=true,editableDescription:c=true,className:p="",rightContent:d,leftContent:l,includeInactiveSlides:f=false})=>{let h=ut(),m=at(ir),v=at(Pi),y=e??(v?m.title:"")??"Untitled",g=o??(v?m.description:"")??"Add a description...",[b,w]=useState(false),[I,k]=useState(false),[S,x]=useState(y),[C,M]=useState(g),P=useRef(null),R=useRef(null);useEffect(()=>{x(y);},[y]),useEffect(()=>{M(g);},[g]),useEffect(()=>{b&&P.current&&(P.current.focus(),P.current.select());},[b]),useEffect(()=>{I&&R.current&&(R.current.focus(),R.current.select());},[I]);let W=()=>{s&&w(true);},O=()=>{c&&k(true);},U=()=>{w(false),S.trim()&&S!==y?r?r(S.trim()):h(Ci(S.trim())):S.trim()||x(y);},N=()=>{k(false),C.trim()&&C!==g?n?n(C.trim()):h(ki(C.trim())):C.trim()||M(g);},q=z=>{z.key==="Enter"?U():z.key==="Escape"&&(x(y),w(false));},F=z=>{z.key==="Enter"?N():z.key==="Escape"&&(M(g),k(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${p}`,children:[l||jsxs("div",{className:"flex items-center gap-4",children:[u&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[b?jsx("input",{ref:P,type:"text",value:S,onChange:z=>x(z.target.value),onBlur:U,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:W,title:S,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${s?"hover:border-primary cursor-text":""}`,children:S}),I?jsx("input",{ref:R,type:"text",value:C,onChange:z=>M(z.target.value),onBlur:N,onKeyDown:F,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:O,title:C,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${c?"hover:border-primary cursor-text":""}`,children:C})]})]}),d||i&&a&&jsx(ad,{onPublish:a,includeInactiveSlides:f})]})};var Yw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Zw=({colors:e=Yw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let[n,i]=useState(true),u=te(he),s=te(l=>l.toolbar.penColor),c=te(l=>l.toolbar.strokeWidth),p=u?.backgroundColor,d=xe();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:n?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-16 left-1/2 z-50 hidden w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-3 shadow-2xl md:bottom-6 md:flex md:p-5 2xl:px-8 2xl:py-6 ${r}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 rounded-full bg-black md:h-3 md:w-3"}),jsx(Ms,{defaultValue:[12],max:28,min:6,step:1,className:"w-16 md:w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",value:[c],onValueChange:l=>d(qr(l[0]))}),jsx("div",{className:"h-5 w-5 rounded-full bg-black md:h-7 md:w-7 lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-sm font-semibold text-[#00000066] md:mb-4",children:"COLOR"}),jsxs(Na,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`hidden h-10 w-10 rounded-full border hover:cursor-pointer md:block lg:h-12 lg:w-12 ${s===l.value?"ring-2 ring-gray-400":""}`,style:{backgroundColor:l.value},onClick:()=>d(ia(l.value))},l.value)),jsx("button",{className:"h-8 w-8 rounded-full border bg-[#2D2F50] hover:cursor-pointer md:hidden",onClick:()=>d(ia("#2D2F50"))}),jsxs("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] md:h-10 md:w-10 lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(ia(l.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-2 text-xs font-semibold whitespace-nowrap text-[#00000066] md:mb-4 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] md:h-10 md:w-10 lg:h-12 lg:w-12",style:{backgroundColor:p},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>d(Qo(l.target.value))})})]})}),jsx("div",{className:"absolute -top-6 left-1/2 flex -translate-x-1/2 flex-col items-center justify-between px-2 md:-top-4",children:jsx("button",{onClick:()=>i(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{weight:"bold",className:"text-gray-600 md:text-xl"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>i(true),className:"fixed bottom-20 left-1/2 z-50 hidden -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl md:bottom-3 md:flex","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var im=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),rd=e=>{let o=Jw(e);return o.charAt(0).toUpperCase()+o.slice(1)},Ds=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),lm=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var dm={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 cm=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:i,...u},s)=>createElement("svg",{ref:s,...dm,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:Ds("lucide",r),...!n&&!lm(u)&&{"aria-hidden":"true"},...u},[...i.map(([c,p])=>createElement(c,p)),...Array.isArray(n)?n:[n]]));var Rs=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(cm,{ref:n,iconNode:o,className:Ds(`lucide-${im(rd(e))}`,`lucide-${e}`,a),...r}));return t.displayName=rd(e),t};var aS=[["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"}]],Wr=Rs("copy",aS);var oS=[["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"}]],zr=Rs("trash-2",oS);var mm=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:i})=>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:r,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:u=>{u.stopPropagation(),n();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Wr,{size:14})}),!a&&jsx("button",{onClick:u=>{u.stopPropagation(),i();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(zr,{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 iS=({softDelete:e=false})=>{let o=ut(),t=at(bo),a=at(xo),r=at(Ai),[n,i]=useState(true),c=(at(h=>h.canvas.slides.find(m=>m.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),p=()=>{r&&o(Ys());},d=h=>{o(Qs(h));},l=h=>{o(Js(h));},f=h=>{t.length>1&&o(Zs({id:h,softDelete:e}));};return c?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:n?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:()=>i(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((h,m)=>jsx(mm,{slide:h,index:m,isSelected:h.id===a,isSingleSlide:t.length===1,onSelect:()=>d(h.id),onDuplicate:()=>l(h.id),onDelete:()=>f(h.id)},h.id))}),jsxs("button",{onClick:p,disabled:!r,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${r?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!n&&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:()=>i(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 lS="SchooplaEditorDB",dS=1,Ha="slides",qa="metadata",nd="schoopla_current_slide_id",gm="presentation_metadata",Kr=()=>new Promise((e,o)=>{let t=indexedDB.open(lS,dS);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Ha)||r.createObjectStore(Ha,{keyPath:"id"}),r.objectStoreNames.contains(qa)||r.createObjectStore(qa,{keyPath:"id"});};}),sd=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Kr(),a=o.transaction([Ha],"readwrite").objectStore(Ha);await new Promise((r,n)=>{let i=a.clear();i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);});for(let r of e)await new Promise((n,i)=>{let u=a.add(r);u.onsuccess=()=>n(!0),u.onerror=()=>i(u.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},id=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Kr(),t=e.transaction([Ha],"readonly").objectStore(Ha);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let i=n.result;console.log("\u2705 Loaded from IndexedDB:",i.length,"slides"),i.length>0&&i[0].images&&console.log("First slide images:",i[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),a(i.length>0?i:null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},Fs=async()=>{try{let e=await Kr(),o=e.transaction([Ha,qa],"readwrite"),t=o.objectStore(Ha),a=o.objectStore(qa);await new Promise((r,n)=>{let i=t.clear();i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);}),await new Promise((r,n)=>{let i=a.clear();i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(nd),localStorage.removeItem("schoopla_presentation_metadata"),await Fc(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},ld=e=>{try{localStorage.setItem(nd,e);}catch(o){console.error("Error saving current slide ID:",o);}},dd=()=>{try{return localStorage.getItem(nd)}catch(e){return console.error("Error loading current slide ID:",e),null}},ud=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},cd=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await Kr(),a=o.transaction([qa],"readwrite").objectStore(qa);await new Promise((r,n)=>{let i=a.put({id:gm,...e});i.onsuccess=()=>r(!0),i.onerror=()=>n(i.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);}}},fd=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await Kr(),t=e.transaction([qa],"readonly").objectStore(qa);return new Promise((a,r)=>{let n=t.get(gm);n.onsuccess=()=>{e.close();let i=n.result;if(i){let{id:u,...s}=i;console.log("\u2705 Loaded presentation metadata:",s),a(s);}else console.log("No presentation metadata found"),a(null);},n.onerror=()=>{e.close(),r(n.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 uS=["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"],cS=["canvas/clearCanvas"],fS=["canvas/setPresentationTitle","canvas/setPresentationDescription"],mS=ud((e,o)=>{sd(e),ld(o);},500),pS=ud(e=>{cd(e);},500),hS=(e,o)=>{sd(e),ld(o);},md=false,xm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let n=t.payload;Al(n).catch(i=>{console.error("Error deleting video blob:",i);});}if(t.type==="canvas/deleteSlide"&&t.payload){let n=t.payload,u=e.getState().canvas.slides.find(s=>s.id===n);u&&u.videos&&u.videos.length>0&&u.videos.forEach(s=>{Al(s.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let n=t.payload,i=e.getState(),s=i.canvas.slides.find(c=>c.id===i.canvas.currentSlideId)?.videos.find(c=>c.id===n);s&&s.videoBlob&&setTimeout(()=>{let c=e.getState(),d=c.canvas.slides.find(l=>l.id===c.canvas.currentSlideId)?.videos.find(l=>l.id!==n&&l.x===s.x+20&&l.y===s.y+20);d&&s.videoBlob&&ao(d.id,s.videoBlob,d.thumbnailDataUrl).catch(l=>{console.error("Error saving duplicated video blob:",l);});},0);}let a=o(t),r=e.getState();if(r.canvas.viewerMode)return a;if(t.type&&cS.includes(t.type)){if(!md){md=true;try{let{slides:n,currentSlideId:i}=r.canvas;hS(n,i);}finally{setTimeout(()=>{md=false;},0);}}}else if(t.type&&uS.includes(t.type)){let{slides:n,currentSlideId:i}=r.canvas;mS(n,i);}else if(t.type&&fS.includes(t.type)){let{presentationMetadata:n}=r.canvas;pS(n);}return a});new QueryClient;var xS=configureStore({reducer:{toolbar:Wl,canvas:Ei},middleware:e=>e({serializableCheck:false}).concat(xm)}),bS=()=>configureStore({reducer:{toolbar:Wl,canvas:Ei},middleware:e=>e({serializableCheck:false})});var vS=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:n=`slide-${Date.now()}`}=o;try{let i=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:i,quality:a,pixelRatio:r}),s=document.createElement("a");s.download=`${n}.${t}`,s.href=u,document.body.appendChild(s),s.click(),document.body.removeChild(s);}catch(i){throw console.error("Error exporting slide:",i),new Error("Failed to export slide")}},yS=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((n,i)=>{try{let u=t==="png"?"image/png":"image/jpeg",s=e.toDataURL({mimeType:u,quality:a,pixelRatio:r});fetch(s).then(c=>c.blob()).then(c=>n(c)).catch(c=>i(c));}catch(u){i(u);}})},wS=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,n=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:n,quality:a,pixelRatio:r})};var SS=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let n=a*a+r*r,i=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/n)),u=o.x+i*a,s=o.y+i*r;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-s,2))},pd=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],n=e[e.length-1];for(let i=1;i<e.length-1;i++){let u=SS(e[i],r,n);u>t&&(t=u,a=i);}if(t>o){let i=pd(e.slice(0,a+1),o),u=pd(e.slice(a),o);return [...i.slice(0,-1),...u]}return [r,n]},LS=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},IS=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},vm=(e,o=1.5)=>{if(e.length<=4)return e;let t=LS(e),a=pd(t,o);return IS(a)},ym=(e,o=1.5)=>({...e,points:vm(e.points,o)}),CS=(e,o=1.5)=>e.map(t=>ym(t,o)),kS=(e,o)=>{let t=e.length/2,a=o.length/2,r=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${r}%`}};var TS=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var wm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((n,i)=>{let u=new Image;u.onload=()=>{let{width:s,height:c}=u;if(s>t||c>a){let h=s/c;s>c?(s=Math.min(s,t),c=s/h):(c=Math.min(c,a),s=c*h);}let p=document.createElement("canvas");p.width=s,p.height=c;let d=p.getContext("2d");if(!d){i(new Error("Failed to get canvas context"));return}d.drawImage(u,0,0,s,c);let l=TS(e),f=p.toDataURL(l,r);n(f);},u.onerror=i,u.src=e;})};var lo=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return a.buffer},Xo=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",MS=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,i=[],u=0;for(let s of e){let c=[],p=[],d=[];for(let l of s.images){let f=l.src;if(t&&f.startsWith("data:"))try{f=await wm(f,{maxWidth:a,maxHeight:r,quality:n});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=lo(f),m=Xo(f);u+=h.byteLength;let v={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,buffer:h,mimeType:m};if(l.audioData&&l.audioData.startsWith("data:")){let y=lo(l.audioData),g=Xo(l.audioData);u+=y.byteLength,v.audioBuffer=y,v.audioMimeType=g;}c.push(v);}}for(let l of s.videos){let f,h;if(l.videoBlob)f=await l.videoBlob.arrayBuffer(),h=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))f=lo(l.videoData),h=Xo(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}u+=f.byteLength;let m={id:l.id,thumbnailDataUrl:l.thumbnailDataUrl,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,isPlaying:l.isPlaying,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isRecorded:l.isRecorded,buffer:f,mimeType:h};if(l.audioData&&l.audioData.startsWith("data:")){let v=lo(l.audioData),y=Xo(l.audioData);u+=v.byteLength,m.audioBuffer=v,m.audioMimeType=y;}p.push(m);}for(let l of s.photoFrames){let f={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:l.draggable,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isCapturing:l.isCapturing};if(l.capturedImageUrl&&l.capturedImageUrl.startsWith("data:")){let h=lo(l.capturedImageUrl),m=Xo(l.capturedImageUrl);u+=h.byteLength,f.buffer=h,f.mimeType=m;}if(l.audioData&&l.audioData.startsWith("data:")){let h=lo(l.audioData),m=Xo(l.audioData);u+=h.byteLength,f.audioBuffer=h,f.audioMimeType=m;}d.push(f);}i.push({...s,images:c,videos:p,photoFrames:d});}return {slides:i,totalSize:u}},AS=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},PS=e=>{let o=new FormData,t=e.slides.map((a,r)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((n,i)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,mimeType:n.mimeType,fileKey:`slide_${r}_image_${i}`,audioFileKey:n.audioBuffer?`slide_${r}_image_${i}_audio`:void 0,audioMimeType:n.audioMimeType})),videos:a.videos.map((n,i)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,isPlaying:n.isPlaying,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isRecorded:n.isRecorded,mimeType:n.mimeType,fileKey:`slide_${r}_video_${i}`,thumbnailFileKey:`slide_${r}_video_${i}_thumbnail`,audioFileKey:n.audioBuffer?`slide_${r}_video_${i}_audio`:void 0,audioMimeType:n.audioMimeType})),photoFrames:a.photoFrames.map((n,i)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,draggable:n.draggable,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isCapturing:n.isCapturing,mimeType:n.mimeType,fileKey:n.buffer?`slide_${r}_photoframe_${i}`:void 0,audioFileKey:n.audioBuffer?`slide_${r}_photoframe_${i}_audio`:void 0,audioMimeType:n.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((n,i)=>{let u=new Blob([n.buffer],{type:n.mimeType}),s=`${n.id}.${$o(n.mimeType)}`;if(o.append(`slide_${r}_image_${i}`,u,s),n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),p=`${n.id}_audio.${$o(n.audioMimeType)}`;o.append(`slide_${r}_image_${i}_audio`,c,p);}}),a.videos.forEach((n,i)=>{let u=new Blob([n.buffer],{type:n.mimeType}),s=`${n.id}.${$o(n.mimeType)}`;if(o.append(`slide_${r}_video_${i}`,u,s),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let c=lo(n.thumbnailDataUrl),p=new Blob([c],{type:"image/jpeg"}),d=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${i}_thumbnail`,p,d);}if(n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),p=`${n.id}_audio.${$o(n.audioMimeType)}`;o.append(`slide_${r}_video_${i}_audio`,c,p);}}),a.photoFrames.forEach((n,i)=>{if(n.buffer&&n.mimeType){let u=new Blob([n.buffer],{type:n.mimeType}),s=`${n.id}.${$o(n.mimeType)}`;o.append(`slide_${r}_photoframe_${i}`,u,s);}if(n.audioBuffer&&n.audioMimeType){let u=new Blob([n.audioBuffer],{type:n.audioMimeType}),s=`${n.id}_audio.${$o(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${i}_audio`,u,s);}});}),o};var RS=()=>{let e=ut(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let r=await id(),n=dd(),i=await fd();if(r&&r.length>0){let u=await Rc(),s=r.map(p=>{if(p.videos&&p.videos.length>0){let d=p.videos.map(l=>{let f=u.get(l.id);if(f){let h=Bc(f.blob);return {...l,objectUrl:h,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return l});return {...p,videos:d}}return p}),c=n&&s.find(p=>p.id===n)?n:s[0].id;e(mo({slides:s,currentSlideId:c}));}e(i?Ti({title:i.title,description:i.description}):Nn(!0));}catch(r){console.error("Error loading persisted slides:",r),e(Nn(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||""})),Im=new WeakSet,Cm=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await ao(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},FS=()=>{let e=ut(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Im.has(a))return;Im.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:i=true}=a;if(i)try{await Fs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(c){console.error("Error clearing local data:",c);}let u=n&&r.find(c=>c.id===n)?n:r[0].id,s=Lm(r);e(mo({slides:s,currentSlideId:u})),await Cm(s);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:i=true}=a;if(i)try{await Fs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(c){console.error("Error clearing local data:",c);}let u=n&&r.find(c=>c.id===n)?n:r[0].id,s=Lm(r);e(mo({slides:s,currentSlideId:u})),await Cm(s);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
7
7
 
8
8
  lucide-react/dist/esm/shared/src/utils.js:
9
9
  lucide-react/dist/esm/defaultAttributes.js:
@@ -18,5 +18,5 @@ lucide-react/dist/esm/lucide-react.js:
18
18
  * This source code is licensed under the ISC license.
19
19
  * See the LICENSE file in the root directory of this source tree.
20
20
  *)
21
- */export{Xy as BASIC_EDITOR_TOOLBAR_CONFIG,Jw as BottomToolbar,Jb as Canvas,jy as DEFAULT_CONTEXT_MENU_CONFIG,Cs as DEFAULT_TOOLBAR_CONFIG,dg as EditorRoot,ad as PublishButton,hr as ScreenRecorder,lS as SlideNavigation,qw as Toolbar,Gw as TopNavBar,_y as VIEWER_TOOLBAR_CONFIG,xi as addFillInTheBlanks,ni as addFlashcard,ai as addImage,ui as addImageAnnotation,ti as addLine,gi as addLongAnswer,mi as addMultipleChoice,li as addPhotoFrame,fi as addPhotoFrameAnnotation,oi as addShape,hi as addShortAnswer,Ys as addSlide,ri as addText,pi as addTrueFalse,ln as addVideo,PS as arrayBufferToBase64,vi as bringToFront,Ii as clearCanvas,ip as clearImageAnnotations,Fs as clearLocalData,dp as clearPhotoFrameAnnotations,$s as createEmptySlide,vS as createViewerStore,Mn as deleteFillInTheBlanks,gn as deleteFlashcard,nn as deleteImage,Fn as deleteLineById,kn as deleteLongAnswer,yn as deleteMultipleChoice,bn as deletePhotoFrame,mn as deleteShape,In as deleteShortAnswer,Zs as deleteSlide,pn as deleteText,Sn as deleteTrueFalse,un as deleteVideo,An as duplicateFillInTheBlanks,xn as duplicateFlashcard,sn as duplicateImage,Li as duplicateLine,Tn as duplicateLongAnswer,wn as duplicateMultipleChoice,vn as duplicatePhotoFrame,fn as duplicateShape,Cn as duplicateShortAnswer,Js as duplicateSlide,hn as duplicateText,Ln as duplicateTrueFalse,cn as duplicateVideo,er as editFlashcard,up as editMultipleChoice,wS as exportSlideAsBlob,yS as exportSlideAsImage,Si as finalizeDrawing,TS as getCompressionStats,SS as getSlideDataURL,dd as loadCurrentSlideId,id as loadFromIndexedDB,Ti as loadPresentationMetadata,fd as loadPresentationMetadataFromDB,mo as loadSlides,Gl as mergeToolbarConfig,si as nextFlashcard,ES as prepareFormData,AS as prepareSlidesForPublishing,ii as previousFlashcard,On as redo,rn as removeLine,np as reorderSlides,cd as savePresentationMetadata,ue as saveToHistory,bo as selectAllSlides,Mi as selectAllSlidesIncludingInactive,Ai as selectCanAddSlide,he as selectCurrentSlide,xo as selectCurrentSlideId,Pi as selectMetadataLoaded,ir as selectPresentationMetadata,hp as selectSlideById,yi as sendToBack,bi as setActivityType,En as setAltText,Dn as setAudioData,Qo as setBackgroundColor,Qs as setCurrentSlide,rr as setEditingActivity,sr as setEditingTextId,fp as setLines,Pn as setLink,Nn as setMetadataLoaded,ia as setPenColor,ki as setPresentationDescription,Ci as setPresentationTitle,za as setShowFlashcardForm,ya as setShowMcqForm,vt as setSketchMode,qr as setStrokeWidth,ea as setTool,rp as setViewerMode,vm as simplifyFlatPoints,ym as simplifyLine,kS as simplifyLines,bS as store,di as toggleImageDrawingMode,wi as toggleLock,ci as togglePhotoFrameDrawingMode,pp as toggleSketchMode,Ua as toggleVideoPlaying,Bn as undo,nr as updateElementOrder,or as updateFillInTheBlanks,go as updateFlashcard,po as updateImage,sp as updateImageAnnotation,cp as updateLastLine,mp as updateLinePosition,Rn as updateLineTransform,ar as updateLongAnswer,ba as updateMultipleChoice,Wa as updatePhotoFrame,lp as updatePhotoFrameAnnotation,ho as updateShape,tr as updateShortAnswer,ei as updateSlideThumbnail,Dt as updateText,va as updateTrueFalse,dn as updateVideo,xe as useDispatch,BS as useInitialSlides,Ji as useModalPortal,te as useSelector,FS as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
+ */export{Xy as BASIC_EDITOR_TOOLBAR_CONFIG,Zw as BottomToolbar,Jb as Canvas,jy as DEFAULT_CONTEXT_MENU_CONFIG,Cs as DEFAULT_TOOLBAR_CONFIG,dg as EditorRoot,ad as PublishButton,hr as ScreenRecorder,iS as SlideNavigation,qw as Toolbar,Kw as TopNavBar,_y as VIEWER_TOOLBAR_CONFIG,xi as addFillInTheBlanks,ni as addFlashcard,ai as addImage,ui as addImageAnnotation,ti as addLine,gi as addLongAnswer,mi as addMultipleChoice,li as addPhotoFrame,fi as addPhotoFrameAnnotation,oi as addShape,hi as addShortAnswer,Ys as addSlide,ri as addText,pi as addTrueFalse,ln as addVideo,AS as arrayBufferToBase64,vi as bringToFront,Ii as clearCanvas,ip as clearImageAnnotations,Fs as clearLocalData,dp as clearPhotoFrameAnnotations,$s as createEmptySlide,bS as createViewerStore,Mn as deleteFillInTheBlanks,gn as deleteFlashcard,nn as deleteImage,Fn as deleteLineById,kn as deleteLongAnswer,yn as deleteMultipleChoice,bn as deletePhotoFrame,mn as deleteShape,In as deleteShortAnswer,Zs as deleteSlide,pn as deleteText,Sn as deleteTrueFalse,un as deleteVideo,An as duplicateFillInTheBlanks,xn as duplicateFlashcard,sn as duplicateImage,Li as duplicateLine,Tn as duplicateLongAnswer,wn as duplicateMultipleChoice,vn as duplicatePhotoFrame,fn as duplicateShape,Cn as duplicateShortAnswer,Js as duplicateSlide,hn as duplicateText,Ln as duplicateTrueFalse,cn as duplicateVideo,er as editFlashcard,up as editMultipleChoice,yS as exportSlideAsBlob,vS as exportSlideAsImage,Si as finalizeDrawing,kS as getCompressionStats,wS as getSlideDataURL,dd as loadCurrentSlideId,id as loadFromIndexedDB,Ti as loadPresentationMetadata,fd as loadPresentationMetadataFromDB,mo as loadSlides,Gl as mergeToolbarConfig,si as nextFlashcard,PS as prepareFormData,MS as prepareSlidesForPublishing,ii as previousFlashcard,On as redo,rn as removeLine,np as reorderSlides,cd as savePresentationMetadata,ue as saveToHistory,bo as selectAllSlides,Mi as selectAllSlidesIncludingInactive,Ai as selectCanAddSlide,he as selectCurrentSlide,xo as selectCurrentSlideId,Pi as selectMetadataLoaded,ir as selectPresentationMetadata,hp as selectSlideById,yi as sendToBack,bi as setActivityType,En as setAltText,Dn as setAudioData,Qo as setBackgroundColor,Qs as setCurrentSlide,rr as setEditingActivity,sr as setEditingTextId,fp as setLines,Pn as setLink,Nn as setMetadataLoaded,ia as setPenColor,ki as setPresentationDescription,Ci as setPresentationTitle,za as setShowFlashcardForm,ya as setShowMcqForm,vt as setSketchMode,qr as setStrokeWidth,ea as setTool,rp as setViewerMode,vm as simplifyFlatPoints,ym as simplifyLine,CS as simplifyLines,xS as store,di as toggleImageDrawingMode,wi as toggleLock,ci as togglePhotoFrameDrawingMode,pp as toggleSketchMode,Ua as toggleVideoPlaying,Bn as undo,nr as updateElementOrder,or as updateFillInTheBlanks,go as updateFlashcard,po as updateImage,sp as updateImageAnnotation,cp as updateLastLine,mp as updateLinePosition,Rn as updateLineTransform,ar as updateLongAnswer,ba as updateMultipleChoice,Wa as updatePhotoFrame,lp as updatePhotoFrameAnnotation,ho as updateShape,tr as updateShortAnswer,ei as updateSlideThumbnail,Dt as updateText,va as updateTrueFalse,dn as updateVideo,xe as useDispatch,FS as useInitialSlides,Ji as useModalPortal,te as useSelector,RS as useSlidesPersistence};//# sourceMappingURL=index.js.map
22
22
  //# sourceMappingURL=index.js.map