PageSourceSearch

https://app.diffit.me/assets/project-0Kp9CxMz.js

js diffit.me collected 2026-10-01 10:35:48 UTC 175,491 bytes, 65 lines download raw bytes

1import{r as l,K as Pt,m as Dt,O as ge,l as $r,Q as St,S as Br,M as Se,R as Ur,T as qt,V as Xt,W as Wr,j as t,X as Hr,Y as Vr,c as Fe,Z as Gr,d as Ue,_ as Ws,$ as Hs,a0 as Vs,a1 as zr,a2 as bs,a3 as qr,a4 as Xr,a5 as Kr,a6 as Re,B as gt,a7 as rt,a8 as Ae,i as Ke,J as Ft,a9 as Jr,aa as is,ab as Yr,ac as Gs,ad as Zr,F as ls,ae as Lt,af as Qr,ag as Mt,ah as en,a as Ot,ai as tn,aj as xt,ak as bt,al as sn,am as rn,an as nn,ao as Ie,ap as cs,aq as on,v as an,t as zs,ar as ln,u as yt,as as cn,at as ys,au as dn,av as qs,aw as un,ax as Rt,ay as ss,az as mn,aA as dt,aB as fn,aC as Xs,aD as Ks,aE as Js,aF as Ys,aG as Zs,aH as It,aI as Qs,aJ as er,aK as pn,aL as hn,aM as gn,aN as xn,aO as bn,aP as yn,aQ as wn,k as vn,aR as kn,aS as jn,aT as _n,aU as Sn,aV as Nn,aW as Cn,aX as rs}from"./index-xyDKSTQ_.js";import{u as En}from"./usePacketState-BNTkvqR8.js";import{u as nt,a as Be,g as tr,P as mt,s as ws,b as Kt,c as Tn,R as sr,d as ds,F as us,e as rr,f as Pn,h as Rn,C as In,E as An,D as Dn,i as te,r as Fn,j as Ln,k as Mn,A as nr,l as or,m as On,N as $n,n as Bn,o as Un,p as Wn,q as Hn,T as Vn,t as Gn,v as zn,U as qn,w as Xn}from"./ResourceContent-DUrrI-ig.js";import{F as Kn,a as Jn}from"./index-Df-i5Qn_.js";import{F as $t}from"./ArrowDownTrayIcon-DpMjdvJg.js";import{_ as Nt,F as ar}from"./DocumentArrowUpIcon-BI29zb1V.js";import{C as Jt}from"./popover-D5Gwjmdj.js";import{F as Yn}from"./PaperAirplaneIcon-DQZuG78U.js";import"./index-BZALXIcq.js";import"./DocumentDuplicateIcon-DOzUv-Le.js";import"./Delayed-COiKZzna.js";import"./index-D1HL1sCW.js";try{let e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},s=new e.Error().stack;s&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[s]="b08f5a1c-f231-4c76-9331-fb694d37b52d",e._sentryDebugIdIdentifier="sentry-dbid-b08f5a1c-f231-4c76-9331-fb694d37b52d")}catch{}function Zn({title:e,titleId:s,...r},n){return l.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":s},r),e?l.createElement("title",{id:s},e):null,l.createElement("path",{fillRule:"evenodd",d:"M7.793 2.232a.75.75 0 0 1-.025 1.06L3.622 7.25h10.003a5.375 5.375 0 0 1 0 10.75H10.75a.75.75 0 0 1 0-1.5h2.875a3.875 3.875 0 0 0 0-7.75H3.622l4.146 3.957a.75.75 0 0 1-1.036 1.085l-5.5-5.25a.75.75 0 0 1 0-1.085l5.5-5.25a.75.75 0 0 1 1.06.025Z",clipRule:"evenodd"}))}const Qn=l.forwardRef(Zn);function eo({title:e,titleId:s,...r},n){return l.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":s},r),e?l.createElement("title",{id:s},e):null,l.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 0 1 .865-.501 48.172 48.172 0 0 0 3.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.
1123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"}))}const to=l.forwardRef(eo);function so({title:e,titleId:s,...r},n){return l.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":s},r),e?l.createElement("title",{id:s},e):null,l.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"}),l.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}))}const ro=l.forwardRef(so);function no({title:e,titleId:s,...r},n){return l.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":s},r),e?l.createElement("title",{id:s},e):null,l.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 12.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 18.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5Z"}))}const ir=l.forwardRef(no);function oo({title:e,titleId:s,...r},n){return l.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":s},r),e?l.createElement("title",{id:s},e):null,l.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7.498 15.25H4.372c-1.026 0-1.945-.694-2.054-1.715a12.137 12.137 0 0 1-.068-1.285c0-2.848.992-5.464 2.649-7.521C5.287 4.247 5.886 4 6.504 4h4.016a4.5 4.5 0 0 1 1.423.23l3.114 1.04a4.5 4.5 0 0 0 1.423.23h1.294M7.498 15.25c.618 0 .991.724.725 1.282A7.471 7.471 0 0 0 7.5 19.75 2.25 2.25 0 0 0 9.75 22a.75.75 0 0 0 .75-.75v-.633c0-.573.11-1.14.322-1.672.304-.76.93-1.33 1.653-1.715a9.04 9.04 0 0 0 2.86-2.4c.498-.634 1.226-1.08 2.032-1.08h.384m-10.253 1.5H9.7m8.075-9.75c.01.05.027.1.05.148.593 1.2.925 2.55.925 3.977 0 1.487-.36 2.89-.999 4.125m.023-8.25c-.076-.365.183-.75.575-.75h.908c.889 0 1.713.518 1.972 1.368.339 1.11.521 2.287.521 3.507 0 1.553-.295 3.036-.831 4.398-.306.774-1.086 1.227-1.918 1.227h-1.053c-.472 0-.745-.556-.5-.96a8.95 8.95 0 0 0 .303-.54"}))}const lr=l.forwardRef(oo);function ao({title:e,titleId:s,...r},n){return l.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":s},r),e?l.createElement("title",{id:s},e):null,l.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6.633 10.25c.806 0 1.533-.446 2.031-1.08a9.041 9.041 0 0 1 2.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 0 0 .322-1.672V2.75a.75.75 0 0 1 .75-.75 2.25 2.25 0 0 1 2.25 2.25c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282m0 0h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 0 1-2.649 7.521c-.388.482-.987.729-1.605.729H13.48c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 0 0-1.423-.23H5.904m10.598-9.75H14.25M5.904 18.5c.083.205.173.405.27.602.197.4-.078.898-.523.898h-.9
108c-.889 0-1.713-.518-1.972-1.368a12 12 0 0 1-.521-3.507c0-1.553.295-3.036.831-4.398C3.387 9.953 4.167 9.5 5 9.5h1.053c.472 0 .745.556.5.96a8.958 8.958 0 0 0-1.302 4.665c0 1.194.232 2.333.654 3.375Z"}))}const cr=l.forwardRef(ao);function io({title:e,titleId:s,...r},n){return l.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":s},r),e?l.createElement("title",{id:s},e):null,l.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z"}))}const lo=l.forwardRef(io);function co({title:e,titleId:s,...r},n){return l.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":s},r),e?l.createElement("title",{id:s},e):null,l.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 3v11.25A2.25 2.25 0 0 0 6 16.5h2.25M3.75 3h-1.5m1.5 0h16.5m0 0h1.5m-1.5 0v11.25A2.25 2.25 0 0 1 18 16.5h-2.25m-7.5 0h7.5m-7.5 0-1 3m8.5-3 1 3m0 0 .5 1.5m-.5-1.5h-9.5m0 0-.5 1.5M9 11.25v1.5M12 9v3.75m3-6v6"}))}const ms=l.forwardRef(co);function uo(e,s,r){const{blocks:n,...i}=s,o=JSON.parse(JSON.stringify(i));o.settings=o.settings??{};const a=new Map((e?.blocks||[]).map(u=>[u.unique_id,u]));o.blocks=(n||[]).map(u=>{const p=u.unique_id,d=a.get(p);if(d&&r.get(p)===u)return d;r.set(p,u);const f=JSON.parse(JSON.stringify(u));return Pt(f),f});const c=new Set(o.blocks.map(u=>u.unique_id));for(const u of r.keys())c.has(u)||r.delete(u);return o}const mo=({children:e})=>{const{isSignedIn:s}=Dt(),{getActivePacketData:r,getActivePacketId:n,getProjectId:i,getAllPackets:o,getActivePacketPremiumBlocks:a,getIsOwner:c,getIsCloning:u,getShowSavedSuccess:p,cloneProjectAndRedirect:d,hideSavedSuccess:f,updatePacketData:m,replacePackets:g,setActivePacketId:b,isStreaming:h,isViewingVersion:x,undoRedoStack:w}=ge(),y=r(),v=n(),j=i(),k=a(),C=c(),D=u(),E=p(),[P,L]=l.useState(null),[W,F]=l.useState(!0),N=l.useRef(null),R=l.useRef(null),M=l.useCallback($r.debounce(async G=>{if(!(!s||!C||x))try{await St(v,G)}catch(J){console.error("Failed to save packet:",J)}},Br,{leading:!1,trailing:!0}),[C,v,s,x]),O=l.useCallback(()=>{Se.track("Cloning Unowned Project",{source:"packet_edit",project_id:j,packet_id:v})},[j,v]),_=l.useCallback(async(G,J)=>{m?.(G,J),St(G,J).catch(console.error),b(G)},[m,b]),T=w,A=l.useCallback(async G=>{if(!G||G<1)return!1;try{const J=await Ur(j,G),q=J?.data;if(!q?.packets)return!1;g(q.packets);const H=q.packets.find(z=>z.packet.id===v);if(H){const z=qt(Xt(JSON.parse(JSON.stringify(H.packet))));z.settings=z.settings??{},z.blocks?.forEach(Pt),L(z)}else if(q.packets.length>0){const z=[...q.packets].sort((V,K)=>V.position-K.position)[0];b(z.packet.id)}return J?.data?.restored_version_number??!0}catch(J){return console.error("restoreProjectToVersion failed",J),!1}},[j,v,g,L,b]),X=En({packet:P,setPacket:L,packetId:v,userOwnsPacket:C,premiumBlocks:k,debouncedSaveToServer:M,undoRedoStack:T,onCloneAttempt:d,isCloning:D,showSavedSuccess:E,maxBlockCount:Vr,projectId:j,getAllPackets:o,trackClone:O,pendingSideEffectRef:R,activePacketId:v,restoreOtherPacket:_,restoreProjectToVersion:A});l.useEffect(()=>()=>{M.flush()},[M]),l.useEffect(()=>{if(R.current){const{cleanedPacket:q,beforeSnapshot:H,persist:z,recordUndo:V,targetPacketId:K}=R.current;R.current=null,V&&T.current?.push({before:H,after:q,meta:{origin:"manual",packetId:K}}),z&&K&&s&&C&&!x&&St(K,q).catch(ae=>console.error("Failed to save pending changes on tab switch:",ae)),m?.(K,q)}if(!y){F(!0);return}if(N.current===v)return;N.current=v;const G=JSON.parse(JSON.stringify(y)),J=qt(Xt(G));J.settings=J.settings??{},J.blocks?.forEach(Pt),L(J),F(!1)},[v]);const se=l.useRef(new Map);l.useEffect(()=>{!h||!y||(L(G=>uo(G,y,se.current)),F(!1))},[h,y]);const ne=l.useRef(h);l.useEffect(()=>{const G=ne.current&&!h;if(ne.current=h,!G)return;const J=y??P;if(!J)return;const q=qt(Xt(JSON.parse(JSON.stringify(J))));q.settings=q.settings??{},q.blocks?.forEach(Pt),L(q)},[h,P,y,v]),l.useEffect(()=>{h||!y||L(G=>{if(!G)return G;const J=Wr(G.blocks,y.blocks);return J===G.blocks?G:{...G,blocks:J}})},[h,y]),l.useEffect(()=>{if(R.current){const{cleanedPacket:G,beforeSnapshot:J,persist:q,recordUndo:H,saveImmediately:z,targetPacketId:V}=R.current;
1if(R.current=null,V&&V!==v){q&&s&&C&&!x&&St(V,G).catch(K=>console.error("Failed to save cross-tab packet data:",K)),m?.(V,G);return}q&&M(G),H&&T.current?.push({before:J,after:G,meta:{origin:"manual",packetId:V}}),m?.(v,G),q&&z&&M.flush()}});const Y=l.useMemo(()=>({...X,isLoading:W,clonePacketAndRedirect:d,hideSavedSuccess:f}),[X,W,d,f]);return t.jsx(Hr.Provider,{value:Y,children:e})},fo=50,po=2,vs=350,ho=()=>{const[e,s]=l.useState([]),[r,n]=l.useState(""),[i,o]=l.useState(null),[a,c]=l.useState(!1),[u,p]=l.useState(!1),[d,f]=l.useState(!0),[m,g]=l.useState(!1),[b,h]=l.useState(null),[x,w]=l.useState({}),[y,v]=l.useState(!1),[j,k]=l.useState(void 0),C=l.useRef(null),D=l.useRef(null),E=l.useRef(null),P=l.useRef({}),L=l.useRef(0),W=l.useCallback((N,R)=>{P.current[N]&&clearInterval(P.current[N]);const M=R.split(/(\s+)/);let O=0;w(T=>({...T,[N]:{currentWordIndex:0,totalWords:M.length,isComplete:!1}}));const _=setInterval(()=>{O+=po,O>=M.length?(O=M.length,clearInterval(_),delete P.current[N],w(T=>({...T,[N]:{currentWordIndex:O,totalWords:M.length,isComplete:!0}})),setTimeout(()=>{w(T=>{const A={...T};return delete A[N],A})},50)):w(T=>({...T,[N]:{currentWordIndex:O,totalWords:M.length,isComplete:!1}}))},fo);P.current[N]=_},[]);l.useEffect(()=>()=>{Object.values(P.current).forEach(N=>{clearInterval(N)})},[]);const F=l.useCallback(N=>{const R=x[N.id];return R?N.content.split(/(\s+)/).slice(0,R.currentWordIndex).join(""):N.content},[x]);return{messages:e,setMessages:s,inputMessage:r,setInputMessage:n,conversationId:i,setConversationId:o,isAwaitingResponse:a,setIsAwaitingResponse:c,isExecutingCommands:u,setIsExecutingCommands:p,isLoadingHistory:d,setIsLoadingHistory:f,hasLoadedGreeting:m,setHasLoadedGreeting:g,copiedMessageId:b,setCopiedMessageId:h,streamingMessages:x,setStreamingMessages:w,showTrialSuccessMessage:y,setShowTrialSuccessMessage:v,showDownArrow:j,setShowDownArrow:k,messagesEndRef:C,textareaRef:D,messagesContainerRef:E,streamingIntervalsRef:P,amountScrolledRef:L,startStreaming:W,getDisplayContent:F}},dr=l.createContext(null),go=()=>{const e=l.useContext(dr);if(!e)throw new Error("useProjectChatSidebarContext must be used within a ProjectChatSidebarProvider");return e},xo=({children:e,isOpen:s,setOpen:r})=>{const{getProjectId:n,getIsOwner:i,cloneProjectAndRedirect:o,refreshProject:a,getActivePacketId:c,switchToPacket:u,markPacketUpdated:p,updatePacketBlocks:d,updatePacketBlocksAndSettings:f,getAllPackets:m,isStreaming:g,outlineState:b,isLoading:h}=ge(),{getPacket:x,setBlockLoading:w,addLoadingBlock:y,deleteBlock:v,setBlocks:j,setBlocksAndSettings:k,getBlock:C,swapBlockWithContent:D,undoToCheckpoint:E,isCheckpointValid:P,hasCheckpoint:L,createCheckpoint:W,recordChatTurn:F,restoreProjectToVersion:N,forceSave:R,undoRedoStackLength:M,getPacketOrientation:O,setPendingSlides:_,clearPendingSlides:T}=Fe(),{doExport:A}=nt(),{user:X,isSignedIn:se}=Gr(),{diffitUser:ne,refreshDiffitUser:Y}=Ue(),{pendingChatInput:G,setPendingChatInput:J,setTitleImageModalOpen:q,setModifyVocabImageModalOpen:H,setModifyCustomActivityImageModalOpen:z,setShareModalOpen:V,setAddToTemplatesModalOpen:K}=Be(),ae=ho(),Q=n(),me=c(),pe=x(),xe=i(),oe=M(),re=O(),ie=!!Q&&h,Ne=l.useCallback((Ce,Ve={})=>{Se.track(Ce,{project_id:Q,active_packet_id:me,...Ve})},[Q,me]),be={isOpen:s,setOpen:r,projectId:Q,activePacketId:me,userOwnsProject:xe,cloneProjectAndRedirect:o,refreshProject:a,switchToPacket:u,markPacketUpdated:p,updatePacketBlocks:d,updatePacketBlocksAndSettings:f,getAllPackets:m,packet:pe,getPacket:x,setBlockLoading:w,addLoadingBlock:y,deleteBlock:v,setBlocks:j,setBlocksAndSettings:k,getBlock:C,swapBlockWithContent:D,undoToCheckpoint:E,isCheckpointValid:P,hasCheckpoint:L,createCheckpoint:W,recordChatTurn:F,restoreProjectToVersion:N,forceSave:R,undoRedoStackLengthValue:oe,orientation:re,setPendingSlides:_,clearPendingSlides:T,doExport:A,user:X,isSignedIn:se,diffitUser:ne,refreshDiffitUser:Y,trackProjectEvent:Ne,isStreaming:g,outlineState:b,isProjectLoading:ie,pendingChatInput:G,setPendingChatInput:J,setTitleImageModalOpen:q,setModifyVocabImageModalOpen:H,setModifyCustomActivityImageModalOpen:z,setShareModalOpen:V,setAddToTemplatesMo
1dalOpen:K,...ae};return t.jsx(dr.Provider,{value:be,children:e})},fs=zr("https://api.diffit.me");async function bo(e,s=1,r=100){return(await fs.get(`/chat/project/${e}/history`,{params:{page:s,per_page:r}})).data}async function yo(e){return(await fs.delete(`/chat/project/${e}/history`)).data}async function ks({messageId:e,conversationId:s,rating:r,text:n}){if(!(!n||!n.trim()))return fs.post("/chat/feedback",{message_id:e,conversation_id:s,rating:r,text:n}).catch(()=>{})}async function*wo(e,s,{signal:r}={}){const[n,i]=await Promise.all([Ws(),Hs()]);let o;try{o=await fetch(`${i}/chat/project/${e}/stream`,{method:"POST",headers:n,body:JSON.stringify(s),signal:r})}catch(a){if(a.name==="AbortError")throw a;yield{type:"error",message:"Network error — please check your connection and try again."};return}if(!o.ok){yield{type:"error",message:"Request failed. Please try again."};return}yield*Vs(o)}async function*vo(e,s,r,{signal:n}={}){const[i,o]=await Promise.all([Ws(),Hs()]);let a;try{a=await fetch(`${o}/chat/project/${e}/stream/${s}/resume?last_event_id=${encodeURIComponent(r)}`,{method:"GET",headers:i,signal:n})}catch(c){if(c.name==="AbortError")throw c;yield{type:"error",message:"Network error — please check your connection and try again."};return}if(!a.ok){if(a.status===404){yield{type:"stream_expired"};return}yield{type:"error",message:"Failed to resume stream. Please try again."};return}yield*Vs(a)}const ko=({messagesContainerRef:e,amountScrolledRef:s,messages:r,streamingMessages:n,setShowDownArrow:i,isAwaitingResponse:o,isLoadingHistory:a})=>{const[c,u]=l.useState(!1),[p,d]=l.useState(!1);l.useEffect(()=>{if(s.current!==-1&&e.current){const g=e.current,b=g.scrollHeight-g.scrollTop-g.clientHeight;if(b<=1)return;const h=Math.max(0,b-1);if(s.current+h>=vs)i(!0),s.current=-1;else{s.current+=h;const x=g.scrollHeight-g.clientHeight-1;g.scrollTo({top:x,behavior:"auto"})}}},[r,n,e,s,i]),l.useEffect(()=>{if(e.current){const g=e.current,b=()=>{const h=g.scrollHeight-g.scrollTop-g.clientHeight;u(g.scrollTop>0),d(h>2),h<vs?(i(!1),s.current===-1&&(s.current=0)):i(!0)};return g.addEventListener("scroll",b),()=>{g.removeEventListener("scroll",b)}}},[e,s,i,u,d]),l.useEffect(()=>{!a&&e.current&&(e.current.scrollTop=e.current.scrollHeight,s.current=0,d(!1))},[a,e,s,d]),l.useEffect(()=>{o&&e.current&&(e.current.scrollTop=e.current.scrollHeight)},[o,e]);const f=l.useCallback(()=>{if(!e.current)return;const g=e.current;g.scrollHeight-g.scrollTop<=g.clientHeight+10&&setTimeout(()=>{e.current&&(e.current.scrollTop=e.current.scrollHeight)},0)},[e]),m=l.useCallback(()=>{e.current&&(e.current.scrollTop=e.current.scrollHeight),i(!1),s.current=0},[e,i,s]);return{scrollToBottomIfNeeded:f,scrollToBottom:m,showTopGradient:c,showBottomGradient:p}},jo=({entityId:e,userOwnsEntity:s,trackEvent:r,getHistoryFn:n,deleteHistoryFn:i,messages:o,setMessages:a,conversationId:c,setConversationId:u,setIsLoadingHistory:p,setHasLoadedGreeting:d})=>{const f=p??(()=>{}),m=d??(()=>{}),g=l.useCallback(async()=>{if(e)try{r("Chat History Cleared",{conversation_id:c,messages_cleared_count:o.length}),await i(),a([]),u(null)}catch(b){console.error("Error clearing chat history:",b),r("Chat Error Occurred",{conversation_id:c,error_type:"clear_history_failed",error_message:b.message})}},[e,c,o.length,r,a,u,i]);return l.useEffect(()=>{if(!s||!e)return;(async()=>{f(!0),m(!1),sessionStorage.getItem("pendingChatUserMessage")&&m(!0);try{const x=await n();if(x&&x.messages){const w=x.messages.map(y=>{const v={id:y.id,message_type:y.message_type,content:y.content,timestamp:new Date(y.timestamp),tool_calls:y.tool_calls||[],tool_call_id:y.tool_call_id,tool_name:y.tool_name,conversation_id:y.conversation_id,fromHistory:!0};if(y.message_type==="tool")try{const j=JSON.parse(y.content);return{id:y.id,message_type:"tool",content:j.status==="success"?j.message||"Content updated!":j.status==="error"?j.message||j.error||"Content failed to update.":"Updating content...",status:j.status,toolCall:{name:j.tool,args:j.args,tool_call_id:j.tool_call_id,checkpoint_id:j.checkpoint_id,affected_block_id:j.affected_block_id,affected_block_t
1itle:j.affected_block_title,message:j.message,image_picker_params:j.image_picker_params,is_premium:j.is_premium,slide_changes:j.slide_changes},timestamp:new Date(y.timestamp),conversation_id:y.conversation_id,fromHistory:!0}}catch(j){return console.error("Error parsing tool message content:",j),null}return v}).filter(Boolean);if(a(w),w.length>0){const y=w[w.length-1];y.conversation_id&&u(y.conversation_id)}}}catch(x){console.error("Error loading chat history:",x),r("Chat Error Occurred",{error_type:"load_history_failed",error_message:x.message})}finally{f(!1)}})()},[e,s]),{clearChatHistory:g}},_o=({projectId:e,packet:s,userOwnsProject:r,messages:n,setMessages:i,conversationId:o,setConversationId:a,setIsLoadingHistory:c,setHasLoadedGreeting:u,trackProjectEvent:p})=>{const d=l.useCallback(()=>bo(e),[e]),f=l.useCallback(()=>yo(e),[e]);return jo({packet:s,entityId:e,userOwnsEntity:r,trackEvent:p,getHistoryFn:d,deleteHistoryFn:f,messages:n,setMessages:i,conversationId:o,setConversationId:a,setIsLoadingHistory:c,setHasLoadedGreeting:u})},So=({messages:e,setMessages:s,undoRedoStackLengthValue:r,isCheckpointValid:n,hasCheckpoint:i,conversationId:o,undoToCheckpoint:a,trackEvent:c,getBlock:u,setBlockLoading:p,addLoadingBlock:d,setPendingSlides:f,activePacketId:m})=>{const g=l.useRef(e);l.useEffect(()=>{g.current=e},[e]),l.useEffect(()=>{s(x=>x.map(w=>w.fromHistory||w.message_type!=="tool"||!w.toolCall?.checkpoint_id||i&&!i(w.toolCall.checkpoint_id)?w:w.status==="success"&&!n(w.toolCall.checkpoint_id)?{...w,status:"rejected"}:w.status==="rejected"&&n(w.toolCall.checkpoint_id)?{...w,status:"success"}:w))},[r,n,i,s,m]);const b=l.useCallback(async x=>{let w=null,y=null;const v=x.args?.block_unique_id;return x.tool==="add_activity_block"||x.tool==="create_custom_activity"?(y=`loading-${bs()}`,await d({canonical_id:x.args.canonical_id,specified_id:y,title:"Loading..."})):v&&x.tool!=="delete_activity_block"&&x.tool!=="show_activity"&&(tr(u(v))?(y=v,f?.(v,{slideIds:null,adding:0})):(w=u(v),y=`loading-${bs()}`,await p(v,y))),{loadingBlockRollbackState:w,loadingBlockId:y}},[d,u,p,f]),h=l.useCallback(async x=>{try{const y=g.current.find(v=>v.message_type==="tool"&&v.toolCall?.checkpoint_id===x)?.toolCall?.name;c("Chat Tool Undo Clicked",{conversation_id:o,tool_name:y}),await a(x),s(v=>v.map(j=>j.message_type==="tool"&&j.toolCall?.checkpoint_id===x?{...j,status:"rejected"}:j))}catch(w){console.error("Failed to undo tool change:",w),c("Chat Error Occurred",{conversation_id:o,error_type:"undo_tool_failed",error_message:w.message}),s(y=>[...y,{id:`error-${Date.now()}`,type:"error",content:"Failed to undo changes. Please try again.",timestamp:new Date}])}},[o,a,s,c]);return{handleSetLoadingStateForTool:b,handleUndoToolChange:h}},No={google_doc:"Exporting to Google Docs",google_slides:"Exporting to Google Slides",google_form:"Exporting to Google Forms",google_classroom_doc:"Exporting to Google Classroom",google_classroom_slides:"Exporting to Google Classroom",docx:"Exporting to Word",pptx:"Exporting to PowerPoint"},Co=({activePacketId:e,messages:s,setMessages:r,conversationId:n,undoRedoStackLengthValue:i,isCheckpointValid:o,hasCheckpoint:a,undoToCheckpoint:c,getBlock:u,setBlockLoading:p,addLoadingBlock:d,setPendingSlides:f,doExport:m,refreshProject:g,trackProjectEvent:b})=>{const{isPremiumUser:h}=Ue(),{handleSetLoadingStateForTool:x,handleUndoToolChange:w}=So({messages:s,setMessages:r,undoRedoStackLengthValue:i,isCheckpointValid:o,hasCheckpoint:a,conversationId:n,undoToCheckpoint:c,trackEvent:b,getBlock:u,setBlockLoading:p,addLoadingBlock:d,setPendingSlides:f,activePacketId:e});return{executeClientAction:l.useCallback(async v=>{switch(v.type){case"export":{const j=v.payload.export_type.toLowerCase();if(!h&&mt.has(j))return b("Chat Premium Export Blocked",{export_type:j}),r(k=>[...k,{id:`premium-export-block-${Date.now()}`,message_type:"assistant",content:`${No[j]||"This export"} is a premium feature. Upgrade to Premium to unlock Google exports, Word, and PowerPoint.`,suggestions:[{label:"See Plans",type:"action",action:"get_premium"}],timestamp:new Date}]),!0;
1j==="print"?r(k=>{const C=[...k];for(let D=C.length-1;D>=0;D--)if(C[D].message_type==="assistant"){const E=C[D].suggestions||[];E.some(L=>L.action==="export"&&L.export_type==="print")||(C[D]={...C[D],suggestions:[...E,{label:"Open print-ready PDF",type:"action",action:"export",export_type:"print"}]});break}return C}):m({exportType:j,blockUniqueIds:v.payload.block_unique_ids||null});break}case"add_resource":await g(),b("Resource Added via Chat",{new_packet_id:v.payload?.packet_id});break;case"scroll_to":break;default:console.warn("Unknown client action type:",v.type)}},[m,g,b,r,h]),handleUndoToolChange:w,handleSetLoadingStateForTool:x}},Eo=[{label:"Tell me about this resource",text:"Tell me about this resource"},{label:"Make this more accessible for struggling readers",text:"Rewrite this reading using simpler vocabulary and shorter sentences"},{label:"Add more collaboration activities ",text:"Suggest some collaboration activities that would work well for this topic"}],To=({trackEvent:e,setInputMessage:s,textareaRef:r,setMessages:n,startStreaming:i,getBlock:o,setTitleImageModalOpen:a,setModifyVocabImageModalOpen:c,setModifyCustomActivityImageModalOpen:u,doExport:p,setShareModalOpen:d,setAddToTemplatesModalOpen:f,extraActionHandlers:m})=>{const{printPacket:g}=nt(),{isOffered:b,openPremiumOffer:h}=qr(),x=l.useCallback((k,C=100)=>{setTimeout(()=>{const D=document.getElementById(k);D&&Xr(D,60,"smooth")},C)},[]),w=l.useCallback((k,C,D="markdown_link")=>{k.preventDefault();const E=C.text;e("Chat Suggestion Clicked",{suggestion_text:E,suggestion_label:C.label,source:D}),s(E),setTimeout(()=>{if(r.current){r.current.focus();const P=E.length;r.current.setSelectionRange(P,P)}},0)},[e,s]),y=l.useCallback((k,C)=>{let D;C!==void 0?(k?.preventDefault?.(),D=C):D=k;const{block_id:E,image_type:P,word_index:L,section_index:W,row_index:F,col_index:N}=D;if(!o(E)){console.warn("Cannot open image picker: block not found or not ready yet",E);return}e("Chat Image Picker Opened",{block_id:E,image_type:P,word_index:L,section_index:W}),P==="title_image"?a({blockId:E}):P==="vocab"?c({blockId:E,wordIndex:L}):P==="custom_activity"&&u({blockId:E,sectionIndex:W,rowIndex:F,colIndex:N}),x(E)},[o,e,a,c,u,x]),v=l.useCallback(k=>{k.action==="export"?k.export_type==="print"?g():p({exportType:k.export_type.toLowerCase()}):k.action==="share"?d({source:"chat_sidebar"}):k.action==="add_to_templates"?f({source:"chat_sidebar"}):k.action==="get_premium"?(e("Get Premium Access Clicked",{location:"chat_export_block"}),b?h("Chat Export Block"):window.open(Kr,"_blank")):m?.[k.action]&&m[k.action](k)},[p,g,d,f,m,e,b,h]),j=l.useCallback(k=>{const C={id:`temp-user-${Date.now()}`,message_type:"user",content:k.text,timestamp:new Date},E={perfect:{content:"Awesome! Would you like to export to share with students?",suggestions:[{label:"Print",type:"action",action:"export",export_type:"print"},{label:"Export to Docs",type:"action",action:"export",export_type:"google_doc"},{label:"Export to Slides",type:"action",action:"export",export_type:"google_slides"},{label:"Export to PDF",type:"action",action:"export",export_type:"pdf"},{label:"Share with a colleague",type:"action",action:"share"},{label:"Save as template",type:"action",action:"add_to_templates"}]},close:{content:"No problem! Tell me what needs to be changed and I'll try to fix it for you.",suggestions:[]},not_close:{content:"Sorry about that! Give me more details about what you're looking for and I'll try again.",suggestions:[]}}[k.feedbackType],P={id:`assistant-${Date.now()}`,message_type:"assistant",content:E.content,suggestions:E.suggestions,timestamp:new Date};n(L=>[...L,C,P]),i(P.id,E.content),e("Unlimited Feedback Response Shown",{feedback_type:k.feedbackType}),setTimeout(()=>{r.current?.focus()},0)},[n,i,e]);return{scrollToBlock:x,handleSuggestionClick:w,handleOpenImagePicker:y,handleActionSuggestion:v,handleUnlimitedFeedback:j,staticSuggestions:Eo}},Po=({projectId:e,activePacketId:s,activePacketIdRef:r,messages:n,setMessages:i,inputMessage:o,setInputMessage:a,conversationId:c,setConversationId:u,isAwaitingResponse:p,setIsAwaitingResponse:d,isExecutingCommands:f,setIsExecutingCommands:m,isLoadingHistory:g,userOwnsProject:b,cloneProjectAndRedirect:h,executeClientAction:x,refreshProject:w,markPacketUpdated:y,updatePacketBlocks:v,updatePacketBlocksAndSettings:j,switchToPacket:k,getAllPackets:C,startStreaming:D,trackProjectEvent:E,textareaRef:P,amountScrolledRef:L,getBlock:W,setTitleImageModalOpen:F,setModifyVocabImageModalOpen:N,setModifyCustomActivityImageModalOpen:R,doExport:M,setShareModalOpen:O,setAddToTemplatesMo
1dalOpen:_,setBlocks:T,setBlocksAndSettings:A,createCheckpoint:X,recordChatTurn:se,restoreProjectToVersion:ne,handleSetLoadingStateForTool:Y,deleteBlock:G,swapBlockWithContent:J,setPendingSlides:q,clearPendingSlides:H})=>{const z=l.useCallback(I=>{I.packet_id&&(k(I.packet_id),setTimeout(()=>window.scrollTo({top:0,behavior:"smooth"}),100))},[k]),{scrollToBlock:V,handleSuggestionClick:K,handleOpenImagePicker:ae,handleActionSuggestion:Q,handleUnlimitedFeedback:me,staticSuggestions:pe}=To({trackEvent:E,setInputMessage:a,textareaRef:P,setMessages:i,startStreaming:D,getBlock:W,setTitleImageModalOpen:F,setModifyVocabImageModalOpen:N,setModifyCustomActivityImageModalOpen:R,doExport:M,setShareModalOpen:O,setAddToTemplatesModalOpen:_,extraActionHandlers:{navigate_to_tab:z}}),xe=l.useRef(n);l.useEffect(()=>{xe.current=n},[n]);const oe=l.useRef(!1),re=Re(T),ie=Re(A),Ne=Re(Y),be=Re(G),Ce=Re(J),Ve=Re(q),Ee=Re(H),Je=Re(se),Ge=Re(ne);l.useEffect(()=>{if(g)return;const I=sessionStorage.getItem("pendingChatUserMessage");if(I)try{const B=JSON.parse(I);sessionStorage.removeItem("pendingChatUserMessage"),ze(B.content)}catch(B){console.error("Failed to parse pending user message:",B),sessionStorage.removeItem("pendingChatUserMessage")}},[b,g]);const We=l.useCallback((I,B)=>{if(!I||I.length===0)return[];const Z=B||C();return I.map(le=>({label:`View "${Z.find(Le=>Le.packet.id===le)?.packet?.title||"Untitled"}"`,type:"action",action:"navigate_to_tab",packet_id:le})).filter(Boolean)},[C]),ze=l.useCallback(async(I=null)=>{const B=I||o.trim();if(!B||oe.current||!I&&(p||f)||!s)return;if(!b){const ce={id:`temp-user-${Date.now()}`,message_type:"user",content:B,timestamp:new Date};i(ye=>[...ye,ce]),a(""),d(!0),sessionStorage.setItem("pendingChatUserMessage",JSON.stringify(ce)),E("Cloning Unowned Project",{source:"chat_sidebar_message_attempt"}),await h();return}if(!e)return;oe.current=!0;const Z={id:`temp-user-${Date.now()}`,message_type:"user",content:B,timestamp:new Date};i(ce=>[...ce,Z]),a(""),L.current=0,d(!0);const le=xe.current,he=le.filter(ce=>!ce.fromHistory&&ce.message_type==="user").length===0,ke=le.filter(ce=>!ce.fromHistory).length+1,Le=le.filter(ce=>ce.message_type==="user").length===0,Vt=le.length+1;E("Chat Message Sent",{conversation_id:c,message_content:Z.content,is_first_message_in_conversation:he,total_messages_in_conversation:ke,is_first_message_in_project:Le,total_messages_in_project:Vt,is_streaming:!0});const Me=[];let fe=null,Ye,Ze="",je=null,ue=null,Te=null,_e=null,ot=0;const vt=[];let Oe=null,qe=!1;const at=new Set;let Qe=null,it=null,lt=!1;const kt=new Set,ct=3e4;let $e=new AbortController,Xe=setTimeout(()=>$e.abort(),ct);const Gt=()=>{clearTimeout(Xe),Xe=setTimeout(()=>$e.abort(),ct)},jt=()=>$e.abort();window.addEventListener("offline",jt);try{let ce=wo(e,{message:Z.content,active_packet_id:s},{signal:$e.signal}),ye=0;const _t=3;for(;;)try{for await(const S of ce){if(Gt(),S._eventId){if(kt.has(S._eventId))continue;kt.add(S._eventId),it=S._eventId}switch(S.type){case"stream_started":Qe=S.stream_id,Ye=S.model??void 0,S.conversation_id&&u(S.conversation_id),S.user_message_id&&i($=>$.map(U=>U.id===Z.id?{...U,id:S.user_message_id}:U));break;case"checkpoint":X?.(S.checkpoint_id);break;case"tool_executing":if(d(!1),m(!0),je=S.message_id,i($=>[...$,{id:S.message_id,message_type:"tool",model:Ye,content:"Updating content...",status:"pending",toolCall:{name:S.tool,args:S.args,checkpoint_id:S.checkpoint_id,packet_id:S.packet_id},timestamp:new Date}]),Ne.current&&S.packet_id===r.current)try{const{loadingBlockId:$,loadingBlockRollbackState:U}=await Ne.current({tool:S.tool,args:S.args||{}});ue=$,Te=U}catch($){console.error("Failed to set block loading state:",$)}break;case"block_update":if(S.packet_id===r.current?(re.current?.(S.blocks,{persist:!1,recordUndo:!1}),at.add(S.packet_id),ue&&Ee.current?.(ue),ue=null,Te=null):(v?.(S.packet_id,S.blocks),y(S.packet_id),Me.includes(S.packet_id)||Me.push(S.packet_id)),je){const $=S.affected?.block_title,U=S.affected?.block_id;i(ee=>ee.map(de=>de.id===je?{...de,status:"success",content:$?`Updated "${$}"`:"Content updated!",toolCall:{...de.toolCall,affected_block_id:U,affected_block_t
1itle:$}}:de))}break;case"packet_update":S.packet_id===r.current?(ie.current?.(S.blocks,S.settings,{persist:!1,recordUndo:!1}),at.add(S.packet_id),ue&&Ee.current?.(ue),ue=null,Te=null):(j?.(S.packet_id,S.blocks,S.settings),y(S.packet_id),Me.includes(S.packet_id)||Me.push(S.packet_id));break;case"tool_error":if(console.error("Tool error during streaming:",S.tool,S.message),ue&&S.packet_id===r.current){try{S.tool==="add_activity_block"||S.tool==="create_custom_activity"?be.current?.(ue,{persist:!1}):Te&&Ce.current?.(ue,Te,{persist:!1})}catch($){console.error("Failed to restore block after tool error:",$)}Ee.current?.(ue),ue=null,Te=null}if(_e&&(Ee.current?.(_e),_e=null),je){const $=je;je=null,i(U=>U.map(ee=>ee.id===$?{...ee,status:"error",content:S.message||"Tool failed."}:ee))}break;case"pre_tool_message_saved":if(S.conversation_id&&u(S.conversation_id),fe&&S.message_id&&fe!==S.message_id){const $=fe;i(U=>U.map(ee=>ee.id===$?{...ee,id:S.message_id}:ee)),fe=S.message_id}break;case"awaiting_review":fe=null,Ze="",d(!0);break;case"tool_done":if(i($=>$.map(U=>U.id===S.message_id?{...U,status:U.status==="pending"?S.success?"success":"error":U.status,content:U.status==="pending"&&S.message?S.message:U.content,toolCall:{...U.toolCall,message:S.message,...S.affected_block_id&&{affected_block_id:S.affected_block_id},...S.affected_block_title&&{affected_block_title:S.affected_block_title},...S.image_picker_params&&{image_picker_params:S.image_picker_params},...S.affected_packet_id&&{affected_packet_id:S.affected_packet_id},...S.is_premium&&{is_premium:!0},...S.slide_changes&&{slide_changes:S.slide_changes}}}:U)),je===S.message_id&&(je=null),S.tool==="save_memory"&&S.memory_created&&Se.track("Memory Added",{source:"chat"}),!S.success&&ue&&S.packet_id===r.current)try{S.tool==="add_activity_block"||S.tool==="create_custom_activity"?be.current?.(ue,{persist:!1}):Te&&Ce.current?.(ue,Te,{persist:!1})}catch($){console.error("Failed to restore block after tool failure:",$)}ue&&Ee.current?.(ue),ue=null,Te=null,_e&&(Ee.current?.(_e),_e=null);break;case"client_action":{if(ot++,vt.push(S.action_type),S.action_type==="add_resource"){const $=S.payload?.packet_id;Oe=(Oe||Promise.resolve()).then(()=>w({forceRefreshIds:[]}).then(U=>($&&(y($),Me.includes($)||Me.push($),E("Resource Added via Chat",{new_packet_id:$})),U)))}else if(S.action_type==="scroll_to")V(S.payload?.block_id);else if(S.action_type==="restore_version"){const $=S.payload?.version_number,U=await Ge.current?.($);if(U){const ee=(C?.()||[]).map(de=>de.packet.id);Je.current?.(U,ee)}}else if(S.action_type==="slides_edit_pending"){if(S.packet_id===r.current){const{block_unique_id:$,slide_ids:U,adding:ee}=S.payload||{};$&&(Ve.current?.($,{slideIds:U??null,adding:ee??0}),_e=$)}}else await x({type:S.action_type,payload:S.payload})&&(qe=!0);break}case"text_delta":if(d(!1),m(!0),qe)break;Ze+=S.content,fe?i($=>$.map(U=>U.id===fe?{...U,content:U.content+S.content}:U)):(fe=`streaming-assistant-${Date.now()}`,i($=>[...$,{id:fe,message_type:"assistant",model:Ye,content:S.content,suggestions:[],timestamp:new Date}]));break;case"text_done":if(qe)break;fe&&(i($=>$.map(U=>U.id===fe?{...U,...S.content?{content:U.content+S.content}:{},suggestionsLoading:!0}:U)),S.content&&(Ze+=S.content));break;case"message_saved":if(S.conversation_id&&u(S.conversation_id),fe&&S.message_id&&fe!==S.message_id){const $=fe;i(U=>U.map(ee=>ee.id===$?{...ee,id:S.message_id}:ee)),fe=S.message_id}break;case"suggestions":{const $=Oe?await Oe:null;if(Oe=null,qe)break;const U=We(Me,$),ee=[...S.suggestions||[],...U];i(de=>{const Pe=de.findLastIndex(ve=>ve.message_type==="assistant");return Pe===-1?de:de.map((ve,we)=>we===Pe?{...ve,suggestions:ee,suggestionsLoading:!1}:ve)});break}case"done":lt=!0,i($=>$.map(U=>U.suggestionsLoading?{...U,suggestionsLoading:!1}:U)),E("Chat Message Received",{conversation_id:c,message_content:Ze,is_streaming:!0,model:Ye}),ot>0&&E("Agentic Client Actions Executed",{conversation_id:c,action_count:ot,action_types:vt}),S.post_version&&Je.current?.(S.post_version.version_number,[...at]);break;case"stream_expired":i($=>[...$,{id:`error-${Date.now()}`,message_type:"error",content:"The response expired. Please send your message again.",timestamp:new Date}]);break;case"error":console.error("Streaming chat error:",S.message),i($=>[...$,{id:`error-${Date.now()}`,message_type:"error",content:S.message||"Sorry, I encountered an error. Please try again.",timestamp:new Date}]);break;default:break}}break}catch(S){if(S.name==="AbortError"&&Qe&&!lt&&ye<_t){ye++,navigator.onLine||await new Promise($=>{const U=()=>{window.removeEventListener("online",U),clearTimeout(ee),$()};window.addEventListener("online",U);const ee=setTimeout(()=>{window.removeEventListener("online",U),$()},3e4)}),$e=new AbortController,clearTimeout(Xe),Xe=setTimeout(()=>$e.abort(),ct),ce=vo(e,Qe,it||"0",{signal:$e.signal});continue}throw S}}catch(ce){console.error("Project streaming chat error:",ce),E("Chat Error Occurred",{conversation_id:c,error_type:ce.name==="AbortError"?"stream_timeout":"send_message_failed",error_message:ce.message,user_message:Z.content}),i(ye=>[...ye.map(S=>S.message_type==="tool"&&S.status==="pending"?{...S,status:"error",content:"Connection interrupted."}:S),{id:`error-${Date.now()}`,message_type:"error",content:ce.name==="AbortError"?"The response timed out. Please try again.":"Sorry, I encountered an error. Please try again.",timestamp:new Date}])}finally{oe.current=!1,clearTimeout(Xe),window.removeEventListener("offline",jt),_e&&(Ee.current?.(_e),_e=null),i(ce=>ce.map(ye=>ye.suggestionsLoading?{...ye,suggestionsLoading:!1}:ye)),d(!1),m(!1),setTimeout(()=>{P.current?.focus()},0),L.current=0}},[o,p,f,e,s,b,E,h,c,V,v,x,w,y,We,i,a,d,m,u,X,P,L,C]);return{sendMessage:ze,scrollToBlock:V,handleSuggestionClick:K,handleOpenImagePicker:ae,handleActionSuggestion:Q,handleUnlimitedFeedback:me,staticSuggestions:pe}},Ro=({inputMessage:e,setInputMessage:s,textareaRef:r,isOpen:n,isAwaitingResponse:i,isExecutingCommands:o,pendingChatInput:a,setPendingChatInput:c,scrollToBottomIfNeeded:u,sendMessage:p})=>{l.useEffect(()=>{a&&n&&(s(a),c(null),setTimeout(()=>{if(r.current){r.current.focus();const h=a.length;r.current.setSelectionRange(h,h)}},0))},[a,n,c,s,r]),l.useEffect(()=>{n&&!a&&setTimeout(()=>{r.current?.focus()},0)},[n,r,a]);const d=l.useCallback(()=>
1{if(!r.current)return;r.current.style.height="auto";const h=200,x=r.current.offsetHeight-r.current.clientHeight,w=Math.min(r.current.scrollHeight+x,h);r.current.style.height=`${w}px`,u()},[r,u]),f=l.useCallback(h=>{const x=h.nativeEvent?.inputType==="insertFromPaste"?h.target.value.trimEnd():h.target.value;s(x)},[s]);l.useEffect(()=>{d()},[e,d]),l.useEffect(()=>{if(!n)return;r.current&&(r.current.style.height="48px");const h=setTimeout(d,310);return()=>clearTimeout(h)},[n,d,r]);const m=l.useCallback(h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),p())},[p]),g=l.useCallback(()=>{setTimeout(()=>{r.current?.focus()},0)},[r]),b=!e.trim()||i||o;return{handleInputChange:f,handleKeyPress:m,resizeTextarea:d,focusTextarea:g,isSendDisabled:b}},Io=({queuedMessage:e,isStreaming:s,isLoadingHistory:r,canSend:n})=>!!e&&!s&&!r&&!!n,Ao=({canQueue:e,isStreaming:s,isLoadingHistory:r,canSend:n,inputMessage:i,setInputMessage:o,sendMessage:a,onQueued:c})=>{const[u,p]=l.useState(null),d=l.useRef(!1),f=l.useCallback(()=>{if(d.current)return;const m=i.trim();if(m){if(e){d.current=!0,p(m),o(""),c?.(m);return}a()}},[e,i,o,a,c]);return l.useEffect(()=>{Io({queuedMessage:u,isStreaming:s,isLoadingHistory:r,canSend:n})&&(p(null),d.current=!1,a(u))},[u,s,r,n,a]),{queuedMessage:u,handleSend:f}},ur=e=>{const s=(e.activities||[]).every(n=>n.status==="ready"),r=(e.versions??[]).every(n=>n.status==="ready");return s&&r},Do=e=>!!e?.packets?.length&&e.packets.every(ur),mr={p:({children:e,node:s})=>s?.position?.start&&s.position.start.column>1||s?.parent?.type==="listItem"?t.jsx("span",{className:"inline",children:e}):t.jsx("p",{className:"mb-2 last:mb-0",children:e}),ul:({children:e})=>t.jsx("ul",{className:"list-disc list-outside pl-4 mb-2 space-y-1",children:e}),ol:({children:e})=>t.jsx("ol",{className:"list-decimal list-outside pl-4 mb-2 space-y-1",children:e}),li:({children:e})=>t.jsx("li",{children:e}),strong:({children:e})=>t.jsx("strong",{className:"font-semibold",children:e}),em:({children:e})=>t.jsx("em",{className:"italic",children:e}),code:({children:e,className:s})=>s?t.jsx("code",{className:"block bg-gray-100 p-2 rounded text-xs font-mono overflow-x-auto",children:e}):t.jsx("code",{className:"bg-gray-200 px-1 py-0.5 rounded text-xs font-mono",children:e}),h1:({children:e})=>t.jsx("h1",{className:"text-base font-bold mb-2",children:e}),h2:({children:e})=>t.jsx("h2",{className:"text-sm font-bold mb-2",children:e}),h3:({children:e})=>t.jsx("h3",{className:"text-sm font-semibold mb-1",children:e}),blockquote:({children:e})=>t.jsx("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic mb-2",children:e}),hr:()=>null},Fo=({inputMessage:e,textareaRef:s,onInputChange:r,onKeyPress:n,onSend:i,isDisabled:o,isSendDisabled:a})=>t.jsx("div",{id:"chat-sidebar-input",className:"pt-2 pb-4 pr-4 flex-shrink-0",children:t.jsxs("div",{className:"relative",children:[t.jsx("textarea",{ref:s,value:e,onChange:r,onKeyPress:n,placeholder:"Ask Diffit...",className:"block w-full overflow-y-auto pr-12 border resize-none focus:outline-none py-2.5 border-gray-200 rounded-2xl shadow-sm hover:border-gray-300 focus:ring-0 focus:border-gray-300 text-base",rows:1,style:{minHeight:"48px",maxHeight:"200px"},disabled:o}),t.jsx("button",{onClick:i,disabled:a,"aria-label":"Send chat message",className:"absolute bg-emerald-600 text-white hover:bg-emerald-700 disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center justify-center transition-colors bottom-1.5 right-2 w-9 h-9 rounded-xl",children:t.jsx(Kn,{className:"size-5"})})]})}),Lo=2e3,fr=({open:e,onClose:s,onSubmit:r,showRating:n=!1,submitLabel:i="Submit"})=>{const[o,a]=l.useState(""),[c,u]=l.useState(null),[p,d]=l.useState(!1),[f,m]=l.useState(void 0),g=l.useRef(null),b=l.useRef(null),h=l.useRef(!1),x=l.useRef(null),w=l.useId(),y=n&&!c,v=l.useRef({rating:c,text:o,onSubmit:r,onClose:s});v.current={rating:c,text:o,onSubmit:r,onClose:s},l.useEffect(()=>(e&&(a(""),u(null),d(!1),h.current=!1),()=>{x.current&&clearTimeout(x.current)}),[e]),l.useLayoutEffect(()=>{g.current&&m(g.current.offsetHeight)},[p,e,n]);const j=()=>
1{if(h.current)return!1;h.current=!0;const{rating:E,text:P,onSubmit:L}=v.current;return L?.({rating:E,text:P}),!0},k=()=>{j(),v.current.onClose?.()},C=()=>{y||!j()||(d(!0),x.current=setTimeout(()=>v.current.onClose?.(),Lo))},D=E=>u(P=>P===E?null:E);return t.jsx(gt,{showModal:e,setShowModal:k,ariaLabel:"Submit Feedback",maxWidth:"sm:max-w-md",initialFocusRef:b,children:t.jsxs("div",{className:"px-1",children:[t.jsx("h3",{className:"text-base font-semibold text-gray-900",children:"Submit Feedback"}),t.jsx("div",{style:{height:f},className:"overflow-hidden transition-[height] duration-200 ease-in-out",children:t.jsx("div",{ref:g,className:"pt-3",children:p?t.jsxs("div",{className:"flex items-center gap-2 text-emerald-600",children:[t.jsx(rt,{className:"h-5 w-5 flex-shrink-0"}),t.jsx("span",{className:"text-sm font-medium",children:"Thanks for your feedback!"})]}):t.jsxs("div",{className:"flex flex-col gap-3",children:[n&&t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Was this resource helpful?"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Ae,{text:"This was helpful",position:"top",anchor:"center",usePortal:!0,zIndex:80,showArrow:!1,children:t.jsx("button",{type:"button",onClick:()=>D("thumbs_up"),className:`p-1.5 rounded transition-colors ${c==="thumbs_up"?"text-emerald-600 bg-emerald-50":"text-gray-500 hover:bg-gray-100"}`,children:t.jsx(cr,{className:"h-4 w-4"})})}),t.jsx(Ae,{text:"This wasn't helpful",position:"top",anchor:"center",usePortal:!0,zIndex:80,showArrow:!1,children:t.jsx("button",{type:"button",onClick:()=>D("thumbs_down"),className:`p-1.5 rounded transition-colors ${c==="thumbs_down"?"text-red-600 bg-red-50":"text-gray-500 hover:bg-gray-100"}`,children:t.jsx(lr,{className:"h-4 w-4"})})})]})]}),t.jsx("div",{className:"flex items-center justify-between gap-3",children:t.jsx("label",{htmlFor:w,className:"text-sm font-medium text-gray-700",children:"How could we make this resource more helpful?"})}),t.jsx("textarea",{ref:b,id:w,value:o,onChange:E=>a(E.target.value),rows:3,className:"block w-full resize-none rounded-lg border border-gray-300 p-2 text-sm focus:border-emerald-500 focus:ring-0",placeholder:"Share your thoughts..."}),t.jsx("div",{className:"flex items-center justify-end",children:t.jsx("button",{type:"button",onClick:C,disabled:y,className:"rounded-md bg-emerald-600 px-3 py-1.5 text-sm text-white transition-colors hover:bg-emerald-700 disabled:cursor-not-allowed disabled:bg-gray-300",children:i})})]})})})]})})},Mo=({message:e,onUndo:s,onFeedback:r,onScrollToBlock:n,onOpenImagePicker:i,onSwitchToPacket:o,isCheckpointValid:a,getBlock:c,activePacketId:u,trackPacketEvent:p})=>{const[d,f]=l.useState(!1),m=e.toolCall,{bts2026Freemium:g,teacherMemory:b}=Ke(),{isLDidentified:h,isFreeTrialUser:x,hasActiveSubscription:w,setShowEditProfileModal:y}=Ue(),v=Jr({isLDidentified:h,hasActiveSubscription:w,isFreeTrialUser:x}),j=!!m?.is_premium&&!!g&&(v==="trial"||v==="free"),k=m?.message&&e.status==="success"?m.message:e.content,C=m?.name==="export_packet"?"Premium Export":"Premium Activity",D=t.jsx(is,{toolTipProps:{text:C},className:"h-3 w-3",wrapperClassName:"inline-block align-text-bottom mx-0.5"}),E=()=>{const H=m?.affected_block_title;if(j&&H&&typeof k=="string"&&k.includes(H)){const z=k.indexOf(H)+H.length;return t.jsxs(t.Fragment,{children:[k.slice(0,z),D,k.slice(z)]})}return t.jsxs(t.Fragment,{children:[k,j?D:null]})},P=m?.checkpoint_id&&a(m.checkpoint_id),L=u&&m?.packet_id&&m.packet_id!==u,W=!L&&!!m?.affected_block_id&&c(m.affected_block_id),F=!!m?.image_picker_params,N=m?.image_picker_params?.thumbnail_url,R=!!m?.affected_packet_id&&!!o,M=L&&!!m?.affected_block_id&&!!o,O=L&&o?()=>{o(m.packet_id),setTimeout(()=>window.scrollTo({top:0,behavior:"smooth"}),100)}:null,_=m?.name==="save_memory"&&!!b&&!!y,T=W||F||R||M||_,A=()=>{_?y("memories"):F?i(m.image_picker_params):R?(o(m.affected_packet_id),setTimeout(()=>window.scrollTo({top:0,behavior:"smooth"}),100)):M?(o(m.packet_id),setTimeout(()=>window.scrollTo({top:0,behavior:"smooth"}),100)):W&&n(m.affected_block_id)},X=Array.isArray(m?.slide_changes)?m.slide_changes:null,se=H=>document.getElementById(H),ne=()=>{const H=m.affected_block_id,z=L?null:tr(c(H)),V=X.find(Q=>Q?.op==="renamed")?.title,K=Q=>!!V&&Kt(Q?.heading)===Kt(V),ae=[];
1return X.forEach((Q,me)=>{if(!Q)return;if(Q.op==="reordered"||Q.op==="renamed"){ae.push({key:`${Q.op}-${me}`,label:Q.op==="reordered"?"Reordered slides":`Renamed deck to "${Q.title}"`,onClick:W?()=>n(H):O});return}if(Q.op!=="updated"&&Q.op!=="added"&&Q.op!=="removed")return;const pe=Q.op==="updated"?"Updated":Q.op==="added"?"Added":"Removed",xe=Q.op==="removed",oe=(Q.slides||[]).filter(ie=>!(Q.op==="updated"&&K(ie)));if(!oe.length)return;const re=ie=>xe?-1:Tn(z,ie);if(oe.length>3){const ie=re(oe[0]?.id);ae.push({key:`${Q.op}-${me}-collapsed`,label:`${pe} ${oe.length} slides`,onClick:ie!==-1?()=>ws(H,ie,se):O})}else oe.forEach((ie,Ne)=>{const be=re(ie?.id),Ce=(be!==-1?be:Ne)+1;ae.push({key:`${Q.op}-${me}-${ie?.id||Ne}`,label:`${pe} ${Kt(ie?.heading)||`Slide ${Ce}`}`,onClick:be!==-1?()=>ws(H,be,se):O})})}),ae},Y=X?.length?ne():null,G=t.jsxs(t.Fragment,{children:[e.status==="error"&&t.jsx("span",{className:"text-sm",children:"❌"}),F&&N&&e.status==="success"?t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ft,{src:N,alt:"Updated image",className:"w-10 h-10 object-cover rounded"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Click to change"})]}):t.jsx("span",{className:`text-sm flex-1 text-left text-gray-600 ${e.status==="rejected"?"line-through":""}`,children:E()}),T&&t.jsx("svg",{className:"h-4 w-4 text-gray-800 ml-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),J=H=>H==="error"?"bg-red-50 border-red-200":"bg-gray-100 border-gray-200",q=(H,z)=>e.status==="success"&&t.jsxs("div",{className:H,children:[t.jsx(Yr,{buttonIcon:t.jsx(ir,{className:"h-4 w-4 text-gray-600"}),buttonClassName:z,customTrackFn:p,location:"Chat Tool Message",buttons:[m.checkpoint_id&&P&&e.status==="success"&&t.jsxs("button",{onClick:()=>s(m.checkpoint_id),className:"w-full flex items-center gap-2 px-3 py-2 text-gray-700 hover:bg-gray-100 text-left",children:[t.jsx(Qn,{className:"h-4 w-4"}),"Undo Change"]},"undo"),t.jsxs("button",{onClick:()=>f(!0),className:"w-full flex items-center gap-2 px-3 py-2 text-gray-700 hover:bg-gray-100 text-left",children:[t.jsx(to,{className:"h-4 w-4"}),t.jsx("span",{children:"Submit Feedback"})]},"feedback")].filter(Boolean)}),t.jsx(fr,{open:d,showRating:!0,onSubmit:({rating:V,text:K})=>r(m,e,{rating:V,text:K}),onClose:()=>f(!1)})]});return Y?.length?t.jsxs("div",{className:`flex items-start rounded-xl border w-fit text-left transition-colors ${J(e.status)}`,children:[t.jsx("div",{className:"flex flex-col gap-0.5 pl-3 pr-2 py-2 min-w-0",children:Y.map((H,z)=>{const V=z===Y.length-1,K=t.jsx("span",{className:`truncate max-w-[200px] ${e.status==="rejected"?"line-through":""}`,children:H.label});return H.onClick?t.jsxs("button",{type:"button",onClick:H.onClick,className:"flex items-center gap-1 text-sm text-gray-800 hover:text-gray-900 hover:underline text-left rounded transition-colors",children:[K,V&&j?D:null,t.jsx("svg",{className:"h-3.5 w-3.5 text-gray-800 flex-shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},H.key):t.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600",children:[K,V&&j?D:null]},H.key)})}),q("pr-1","p-1.5 hover:bg-gray-200 rounded-xl")]}):t.jsxs("div",{className:`flex rounded-xl border w-fit text-left items-center transition-colors ${J(e.status)} ${T?"hover:bg-gray-200 cursor-pointer":""}`,onClick:T?A:void 0,children:[T?t.jsx("div",{className:"flex items-center pl-3 pr-2 py-2 text-gray-800",children:G}):t.jsx("div",{className:"flex gap-2 pl-3 pr-2 py-2",children:G}),q("pr-1",T?"p-1.5 hover:bg-gray-100 rounded-xl":"")]})},js=({message:e,isStreaming:s,isLastAssistantMessage:r,displayContent:n,copiedMessageId:i,onThumbsFeedback:o,onCopyMessage:a,onUndoToolChange:c,onSubmitFeedback:u,onScrollToBlock:p,onOpenImagePicker:d,onSwitchToPacket:f,isCheckpointValid:m,getBlock:g,activePacketId:b,trackPacketEvent:h,renderContentWithSuggestions:x})=>{const[w,y]=l.useState(null);if(e.message_type==="tool"&&e.toolCall)return t.jsx(Mo,{message:e,onUndo:c,onFeedback:u,onScrollToBlock:p,onOpenImagePicker:d,onSwitchToPacket:f,isCheckpointValid:m,getBlock:g,activePacketId:b,trackPacketEvent:h});const v=()=>e.message_type==="user"?"rounded-xl px-3 py-2 max-w-[80%] bg-gray-200 text-gray-900":e.message_type==="error"?"rounded-xl p-3 max-w-[80%] bg-gray-200 text-red-800":"rounded-xl px-3 pt-3 pb-1 w-full text-gray-900";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex ${e.message_type==="user"?"justify-end mb-1 mt-3":"justify-start"}`,children:t.jsx("div",{className:v(),children:t.jsx("div",{className:"text-sm",children:e.message_type==="assistant"?t.jsx(t.Fragment,{children:x(n)}):t.jsx(Gs,{className:"prose prose-sm max-w-none",components:mr,children:e.content})})})}),e.message_type==="assistant"&&r&&!s&&!e.fromGreeting&&t.jsxs("div",{className:"flex gap-1 mt-2 justify-start ml-2",children:[t.jsx(Ae,{text:"This was helpful",position:"top",anchor:"left",showArrow:!1,children:t.jsx("button",{onClick:()=>y("thumbs_up"),"aria-label":"This was helpful",className:"p-1.5 text-gray-500 hover:text-emerald-600 hover:bg-gray-100 rounded transition-colors",children:t.jsx(cr,{className:"h-4 w-4"})})}),t.jsx(fr,{open:w!==null,showRating:!1,onSubmit:({text:j})=>o(e,w,j),onClose:()=>y(null)}),t.jsx(Ae,{text:"This wasn't helpful",position:"top",anchor:"left",showArrow:!1,children:t.jsx("button",{onClick:()=>y("thumbs_down"),"aria-label":"This wasn't helpful",className:"p-1.5 text-gray-500 hover:text-red-600 hover:bg-gray-100 rounded transition-colors",children:t.jsx(lr,{className:"h-4 w-4"})})}),t.jsx(Ae,{text:i===e.id?"Copied!":"Copy message",position:"top",anchor:"left",showArrow:!1,children:t.jsx("button",{onClick:()=>a(e),"aria-label":"Copy Message",className:"p-1.5 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors",children:t.jsx(Zr,{className:"h-4 w-4"})})})]}),e.message_type==="assistant"&&!s&&!r&&e.suggestions?.length>0&&t.jsx("div",{className:"flex flex-col gap-1 mt-1.5 mb-1",children:e.suggestions.slice(0,3).map((j,k)=>t.jsx("span",{className:"text-xs text-gray-400 bg-gray-100 rounded-full px-2.5 py-1 w-fit",children:j.label},k))})]})},Oo=()=>t.jsxs("div",{className:"flex items-center gap-2 my-4 mx-3",children:[t.jsx("div",{className:"flex-1 h-px bg-gray-300"}),t.jsx("span",{className:"text-xs font-normal text-gray-500",children:"Previous session"}),t.jsx("div",{className:"flex-1 h-px bg-gray-300"})]}),$o=({outlineState:e,isStreaming:s})=>{if(!e?.packets?.length)return null;const r=e.packets.find(o=>o.role==="primary"),n=o=>!s||ur(o),i=r?n(r):!0;return t.jsxs("div",{className:"flex flex-col gap-3 pt-6",children:[!i&&t.jsx("p",{className:"text-sm text-gray-500 px-3",children:"Your resource is loading..."}),e.packets.map((o,a)=>{const c=n(o);return t.jsxs(Bo,{title:o.title||"Resource",done:c,defaultOpen:!0,animationOffset:a*.06,children:[(o.activities||[]).map((u,p)=>t.jsx(Uo,{name:u.name,state:u.status,delay:p*.06},u.index)),o.role==="primary"&&o.versions?.length>0&&t.jsxs("div",{className:"border-t border-gray-200 mt-2 pt-2",children:[t.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Also creating:"}),o.versions.map(u=>{let p;return u.role==="translation"?p=u.title||`${u.language} Translation`:u.role==="releveled"?p=u.title||`${u.reading_level} Version`:p=u.title||"Additional Version",t.jsx(Wo,{label:p,state:u.status},u.packet_index)})]})]},o.packet_index)})]})},Bo=({title:e,done:s,animationOffset:r=0,children:n})=>{const[i,o]=l.useState(!0);return t.jsxs("div",{className:"rounded-xl border border-gray-300 bg-gray-50 overflow-hidden animate-outline-item-enter ",style:{animationDelay:`${r}s`},children:[t.jsxs("button",{type:"button",onClick:()=>o(a=>!a),className:"flex w-full items-center gap-2 px-3 py-2.5 text-left rounded-xl hover:bg-gray-100 transition-colors duration-150",children:[s?t.jsx("span",{className:"animate-outline-check-pop",children:t.jsx(ls,{className:"h-4 w-4 text-emerald-600 flex-shrink-0",style:{strokeWidth:2.5}})}):t.jsx(Lt,{color:"text-emerald-600",size:4,className:"flex-shrink-0"}),t.jsx("span",{className:`text-sm font-medium truncate flex-1 ${s?"text-gray-800":"text-gray-600"}`,children:e}),t.jsx(Qr,{className:`h-4 w-4 text-gray-400 flex-shrink-0 transition-transform duration-200 ${i?"":"rotate-180"}`,style:{strokeWidth:2}})]}),n&&i&&t.jsx("div",{className:"border-t border-gray-200 px-3 py-1.5",children:n})]})},Uo=({name:e,state:s,delay:r=0})=>t.jsxs("div",{className:"flex items-center gap-2 py-1.5 animate-outline-item-enter",style:{animationDelay:`${r}s`},children:[t.jsx("div",{className:"flex h-4 w-4 items-center justify-center flex-shrink-0",children:s==="ready"?t.jsx("span",{className:"animate-outline-check-pop",children:t.jsx(ls,{className:"h-3.5 w-3.5 text-emerald-600",style:{strokeWidth:2.5}})}):t.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-gray-300"})}),t.jsx("span",{className:`text-sm transition-colors duration-500 ${s==="ready"?"text-gray-800":"text-gray-400 animate-outline-pulse"}`,children:e})]}),Wo=({label:e,state:s})=>t.jsxs("div",{className:"flex items-center gap-2 py-1",children:[t.jsx("div",{className:"flex h-4 w-4 items-center justify-center flex-shrink-0",children:s==="ready"?t.jsx("span",{className:"animate-outline-check-pop",children:t.jsx(ls,{className:"h-3.5 w-3.5 text-emerald-600",style:{strokeWidth:2.5}})}):t.jsx(Lt,{color:"text-emerald-600",size:3,className:"flex-shrink-0"})}),t.jsx("span",{className:`text-sm ${s==="ready"?"text-gray-800":"text-gray-400 animate-outline-pulse"}`,children:e})]}),Ct=({text:e="Thinking"})=>t.jsx("div",{className:"flex justify-start",children:t.jsx("div",{className:"px-3 pt-3 pb-1 text-gray-800",children:t.jsxs("div",{className:"text-sm flex items-center gap-2",children:[t.jsx("span",{children:e}),t.jsx("span",{className:"inline-block w-2 h-2 bg-emerald-600 rounded-full animate-pulse"}),t.jsx("span",{className:"inline-block w-2 h-2 bg-emerald-600 rounded-full animate-pulse delay-75"}),t.jsx("span",{className:"inline-block w-2 h-2 bg-emerald-600 rounded-full animate-pulse delay-150"})]})})}),Ho=({visible:e,onClick:s})=>t.jsx("div",{className:`absolute bottom-4 left-1/2 transform -translate-x-1/2 -translate-y-2 pointer-events-none z-10 transition-opacity duration-300 ease-in-out ${e?"opacity-100":"opacity-0"}`,children:t.jsx("button",{onClick:s,"aria-label":"Scroll to bottom",className:"bg-white border border-gray-300 rounded-full p-2 pointer-events-auto hover:bg-gray-100 text-gray-800 shadow-lg",children:t.jsx(Jn,{className:"h-4 w-4 text-gray-700"})})}),Vo=300,Go=6,zo=1e3,qo=({unlimitedRequest:e,followUpContext:s})=>{const[r,n]=l.useState(!1);if(!e)return null;const i=Array.isArray(s)?s.filter(u=>u&&u.question):[],o=e.length>Vo||e.split(`
2`).length>Go,a=o&&!r,c=a?e.slice(0,zo):e;return t.jsx(t.Fragment,{children:t.jsx("div",{className:"flex justify-end pt-3 text-sm",children:t.jsxs("div",{className:"rounded-xl px-3 py-2 max-w-[80%] bg-gray-200 text-gray-900",children:[t.jsx("p",{className:`text-sm whitespace-pre-wrap break-words ${a?"line-clamp-6":o?"-mr-2 pr-2 max-h-[60vh] overflow-y-auto bubble-scrollbar":""}`,children:c}),i.length>0&&t.jsx("div",{className:"grid",style:{gridTemplateRows:r?"1fr":"0fr",maxWidth:r?"500px":0,overflow:"hidden",transition:r?"grid-template-rows 300ms ease-in-out, max-width 0ms 0ms":"grid-template-rows 300ms ease-in-out, max-width 0ms 300ms"},children:t.jsx("div",{className:"overflow-hidden",children:t.jsx("ul",{className:"list-disc list-outside pl-4 mb-2 space-y-1",children:i.map(({question:u,answers:p})=>t.jsxs("li",{children:[u,":"," ",Array.isArray(p)?p.join(", ")||"—":p||"—"]}
2,u))})})}),(i.length>0||o)&&t.jsx("button",{onClick:()=>n(!r),className:"text-xs text-gray-600 hover:text-gray-800 mt-1 font-medium",children:r?"see less":"see more"})]})})})},Xo=({suggestionHeader:e})=>t.jsxs("div",{className:"flex flex-col mt-3 rounded-xl bg-gray-50 px-[5px] pt-1 pb-1 border border-gray-200","aria-hidden":"true",children:[e&&t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"px-1.5 pt-2.5 pb-3 text-sm text-gray-900",children:e}),t.jsx("div",{className:"-mx-[5px] border-b border-gray-200"})]}),t.jsx("div",{className:"flex items-center mx-1 px-2 py-2.5",children:t.jsx("div",{className:"h-4 w-36 rounded bg-gray-200/60 animate-pulse"})}),t.jsx("div",{className:"border-b border-gray-100 mx-2"}),t.jsx("div",{className:"flex items-center mx-1 px-2 py-2.5",children:t.jsx("div",{className:"h-4 w-44 rounded bg-gray-200/60 animate-pulse"})}),t.jsx("div",{className:"border-b border-gray-100 mx-2"}),t.jsx("div",{className:"flex items-center mx-1 px-2 py-2.5",children:t.jsx("div",{className:"h-4 w-28 rounded bg-gray-200/60 animate-pulse"})})]}),_s=({suggestions:e,suggestionHeader:s,onSuggestionClick:r,onActionClick:n,onUnlimitedFeedbackClick:i,unlimitedRequest:o,followUpContext:a,trackPacketEvent:c})=>{if(!e||e.length===0)return null;const u=(f,m)=>{m.type==="action"?(f.preventDefault(),c("Chat Action Suggestion Clicked",{action:m.action,label:m.label}),n(m)):m.type==="unlimited_feedback"?(f.preventDefault(),c("Unlimited Feedback Suggestion Clicked",{feedback_type:m.feedbackType,label:m.label,request:o||"",follow_up_context:a||[]}),i(m)):r(f,m,"suggestion_button")},p=f=>f.label,d=f=>f.type==="action"&&f.action==="navigate_to_tab";return t.jsxs("div",{className:"flex flex-col mt-3 rounded-xl bg-gray-50 px-[5px] pt-1 pb-1 border border-gray-200",children:[s&&t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"px-1.5 pt-2.5 pb-3 text-sm text-gray-900",children:s}),t.jsx("div",{className:"-mx-[5px] border-b border-gray-200"})]}),e.map((f,m)=>t.jsxs("div",{children:[m>0&&t.jsx("div",{className:"border-b border-gray-100 mx-2"}),t.jsx("div",{className:`pb-0.5 ${m===0&&s?"pt-1":"pt-0.5"}`,children:t.jsxs("button",{onClick:g=>u(g,f),className:"w-full flex items-center justify-between px-1.5 py-2 text-sm text-gray-600 hover:bg-gray-200/60 hover:text-gray-900 rounded-md transition-colors cursor-pointer",title:p(f),children:[t.jsxs("span",{className:"flex items-center gap-x-1.5 text-left",children:[d(f)&&t.jsx(Mt,{className:"h-4 w-4 flex-shrink-0"}),p(f)]}),t.jsx(en,{className:"h-4 w-4 text-gray-400 flex-shrink-0 mr-2"})]})})]},m))]})},Ss=["🎉","🎊","🌟","🎈","🍎","📚","✅"],Ko=()=>Ss[Math.floor(Math.random()*Ss.length)],Jo=({userOwnsPacket:e})=>{const[s]=l.useState(Ko);return t.jsxs("div",{className:"pt-6 pb-1 w-full px-3",children:[t.jsx("p",{className:"text-3xl mb-2",children:s}),t.jsx("p",{className:"text-sm text-gray-600",children:"Ready!"}),t.jsx("p",{className:"text-base font-medium text-gray-800 mt-1",children:e?"Chat with Diffit to refine, adapt, and customize your resources.":"Chat with Diffit to adapt this resource for your classroom."})]})},Yo=16,Zo=({messagesContainerRef:e,children:s,showBottomGradient:r,showTopGradient:n})=>{const[i,o]=l.useState(0);l.useEffect(()=>{const d=e.current;if(!d)return;const f=()=>o(d.offsetWidth-d.clientWidth);f();const m=new ResizeObserver(f);return m.observe(d),()=>m.disconnect()},[e]);const[a,c]=l.useState(!1),u=l.useRef(null);l.useEffect(()=>()=>clearTimeout(u.current),[]);const p=d=>{d.nativeEvent?.isTrusted&&(c(!0),clearTimeout(u.current),u.current=setTimeout(()=>c(!1),1e3))};return t.jsxs("div",{className:"relative flex-1 min-h-0",children:[t.jsx("div",{className:`pointer-events-none absolute top-0 left-0 right-0 h-16 bg-gradient-to-b from-gray-100 to-transparent z-10 transition-opacity duration-200 ${n?"opacity-100":"opacity-0"}`}),t.jsx("div",{className:`pointer-events-none absolute bottom-0 left-0 right-0 h-16 bg-gradient-to-t from-gray-100 to-transparent z-10 transition-opacity duration-200 ${r?"opacity-100":"opacity-0"}`}),t.jsx("div",{ref:e,id:"chat-sidebar-messages",className:`h-full overflow-y-scroll overscroll-contain chat-scrollbar ${a?"chat-scrollbar-visible":""}`,onScroll:p,children:t.jsx("div",{className:"min-h-full flex flex-col justify-start space-y-3",style:{paddingRight:Math.max(0,Yo-i)},children:s})})]})},Qo=({messages:e,streamingMessages:s,isAwaitingResponse:r,isExecutingCommands:n,isLoadingHistory:i,isProjectLoading:o,userOwnsPacket:a,copiedMessageId:c,showDownArrow:u,showTopGradient:p,showBottomGradient:d,isStreaming:f,isAwaitingImages:m,queuedMessage:g,outlineState:b,inputSuggestionsLoading:h,inputSuggestions:x,inputMessage:w,messagesContainerRef:y,messagesEndRef:v,unlimitedRequest:j,followUpContext:k,isClonedPacket:C,onSuggestionClick:D,onActionClick:E,onUnlimitedFeedbackClick:P,onThumbsFeedback:L,onCopyMessage:W,onUndoToolChange:F,onSubmitFeedback:N,onScrollToBlock:R,onOpenImagePicker:M,onSwitchToPacket:O,onScrollToBottom:_,isCheckpointValid:T,getBlock:A,activePacketId:X,getDisplayContent:se,trackPacketEvent:ne,renderContentWithSuggestions:Y})=>{const G=!!b?.packets?.length,J=!!o||a&&i,q=(!f||m)&&e.length===0&&!g&&!J,[H,z]=l.useState(null);return l.useEffect(()=>{const V=y.current;if(!q||!V||V.clientHeight===0){z(null);return}const ae=!!b?.packets?.length||a&&!C?40:0;z(V.clientHeight-ae)},[q,y,e.length,b,a,C]),l.useEffect(()=>{if(H==null)return;const V=y.current;if(!V)return;const K=requestAnimationFrame(()=>{V.scrollTop=V.scrollHeight,V.dispatchEvent(new Event("scroll"))});return()=>cancelAnimationFrame(K)},[H,y]),t.jsxs(Zo,{messagesContainerRef:y,showTopGradient:p,showBottomGradient:d,children:[a&&!i&&e.length===0&&!q&&!G&&t.jsx(Ct,{text:"Loading"}),a&&!C&&t.jsx(qo,{unlimitedRequest:j,followUpContext:k}),G&&b&&t.jsx($o,{outlineState:b,isStreaming:f}),J&&!f&&!G&&e.length===0&&t.jsx(Ct,{text:"Loading"}),q&&t.jsxs("div",{className:"flex flex-col",style:{animation:"outlineItemEnter 0.3s ease-out 0.1s both",height:H!=null?`${H}px`:void 0},children:[t.jsx("div",{className:"flex-1 flex items-start pt-6",children:t.jsx(Jo,{userOwnsPacket:a})}),x?.length>0&&!w?.trim()&&t.jsx("div",{className:"relative z-[8]",children:t.jsx(_s,{suggestions:x,suggestionHeader:"Try these to get started:",onSuggestionClick:D,onActionClick:E,onUnlimitedFeedbackClick:P,trackPacketEvent:ne})})]}),t.jsx(Ho,{visible:u,onClick:_}),e.map((V,K)=>{if(!V.content&&!V.toolCall&&!V.isInputSummary)return null;let ae=null;for(let oe=K-1;oe>=0;oe--)if(e[oe].content||e[oe].toolCall){ae=e[oe];break}const Q=!V.fromHistory&&ae?.fromHistory===!0,me=V.message_type==="assistant"&&K===e.length-1,pe=!!s[V.id],xe=se(V);return t.jsxs("div",{children:[Q&&t.jsx(Oo,{}),t.jsx(js,{message:V,isStreaming:pe,isLastAssistantMessage:me,displayContent:xe,copiedMessageId:c,unlimitedRequest:j,followUpContext:k,onSuggestionClick:D,onActionClick:E,onUnlimitedFeedbackClick:P,onThumbsFeedback:L,onCopyMessage:W,onUndoToolChange:F,onSubmitFeedback:N,onScrollToBlock:R,onOpenImagePicker:M,onSwitchToPacket:O,isCheckpointValid:T,getBlock:A,activePacketId:X,trackPacketEvent:ne,renderContentWithSuggestions:Y})]},K)}),g&&t.jsxs(t.Fragment,{children:[t.jsx("div",{children:t.jsx(js,{message:{message_type:"user",content:g}})}),t.jsx(Ct,{text:"Waiting for all images to load"})]}),!q&&(x?.length>0||h)&&!w?.trim()&&!f&&!r&&!n&&t.jsx("div",{className:"!mt-auto relative z-[8]",children:h?t.jsx(Xo,{}):t.jsx(_s,{suggestions:x,onSuggestionClick:D,onActionClick:E,onUnlimitedFeedbackClick:P,trackPacketEvent:ne})}),r&&t.jsx(Ct,{text:"Thinking"}),t.jsx("div",{ref:v,className:"!mt-2"})]})},ea=()=>{const e=go(),{isOpen:s,projectId:r,activePacketId:n,userOwnsProject:i,cloneProjectAndRedirect:o,refreshProject:a,switchToPacket:c,markPacketUpdated:u,updatePacketBlocks:p,updatePacketBlocksAndSettings:d,getAllPackets:f,packet:m,getBlock:g,setBlockLoading:b,addLoadingBlock:h,deleteBlock:x,setBlocks:w,setBlocksAndSettings:y,swapBlockWithContent:v,undoToCheckpoint:j,isCheckpointValid:k,hasCheckpoint:C,createCheckpoint:D,recordChatTurn:E,restoreProjectToVersion:P,undoRedoStackLengthValue:L,setPendingSlides:W,clearPendingSlides:F,doExport:N,user:R,trackProjectEvent:M,isStreaming:O,outlineState:_,isProjectLoading:T,pendingChatInput:A,setPendingChatInput:X,setTitleImageModalOpen:se,setModifyVocabImageModalOpen:ne,setModifyCustomActivityImageModalOpen:Y,setShareModalOpen:G,setAddToTemplatesMo
2dalOpen:J,messages:q,setMessages:H,inputMessage:z,setInputMessage:V,conversationId:K,setConversationId:ae,isAwaitingResponse:Q,setIsAwaitingResponse:me,isExecutingCommands:pe,setIsExecutingCommands:xe,isLoadingHistory:oe,setIsLoadingHistory:re,setHasLoadedGreeting:ie,copiedMessageId:Ne,setCopiedMessageId:be,streamingMessages:Ce,showDownArrow:Ve,setShowDownArrow:Ee,messagesEndRef:Je,textareaRef:Ge,messagesContainerRef:We,amountScrolledRef:ze,startStreaming:I,getDisplayContent:B}=e,Z=Re(n),{scrollToBottomIfNeeded:le,scrollToBottom:he,showTopGradient:ke,showBottomGradient:Le}=ko({messagesContainerRef:We,amountScrolledRef:ze,messages:q,streamingMessages:Ce,setShowDownArrow:Ee,isAwaitingResponse:Q,isLoadingHistory:oe}),{executeClientAction:Vt,handleUndoToolChange:Me,handleSetLoadingStateForTool:fe}=Co({activePacketId:n,messages:q,setMessages:H,conversationId:K,undoRedoStackLengthValue:L,isCheckpointValid:k,hasCheckpoint:C,undoToCheckpoint:j,getBlock:g,setBlockLoading:b,addLoadingBlock:h,setPendingSlides:W,doExport:N,refreshProject:a,trackProjectEvent:M});_o({projectId:r,packet:m,userOwnsProject:i,messages:q,setMessages:H,c
2onversationId:K,setConversationId:ae,setIsLoadingHistory:re,setHasLoadedGreeting:ie,trackProjectEvent:M});const{sendMessage:Ye,scrollToBlock:Ze,handleSuggestionClick:je,handleOpenImagePicker:ue,handleActionSuggestion:Te,handleUnlimitedFeedback:_e,staticSuggestions:ot}=Po({projectId:r,activePacketId:n,activePacketIdRef:Z,messages:q,setMessages:H,inputMessage:z,setInputMessage:V,conversationId:K,setConversationId:ae,isAwaitingResponse:Q,setIsAwaitingResponse:me,isExecutingCommands:pe,setIsExecutingCommands:xe,isLoadingHistory:oe,userOwnsProject:i,cloneProjectAndRedirect:o,executeClientAction:Vt,refreshProject:a,markPacketUpdated:u,updatePacketBlocks:p,updatePacketBlocksAndSettings:d,switchToPacket:c,getAllPackets:f,startStreaming:I,trackProjectEvent:M,textareaRef:Ge,amountScrolledRef:ze,getBlock:g,setTitleImageModalOpen:se,setModifyVocabImageModalOpen:ne,setModifyCustomActivityImageModalOpen:Y,doExport:N,setShareModalOpen:G,setAddToTemplatesModalOpen:J,setBlocks:w,setBlocksAndSettings:y,createCheckpoint:D,recordChatTurn:E,restoreProjectToVersion:P,handleSetLoadingStateForTool:fe,deleteBlock:x,swapBlockWithContent:v,setPendingSlides:W,clearPendingSlides:F}),{chatQueueDuringImageStreaming:vt}=Ke(),Oe=!!vt&&O&&Do(_),qe=O&&!Oe,at=l.useCallback($=>M("Chat Message Queued",{message_length:$.length}),[M]),{queuedMessage:Qe,handleSend:it}=Ao({canQueue:Oe,isStreaming:O,isLoadingHistory:oe,canSend:!!(n&&r),inputMessage:z,setInputMessage:V,sendMessage:Ye,onQueued:at}),lt=!!Qe,{handleInputChange:kt,handleKeyPress:ct,isSendDisabled:$e}=Ro({inputMessage:z,setInputMessage:V,textareaRef:Ge,isOpen:s,isAwaitingResponse:Q,isExecutingCommands:pe,pendingChatInput:A,setPendingChatInput:X,scrollToBottomIfNeeded:le,sendMessage:it}),Xe=l.useCallback(($,U,{rating:ee=null,text:de=""}={})=>{const Pe=U?.id||"",ve=K||"";M("Chat Feedback Opened",{conversation_id:ve,feedback_type:"tool_specific",message_id:Pe,tool_name:$?.tool,has_text:!!de?.trim(),helpfulness:ee||"none",model:U?.model}),ee&&M("Chat Message Feedback",{conversation_id:ve,feedback_type:ee,message_id:Pe,has_text:!!de?.trim(),model:U?.model}),ks({messageId:Pe,conversationId:ve,rating:ee,text:de})},[K,M]),Gt=l.useCallback(($,U,ee="")=>{const de=$?.id||"",Pe=K||"";M("Chat Message Feedback",{conversation_id:Pe,feedback_type:U,message_id:de,has_text:!!ee?.trim(),model:$?.model}),ks({messageId:de,conversationId:Pe,rating:U,text:ee})},[K,M]),jt=l.useCallback(async $=>{try{const U=$.content;await navigator.clipboard.writeText(U),be($.id),M("Chat Message Copied",{conversation_id:K,message_id:$.id}),setTimeout(()=>{be(null)},2e3)}catch(U){console.error("Failed to copy message:",U)}},[]),ce=l.useCallback($=>{const U={...mr,a:({href:ee,children:de,...Pe})=>{if(ee&&ee.startsWith("suggestion:")){const ve=decodeURIComponent(ee.replace("suggestion:","")),we={label:de,text:ve};return t.jsx("a",{onClick:zt=>je(zt,we),className:"inline font-bold underline whitespace-normal vertical-align-baseline text-emerald-700 hover:text-emerald-900 cursor-pointer transition-colors",title:"Click to use this suggestion",children:de})}if(ee&&ee.startsWith("image_picker:"))try{const we=ee.replace("image_picker:","").split("|"),zt={block_id:we[0],image_type:we[1],word_index:we[2]?parseInt(we[2],10):void 0,section_index:we[3]?parseInt(we[3],10):void 0,row_index:we[4]?parseInt(we[4],10):void 0,col_index:we[5]?parseInt(we[5],10):void 0};return t.jsx("a",{onClick:Or=>ue(Or,zt),className:"inline font-bold underline whitespace-normal vertical-align-baseline text-emerald-700 hover:text-emerald-900 cursor-pointer transition-colors",title:"Click to pick a different image",children:de})}catch(ve){return console.error("Failed to parse image picker params:",ve),t.jsx("span",{children:de})}return t.jsx("a",{href:ee,target:"_blank",rel:"noopener noreferrer",className:"underline",...Pe,children:de})}};return t.jsx(Gs,{className:"prose prose-sm max-w-none",components:U,urlTransform:ee=>ee,children:$})},[je,ue]),ye=[...q].reverse().find($=>$.message_type==="assistant"),_t=ye?.suggestionsLoading??!1,S=ye?.suggestions?.length>0?ye.suggestions:q.length===0?ot:[];return t.jsx("div",{id:"project-chat-sidebar",className:"flex flex-col h-full",children:t.jsx("div",{id:"project-chat-sidebar-content",className:"flex flex-col flex-1 min-h-0 overscroll-contain",children:t.jsxs("div",{className:"flex flex-col flex-1 ml-4 pt-6 min-h-0",children:[t.jsx(Qo,{messages:q,streamingMessages:Ce,isAwaitingResponse:Q,isLoadingHistory:oe,isProjectLoading:T,userOwnsPacket:i,copiedMessageId:Ne,showDownArrow:Ve,showTopGradient:ke,showBottomGradient:Le,isStreaming:O,isAwaitingImages:Oe,queuedMessage:Qe,outlineState:_,messagesContainerRef:We,messagesEndRef:Je,unlimitedRequest:m?.input_flags_json?.unlimited_request,followUpContext:m?.input_flags_json?.follow_up_context,onSuggestionClick:je,onActionClick:Te,onUnlimitedFeedbackClick:_e,onThumbsFeedback:Gt,onCopyMessage:jt,onUndoToolChange:Me,onSubmitFeedback:Xe,onScrollToBlock:Ze,onOpenImagePicker:ue,onSwitchToPacket:c,onScrollToBottom:he,isCheckpointValid:k,getBlock:g,activePacketId:n,getDisplayContent:B,trackPacketEvent:M,renderContentWithSuggestions:ce,inputSuggestions:S,inputSuggestionsLoading:_t,inputMessage:z}),t.jsx(Fo,{inputMessage:z,textareaRef:Ge,onInputChange:kt,onKeyPress:ct,onSend:it,isDisabled:qe||lt,isSe
2ndDisabled:$e||qe||lt})]})})})},ta=({isOpen:e,setOpen:s})=>t.jsx(xo,{isOpen:e,setOpen:s,children:t.jsx(ea,{})}),sa=({readOnly:e=!1,trackProjectEvent:s})=>{const{getProjectTitle:r,updateProjectTitle:n,getIsOwner:i}=ge(),[o,a]=l.useState(r()||""),[c,u]=l.useState(!1),[p,d]=l.useState(0),f=l.useRef(null),m=l.useRef(null),g=i();l.useEffect(()=>{const y=r();y&&y!==o&&a(y)},[r]);const b=()=>{e||(m.current&&d(m.current.offsetWidth),u(!0),setTimeout(()=>{if(f.current){f.current.focus();const y=f.current.value.length;f.current.setSelectionRange(y,y)}},0))},h=()=>{u(!1);const y=r();o?o!==y&&(s("Project Title Updated",{original_project_title:y,edited_project_title:o}),n(o)):a(y||"")};l.useEffect(()=>{m.current&&d(m.current.offsetWidth)},[o]);const x=r()||"";return t.jsx(Ae,{text:x.length>40?x:"",position:"bottom",children:t.jsx("div",{className:"flex items-center min-w-0 w-full",children:t.jsx("div",{className:"relative flex items-center min-w-0 w-full",children:c?t.jsx("textarea",{ref:f,style:{width:`${p}px`},id:"project-title",className:`
3              w-full text-gray-800 text-sm resize-none
4              border
5              border-emerald-600
6              bg-transparent
7              font-medium
8              outline-none
9              focus:outline-none
10              focus:ring-0
11              focus:border-emerald-600
12              rounded-lg
13              py-1
14              px-2
15            `,value:o,onChange:y=>a(y.target.value),onBlur:h,onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),y.target.blur())},name:"project-title","aria-label":"Resource Title"}):g?t.jsx("div",{ref:m,onClick:b,className:`
16              ${e?"cursor-default":"cursor-text hover:border-gray-400"}
17              text-gray-800 text-sm text-balance line-clamp-2
18              border
19              border-transparent
20              bg-transparent
21              font-medium
22              rounded-lg
23              py-1
24              px-2
25            `,children:o}):t.jsx(Ae,{text:o,position:"bottom",children:t.jsx("div",{ref:m,rows:2,onClick:b,className:`
26                ${e?"cursor-default":"cursor-text hover:border-gray-400"}
27                text-gray-800 text-sm text-balance line-clamp-2
28                border
29                border-transparent
30                bg-transparent
31                font-medium
32                rounded-lg
33                py-1
34                px-2
35              `,children:o})})})})})},ra=()=>{const{isViewingVersion:e,versionMeta:s}=ge(),{setHistoryDrawerOpen:r}=Be(),[n,i]=Ot();if(!e)return null;const o=()=>{const c=new URLSearchParams(n);c.delete("version"),i(c,{replace:!0})},a=s?.capturedAt?tn(new Date(s.capturedAt),{addSuffix:!0}):null;return t.jsx("div",{className:"sticky top-0 z-[11] w-full bg-amber-50 border-b border-amber-200 print:hidden",children:t.jsxs("div",{className:"flex items-center justify-between px-6 py-2",children:[t.jsxs("span",{className:"text-amber-800 text-sm font-medium",children:[t.jsxs("span",{children:["Viewing version ",s?.versionNumber]}),a&&t.jsxs("span",{children:[" · captured ",a]})]}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx("button",{onClick:o,className:"text-amber-700 hover:text-amber-900 text-sm font-semibold px-3 py-1 rounded-md hover:bg-amber-100 transition-colors focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-1",children:t.jsx("span",{children:"Exit"})})})]})})},na=({trackProjectEvent:e,addButton:s,undoButton:r,redoButton:n,presentButton:i,exportButton:o,packets:a=[]})=>{const{getAllPackets:c,getActivePacketId:u,switchToPacket:p,getProjectId:d,getIsOwner:f,refreshProject:m,reorderPackets:g,setRemoveResourceConfirmation:b,getUpdatedPacketIds:h}=ge(),{printPacket:x}=nt(),{setPacketSettingsModalOpen:w}=Be(),{getPacket:y}=Fe(),{printShortcutIcon:v}=Ke();a=a.length?a:c();const j=u(),k=d(),C=f(),D=h(),{isStreaming:E,isViewingVersion:P}=ge(),W=a.find(I=>I.packet.id===j)?.packet?.orientation==="16x9"?sr:ds,F=y(),N=F?.blocks||[],R=E&&N.some(I=>I.canonical_id?.startsWith("loading")),M=l.useRef(!0),[O,_]=l.useState(!1),T=l.useRef(new Set),[A,X]=l.useState(new Set);l.useEffect(()=>
35{if(a.length<=1){M.current=!0,T.current=new Set;return}const I=new Set(a.map(Z=>Z.packet.id));if(M.current){_(!0);const Z=setTimeout(()=>_(!1),400);return T.current=I,M.current=!1,()=>clearTimeout(Z)}const B=new Set;if(I.forEach(Z=>{T.current.has(Z)||B.add(Z)}),B.size>0){X(B);const Z=setTimeout(()=>{X(le=>le.size>0?new Set:le)},350);return T.current=I,()=>clearTimeout(Z)}T.current=I},[a]);const[se,ne]=l.useState(null),[Y,G]=l.useState(null),[J,q]=l.useState(null),[H,z]=l.useState(0),V=l.useRef(null),K=l.useRef({});l.useEffect(()=>{if(V.current!==null){const I=V.current;V.current=null;const B=K.current[I];B&&B.focus()}});const ae=l.useRef(null),[Q,me]=l.useState(!1),[pe,xe]=l.useState(!1),oe=l.useCallback(()=>{const I=ae.current;I&&(me(I.scrollLeft>1),xe(I.scrollLeft+I.clientWidth<I.scrollWidth-1))},[]);l.useEffect(()=>{const I=ae.current;if(!I)return;oe(),I.addEventListener("scroll",oe);const B=new ResizeObserver(oe);return B.observe(I),()=>{I.removeEventListener("scroll",oe),B.disconnect()}},[a.length,oe]);const re=I=>{const B=ae.current;B&&B.scrollBy({left:I*150,behavior:"smooth"})};if(!a.length)return null;const ie=(I,B)=>{const Z=[...a],[le]=Z.splice(I,1);Z.splice(B,0,le),g(Z),e("Tabs Reordered",{from_index:I,to_index:B})},Ne=(I,B)=>{G(B),I.dataTransfer.effectAllowed="move",I.dataTransfer.setData("text/plain",B.toString())},be=(I,B)=>{I.preventDefault(),I.dataTransfer.dropEffect="move",Y!==null&&B!==Y&&q(B)},Ce=()=>{q(null)},Ve=(I,B)=>{if(I.preventDefault(),Y===null||Y===B){G(null),q(null);return}ie(Y,B),G(null),q(null)},Ee=()=>{G(null),q(null)},Je=(I,B,Z)=>{Z.stopPropagation(),ne(null);const le=a.findIndex(ke=>ke.packet.id===I);let he=null;le>0?he=a[le-1].packet.id:a.length>1&&(he=a[1].packet.id),b({packetId:I,packetTitle:B,projectId:k,onConfirm:async()=>{try{await sn(k,I),e("Resource Removed",{packet_id:I}),I===j&&he&&p(he),await m()}catch(ke){console.error("Failed to remove resource:",ke),ke.response?.status===400?alert("Cannot remove the last resource from a set."):alert("Failed to remove resource. Please try again.")}}})},Ge=(I,B)=>{B.stopPropagation(),ne(null),I!==j&&p(I),setTimeout(()=>{w(!0)},50),e("Tab Settings Clicked",{packet_id:I})},We=(I,B)=>{const Z=a.length;for(let le=1;le<=Z;le++){const he=((I+B*le)%Z+Z)%Z;if(K.current[he]){z(he),K.current[he].focus();return}}},ze=(I,B)=>{if(I.target!==I.currentTarget)return;const Z=a.length-1;if(I.key==="ArrowRight")if(I.ctrlKey||I.metaKey){if(!C||B>=Z)return;I.preventDefault(),ie(B,B+1),z(B+1),V.current=B+1}else I.preventDefault(),We(B,1);else if(I.key==="ArrowLeft")if(I.ctrlKey||I.metaKey){if(!C||B<=0)return;I.preventDefault(),ie(B,B-1),z(B-1),V.current=B-1}else I.preventDefault(),We(B,-1);else I.key==="Home"?(I.preventDefault(),z(0),K.current[0]?.focus()):I.key==="End"?(I.preventDefault(),z(Z),K.current[Z]?.focus()):(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),p(a[B].packet.id))};return t.jsxs("div",{className:`group/tabs relative flex items-center max-w-full bg-gray-100 border border-gray-200 pl-1 pr-1.5 rounded-2xl transition-[width] duration-200 ease-out py-1 mx-2 ${O?"animate-tab-bar-fade-in":""}`,style:{width:W},children:[t.jsxs("div",{className:"relative flex items-center min-w-0 max-w-full",children:[Q&&t.jsx("button",{type:"button",onClick:()=>re(-1),className:"absolute left-1.5 z-10 flex-shrink-0 p-1 rounded-full text-gray-500 hover:text-gray-800 transition-opacity duration-150 bg-gray-100/90 hover:bg-gray-200","aria-label":"Scroll tabs left",children:t.jsx(xt,{className:"h-4 w-4"})}),t.jsx("div",{ref:ae,role:"tablist","aria-label":"Resources",className:"flex items-center gap-x-1 overflow-x-hidden min-w-0 max-w-full rounded-xl",children:a.map((I,B)=>{const{packet:Z}=I,le=Z._isLoadingSecondary,he=A.has(Z.id),ke=Z?.title||"Untitled";return le?t.jsx("div",{className:`flex-shrink-0 ${he?"animate-tab-emerge":""}`,children:t.jsxs("div",{className:"flex items-center pl-3 pr-3 py-2.5 rounded-xl bg-gray-100 text-gray-400 border border-transparent select-none animate-outline-pulse",title:`${ke} — generating...`,children:[t.jsx("div",{className:"flex-shrink-0",children:Z.orientation==="16x9"?t.jsx(ms,{className:"h-4 w-4"}):t.jsx(Mt,{className:"h-4 w-4"})}),t.jsx("span",{className:"text-sm font-normal truncate ml-1.5 max-w-[150px]",children:ke})]})},Z.id):t.jsx(oa,{packetData:I,index:B,isActive:Z.id===j,isGenerating:Z.id===j&&R,hasUpdate:Z.id!==j&&D.has(Z.id),isEmerging:he,isDragging:Y===B,isAnyDragging:Y!==null,isDragOver:J===B,isOwner:C&&!P,isFocused:H===B,tabRef:Le=>K.current[B]=Le,onKeyDown:Le=>ze(Le,B),onFocus:()=>z(B),activePacketFromContext:F,openMenuId:se,setOpenMenuId:ne,switchToPacket:p,onDragStart:Ne,onDragOver:be,onDragLeave:Ce,onDrop:Ve,onDragEnd:Ee,onSettings:Ge,onRemoveResource:Je,showRemove:a.length>1,undoButton:r,redoButton:n},Z.id)})}),pe&&t.jsx("button",{type:"button",onClick:()=>re(1),className:"absolute right-1.5 z-10 flex-shrink-0 p-1 rounded-full bg-gray-100/90 text-gray-500 hover:text-gray-800 hover:bg-gray-200 transition-opacity duration-150","aria-label":"Scroll tabs right",children:t.jsx(bt,{className:"h-4 w-4"})})]}),s&&t.jsx("div",{className:"flex-shrink-0 ml-2",children:s}),o&&t.jsxs("div",{className:"flex-shrink-0 flex items-center gap-x-2 ml-auto pl-2",children:[v&&t.jsx("button",{onClick:()=>{e("Print Clicked",{location:"tab_bar"},{includeBlocks:!0}),x()},className:"px-2 py-2 rounded-xl hover:bg-gray-200 flex items-center text-gray-600 hover:text-gray-900","aria-label":"Print",children:t.jsx(us,{className:"size-5"})}),i,o]})]})},oa=({packetData:e,index:s,isActive:r,isGenerating:n,hasUpdate:i,isEmerging:o,isDragging:a,isAnyDragging:c,isDragOver:u,isOwner:p,isFocused:d,tabRef:f,onKeyDown:m,onFocus:g,activePacketFromContext:b,openMenuId:h,setOpenMenuId:x,switchToPacket:w,onDragStart:y,onDragOver:v,onDragLeave:j,onDrop:k,onDragEnd:C,onSettings:D,onRemoveResource:E,showRemove:P,undoButton:L,redoButton:W})=>{const{packet:F}=e,N=F?.title||"Untitled",R=l.useRef(null),[M,O]=l.useState(!1),{isSignedIn:_}=Dt(),T=l.useCallback(()=>{const A=R.current;A&&O(A.scrollWidth>A.clientWidth)},[]);return l.useEffect(()=>{T();const A=new ResizeObserver(T);return R.current&&A.observe(R.current),()=>A.disconnect()},[N,T]),t.jsx("div",{className:`group/tabpill ${r?"shrink min-w-[9rem]":"shrink-[100] min-w-[5.5rem]"} transition-[min-width] duration-200 ease-out ${u?"ring-2 ring-gray-400 rounded-xl":""} ${o?"animate-tab-emerge":""}`,role:"tab","aria-selected":r,tabIndex:d?0:-1,ref:f,draggable:p?"true":"false",onDragStart:A=>p&&y(A,s),onDragOver:A=>v(A,s),onDragLeave:j,onDrop:A=>k(A,s),onDragEnd:C,onKeyDown:m,onFocus:g,children:t.jsxs("div",{onClick:()=>w(F.id),className:`
36        group/tab flex items-center rounded-xl cursor-pointer
37        transition-all duration-200 ease-out select-none
38        relative pl-3 py-2.5 min-w-0
39
40        ${r?"pr-2 bg-white text-gray-800 border border-gray-200 group-focus-visible/tabpill:ring-2 group-focus-visible/tabpill:ring-emerald-600 group-focus-visible/tabpill:outline-none":""}
41        ${r?"":"pr-3 bg-gray-100 text-gray-600 hover:bg-gray-200 border border-transparent group-focus-visible/tabpill:bg
41-gray-200 group-focus-visible/tabpill:outline-none"}
42
43        ${a?"opacity-50 scale-95":""}
44        ${p?"cursor-grab active:cursor-grabbing":""}
45        ${n?"animate-outline-pulse":""}
46      `,children:[t.jsx("div",{className:"flex-shrink-0",children:e.packet.orientation==="16x9"?t.jsx(ms,{className:"h-4 w-4"}):t.jsx(Mt,{className:"h-4 w-4"})}),t.jsx(Ae,{text:N,position:"bottom",anchor:"center",showArrow:!0,usePortal:!0,size:"xs",offset:5,className:"min-w-0",disabled:!M||c||h!==null,children:t.jsx("span",{ref:R,className:`text-sm font-normal truncate ml-1.5 min-w-0 transition-[max-width] duration-200 ease-out ${r?"max-w-[180px]":"max-w-[150px]"} ${i?"animate-shimmer bg-[length:300%_100%] bg-clip-text text-transparent bg-[linear-gradient(90deg,#4b5563_30%,#d1d5db_50%,#4b5563_70%)]":""}`,children:N})}),r&&L,r&&W,(p||!_)&&r&&t.jsx(ia,{packet:r&&b?b:F,isActive:r,onOpenChange:A=>x(A?F.id:null),onSettings:A=>D(F.id,A),onRemove:A=>E(F.id,N,A),showRemove:P}),t.jsx("span",{"aria-label":i?"New content available":void 0,className:`text-[10px] font-semibold uppercase rounded-full bg-white text-emerald-500 inline-flex flex-shrink-0 overflow-hidden transition-all duration-200 ease-out ${i?"max-w-[40px] px-1.5 py-0.5 ml-0.5 opacity-100":"max-w-0 px-0 py-0 ml-0 opacity-0"}`,children:"new"})]})})},aa=({open:e,onOpenChange:s})=>(l.useEffect(()=>{s?.(e)},[e,s]),null),Ns=384,ia=({packet:e,isActive:s,onOpenChange:r,onSettings:n,onRemove:i,showRemove:o})=>{const[a,c]=l.useState({top:0,left:0}),u=m=>{const g=m.getBoundingClientRect(),b=g.left+Ns>window.innerWidth-8;c({top:g.bottom+4,left:b?g.right-Ns:g.left})},d=rn(e).map(m=>nn(m)).filter(Boolean),f=m=>`w-full px-3 py-2 text-left ${m?"bg-gray-100":""} rounded-lg text-sm text-gray-700 transition-colors whitespace-nowrap flex items-center gap-2.5`;return t.jsx(Ie,{as:"div",className:"flex items-center",children:({open:m})=>t.jsxs(t.Fragment,{children:[t.jsx(aa,{open:m,onOpenChange:r}),t.jsx(Ie.Button,{"aria-label":"Tab options",onClick:g=>{g.stopPropagation(),u(g.currentTarget)},onKeyDown:g=>{(g.key==="Enter"||g.key===" "||g.key==="ArrowDown")&&u(g.currentTarget)},className:`rounded-full hover:bg-gray-200 focus-visible:bg-gray-200 focus-visible:outline-none
47          ${s?"p-1.5 -my-1 flex-shrink-0 ml-0.5":"p-0.5 absolute right-1 bg-gray-200 hidden group-hover/tab:block"}`,title:"More options",children:t.jsx(ir,{className:`h-4 w-4 ${s?"text-gray-800":"text-gray-600"}`})}),m&&cs.createPortal(t.jsx("div",{className:"fixed z-[100]",style:{top:`${a.top}px`,left:`${a.left}px`},onClick:g=>g.stopPropagation(),children:t.jsxs(Ie.Items,{static:!0,className:"w-auto max-w-sm bg-white rounded-xl shadow-lg border border-gray-200 p-1.5 focus:outline-none",children:[d.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-3 py-2",children:[t.jsxs("div",{className:"flex items-center gap-x-1.5 text-xs font-medium text-gray-500 mb-1.5",children:[t.jsx(on,{className:"h-3.5 w-3.5"}),t.jsx("span",{children:"Standards & Skills"})]}),t.jsx("div",{className:"flex flex-wrap gap-1",children:d.map(g=>t.jsx("span",{className:"inline-block px-2 py-0.5 text-xs font-medium text-gray-700 bg-gray-100 rounded-full",children:g},g))})]}),t.jsx("div",{className:"my-1 border-b border-gray-100"})]}),t.jsx(Ie.Item,{children:({active:g})=>t.jsxs("button",{onClick:n,className:f(g),children:[t.jsx(ro,{className:"h-4 w-4 flex-shrink-0"}),"Resource Settings"]})}),o&&t.jsx(Ie.Item,{children:({active:g})=>t.jsxs("button",{onClick:i,className:f(g),children:[t.jsx(an,{className:"h-4 w-4 flex-shrink-0"}),"Remove"]})})]})}),document.body)]})})},la=()=>{const{getAllPackets:e,getActivePacketId:s,switchToPacket:r}=ge(),n=e(),i=s(),o=l.useRef(null);return l.useEffect(()=>{o.current?.scrollIntoView({inline:"nearest",block:"nearest"})},[i]),n.length<2?null:t.jsx("div",{role:"tablist","aria-label":"Resources",className:"flex items-center gap-x-1 overflow-x-auto px-3 bg-white border-b border-gray-200 print:hidden",children:n.map(({packet:a})=>{const c=a.id===i,u=a?.title||"Untitled",p=a.orientation==="16x9"?ms:Mt;return a._isLoadingSecondary?t.jsxs("div",{title:`${u} — generating...`,className:"flex items-center gap-x-1.5 flex-shrink-0 px-3 py-3 border-b-2 border-transparent text-gray-400 animate-pulse",children:[t.jsx(p,{className:"h-4 w-4 flex-shrink-0"}),t.jsx("span",{className:"text-sm truncate max-w-[9rem]",children:u})]},a.id):t.jsxs("button",{ref:c?o:null,type:"button",role:"tab","aria-selected":c,onClick:()=>r(a.id),className:`flex items-center gap-x-1.5 flex-shrink-0 px-3 py-3 border-b-2 transition-colors ${c?"border-emerald-600 text-gray-900 font-medium":"border-transparent text-gray-500"}`,children:[t.jsx(p,{className:"h-4 w-4 flex-shrink-0"}),t.jsx("span",{className:"text-sm truncate max-w-[9rem]",children:u})]},a.id)})})},ca=[{id:"simplified",title:"Scaffolded Version",prompt:"Create an accessible version as a new resource, with adaptations and scaffolds for students at this reading level: "},{id:"advanced",title:"Advanced Version",prompt:"Create an advanced version as a new resource, with extensions and extra challenge for students at this reading level: "},{id:"translate",title:"Translation",prompt:"Create a translation of this resource in this language: "},{id:"teacher-guide",title:"Teacher Guide",prompt:"Create a teacher guide as a new resource."},{id:"slides",title:"Slides",prompt:"Create a front-of-room slides version as a new resource."},{divider:!0},{id:"custom",title:"Custom",prompt:"Create an additional resource that "}],da=()=>{const[e,s]=l.useState(!1),r=l.useRef(null),{getProjectId:n,getPacketCount:i}=ge(),{setChatModalOpen:o,setPendingChatInput:a}=Be(),c=n(),u=i();l.useEffect(()=>{const f=m=>{r.current&&!r.current.contains(m.target)&&s(!1)};return e&&document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[e]);const p=()=>{Se.track("Add Resource Button Clicked",{project_id:c,packet_count:u}),s(!e)},d=f=>{s(!1),Se.track("Add Resource Option Selected",{project_id:c,option_id:f.id,option_title:f.title}),a(f.prompt),o(!0)};return t.jsxs("div",{ref:r,className:"relative",children:[t.jsx(Ae,{text:"Add Resource",position:"bottom",anchor:"center",showArrow:!0,disabled:e,children:t.jsx("button",{onClick:p,className:"px-2.5 py-2.5 rounded-xl hover:bg-gray-200 flex items-center text-gray-600 hover:text-gray-900","aria-label":"Add Resource",children:t.jsx(zs,{className:"size-4"})})}),e&&t.jsx("div",{className:"absolute top-full right-0 mt-1 bg-white shadow-lg z-50 border border-gray-200 w-auto rounded-xl p-1.5",children:ca.map((f,m)=>f.divider?t.jsx("div",{className:"my-1 mx-2 border-t border-gray-200"},`div-${m}`):t.jsx("button",{onClick:()=>d(f),className:"w-full px-3 py-2 text-left hover:bg-gray-100 rounded-lg text-sm text-gray-700 transition-colors whitespace-nowrap",children:f.title},f.id))})]})},ua=({blocks:e,documentRef:s,isStreaming:r})=>{const{getProjectId:n,isViewingVersion:i}=ge(),o=(a,c={})=>{Se.track(a,{...c,project_id:n()})};return t.jsx(rr,{blocks:e,documentRef:s,showPrintFooter:!0,hideFooter:i,trackEvent:o,isStreaming:r})},Cs="bg-gray-200/60 rounded-full h-3",ma=["w-3/4","w-full","w-5/6","w-2/3","w-full","w-4/5","w-3/5","w-full","w-5/6","w-3/4","w-2/3","w-full","w-4/5"],fa=["w-3/4","w-full","w-5/6","w-2/3"],pa=5,ut=({orientation:e="portrait",offsetTop:s=!1})=>{const r="w-full md:w-[75%]",n=s?"mt-8":"",i=s?{overflowAnchor:"none"}
47:void 0,o="bg-gradient-to-b from-white to-transparent rounded-lg p-8 animate-pulse overflow-hidden md:overflow-visible";return e==="16x9"?t.jsxs("div",{className:`max-w-[1010px] aspect-[16/9] ${r} ${n} ${o} flex gap-6`,style:i,children:[t.jsx("div",{className:"bg-gray-200/60 rounded-lg aspect-square h-full flex-shrink-0"}),t.jsx("div",{className:"flex flex-col gap-3 flex-1 justify-center",children:fa.map((a,c)=>t.jsx("div",{className:`${Cs} ${a}`},c))})]}):t.jsxs("div",{className:`max-w-[820px] aspect-[8.5/11] ${r} ${n} ${o}`,style:i,children:[t.jsx("div",{className:"bg-gray-200/60 rounded-lg w-full h-1/2 mb-6"}),t.jsx("div",{className:"flex flex-col gap-3",children:ma.map((a,c)=>t.jsx("div",{className:`${Cs} ${a} ${c>=pa?"hidden md:block":""}`},c))})]})},ha=({onClose:e,config:s})=>{const{packetId:r,packetTitle:n,projectId:i,onConfirm:o}=s,a=()=>{Se.track("Resource Deleted From Project",{project_id:i,packet_id:r,packet_title:n}),o(),e()};return t.jsx(gt,{showModal:!0,setShowModal:e,title:"Remove Resource?",iconBackground:"bg-red-100",icon:t.jsx(ln,{className:"w-5 h-5 text-red-600"}),children:t.jsxs("div",{children:[t.jsx("div",{className:"text-sm text-gray-600 text-center",children:t.jsxs("p",{children:["Remove ",t.jsx("span",{className:"font-bold",children:n})," from this set?"]})}),t.jsxs("div",{className:"flex flex-row mt-4 gap-x-2 text-sm items-center justify-center font-bold",children:[t.jsx("button",{className:"bg-white hover:bg-gray-100 border border-gray-300 text-gray-500 px-4 py-2 rounded-md",onClick:e,children:"Cancel"}),t.jsx("button",{className:"bg-red-600 hover:bg-red-500 text-white px-4 py-2 rounded-md",onClick:a,children:"Remove"})]})]})})};function ga(e,s){return e[13]=1,e[14]=s>>8,e[15]=s&255,e[16]=s>>8,e[17]=s&255,e}const pr=112,hr=72,gr=89,xr=115;let Yt;function xa(){const e=new Int32Array(256);for(let s=0;s<256;s++){let r=s;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[s]=r}return e}function ba(e){let s=-1;Yt||(Yt=xa());for(let r=0;r<e.length;r++)s=Yt[(s^e[r])&255]^s>>>8;return s^-1}function ya(e){const s=e.length-1;for(let r=s;r>=4;r--)if(e[r-4]===9&&e[r-3]===pr&&e[r-2]===hr&&e[r-1]===gr&&e[r]===xr)return r-3;return 0}function wa(e,s,r=!1){const n=new Uint8Array(13);s*=39.3701,n[0]=pr,n[1]=hr,n[2]=gr,n[3]=xr,n[4]=s>>>24,n[5]=s>>>16,n[6]=s>>>8,n[7]=s&255,n[8]=n[4],n[9]=n[5],n[10]=n[6],n[11]=n[7],n[12]=1;const i=ba(n),o=new Uint8Array(4);if(o[0]=i>>>24,o[1]=i>>>16,o[2]=i>>>8,o[3]=i&255,r){const a=ya(e);return e.set(n,a),e.set(o,a+13),e}else{const a=new Uint8Array(4);a[0]=0,a[1]=0,a[2]=0,a[3]=9;const c=new Uint8Array(54);return c.set(e,0),c.set(a,33),c.set(n,37),c.set(o,50),c}}const va="AAlwSFlz",ka="AAAJcEhZ",ja="AAAACXBI";function _a(e){let s=e.indexOf(va);return s===-1&&(s=e.indexOf(ka)),s===-1&&(s=e.indexOf(ja)),s}const br="[modern-screenshot]",He=typeof window<"u",Sa=He&&"Worker"in window,Na=He&&"atob"in window,Ca=He&&"btoa"in window,ps=He?window.navigator?.userAgent:"",yr=ps.includes("Chrome"),At=ps.includes("AppleWebKit")&&!yr,hs=ps.includes("Firefox"),Ea=e=>e&&"__CONTEXT__"in e,Ta=e=>e.constructor.name==="CSSFontFaceRule",Pa=e=>e.constructor.name==="CSSImportRule",De=e=>e.nodeType===1,wt=e=>typeof e.className=="object",wr=e=>e.tagName==="image",Ra=e=>e.tagName==="use",ft=e=>De(e)&&typeof e.style<"u"&&!wt(e),Ia=e=>e.nodeType===8,Aa=e=>e.nodeType===3,st=e=>e.tagName==="IMG",Bt=e=>e.tagName==="VIDEO",Da=e=>e.tagName==="CANVAS",Fa=e=>e.tagName==="TEXTAREA",La=e=>e.tagName==="INPUT",Ma=e=>e.tagName==="STYLE",Oa=e=>e.tagName==="SCRIPT",$a=e=>e.tagName==="SELECT",Ba=e=>e.tagName==="SLOT",Ua=e=>e.tagName==="IFRAME",Wa=(...e)=>console.warn(br,...e);function Ha(e){const s=e?.createElement?.("canvas");return s&&(s.height=s.width=1),!!s&&"toDataURL"in s&&!!s.toDataURL("image/webp").includes("image/webp")}const ns=e=>e.startsWith("data:");function vr(e,s){if(e.match(/^[a-z]+:\/\//i))return e;if(He&&e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i)||!He)return e;const r=Ut().implementation.createHTMLDocument(),n=r.createElement("base"),i=r.createElement("a");return r.head.appendChild(n),r.body.appendChild(i),s&&(n.href=s),i.href=e,i.href}function Ut(e){return(e&&De(e)?e?.ownerDocument:e)??window.document}const Wt="http://www.w3.org/2000/svg";function Va(e,s,r){const n=Ut(r).createElementNS(Wt,"svg");return n.setAttributeNS(null,"width",e.toString()),n.setAttributeNS(null,"height",s.toString()),n.setAttributeNS(null,"viewBox",`0 0 ${e} ${s}`),n}function Ga(e,s){let r=new XMLSerializer().serializeToString(e);return s&&(r=r.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"")),`data:image/svg+xml;charset=utf-8,${encodeURIComponent(r)}`}function za(e,s){return new Promise((r,n)=>{const i=new FileReader;i.onload=()=>r(i.result),i.onerror=()=>n(i.error),i.onabort=()=>n(new Error(`Failed read blob to ${s}`)),i.readAsDataURL(e)})}const qa=e=>za(e,"dataUrl");function tt(e,s){const r=Ut(s).createElement("img");return r.decoding="sync",r.loading="eager",r.src=e,r}function pt(e,s){return new Promise(r=>{const{timeout:n,ownerDocument:i,onError:o,onWarn:a}=s??{},c=typeof e=="string"?tt(e,Ut(i)):e;let u=null,p=null;function d(){r(c),u&&clearTimeout(u),p?.()}if(n&&(u=setTimeout(d,n)),Bt(c)){const f=c.currentSrc||c.src;if(!f)return c.poster?pt(c.poster,s).then(r):d();if(c.readyState>=2)return d();const m=d,g=b=>{a?.("Failed video load",f,b),o?.(b),d()};p=()=>{c.removeEventListener("loadeddata",m),c.removeEventListener("error",g)},c.addEventListener("loadeddata",m,{once:!0}),c.addEventListener("error",g,{once:!0})}else{const f=wr(c)?c.href.baseVal:c.currentSrc||c.src;if(!f)return d();const m=async()=>
47{if(st(c)&&"decode"in c)try{await c.decode()}catch(b){a?.("Failed to decode image, trying to render anyway",c.dataset.originalSrc||f,b)}d()},g=b=>{a?.("Failed image load",c.dataset.originalSrc||f,b),d()};if(st(c)&&c.complete)return m();p=()=>{c.removeEventListener("load",m),c.removeEventListener("error",g)},c.addEventListener("load",m,{once:!0}),c.addEventListener("error",g,{once:!0})}})}async function Xa(e,s){ft(e)&&(st(e)||Bt(e)?await pt(e,s):await Promise.all(["img","video"].flatMap(r=>Array.from(e.querySelectorAll(r)).map(n=>pt(n,s)))))}const kr=(function(){let s=0;const r=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${r()}${s}`)})();function jr(e){return e?.split(",").map(s=>s.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}let Es=0;function Ka(e){const s=`${br}[#${Es}]`;return Es++,{time:r=>e&&console.time(`${s} ${r}`),timeEnd:r=>e&&console.timeEnd(`${s} ${r}`),warn:(...r)=>e&&Wa(...r)}}function Ja(e){return{cache:e?"no-cache":"force-cache"}}async function gs(e,s){return Ea(e)?e:_r(e,{...s,autoDestruct:!0})}async function _r(e,s){const{scale:r=1,workerUrl:n,workerNumber:i=1}=s||{},o=!!s?.debug,a=s?.features??!0,c=e.ownerDocument??(He?window.document:void 0),u=e.ownerDocument?.defaultView??(He?window:void 0),p=new Map,d={width:0,height:0,quality:1,type:"image/png",scale:r,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:3e4,progress:null,debug:o,fetch:{requestInit:Ja(s?.fetch?.bypassingCache),placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1,...s?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber:i,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...s,__CONTEXT__:!0,log:Ka(o),node:e,ownerDocument:c,ownerWindow:u,dpi:r===1?null:96*r,svgStyleElement:Sr(c),svgDefsElement:c?.createElementNS(Wt,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:Sa&&n&&i?i:0})].map(()=>{try{const g=new Worker(n);return g.onmessage=async b=>{const{url:h,result:x}=b.data;x?p.get(h)?.resolve?.(x):p.get(h)?.reject?.(new Error(`Error receiving message from worker: ${h}`))},g.onmessageerror=b=>{const{url:h}=b.data;p.get(h)?.reject?.(new Error(`Error receiving message from worker: ${h}`))},g}catch(g){return d.log.warn("Failed to new Worker",g),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[Ha(c)&&"image/webp","image/svg+xml","image/*","*/*"].filter(
47Boolean).join(",")};q=0.8`,requests:p,drawImageCount:0,tasks:[],features:a,isEnable:g=>g==="restoreScrollPosition"?typeof a=="boolean"?!1:a[g]??!1:typeof a=="boolean"?a:a[g]??!0};d.log.time("wait until load"),await Xa(e,{timeout:d.timeout,onWarn:d.log.warn}),d.log.timeEnd("wait until load");const{width:f,height:m}=Ya(e,d);return d.width=f,d.height=m,d}function Sr(e){if(!e)return;const s=e.createElement("style"),r=s.ownerDocument.createTextNode(`
48.______background-clip--text {
49  background-clip: text;
50  -webkit-background-clip: text;
51}
52`);return s.appendChild(r),s}function Ya(e,s){let{width:r,height:n}=s;if(De(e)&&(!r||!n)){const i=e.getBoundingClientRect();r=r||i.width||Number(e.getAttribute("width"))||0,n=n||i.height||Number(e.getAttribute("height"))||0}return{width:r,height:n}}async function Za(e,s){const{log:r,timeout:n,drawImageCount:i,drawImageInterval:o}=s;r.time("image to canvas");const a=await pt(e,{timeout:n,onWarn:s.log.warn}),{canvas:c,context2d:u}=Qa(e.ownerDocument,s),p=()=>{try{u?.drawImage(a,0,0,c.width,c.height)}catch(d){s.log.warn("Failed to drawImage",d)}};if(p(),s.isEnable("fixSvgXmlDecode"))for(let d=0;d<i;d++)await new Promise(f=>{setTimeout(()=>{p(),f()},d+o)});return s.drawImageCount=0,r.timeEnd("image to canvas"),c}function Qa(e,s){const{width:r,height:n,scale:i,backgroundColor:o,maximumCanvasSize:a}=s,c=e.createElement("canvas");c.width=Math.floor(r*i),c.height=Math.floor(n*i),c.style.width=`${r}px`,c.style.height=`${n}px`,a&&(c.width>a||c.height>a)&&(c.width>a&&c.height>a?c.width>c.height?(c.height*=a/c.width,c.width=a):(c.width*=a/c.height,c.height=a):c.width>a?(c.height*=a/c.width,c.width=a):(c.width*=a/c.height,c.height=a));const u=c.getContext("2d");return u&&o&&(u.fillStyle=o,u.fillRect(0,0,c.width,c.height)),{canvas:c,context2d:u}}function Nr(e,s){if(e.ownerDocument)try{const o=e.toDataURL();if(o!=="data:,")return tt(o,e.ownerDocument)}catch(o){s.log.warn("Failed to clone canvas",o)}const r=e.cloneNode(!1),n=e.getContext("2d"),i=r.getContext("2d");try{return n&&i&&i.putImageData(n.getImageData(0,0,e.width,e.height),0,0),r}catch(o){s.log.warn("Failed to clone canvas",o)}return r}function ei(e,s){try{if(e?.contentDocument?.body)return xs(e.contentDocument.body,s)}catch(r){s.log.warn("Failed to clone iframe",r)}return e.cloneNode(!1)}function ti(e){const s=e.cloneNode(!1);return e.currentSrc&&e.currentSrc!==e.src&&(s.src=e.currentSrc,s.srcset=""),s.loading==="lazy"&&(s.loading="eager"),s}async function si(e,s){if(e.ownerDocument&&!e.currentSrc&&e.poster)return tt(e.poster,e.ownerDocument);const r=e.cloneNode(!1);r.crossOrigin="anonymous",e.currentSrc&&e.currentSrc!==e.src&&(r.src=e.currentSrc);const n=r.ownerDocument;if(n){let i=!0;if(await pt(r,{onError:()=>i=!1,onWarn:s.log.warn}),!i)return e.poster?tt(e.poster,e.ownerDocument):r;r.currentTime=e.currentTime,await new Promise(a=>{r.addEventListener("seeked",a,{once:!0})});const o=n.createElement("canvas");o.width=e.offsetWidth,o.height=e.offsetHeight;try{const a=o.getContext("2d");a&&a.drawImage(r,0,0,o.width,o.height)}catch(a){return s.log.warn("Failed to clone video",a),e.poster?tt(e.poster,e.ownerDocument):r}return Nr(o,s)}return r}function ri(e,s){return Da(e)?Nr(e,s):Ua(e)?ei(e,s):st(e)?ti(e):Bt(e)?si(e,s):e.cloneNode(!1)}function ni(e){let s=e.sandbox;if(!s){const{ownerDocument:r}=e;try{r&&(s=r.createElement("iframe"),s.id=`__SANDBOX__-${kr()}`,s.width="0",s.height="0",s.style.visibility="hidden",s.style.position="fixed",r.body.appendChild(s),s.contentWindow?.document.write('
52<!DOCTYPE html><meta charset="UTF-8"><title></title><body>'),e.sandbox=s)}catch(n){e.log.warn("Failed to getSandBox",n)}}return s}const oi=["width","height","-webkit-text-fill-color"],ai=["stroke","fill"];function Cr(e,s,r){const{defaultComputedStyles:n}=r,i=e.nodeName.toLowerCase(),o=wt(e)&&i!=="svg",a=o?ai.map(h=>[h,e.getAttribute(h)]).filter(([,h])=>h!==null):[],c=[o&&"svg",i,a.map((h,x)=>`${h}=${x}`).join(","),s].filter(Boolean).join(":");if(n.has(c))return n.get(c);const p=ni(r)?.contentWindow;if(!p)return new Map;const d=p?.document;let f,m;o?(f=d.createElementNS(Wt,"svg"),m=f.ownerDocument.createElementNS(f.namespaceURI,i),a.forEach(([h,x])=>{m.setAttributeNS(null,h,x)}),f.appendChild(m)):f=m=d.createElement(i),m.textContent=" ",d.body.appendChild(f);const g=p.getComputedStyle(m,s),b=new Map;for(let h=g.length,x=0;x<h;x++){const w=g.item(x);oi.includes(w)||b.set(w,g.getPropertyValue(w))}return d.body.removeChild(f),n.set(c,b),b}function Er(e,s,r){const n=new Map,i=[],o=new Map;if(r)for(const c of r)a(c);else for(let c=e.length,u=0;u<c;u++){const p=e.item(u);a(p)}for(let c=i.length,u=0;u<c;u++)o.get(i[u])?.forEach((p,d)=>n.set(d,p));function a(c){const u=e.getPropertyValue(c),p=e.getPropertyPriority(c),d=c.lastIndexOf("-"),f=d>-1?c.substring(0,d):void 0;if(f){let m=o.get(f);m||(m=new Map,o.set(f,m)),m.set(c,[u,p])}s.get(c)===u&&!p||(f?i.push(f):n.set(c,[u,p]))}return n}function ii(e,s,r,n){const{ownerWindow:i,includeStyleProperties:o,currentParentNodeStyle:a}=n,c=s.style,u=i.getComputedStyle(e),p=Cr(e,null,n);a?.forEach((f,m)=>{p.delete(m)});const d=Er(u,p,o);d.delete("transition-property"),d.delete("all"),d.delete("d"),d.delete("content"),r&&(d.delete("margin-top"),d.delete("margin-right"),d.delete("margin-bottom"),d.delete("margin-left"),d.delete("margin-block-start"),d.delete("margin-block-end"),d.delete("margin-inline-start"),d.delete("margin-inline-end"),d.set("box-sizing",["border-box",""])),d.get("background-clip")?.[0]==="text"&&s.classList.add("______background-clip--text"),yr&&(d.has("font-kerning")||d.set("font-kerning",["normal",""]),(d.get("overflow-x")?.[0]==="hidden"||d.get("overflow-y")?.[0]==="hidden")&&d.get("text-overflow")?.[0]==="ellipsis"&&e.scrollWidth===e.clientWidth&&d.set("text-overflow",["clip",""]));for(let f=c.length,m=0;m<f;m++)c.removeProperty(c.item(m));return d.forEach(([f,m],g)=>{c.setProperty(g,f,m)}),d}function li(e,s){(Fa(e)||La(e)||$a(e))&&s.setAttribute("value",e.value)}const ci=[":before",":after"],di=[":-webkit-scrollbar",":-webkit-scrollbar-button",":-webkit-scrollbar-thumb",":-webkit-scrollbar-track",":-webkit-scrollbar-track-piece",":-webkit-scrollbar-corner",":-webkit-resizer"];function ui(e,s,r,n,i){const{ownerWindow:o,svgStyleElement:a,svgStyles:c,currentNodeStyle:u}=n;if(!a||!o)return;function p(d){const f=o.getComputedStyle(e,d);let m=f.getPropertyValue("content");if(!m||m==="none")return;i?.(m),m=m.replace(/(')|(")|(counter\(.+\))/g,"");const g=[kr()],b=Cr(e,d,n);u?.forEach((v,j)=>{b.delete(j)});const h=Er(f,b,n.includeStyleProperties);h.delete("content"),h.delete("-webkit-locale"),h.get("background-clip")?.[0]==="text"&&s.classList.add("______background-clip--text");const x=[`content: '${m}';`];if(h.forEach(([v,j],k)=>{x.push(`${k}: ${v}${j?" !important":""};`)}),x.length===1)return;try{s.className=[s.className,...g].join(" ")}catch(v){n.log.warn("Failed to copyPseudoClass",v);return}const w=x.join(`
53  `);let y=c.get(w);y||(y=[],c.set(w,y)),y.push(`.${g[0]}:${d}`)}ci.forEach(p),r&&di.forEach(p)}const Ts=new Set(["symbol"]);async function Ps(e,s,r,n,i){if(De(r)&&(Ma(r)||Oa(r))||n.filter&&!n.filter(r))return;Ts.has(s.nodeName)||Ts.has(r.nodeName)?n.currentParentNodeStyle=void 0:n.currentParentNodeStyle=n.currentNodeStyle;const o=await xs(r,n,!1,i);n.isEnable("restoreScrollPosition")&&mi(e,o),s.appendChild(o)}async function Rs(e,s,r,n){const i=(De(e)?e.shadowRoot?.firstChild:void 0)??e.firstChild;for(let o=i;o;o=o.nextSibling)if(!Ia(o))if(De(o)&&Ba(o)&&typeof o.assignedNodes=="function"){const a=o.assignedNodes();for(let c=0;c<a.length;c++)await Ps(e,s,a[c],r,n)}else await Ps(e,s,o,r,n)}function mi(e,s){if(!ft(e)||!ft(s))return;const{scrollTop:r,scrollLeft:n}=e;if(!r&&!n)return;const{transform:i}=s.style,o=new DOMMatrix(i),{a,b:c,c:u,d:p}=o;o.a=1,o.b=0,o.c=0,o.d=1,o.translateSelf(-n,-r),o.a=a,o.b=c,o.c=u,o.d=p,s.style.transform=o.toString()}
53function fi(e,s){const{backgroundColor:r,width:n,height:i,style:o}=s,a=e.style;if(r&&a.setProperty("background-color",r,"important"),n&&a.setProperty("width",`${n}px`,"important"),i&&a.setProperty("height",`${i}px`,"important"),o)for(const c in o)a[c]=o[c]}const pi=/^[\w-:]+$/;async function xs(e,s,r=!1,n){const{ownerDocument:i,ownerWindow:o,fontFamilies:a}=s;if(i&&Aa(e))return n&&/\S/.test(e.data)&&n(e.data),i.createTextNode(e.data);if(i&&o&&De(e)&&(ft(e)||wt(e))){const u=await ri(e,s);if(s.isEnable("removeAbnormalAttributes")){const b=u.getAttributeNames();for(let h=b.length,x=0;x<h;x++){const w=b[x];pi.test(w)||u.removeAttribute(w)}}const p=s.currentNodeStyle=ii(e,u,r,s);r&&fi(u,s);let d=!1;if(s.isEnable("copyScrollbar")){const b=[p.get("overflow-x")?.[0],p.get("overflow-y")?.[0]];d=b.includes("scroll")||(b.includes("auto")||b.includes("overlay"))&&(e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth)}const f=p.get("text-transform")?.[0],m=jr(p.get("font-family")?.[0]),g=m?b=>{f==="uppercase"?b=b.toUpperCase():f==="lowercase"?b=b.toLowerCase():f==="capitalize"&&(b=b[0].toUpperCase()+b.substring(1)),m.forEach(h=>{let x=a.get(h);x||a.set(h,x=new Set),b.split("").forEach(w=>x.add(w))})}:void 0;return ui(e,u,d,s,g),li(e,u),Bt(e)||await Rs(e,u,s,g),u}const c=e.cloneNode(!1);return await Rs(e,c,s),c}function Tr(e){if(e.ownerDocument=void 0,e.ownerWindow=void 0,e.svgStyleElement=void 0,e.svgDefsElement=void 0,e.svgStyles.clear(),e.defaultComputedStyles.clear(),e.sandbox){try{e.sandbox.remove()}catch(s){e.log.warn("Failed to destroyContext",s)}e.sandbox=void 0}e.workers=[],e.fontFamilies.clear(),e.fontCssTexts.clear(),e.requests.clear(),e.tasks=[]}function hi(e){const{url:s,timeout:r,responseType:n,...i}=e,o=new AbortController,a=r?setTimeout(()=>o.abort(),r):void 0;return fetch(s,{signal:o.signal,...i}).then(c=>{if(!c.ok)throw new Error("Failed fetch, not 2xx response",{cause:c});switch(n){case"arrayBuffer":return c.arrayBuffer();case"dataUrl":return c.blob().then(qa);default:return c.text()}}).finally(()=>clearTimeout(a))}function ht(e,s){const{url:r,requestType:n="text",responseType:i="text",imageDom:o}=s;let a=r;const{timeout:c,acceptOfImage:u,requests:p,fetchFn:d,fetch:{requestInit:f,bypassingCache:m,placeholderImage:g},font:b,workers:h,fontFamilies:x}=e;n==="image"&&(At||hs)&&e.drawImageCount++;let w=p.get(r);if(!w){m&&m instanceof RegExp&&m.test(a)&&(a+=(/\?/.test(a)?"&":"?")+new Date().getTime());const y=n.startsWith("font")&&b&&b.minify,v=new Set;y&&n.split(";")[1].split(",").forEach(D=>{x.has(D)&&x.get(D).forEach(E=>v.add(E))});const j=y&&v.size,k={url:a,timeout:c,responseType:j?"arrayBuffer":i,headers:n==="image"?{accept:u}:void 0,...f};w={type:n,resolve:void 0,reject:void 0,response:null},w.response=(async()=>{if(d&&n==="image"){const C=await d(r);if(C)return C}return!At&&r.startsWith("http")&&h.length?new Promise((C,D)=>{h[p.size&h.length-1].postMessage({rawUrl:r,...k}),w.resolve=C,w.reject=D}):hi(k)})().catch(C=>{if(p.delete(r),n==="image"&&g)return e.log.warn("Failed to fetch image base64, trying to use placeholder image",a),typeof g=="string"?g:g(o);throw C}),p.set(r,w)}return w.response}async function Pr(e,s,r,n){if(!Rr(e))return e;for(const[i,o]of gi(e,s))try{const a=await ht(r,{url:o,requestType:n?"image":"text",responseType:"dataUrl"});e=e.replace(xi(i),`$1${a}$3`)}catch(a){r.log.warn("Failed to fetch css data url",i,a)}return e}function Rr(e){return/url\((['"]?)([^'"]+?)\1\)/.test(e)}const Ir=/url\((['"]?)([^'"]+?)\1\)/g;function gi(e,s){const r=[];return e.replace(Ir,(n,i,o)=>(r.push([o,vr(o,s)]),n)),r.filter(([n])=>!ns(n))}function xi(e){const s=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${s})(['"]?\\))`,"g")}const bi=["background-image","border-image-source","-webkit-border-image","-webkit-mask-image","list-style-image"];function yi(e,s){return bi.map(r=>{const n=e.getPropertyValue(r);return!n||n==="none"?null:((At||hs)&&s.drawImageCount++,Pr(n,null,s,!0).then(i=>{!i||n===i||e.setProperty(r,i,e.getPropertyPriority(r))}))}).filter(Boolean)}function wi(e,s){if(st(e)){const r=e.currentSrc||e.src;if(!ns(r))return[ht(s,{url:r,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(n=>
53{n&&(e.srcset="",e.dataset.originalSrc=r,e.src=n||"")})];(At||hs)&&s.drawImageCount++}else if(wt(e)&&!ns(e.href.baseVal)){const r=e.href.baseVal;return[ht(s,{url:r,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(n=>{n&&(e.dataset.originalSrc=r,e.href.baseVal=n||"")})]}return[]}function vi(e,s){const{ownerDocument:r,svgDefsElement:n}=s,i=e.getAttribute("href")??e.getAttribute("xlink:href");if(!i)return[];const[o,a]=i.split("#");if(a){const c=`#${a}`,u=r?.querySelector(`svg ${c}`);if(o&&e.setAttribute("href",c),n?.querySelector(c))return[];if(u)return n?.appendChild(u.cloneNode(!0)),[];if(o)return[ht(s,{url:o,responseType:"text"}).then(p=>{n?.insertAdjacentHTML("beforeend",p)})]}return[]}function Ar(e,s){const{tasks:r}=s;De(e)&&((st(e)||wr(e))&&r.push(...wi(e,s)),Ra(e)&&r.push(...vi(e,s))),ft(e)&&r.push(...yi(e.style,s)),e.childNodes.forEach(n=>{Ar(n,s)})}async function ki(e,s){const{ownerDocument:r,svgStyleElement:n,fontFamilies:i,fontCssTexts:o,tasks:a,font:c}=s;if(!(!r||!n||!i.size))if(c&&c.cssText){const u=As(c.cssText,s);n.appendChild(r.createTextNode(`${u}
54`))}else{const u=Array.from(r.styleSheets).filter(d=>{try{return"cssRules"in d&&!!d.cssRules.length}catch(f){return s.log.warn(`Error while reading CSS rules from ${d.href}`,f),!1}});await Promise.all(u.flatMap(d=>Array.from(d.cssRules).map(async(f,m)=>{if(Pa(f)){let g=m+1;const b=f.href;let h="";try{h=await ht(s,{url:b,requestType:"text",responseType:"text"})}catch(w){s.log.warn(`Error fetch remote css import from ${b}`,w)}const x=h.replace(Ir,(w,y,v)=>w.replace(v,vr(v,b)));for(const w of _i(x))try{d.insertRule(w,w.startsWith("@import")?g+=1:d.cssRules.length)}catch(y){s.log.warn("Error inserting rule from remote css import",{rule:w,error:y})}}}))),u.flatMap(d=>Array.from(d.cssRules)).filter(d=>Ta(d)&&Rr(d.style.getPropertyValue("src"))&&jr(d.style.getPropertyValue("font-family"))?.some(f=>i.has(f))).forEach(d=>{const f=d,m=o.get(f.cssText);m?n.appendChild(r.createTextNode(`${m}
55`)):a.push(Pr(f.cssText,f.parentStyleSheet?f.parentStyleSheet.href:null,s).then(g=>{g=As(g,s),o.set(f.cssText,g),n.appendChild(r.createTextNode(`${g}
56`))}))})}}const ji=/(\/\*[\s\S]*?\*\/)/g,Is=/((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi;function _i(e){if(e==null)return[];const s=[];let r=e.replace(ji,"");for(;;){const o=Is.exec(r);if(!o)break;s.push(o[0])}r=r.replace(Is,"");const n=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,i=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let o=n.exec(r);if(o)i.lastIndex=n.lastIndex;else if(o=i.exec(r),o)n.lastIndex=i.lastIndex;else break;s.push(o[0])}return s}const Si=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Ni=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function As(e,s){const{font:r}=s,n=r?r?.preferredFormat:void 0;return n?e.replace(Ni,i=>{for(;;){const[o,,a]=Si.exec(i)||[];if(!a)return"";if(a===n)return`src: ${o};`}}):e}async function Ci(e,s){const r=await gs(e,s);if(De(r.node)&&wt(r.node))return r.node;const{ownerDocument:n,log:i,tasks:o,svgStyleElement:a,svgDefsElement:c,svgStyles:u,font:p,progress:d,autoDestruct:f,onCloneNode:m,onEmbedNode:g,onCreateForeignObjectSvg:b}=r;i.time("clone node");const h=await xs(r.node,r,!0);if(a&&n){let j="";u.forEach((k,C)=>{j+=`${k.join(`,
57`)} {
58  ${C}
59}
60`}),a.appendChild(n.createTextNode(j))}i.timeEnd("clone node"),await m?.(h),p!==!1&&De(h)&&(i.time("embed web font"),await ki(h,r),i.timeEnd("embed web font")),i.time("embed node"),Ar(h,r);const x=o.length;let w=0;const y=async()=>{for(;;){const j=o.pop();if(!j)break;try{await j}catch(k){r.log.warn("Failed to run task",k)}d?.(++w,x)}};d?.(w,x),await Promise.all([...Array.from({length:4})].map(y)),i.timeEnd("embed node"),await g?.(h);const v=Ei(h,r);return c&&v.insertBefore(c,v.children[0]),a&&v.insertBefore(a,v.children[0]),f&&Tr(r),await b?.(v),v}function Ei(e,s){const{width:r,height:n}=s,i=Va(r,n,e.ownerDocument),o=i.ownerDocument.createElementNS(i.namespaceURI,"foreignObject");return o.setAttributeNS(null,"x","0%"),o.setAttributeNS(null,"y","0%"),o.setAttributeNS(null,"width","100%"),o.setAttributeNS(null,"height","100%"),o.append(e),i.appendChild(o),i}async function Ti(e,s){const r=await gs(e,s),n=await Ci(r),i=Ga(n,r.isEnable("removeControlCharacter"));r.autoDestruct||(r.svgStyleElement=Sr(r.ownerDocument),r.svgDefsElement=r.ownerDocument?.createElementNS(Wt,"defs"),r.svgStyles.clear());const o=tt(i,n.ownerDocument);return await Za(o,r)}async function Pi(e,s){const r=await gs(e,s),{log:n,quality:i,type:o,dpi:a}=r,c=await Ti(r);n.time("canvas to data url");let u=c.toDataURL(o,i);if(["image/png","image/jpeg"].includes(o)&&a&&Na&&Ca){const[p,d]=u.split(",");let f=0,m=!1;if(o==="image/png"){const v=_a(d);v>=0?(f=Math.ceil((v+28)/3)*4,m=!0):f=33/3*4}else o==="image/jpeg"&&(f=18/3*4);const g=d.substring(0,f),b=d.substring(f),h=window.atob(g),x=new Uint8Array(h.length);for(let v=0;v<x.length;
60v++)x[v]=h.charCodeAt(v);const w=o==="image/png"?wa(x,a,m):ga(x,a),y=window.btoa(String.fromCharCode(...w));u=[p,",",y,b].join("")}return n.timeEnd("canvas to data url"),u}const Ri='var B=Object.defineProperty;var b=Object.getOwnPropertySymbols;var y=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var g=(r,t,e)=>t in r?B(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,U=(r,t)=>{for(var e in t||(t={}))y.call(t,e)&&g(r,e,t[e]);if(b)for(var e of b(t))F.call(t,e)&&g(r,e,t[e]);return r};var p=(r,t)=>{var e={};for(var o in r)y.call(r,o)&&t.indexOf(o)<0&&(e[o]=r[o]);if(r!=null&&b)for(var o of b(r))t.indexOf(o)<0&&F.call(r,o)&&(e[o]=r[o]);return e};var x=(r,t,e)=>new Promise((o,w)=>{var h=n=>{try{d(e.next(n))}catch(u){w(u)}},R=n=>{try{d(e.throw(n))}catch(u){w(u)}},d=n=>n.done?o(n.value):Promise.resolve(n.value).then(h,R);d((e=e.apply(r,t)).next())});(function(){"use strict";var u;const r="[modern-screenshot]",e=typeof window!="undefined"?(u=window.navigator)==null?void 0:u.userAgent:"",o=e.includes("Chrome");e.includes("AppleWebKit"),e.includes("Firefox");const w=(...a)=>console.warn(r,...a);function h(a,l){return new Promise((i,s)=>{const c=new FileReader;c.onload=()=>i(c.result),c.onerror=()=>s(c.error),c.onabort=()=>s(new Error(`Failed read blob to ${l}`)),c.readAsDataURL(a)})}const R=a=>h(a,"dataUrl");function d(a){const E=a,{url:l,timeout:i,responseType:s}=E,c=p(E,["url","timeout","responseType"]),m=new AbortController,A=i?setTimeout(()=>m.abort(),i):void 0;return fetch(l,U({signal:m.signal},c)).then(f=>{if(!f.ok)throw new Error("Failed fetch, not 2xx response",{cause:f});switch(s){case"arrayBuffer":return f.arrayBuffer();case"dataUrl":return f.blob().then(R);case"text":default:return f.text()}}).finally(()=>clearTimeout(A))}const n=self;n.onmessage=a=>x(this,null,function*(){const l=a.data,i=l.rawUrl||l.url;try{const s=yield d(l);n.postMessage({url:i,result:s})}catch(s){w(s),n.postMessage({url:i})}})})();\n',Dr=()=>t.jsxs("div",{className:"w-full mt-2 mb-4 bg-white shadow-lg rounded-sm overflow-hidden",children:[t.jsxs("div",{className:"flex justify-between items-center px-4 py-2 border-b border-gray-200 animate-pulse",children:[t.jsx("div",{className:"bg-gray-200 rounded h-3 w-1/2"}),t.jsx("div",{className:"bg-gray-200 rounded h-3 w-20"})]}),t.jsx(ut,{})]}),Ii=({count:e=2})=>t.jsx("div",{className:"flex flex-col items-center w-full px-4 print:hidden animate-fade-in",children:Array.from({length:e}).map((s,r)=>t.jsx(Dr,{},r))}),Ai=()=>{const{getPacketId:e}=Fe(),{projectId:s}=yt(),{diffitUser:r,isLDidentified:n}=Ue(),{emailResourceToSelf:i}=Ke(),{trackPacketEvent:o}=Pn(),[a,c]=l.useState("idle"),[u,p]=l.useState(null),d=n&&i&&!!r?.email,f=async()=>{c("sending"),p(null),o("Email Resource To Self Clicked",{location:"mobile_packet"});try{await cn(e(),s),o("Email Resource To Self Success",{location:"mobile_packet"}),c("sent")}catch(m){p(m.response?.data?.user_error_message||"Failed to send. Please try again."),c("error")}};return d?a==="sent"?t.jsxs("p",{role:"status",className:"flex items-center gap-1 text-xs font-medium text-gray-500",children:[t.jsx(rt,{className:"h-4 w-4 text-green-600"}),"Sent to ",r.email]}):t.jsxs(t.Fragment,{children:[a==="error"&&t.jsx("span",{role:"status",className:"text-xs text-red-600",children:u}),t.jsxs("button",{type:"button",onClick:f,disabled:a==="sending",className:"flex flex-row items-center gap-x-0.5 text-xs font-medium text-gray-500 underline hover:text-gray-700 disabled:opacity-50",children:[a==="sending"?"Sending…":"Edit on Desktop, Email me a link",t.jsx(bt,{className:"h-3 w-3"})]})]}):t.jsx("p",{className:"text-center text-xs text-gray-500",children:"Edit resources in our desktop version."})},Di=300,Fi=250,Li=24*1024*1024,Zt="__pending_block__",Mi=!(typeof navigator<"u"&&navigator.userAgent.includes("AppleWebKit")&&!navigator.userAgent.includes("Chrome"));let Qt=null;const Oi=()=>(Qt||(Qt=URL.createObjectURL(new Blob([Ri],{type:"application/javascript"}))),Qt),$i=({blocks:e,documentRef:s})=>{const{isLoading:r,getTitleOfBlock:n}=Fe(),[i,o]=l.useState(null),a=!!e?.some(ys),[c,u]=l.useState(!0),p=Rn(),[d,f]=l.useState(!p);l.useEffect(()=>{if(p){f(!1);return}const N=setTimeout(()=>f(!0),Fi);return()=>clearTimeout(N)},[p]);const[m,g]=l.useState(!1),[b,h]=l.useState(0),x=l.useRef(null),w=l.useRef(0),y=l.useRef(new Map),v=l.useRef(0),j=N=>{const R=y.current.get(N);return R?(y.current.delete(N),y.current.set(N,R),R):null},k=(N,R)=>{const M=y.current.get(N);M&&(v.current-=M.image.length),y.current.delete(N),y.current.set(N,R),v.current+=R.image.length;for(const[O,_]of y.current){if(v.current<=Li)break;O!==N&&(y.current.delete(O),v.current-=_.image.length)}},C=l.useMemo(()=>(e??[]).flatMap(N=>{const R=y.current.get(N.unique_id);return!R||R.signature!==JSON.stringify(N)?[]:[{blockId:N.unique_id,image:R.image}]}),[e]),D=!!i?.some(({blockId:N})=>e?.some(R=>R.unique_id===N)),E=C.length===(e?.length??0),P=D?i:E?C:null,L=!!P?.length,W=!L||a||m,F=async(N,R)=>
60{if(!N)return null;const M=N.querySelectorAll("[data-block-id]"),O=Array.from(M).map(T=>({element:T,blockId:T.getAttribute("data-block-id"),width:T.offsetWidth,height:T.offsetHeight,measuring:!!T.querySelector("[data-loading-placeholder]")})),_=[];try{await document.fonts.ready;for(const{element:T,blockId:A,width:X,height:se,measuring:ne}of O){if(R!==w.current)break;try{const Y=e?.find(H=>H.unique_id===A);if(ys(Y)){_.push({blockId:A,image:Zt});continue}if(ne){_.push({blockId:A,image:Zt,measuring:!0});continue}if(X===0||se===0){console.warn("Skipping screenshot for element with no dimensions:",T),_.push({blockId:A,image:null});continue}const G=JSON.stringify(Y),J=j(A);if(J?.signature===G&&J.width===X&&J.height===se){_.push({blockId:A,image:J.image});continue}const q=await _r(T,{...Mi?{workerUrl:Oi(),workerNumber:1}:{},scale:2,type:"image/webp",quality:.9,requestInit:{mode:"cors"}});try{const H=await Pi(q);H||console.warn("No image data generated for element"),_.push({blockId:A,image:H||null}),H&&k(A,{signature:G,width:X,height:se,image:H})}finally{q.workers?.forEach(H=>H.terminate()),Tr(q)}await new Promise(H=>setTimeout(H,0))}catch(Y){console.warn("Failed to generate image:",Y,Y.stack),_.push({blockId:A,image:null})}}return _.length>0?_:null}catch(T){return console.warn("Font loading error:",T),null}};return l.useEffect(()=>{if(!d)return;(async()=>{const R=++w.current,M=x.current;if(M){const O=await F(M,R);if(R!==w.current)return;g(!!O?.some(_=>_.measuring)),o(O||null)}})()},[e,r,d,b]),l.useEffect(()=>{const N=x.current;if(!m||!N)return;const R=()=>{N.querySelector("[data-loading-placeholder]")||(g(!1),h(O=>O+1))},M=new MutationObserver(R);return M.observe(N,{childList:!0,subtree:!0}),R(),()=>M.disconnect()},[m]),l.useEffect(()=>{if(!L){u(!0);return}const N=setTimeout(()=>u(!1),Di);return()=>clearTimeout(N)},[L]),t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:x,className:"fixed top-0 -left-[4000px] w-fit h-0",children:t.jsx(rr,{blocks:e,documentRef:s,specificWidth:820,isOffscreenCapture:!0})}),t.jsx("div",{className:"flex flex-col items-center w-full px-4",children:t.jsx("div",{className:"flex flex-wrap items-center justify-center gap-x-2 gap-y-1 pt-6 pb-4",children:W?t.jsxs(t.Fragment,{children:[t.jsx(Lt,{size:4}),t.jsx("span",{className:"text-xs text-gray-500",children:"Loading Resources"})]}):t.jsx(Ai,{})})}),t.jsxs("div",{className:"relative",children:[c&&t.jsx("div",{className:L?"absolute inset-x-0 top-0 z-10 pointer-events-none transition-opacity duration-300 opacity-0":"transition-opacity duration-300 opacity-100",children:t.jsx(Ii,{count:e?.length||2})}),L&&t.jsxs("div",{className:"flex flex-col items-center w-full px-4 animate-fade-in",children:[P&&P.map(({blockId:N,image:R})=>{const M=e?.find(O=>O.unique_id===N);return M?R===Zt?t.jsx(Dr,{},N):R?t.jsxs("div",{className:"w-full mt-2 mb-4 mx-4 print:shadow-none shadow-lg rounded-sm overflow-hidden",children:[t.jsxs("div",{className:"flex bg-white text-xs justify-between items-center px-4 py-2 border-b border-gray-200",children:[t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx("span",{className:"font-semibold truncate block",children:n(M.unique_id)})}),t.jsx("div",{className:"flex items-center shrink-0 whitespace-nowrap",children:t.jsx(In,{block:M,labelled:!0})})]}),t.jsx(Ft,{src:R,alt:n(M.unique_id),className:"object-contain",style:{imageRendering:"-webkit-optimize-contrast",backfaceVisibility:"hidden",transform:"translateZ(0)"}})]},N):null:null}),t.jsxs("div",{className:"px-4 print:hidden",children:[t.jsx("div",{className:"w-full h-[1px] bg-gray-200 my-6"}),t.jsx(An,{})]})]})]})]})},Bi=e=>e.metaKey&&e.key==="z"||e.ctrlKey&&e.key==="z",Ui=e=>e.metaKey&&e.shiftKey&&e.key==="z"||e.ctrlKey&&e.key==="y",Wi=({canUndo:e,canRedo:s,undo:r,redo:n,trackEvent:i})=>{l.useEffect(()=>{const o=a=>{document.activeElement.hasAttribute("data-lexical-editor")||(s()&&Ui(a)?(a.stopPropagation(),a.preventDefault(),n(),i("Redo",{location:"keyboard"})):e()&&Bi(a)&&(a.stopPropagation(),a.preventDefault(),r(),i("Undo",{location:"keyboard"})))};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,s,r,n,i])},Hi=({getPacketOrientation:e,isDiffitBotUser:s,trackEvent:r})=>{l.useEffect(()=>{const n=()=>{s||r("Printed",{includeBlocks:!0});const a=`@page { size: ${e()==="16x9"?"landscape":"portrait"}; }`,c=document.head||document.getElementsByTagName("head")[0],u=document.createElement("style");u.type="text/css",u.media="print",u.setAttribute("data-diffit-print-style","true"),u.styleSheet?u.styleSheet.cssText=a:u.appendChild(document.createTextNode(a)),c.appendChild(u)},i=()=>{const o=document.querySelector('style[data-diffit-print-style="true"]');o&&o.remove()};return window.addEventListener("beforeprint",n),window.addEventListener("afterprint",i),()=>{window.removeEventListener("beforeprint",n),window.removeEventListener("afterprint",i),i()}},[e,s,r])}
60,Vi=({focusedSubresource:e,trackEvent:s})=>{l.useEffect(()=>{const r=()=>{s("Browser Copy",{resource_type:e?.type})};return window.addEventListener("copy",r),()=>window.removeEventListener("copy",r)},[e,s])},Ds=560,es=400,et=272,Gi=70,Fs=40,Ls=16,Ms=360,zi=4;function qi(e,s){if(e>=s+Fs*2+Ds)return{idealWidth:Ds,isOverlay:!1};const r=e-s-Fs*2;if(r>=es)return{idealWidth:r,isOverlay:!1};if((e-es-s)/2>=Ls)return{idealWidth:es,isOverlay:!1};const i=e-s-Ls*2;return i>=et?{idealWidth:i,isOverlay:!1}:e-et>=s-Gi?{idealWidth:et,isOverlay:!1}:{idealWidth:et,isOverlay:!0}}function Xi({resourceWidth:e,isChatOpen:s,onToggleChat:r}){const[n,i]=dn("chatSidebarWidth",Ms),[o,a]=l.useState(!1),[c,u]=l.useState(!1),p=l.useRef(n||Ms),d=l.useRef({startX:0,startWidth:0}),f=l.useRef(null),m=l.useRef(null),[g,b]=l.useState(0),{idealWidth:h,isOverlay:x}=qi(g,e);l.useEffect(()=>{const v=m.current;if(!v)return;const j=new ResizeObserver(k=>{for(const C of k)b(C.contentRect.width)});return j.observe(v),()=>j.disconnect()},[]);const w=l.useCallback(v=>{v.preventDefault();const j=v.clientX,k=s?n:0,C=v.target,D=h;d.current={startX:j,startWidth:k},a(!0);let E=!1;const P=W=>{const F=W.clientX-j;if(!E&&Math.abs(F)>zi&&(E=!0,document.body.style.userSelect="none"),E){const N=Math.min(k+F,D);N<et?i(0):i(N)}},L=W=>{if(document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",L),document.body.style.userSelect="",a(!1),u(!1),!E)(f.current?.contains(C)||!s)&&r();else{const F=W.clientX-j;k+F<et?(s&&r(),i(p.current)):s||r()}};document.addEventListener("mousemove",P),document.addEventListener("mouseup",L)},[s,n,i,r,h]);l.useEffect(()=>{s&&n>0&&(p.current=n)},[n,s]);const y=g>0?Math.min(n,h):n;return l.useMemo(()=>({effectiveWidth:y,idealWidth:h,handleMouseDown:w,containerRef:m,handleIndicatorRef:f,isOverlay:x,isDragging:o,isHandleHovered:c,setIsHandleHovered:u}),[y,h,w,m,f,x,o,c,u])}const Ki=1500,Ji=["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"," "],Yi=({chatHeader:e,resourceHeader:s,chatContent:r,resourceContent:n,isChatOpen:i,onToggleChat:o,scrollKey:a,resourceWidth:c=ds})=>{const{breakpoint:u}=qs(),p=u==="md",{effectiveWidth:d,handleMouseDown:f,containerRef:m,handleIndicatorRef:g,isOverlay:b,isDragging:h,isHandleHovered:x,setIsHandleHovered:w}=Xi({resourceWidth:c,isChatOpen:i,onToggleChat:o}),y=l.useRef(null),v=l.useRef(new Map),j=l.useRef(a),k=l.useRef(null),C=l.useCallback(()=>{k.current!==null&&(k.current=null,y.current&&(y.current.style.overflowAnchor=""))},[]);l.useEffect(()=>{const F=y.current;if(!F)return;const N=()=>{k.current===null&&j.current&&v.current.set(j.current,F.scrollTop)},R=()=>C(),_=[["scroll",N],["wheel",R],["touchstart",R],["pointerdown",T=>{T.offsetX>=F.clientWidth&&C()}],["keydown",T=>{Ji.includes(T.key)&&C()}]];for(const[T,A]of _)F.addEventListener(T,A,{passive:!0});return()=>{for(const[T,A]of _)F.removeEventListener(T,A)}},[]),l.useLayoutEffect(()=>{const F=y.current;if(j.current=a,!a||!F)return;const N=v.current.get(a)??0,R=()=>F.scrollHeight-F.clientHeight>=N;if(!N||R()){F.scrollTo({top:N,behavior:"instant"});return}k.current=N,F.style.overflowAnchor="none";const M=performance.now()+Ki;let O=!1,_=requestAnimationFrame(function T(){if(k.current!==null){if(!O&&R()&&(F.scrollTop=N,O=!0),performance.now()>M){C();return}_=requestAnimationFrame(T)}});return()=>{cancelAnimationFrame(_),C()}},[a]);const[D,E]=l.useState(0);l.useEffect(()=>{const F=y.current;if(!F)return;const N=()=>E(F.offsetWidth-F.clientWidth);N();const R=new ResizeObserver(N);return R.observe(F),()=>R.disconnect()},[]);const P=(p||b)&&i,L=i?d:0,W=L===0;return t.jsxs("div",{ref:m,className:"flex h-full overflow-hidden print:overflow-visible print:h-auto relative",children:[t.jsxs("div",{className:`print:hidden flex-shrink-0 flex flex-col border-r border-gray-200 bg-gray-100 overflow-hidden ease-in-out
61          ${h?"":"transition-[width] duration-300"}
62          ${P?"absolute left-0 top-0 bottom-0 z-20 shadow-xl":"relative"}
63          ${i?"":"border-r-0"}
64        `,style:{width:L},children:[t.jsx("div",{className:`flex-shrink-0 pt-[18px] bg-gray-100 transition-opacity duration-200 ${i?"opacity-100":"opacity-0 pointer-events-none"}`,style:{height:"72px",width:d},children:e}),t.jsx("div",{className:`flex-1 min-h-0 overflow-y-auto overflow-x-hidden overscroll-contain transition-opacity duration-200 ${i?"opacity-100":"opacity-0 pointer-events-none"}`,style:{width:d},children:r})]}),t.jsx("div",{onMouseDown:f,onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),className:`print:hidden absolute top-0 bottom-0 flex items-center ${P?"z-30":"z-[9]"} ${W?"justify-start":"justify-center"} ${h?"":"transition-[left] duration-300 ease-in-out"}`,style:{left:W?0:L-8,width:"16px",cursor:W||P?"pointer":"col-resize"},children:t.jsx("button",{ref:g,type:"button","aria-label":W?"Open chat sidebar":"Close chat sidebar","aria-expanded":!W,onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),o())},className:`flex items-center justify-center w-[18px] py-2 border border-gray-200 hover:bg-gray-50 focus-visible:bg-gray-50 transition-all ${W?"bg-gray-100 rounded-r-lg opacity-100 border-l-0":P?"bg-white shadow-sm rounded-lg opacity-100":`bg-white shadow-sm rounded-lg focus:opacity-100 focus:duration-100 ${h||x?"opacity-100 duration-100 cursor-col-resize":"opacity-0 duration-500"}`}`,children:W?t.jsx(bt,{className:"h-4 w-4 text-gray-400"}):P?t.jsx(xt,{className:"h-4 w-4 text-gray-400"}):t.jsx(Dn,{sx:{fontSize:18,color:"rgb(209, 213, 219)"}})})}),P&&t.jsx("div",{className:"absolute inset-0 z-10 bg-black/10",onClick:o}),t.jsxs("div",{className:"flex-1 flex flex-col min-w-0 bg-gray-50 print:bg-white",children:[t.jsx("div",{className:"flex-shrink-0 print:hidden pt-[18px] pb-0.5 bg-gray-50 relative z-10",style:{height:"72px",paddingRight:D},children:s}),t.jsx("div",{ref:y,className:"flex-1 min-h-0 overflow-y-auto overflow-x-hidden print:overflow-visible",style:{scrollbarGutter:"stable"},children:n})]})]})},Zi=({titleComponent:e,rightContent:s})=>t.jsxs("div",{className:"flex items-center justify-between h-full pl-[20px] pr-4 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:e}),s&&t.jsx("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:s})]}),Qi=({children:e})=>t.jsxs("div",{className:"grid grid-cols-[1fr_auto_1fr] items-center h-full px-4 min-w-0",children:[t.jsx("div",{}),t.jsx("div",{className:"min-w-0",children:e}),t.jsx("div",{})]}),el={[te.DOC]:"Google Docs",[te.SLIDES]:"Google Slides",[te.DOCX]:"Microsoft Word",[te.PPTX]:"Microsoft PowerPoint",[te.PDF]:"PDF"},os=(e,s)=>{const r=s==="16x9";return e===te.DOC||e===te.DOCX?!r:e===te.PPTX?r:!0},Fr=e=>![te.FORM,te.CLASSROOM_DOC,te.CLASSROOM_SLIDES,te.CANVA].includes(e),tl=({onClose:e,config:s})=>{const{exportType:r,currentPacketTitle:n,allPackets:i,onExportThis:o,onExportAll:a}=s,c=el[r]||"file",u=i?.length||0,d=i?.filter(({packet:x})=>os(r,x?.orientation||"8.5x11"))?.length||0,f=u-d,m=()=>{o(),e()},g=()=>{a(),e()},b=d>0,h=d===0&&u>0;return t.jsx(gt,{showModal:!0,setShowModal:e,title:`Export to ${c}
64`,iconBackground:"bg-emerald-100",icon:t.jsx($t,{className:"w-5 h-5 text-emerald-600"}),children:t.jsxs("div",{className:"mt-4",children:[t.jsxs("p",{className:"text-sm text-gray-600 text-center mb-6",children:['Would you like to export only "',n,'" or all resources in the set?']}),t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsxs("button",{className:"w-full flex items-center gap-3 p-4 rounded-lg border border-gray-200 hover:border-emerald-500 hover:bg-emerald-50 transition-colors text-left",onClick:m,children:[t.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center",children:t.jsx(un,{className:"w-5 h-5 text-gray-600"})}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("p",{className:"font-medium text-gray-900 truncate",children:n}),t.jsx("p",{className:"text-sm text-gray-500",children:"Single resource"})]})]}),t.jsxs("button",{className:`w-full flex items-center gap-3 p-4 rounded-lg border transition-colors text-left ${b?"border-gray-200 hover:border-emerald-500 hover:bg-emerald-50":"border-gray-100 bg-gray-50 cursor-not-allowed"}`,onClick:b?g:void 0,disabled:!b,children:[t.jsx("div",{className:`flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center ${b?"bg-emerald-100":"bg-gray-100"}`,children:t.jsx(Rt,{className:`w-5 h-5 ${b?"text-emerald-600":"text-gray-400"}`})}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("p",{className:`font-medium ${b?"text-gray-900":"text-gray-400"}`,children:"All Resources"}),t.jsx("p",{className:`text-sm ${b?"text-gray-500":"text-gray-400"}`,children:h?"No compatible resources for this format":f>0?t.jsxs(t.Fragment,{children:[d," of ",u," resources",t.jsxs("span",{className:"text-amber-600",children:[" (",f," incompatible)"]})]}):`${u} resources`})]})]}),f>0&&!h&&t.jsx("p",{className:"text-xs text-amber-600 text-center mt-1",children:r===te.DOC||r===te.DOCX?"Slides-format resources (16:9) cannot be exported to document formats":"Portrait resources cannot be exported to PowerPoint"})]}),t.jsx("div",{className:"flex justify-center mt-6",children:t.jsx("button",{className:"px-4 py-2 text-sm text-gray-500 hover:text-gray-700",onClick:e,children:"Cancel"})})]})})},Et=10,sl=6,Lr=({location:e="share_dialog",trackEvent:s})=>{const{getPacketId:r}=Fe(),{projectId:n}=yt(),i=r(),{shareAddressBook:o}=Ke(),{isLDidentified:a,diffitUser:c}=Ue(),u=c?.id,[p,d]=l.useState([""]),[f,m]=l.useState(!1),[g,b]=l.useState(null),[h,x]=l.useState(!1),[w,y]=l.useState([]),v=l.useRef([]),j=l.useRef(!1),k=l.useRef(!1),C=l.useId();l.useEffect(()=>{v.current[0]?.focus()},[]),l.useEffect(()=>{!o||!a||!u||y(Fn(u))},[o,a,u]);const D=o&&a&&w.length>0,E=new Set(p.map(_=>_.trim().toLowerCase()).filter(Boolean)),P=w.filter(_=>!E.has(_)).slice(0,sl);l.useEffect(()=>{!D||k.current||(k.current=!0,s?.("Share Address Book Shown",{location:e,recents_count:w.length}))},[D,w.length,e,s]);const L=_=>{const T=p.findIndex(A=>!A.trim());if(T===-1&&p.length>=Et){b(`You can email up to ${Et} people at a time.`);return}d(A=>T!==-1?A.map((X,se)=>se===T?_:X):[...A,_]),b(null),s?.("Share Address Book Recipient Added",{location:e})},W=_=>{y(Ln(u,_)),s?.("Share Address Book Recipient Removed",{location:e})};l.useEffect(()=>{j.current&&(j.current=!1,v.current[p.length-1]?.focus())},[p.length]);const F=(_,T)=>{d(A=>A.map((X,se)=>se===_?T:X)),b(null)},N=()=>{if(p.some(_=>!dt(_))){b("Please enter a valid email address.");return}if(p.length>=Et){b(`You can email up to ${Et} people at a time.`);return}b(null),j.current=!0,d(_=>[..._,""])},R=(_,T)=>{_.key==="Enter"&&dt(p[T])&&(_.preventDefault(),N())},M=_=>{d(T=>{const A=T.filter((X,se)=>se!==_);return A.length?A:[""]}),b(null)},O=async()=>{const _=p.map(X=>X.trim()).filter(Boolean);if(_.some(X=>!dt(X))){b("Please enter a valid email address.");return}const T=[...new Set(_)];if(T.length===0){b("Add at least one email address.");return}m(!0),b(null);const A=T.filter(X=>w.includes(X.toLowerCase())).length;s?.("Share With Colleagues Submit Clicked",{location:e,recipient_count:T.length,known_recipient_count:A});try{const X=await fn(i,T.map(ne=>({email:ne})),n);s?.("Share With Colleagues Success",{location:e,recipient_count:T.length,known_recipient_count:A}),x(!0),d([""]);const se=new Set((X?.data?.errors||[]).map(ne=>String(ne).trim().toLowerCase()));y(Mn(u,T.filter(ne=>!se.has(ne.toLowerCase())),c?.email)),setTimeout(()=>x(!1),3e3)}catch(X){b(X.message||"Failed to share. Please try again.")}finally{m(!1)}};return t.jsxs("div",{className:"mt-2",children:[t.jsx("p",{className:"px-2 text-base font-medium text-gray-700 text-balance",children:"Email colleagues a copy of this resource."}),D&&P.length>0&&t.jsxs("div",{className:"mt-4 px-2",children:[t.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-gray-500",children:"Recent"}),t.jsx("ul",{className:"mt-2 flex flex-wrap gap-2",children:P.map(_=>t.jsx("li",{children:t.jsxs("span",{className:"group inline-flex items-center rounded-full border border-gray-300 bg-white pr-1 text-sm text-gray-700 shadow-sm hover:border-emerald-500 hover:bg-emerald-50",children:[t.jsx("button",{type:"button",onClick:()=>L(_),"aria-label":`Add ${_}`,className:"max-w-[14rem] truncate rounded-l-full py-1.5 pl-3 pr-1 focus:outline-none focus:ring-2 focus:ring-emerald-500",children:_}),t.jsx("button",{type:"button",onClick:()=>W(_),"aria-label":`Remove ${_} from recent recipients`,className:"rounded-full p-0.5 text-gray-400 hover:text-gray-700 focus:outline-none focus:ring-2 focus:ring-emerald-500",children:t.jsx(ss,{className:"h-4 w-4"})})]})},_))})]}),D&&t.jsx("datalist",{id:C,children:w.map(_=>t.jsx("option",{value:_},_))}),p.map((_,T)=>t.jsxs("div",{className:`group relative ${T===0?"mt-6":"mt-2"}`,children:[t.jsx(mn,{className:`pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400 ${dt(_)?"group-hover:hidden":""}`}),t.jsx("input",{ref:A=>{v.current[T]=A}
64,type:"email",value:_,onChange:A=>F(T,A.target.value),onKeyDown:A=>R(A,T),list:D?C:void 0,placeholder:"Enter email address",className:"w-full rounded-xl border border-gray-300 pl-10 pr-3 py-3.5 text-sm text-gray-900 shadow-sm focus:outline-none focus:ring-emerald-500 focus:border-emerald-500"}),dt(_)&&t.jsx("button",{type:"button",onClick:()=>M(T),"aria-label":"Remove email",className:"absolute left-3 top-1/2 hidden -translate-y-1/2 items-center justify-center text-gray-400 hover:text-gray-600 group-hover:flex",children:t.jsx(ss,{className:"h-5 w-5"})})]},T)),t.jsx("button",{type:"button",onClick:N,className:"mt-2 flex w-full items-center justify-center rounded-xl px-4 py-3 text-sm font-medium text-gray-600 hover:bg-gray-50",children:t.jsxs("span",{className:"relative",children:[t.jsx(zs,{className:"absolute -left-5 top-1/2 h-4 w-4 -translate-y-1/2"}),"Add another email"]})}),g&&t.jsx("p",{className:"mt-3 text-sm text-red-700 bg-red-50 border border-red-200 rounded-md px-3 py-2",children:g}),h&&t.jsxs("p",{className:"mt-3 flex items-center gap-1.5 text-sm text-emerald-700",children:[t.jsx(rt,{className:"h-4 w-4"}),"Sent! Your colleagues will receive a copy by email shortly."]}),t.jsx("button",{type:"button",onClick:O,disabled:f||p.every(_=>!_.trim()),className:"mt-2 w-full rounded-lg bg-emerald-600 px-4 py-3 text-sm font-medium text-white hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 disabled:opacity-50 disabled:cursor-not-allowed",children:f?"Sending…":"Send"})]})},rl="focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-600",nl="Discoverable by other teachers",ol="Anyone with the link can still open it.",al=({isPublic:e,onChange:s,disabled:r=!1})=>{const[n,i]=l.useState(!1),o=n||r,a=async c=>{if(!o){i(!0);try{await s(c)}finally{i(!1)}}};return t.jsxs(Nt.Group,{as:"div",className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx(Nt.Label,{className:"block cursor-pointer text-sm text-gray-700",children:nl}),!e&&t.jsx(Nt.Description,{className:"mt-0.5 block text-xs text-gray-500",children:ol})]}),t.jsx(Nt,{checked:e,onChange:a,"aria-disabled":o||void 0,className:`relative mt-0.5 inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out ${rl} ${e?"bg-emerald-600":"bg-gray-200"}`,children:t.jsx("span",{"aria-hidden":"true",className:`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${e?"translate-x-4":"translate-x-0"}`})})]})},Ht="focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-600",ts=({icon:e,label:s,onClick:r})=>t.jsxs("button",{type:"button",onClick:r,className:`flex flex-col items-center gap-2 group rounded-lg ${Ht}`,children:[t.jsx("span",{className:"h-14 w-14 rounded-full bg-gray-100 group-hover:bg-gray-200 flex items-center justify-center text-gray-700 transition-colors",children:e}),t.jsx("span",{className:"text-xs text-gray-700 text-center leading-tight",children:s})]}),Os=({option:e,isPremiumUser:s,showPremiumCrowns:r,onSelect:n})=>{const i=mt.has(e.exportType),o=i&&!s,a=o||i&&r;return t.jsxs("button",{type:"button",onClick:()=>n(e),"aria-disabled":o||void 0,className:`relative flex flex-col items-center gap-2 group rounded-lg ${Ht} ${o?"cursor-default opacity-60":""}`,children:[t.jsx("span",{className:`h-14 w-14 rounded-full bg-gray-100 flex items-center justify-center text-gray-700 transition-colors ${o?"":"group-hover:bg-gray-200"}`,children:e.icon?t.jsx(Ft,{src:e.icon,alt:e.text,className:"h-7 w-7"}):t.jsx($t,{className:"h-6 w-6"})}),a&&t.jsx(is,{wrapperClassName:"absolute -top-1 right-1.5",className:"h-4 w-4",toolTipProps:{text:void 0}}),t.jsx("span",{className:"text-xs text-gray-700 text-center leading-tight",children:e.text})]})},as=l.forwardRef(({icon:e,label:s,trailing:r,onClick:n},i)=>t.jsxs("button",{ref:i,type:"button",onClick:n,className:`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-gray-50 ${Ht}`,children:[t.jsx("span",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-gray-100 text-gray-600",children:e}),t.jsx("span",{className:"flex flex-1 items-center gap-2 text-sm font-medium text-gray-900",children:s}),r]}));as.displayName="ActionRow";const $s=({trackEvent:e,pill:s,disabled:r,onExportClick:n})=>{const{doExport:i,printPacket:o,canvaEnabled:a}
64=nt(),{userLoginType:c,isPremiumUser:u}=Ue(),p=Xs(),{showTrialCountdown:d,showPremiumCrowns:f}=Ks();Js(e,d,"share_dialog");const{getPacketOrientation:m,hasMath:g,getPacketId:b}=Fe(),{setExportFollowUpModalOpen:h}=Be(),{setProjectVisibility:x,getIsPublic:w,getIsOwner:y}=ge(),{resourceVisibilityControl:v}=Ke(),j=v&&y(),{projectId:k}=yt(),[C,D]=l.useState("main"),[E,P]=l.useState(!1),[L,W]=l.useState(!1),F=l.useRef(null),N=l.useRef(!1),R=l.useRef(null),M=m()==="16x9",O=c==="google",_=g(),T=b(),{googleButtons:A,otherButtons:X}=or(M,O,_,a),se=[...A.filter(re=>!re.hidden&&!re.disabled),...X.filter(re=>!re.hidden&&!re.disabled)];l.useEffect(()=>{C==="main"&&N.current&&(F.current?.focus(),N.current=!1)},[C]);const ne=()=>{e("Share Clicked",{location:"header"}),D("main"),N.current=!1},Y=()=>{N.current=!0,D("invite")},G=()=>D("main"),J=re=>{if(re.exportType==="print"){e("Print Clicked",{location:"header"},{includeBlocks:!0}),o(),R.current?.();return}if(!(!u&&mt.has(re.exportType))){if(n&&Fr(re.exportType)){n(re.exportType),R.current?.();return}if(re.exportType===te.FORM){e("Export Clicked",{export_type:re.exportType},{includeBlocks:!0}),h({type:re.exportType}),R.current?.();return}e("Exported",{export_type:re.exportType,location:"header"},{includeBlocks:!0}),i({exportType:re.exportType,location:"header"}),R.current?.()}},q=()=>{e("Copied Link",{location:"share_dialog"},{includeBlocks:!0}),navigator.clipboard.writeText(p(window.location.href,{linkSource:Qs.COPY_LINK_SHARE_DIALOG})),P(!0),setTimeout(()=>P(!1),2e3)},H=async re=>{const ie=await x(re);ie!==null&&e("Resource Visibility Changed",{is_public:ie,location:"share_dialog"})},z=()=>{T&&(e("Published As Template",{location:"share_dialog",packet_id:T}),x(!0),window.open(er(T,{mode:"template"}),"_blank","noopener"),R.current?.())},V=()=>{e("Share To Shared Folder Clicked",{location:"share_dialog"}),W(!0),R.current?.()},K=t.jsx(ts,{icon:t.jsx(us,{className:"h-6 w-6","aria-hidden":"true"}),label:"Print",onClick:()=>J({exportType:"print"})},"print"),ae={isPremiumUser:u,showPremiumCrowns:f,onSelect:J},Q=t.jsx(Os,{option:{text:"PDF",exportType:te.PDF},...ae},"pdf"),me=t.jsx(ts,{icon:t.jsx(ar,{className:"h-6 w-6","aria-hidden":"true"}),label:"Publish as a Template",onClick:z},"template"),pe=t.jsx(ts,{icon:t.jsx(Rt,{className:"h-6 w-6","aria-hidden":"true"}),label:"Add to folder",onClick:V},"folder"),xe=se.map(re=>t.jsx(Os,{option:re,...ae},re.text)),oe=(u?[...xe,me,pe,K,Q]:[K,Q,me,pe,...xe]).filter(Boolean);return t.jsx(Jt,{as:"div",className:"relative",children:({open:re,close:ie})=>(R.current=ie,t.jsxs(t.Fragment,{children:[t.jsx(Ae,{text:re?"":"Share & Export",position:"bottom",anchor:"center",showArrow:!0,children:t.jsx(Jt.Button,{disabled:r,onClick:ne,className:`whitespace-nowrap text-sm font-medium transition-colors ${r?"bg-gray-300 text-white cursor-default":"bg-emerald-600 text-white hover:bg-emerald-700 cursor-pointer"} ${s?"px-3 py-2 rounded-xl":"px-2.5 py-2.5 rounded-xl"}`,children:"Share"})}),t.jsx(Ys,{as:l.Fragment,enter:"transition ease-out duration-100",enterFrom:"opacity-0 scale-95",enterTo:"opacity-100 scale-100",leave:"transition ease-in duration-75",leaveFrom:"opacity-100 scale-100",leaveTo:"opacity-0 scale-95",children:t.jsxs(Jt.Panel,{className:"absolute top-full right-0 mt-1.5 z-50 w-80 max-w-[calc(100vw-2rem)] max-h-[calc(100vh-6rem)] overflow-y-auto origin-top-right rounded-xl bg-white p-4 shadow-lg border border-gray-200 focus:outline-none",children:[C==="invite"&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:G,"aria-label":"Back",className:`-ml-1.5 flex h-8 w-8 items-center justify-center rounded-lg text-gray-500 hover:bg-gray-100 ${Ht}`,children:t.jsx(xt,{className:"h-5 w-5"})}),t.jsx("h3",{className:"min-w-0 break-words text-sm font-semibold text-gray-900",children:"Email to Colleagues"})]}),C==="invite"?t.jsx(Lr,{location:"share_dialog",trackEvent:e}):t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(as,{ref:F,icon:t.jsx(Yn,{className:"h-5 w-5"}
64),label:"Email to Colleagues",trailing:t.jsx(bt,{className:"h-5 w-5 text-gray-400"}),onClick:Y}),t.jsx(as,{icon:E?t.jsx(rt,{className:"h-5 w-5 text-emerald-600"}):t.jsx(Zs,{className:"h-5 w-5"}),label:E?t.jsx("span",{className:"text-emerald-600",children:"Copied!"}):"Copy link",onClick:q})]}),t.jsx("div",{className:"border-t border-gray-200"}),t.jsx("div",{className:"grid grid-cols-4 gap-x-3 gap-y-4",children:oe}),j&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"border-t border-gray-200"}),t.jsx(al,{isPublic:w(),onChange:H})]}),!u&&t.jsx(It,{mode:"free",location:"share_dialog",trackEvent:e}),d&&t.jsx(It,{mode:"trial",location:"share_dialog",trackEvent:e})]})]})}),t.jsx(nr,{packetId:T,projectId:k,showModal:L,setShowModal:W,source:"share_dialog"})]}))})},Mr='[data-container-type="page"]',il=({onClose:e})=>{const[s,r]=l.useState(0),[n,i]=l.useState(0),[o,a]=l.useState(!0),c=l.useRef(null),u=l.useRef(null),p=l.useRef(null),d=l.useRef(!1),f=()=>{const h=c.current;return[...document.querySelectorAll(Mr)].filter(x=>!h||!h.contains(x))},m=h=>r(x=>Math.max(0,Math.min(f().length-1,x+h)));l.useEffect(()=>{const h=c.current;h?.focus(),h?.requestFullscreen?.().catch(()=>{});const x=()=>{document.fullscreenElement||e()};return document.addEventListener("fullscreenchange",x),()=>{document.removeEventListener("fullscreenchange",x),document.fullscreenElement===h&&document.exitFullscreen().catch(()=>{})}},[]),l.useEffect(()=>{const h=x=>{x.target instanceof Element&&x.target.closest("[data-present-controls]")||(["ArrowRight","ArrowDown","PageDown"," ","Enter"].includes(x.key)?(x.preventDefault(),x.stopPropagation(),m(1)):["ArrowLeft","ArrowUp","PageUp"].includes(x.key)?(x.preventDefault(),x.stopPropagation(),m(-1)):x.key==="Escape"&&e())};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[]),l.useEffect(()=>{const h=()=>{a(!0),clearTimeout(p.current),p.current=setTimeout(()=>{d.current||a(!1)},3e3)};return h(),window.addEventListener("mousemove",h),()=>{clearTimeout(p.current),window.removeEventListener("mousemove",h)}},[]),l.useEffect(()=>{const h=f();if(i(h.length),h.length&&s>h.length-1){r(h.length-1);return}const x=h[s],w=u.current;if(!x||!w)return;const{width:y,height:v}=x.getBoundingClientRect();if(!y||!v)return;const j=x.cloneNode(!0),k=x.querySelectorAll("textarea");j.querySelectorAll("textarea").forEach((D,E)=>{D.value=k[E]?k[E].value:""}),j.removeAttribute("id"),j.querySelectorAll("[id]").forEach(D=>D.removeAttribute("id")),w.replaceChildren(j);const C=()=>{const D=Math.min(window.innerWidth*.94/y,window.innerHeight*.94/v);w.style.width=`${y}px`,w.style.height=`${v}px`,w.style.transform=`scale(${D})`};return C(),window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[s]);const g={onMouseEnter:()=>{d.current=!0},onMouseLeave:()=>{d.current=!1}},b=`transition-opacity duration-300 ${o?"opacity-100":"opacity-0 pointer-events-none"}`;return cs.createPortal(t.jsxs("div",{ref:c,role:"dialog","aria-modal":"true","aria-label":"Slide presentation",tabIndex:-1,className:`fixed inset-0 z-[9999] flex items-center justify-center bg-gray-950 select-none focus:outline-none ${o?"":"cursor-none"}`,onClick:()=>m(1),children:[t.jsx("div",{ref:u,className:"pointer-events-none flex-shrink-0"}),t.jsx("button",{type:"button","data-present-controls":!0,onClick:h=>{h.stopPropagation(),e()},"aria-label":"Exit presentation",...g,className:`absolute top-4 right-4 rounded-full p-2 text-white/70 hover:text-white hover:bg-white/10 ${b}`,children:t.jsx(ss,{className:"h-6 w-6"})}),t.jsxs("div",{"data-present-controls":!0,className:`absolute bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-2 rounded-full bg-black/60 px-3 py-1.5 text-white/90 ${b}`,...g,onClick:h=>h.stopPropagation(),children:[t.jsx("button",{type:"button",onClick:()=>m(-1),disabled:s===0,"aria-label":"Previous slide",className:"p-1 rounded-full hover:bg-white/10 disabled:opacity-30 disabled:hover:bg-transparent",children:t.jsx(xt,{className:"h-5 w-5"})}),t.jsx("span",{className:"text-sm tabular-nums","aria-live":"polite",children:`${s+1} / ${n}`}),t.jsx("button",{type:"button",onClick:()=>m(1),disabled:s>=n-1,"aria-label":"Next slide",className:"p-1 rounded-full hover:bg-white/10 disabled:opacity-30 disabled:hover:bg-transparent",children:t.jsx(bt,{className:"h-5 w-5"})})]})]}),document.body)},ll=({trackEvent:e,disabled:s})=>{const{getPacketOrientation:r}=Fe(),[n,i]=l.useState(!1);if(r()!=="16x9")return null;const o=()=>{const a=document.querySelectorAll(Mr);a.length&&(e("Present Clicked",{location:"header",slide_count:a.length}),i(!0))};return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",onClick:o,disabled:s,className:`flex items-center gap-1.5 whitespace-nowrap px-3 py-2 rounded-xl text-sm font-medium transition-colors ${s?"text-gray-400 cursor-default":"text-gray-700 hover:bg-gray-200"}`,children:[t.jsx(lo,{className:"h-4 w-4"}),t.jsx("span",{children:"Present"})]}),n&&t.jsx(il,{onClose:()=>i(!1)})]})},Tt=e=>`w-full text-left px-3 py-2 rounded-lg transition-colors text-sm flex items-center gap-2.5 ${e?"bg-gray-100 text-gray-900":"text-gray-700"}`,Bs=({trackEvent:e,pill:s,disabled:r,onExportClick:n})=>{const{doExport:i,printPacket:o,canvaEnabled:a}
64=nt(),{userLoginType:c,isPremiumUser:u}=Ue(),p=Xs(),{showTrialCountdown:d,showPremiumCrowns:f}=Ks();Js(e,d,"export_menu");const{getPacketOrientation:m,hasMath:g,getPacket:b}=Fe(),{setProjectVisibility:h}=ge(),{setExportFollowUpModalOpen:x}=Be(),{projectId:w}=yt(),y=m()==="16x9",v=c==="google",j=g(),[k,C]=l.useState(!1),[D,E]=l.useState(!1),[P,L]=l.useState("main"),{googleButtons:W,otherButtons:F}=or(y,v,j,a),N=[{text:"Download PDF",exportType:te.PDF},{text:"Print",exportType:"print"},{divider:!0},{text:"Publish as a Template",exportType:"publish_template"}],R=[...W,{divider:!0},...F],M=u?[...R,{divider:!0},...N]:[...N,{divider:!0},...R],O=(_,T)=>{if(_.divider)return t.jsx("div",{className:"my-1 mx-2 border-t border-gray-200"},`div-${T}`);const A=!u&&mt.has(_.exportType);return!_.hidden&&!_.disabled&&t.jsx(Ie.Item,{disabled:A,children:({active:X})=>t.jsxs("button",{onClick:()=>{if(!A)if(_.exportType==="print")e("Print Clicked",{location:"header"},{includeBlocks:!0}),o();else if(_.exportType==="publish_template"){const se=b()?.id;if(!se)return;e("Published As Template",{location:"header",packet_id:se}),h(!0),window.open(er(se,{mode:"template"}),"_blank","noopener")}else n&&Fr(_.exportType)?n(_.exportType):_.exportType===te.FORM?(e("Export Clicked",{export_type:_.exportType},{includeBlocks:!0}),x({type:_.exportType})):(_.exportType===te.PDF?e("Exported",{export_type:te.PDF,location:"header"},{includeBlocks:!0}):e("Exported",{export_type:_.exportType},{includeBlocks:!0}),i({exportType:_.exportType,location:"header"}))},className:Tt(X)+(A?" opacity-50 pointer-events-none":""),children:[_.icon?t.jsx(Ft,{src:_.icon,alt:_.text,className:"h-4 w-4 flex-shrink-0"}):_.exportType==="print"?t.jsx(us,{className:"h-4 w-4 flex-shrink-0"}):_.exportType==="publish_template"?t.jsx(ar,{className:"h-4 w-4 flex-shrink-0"}):t.jsx($t,{className:"h-4 w-4 flex-shrink-0"}),_.text,(A||f)&&mt.has(_.exportType)&&t.jsx(is,{wrapperClassName:"ml-auto",className:"h-3.5 w-3.5",toolTipProps:{text:void 0,position:"bottom",anchor:"center"}})]})},_.text)};return t.jsxs(Ie,{as:"div",className:"relative",children:[t.jsx(Ie.Button,{disabled:r,onClick:()=>{L("main"),e("Export Clicked")},className:`whitespace-nowrap text-sm font-medium transition-colors ${r?"bg-gray-300 text-white cursor-default":"bg-emerald-600 text-white hover:bg-emerald-700 cursor-pointer"} ${s?"px-3 py-2 rounded-xl":"px-2.5 py-2.5 rounded-xl"}`,children:"Export"}),t.jsx(Ys,{as:l.Fragment,enter:"transition ease-out duration-100",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"transition ease-in duration-75",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:t.jsx(Ie.Items,{className:`absolute top-full right-0 mt-1.5 z-50 ${P==="invite"?"w-72":!u||d?"w-64":"w-56"} rounded-xl bg-white p-1.5 shadow-lg border border-gray-200 focus:outline-none`,children:P==="invite"?t.jsxs("div",{onKeyDown:_=>_.key!=="Escape"&&_.stopPropagation(),children:[t.jsx("button",{type:"button",onClick:()=>L("main"),"aria-label":"Back",className:"-ml-0.5 mb-1 flex h-8 w-8 items-center justify-center rounded-lg text-gray-500 hover:bg-gray-100",children:t.jsx(xt,{className:"h-5 w-5"})}),t.jsx(Lr,{location:"export_menu",trackEvent:e})]}):t.jsxs(t.Fragment,{children:[d&&t.jsx(It,{mode:"trial",location:"export_menu",trackEvent:e}),(u?M:N).map(O),t.jsxs("button",{onClick:()=>{e("Copied Link",{location:"header"},{includeBlocks:!0}),navigator.clipboard.writeText(p(window.location.href,{linkSource:Qs.COPY_LINK_EXPORT_MENU})),C(!0),setTimeout(()=>C(!1),2e3)},className:`${Tt(!1)} hover:bg-gray-100 hover:text-gray-900`,children:[k?t.jsx(rt,{className:"h-4 w-4 flex-shrink-0 text-emerald-600"}):t.jsx(Zs,{className:"h-4 w-4 flex-shrink-0"}),k?t.jsx("span",{className:"text-emerald-600",children:"Copied!"}):"Copy Link"]}),t.jsx(Ie.Item,{children:({active:_})=>t.jsxs("button",{onClick:()=>{e("Share To Shared Folder Clicked",{location:"export_menu"}),E(!0)},className:Tt(_),children:[t.jsx(Rt,{className:"h-4 w-4 flex-shrink-0"}),"Add to folder"]})}),t.jsx("div",{className:"my-1 mx-2 border-t border-gray-200"}),t.jsxs("button",{type:"button",onClick:()=>{e("Share Clicked",{location:"header"}),L("invite")},className:`${Tt(!1)} hover:bg-gray-100 hover:text-gray-900`,children:[t.jsx(pn,{className:"h-4 w-4 flex-shrink-0"}
64),"Share with Colleagues"]}),!u&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"my-1 mx-2 border-t border-gray-200"}),R.map(O),t.jsx(It,{mode:"free",location:"export_menu",trackEvent:e})]}),t.jsxs("div",{className:"text-xs text-gray-500 bg-gray-50 rounded-lg px-3 py-2 mt-1",children:[t.jsx("span",{className:"font-medium",children:"Tip:"})," Everything you create on Diffit is in"," ",t.jsxs("span",{className:"ml-0.5 inline-flex items-center gap-1 align-text-bottom translate-y-px",children:[t.jsx(Rt,{className:"h-3.5 w-3.5"}),"My Resources"]})]})]})})}),t.jsx(nr,{packetId:b()?.id,projectId:w,showModal:D,setShowModal:E,source:"export_menu"})]})},cl=({children:e})=>{const[s,r]=l.useState(null),{sidebarHidden:n}=hn();return l.useEffect(()=>{r(document.getElementById(gn))},[n]),s?cs.createPortal(e,s):null},dl={[te.DOC]:"Google Docs",[te.SLIDES]:"Google Slides",[te.DOCX]:"Microsoft Word",[te.PPTX]:"Microsoft PowerPoint",[te.PDF]:"PDF"},ul=({isOpen:e,progress:s,exportType:r,onCancel:n})=>{const i=dl[r]||"files",o=s?.current||0,a=s?.total||0,c=s?.currentTitle||"",u=a>0?Math.round(o/a*100):0;return t.jsx(gt,{showModal:e,setShowModal:()=>{},title:`Exporting to ${i}`,iconBackground:"bg-emerald-100",icon:t.jsx($t,{className:"w-5 h-5 text-emerald-600"}),isExitable:!1,children:t.jsxs("div",{className:"mt-4",children:[t.jsxs("div",{className:"text-center mb-4",children:[t.jsxs("p",{className:"text-sm text-gray-600",children:["Exporting resource ",t.jsx("span",{className:"font-semibold",children:o})," of"," ",t.jsx("span",{className:"font-semibold",children:a})]}),c&&t.jsx("p",{className:"text-sm text-gray-500 mt-1 truncate max-w-xs mx-auto",children:c})]}),t.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2 mb-4",children:t.jsx("div",{className:"bg-emerald-600 h-2 rounded-full transition-all duration-300 ease-out",style:{width:`${u}%`}})}),t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(Lt,{})}),t.jsx("p",{className:"text-xs text-gray-400 text-center mb-4",children:"Please keep this window open until export completes"}),t.jsx("div",{className:"flex justify-center",children:t.jsx("button",{className:"px-4 py-2 text-sm text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-md transition-colors",onClick:n,children:"Cancel"})})]})})},ml={[te.DOC]:"https://docs.google.com/document/d/",[te.SLIDES]:"https://docs.google.com/presentation/d/",[te.CLASSROOM_DOC]:"https://docs.google.com/document/d/",[te.CLASSROOM_SLIDES]:"https://docs.google.com/presentation/d/"},fl=e=>[te.DOC,te.SLIDES].includes(e),pl=e=>[te.DOCX,te.PPTX,te.PDF].includes(e),Us=(e,s)=>{const r=ml[e];return r?`${r}${s}`:null},hl=({isOpen:e,results:s,onClose:r})=>{const{exportType:n,results:i,successCount:o,errorCount:a,skippedCount:c}=s||{};if(!s)return null;const u=fl(n),p=pl(n),d=i?.filter(k=>k.success&&k.googleId)||[],f=i?.filter(k=>k.skipped)||[],m=i?.filter(k=>!k.success&&!k.skipped)||[],g=()=>{d.forEach(k=>{const C=Us(n,k.googleId);C&&window.open(C,"_blank")})},b=k=>{const C=Us(n,k);C&&window.open(C,"_blank")},h=a>0,x=c>0,w=o===0&&(a>0||c>0),y=()=>w?t.jsx(bn,{className:"w-5 h-5 text-red-600"}):h||x?t.jsx(yn,{className:"w-5 h-5 text-amber-600"}):t.jsx(rt,{className:"w-5 h-5 text-emerald-600"}),v=()=>w?"bg-red-100":h||x?"bg-amber-100":"bg-emerald-100",j=()=>w?"Export Failed":h?"Export Completed with Errors":x?"Export Completed":"Export Complete!";return t.jsx(gt,{showModal:e,setShowModal:r,title:j(),iconBackground:v(),icon:y(),children:t.jsxs("div",{className:"mt-4",children:[t.jsx("div",{className:"text-center mb-4",children:p?t.jsx("p",{className:"text-sm text-gray-600",children:o>0?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-semibold",children:o})," ",o===1?"file has":"files have"," been downloaded"]}):"No files were downloaded"}):t.jsx("p",{className:"text-sm text-gray-600",children:o>0?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-semibold",children:o})," ",o===1?"file was":"files were"," created in your Google Drive"]}):"No files were created"})}),u&&d.length>0&&t.jsxs("div",{className:"mb-4",children:[t.jsx("div",{className:"max-h-48 overflow-y-auto border border-gray-200 rounded-lg divide-y divide-gray-100",children:d.map(k=>t.jsxs("div",{className:"flex items-center justify-between p-3 hover:bg-gray-50",children:[t.jsx("span",{className:"text-sm text-gray-700 truncate flex-1 mr-2",children:k.title}),t.jsxs("button",{className:"flex items-center gap-1 text-sm text-emerald-600 hover:text-emerald-700 font-medium",onClick:()=>b(k.googleId),children:["Open",t.jsx(xn,{className:"w-4 h-4"})]})]},k.packetId))}),d.length>1&&t.jsxs("button",{className:"mt-3 w-full py-2 px-4 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium rounded-lg transition-colors",onClick:g,children:["Open All (",d.length," files)"]})]}),f.length>0&&t.jsxs("div",{className:"mb-4 p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[t.jsxs("p",{className:"text-sm text-amber-800 font-medium mb-1",children:[f.length," ",f.length===1?"resource was":"resources were"," skipped"]}),t.jsx("p",{className:"text-xs text-amber-700",children:n===te.DOC||n===te.DOCX?"Slides-format resources (16:9) cannot be exported to document formats":n===te.PPTX?"Portrait resources cannot be exported to PowerPoint":"Some resources were incompatible with this export format"}),t.jsxs("div",{className:"mt-2 text-xs text-amber-600",children:[f.slice(0,3).map(k=>t.jsxs("div",{className:"truncate",children:["• ",k.title]},k.packetId)),f.length>3&&t.jsxs("div",{className:"text-amber-500",children:["...and ",f.length-3," more"]})]})]}),m.length>0&&t.jsxs("div",{className:"mb-4 p-3 bg-red-50 border border-red-200 rounded-lg",children:[t.jsxs("p",{className:"text-sm text-red-800 font-medium mb-1",children:[m.length," ",m.length===1?"resource":"resources"," failed to export"]}),t.jsxs("div",{className:"mt-2 text-xs text-red-600",children:[m.slice(0,3).map(k=>t.jsxs("div",{className:"truncate",children:["• ",k.title,": ",k.error||"Unknown error"]},k.packetId)),m.length>3&&t.jsxs("div",{className:"text-red-500",children:["...and ",m.length-3," more"]})]})]}),t.jsx(On,{surface:"multi_export",exportFailed:o===0}),t.jsx("div",{className:"flex justify-center mt-4",children:t.jsx("button",{className:"px-6 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-medium rounded-lg transition-colors",onClick:r,children:"Done"})})]})})},gl=e=>{const[s,r]=l.useState(null),[n,i]=l.useState(null),[o,a]=l.useState(null),[c,u]=l.useState(null),p=l.useRef(!1),{getAllPackets:d,getActivePacketTitle:f,switchToPacket:m,getActivePacketId:g}=ge(),{doExport:b,doExportSilent:h,checkAuth:x}=nt(),[w,y]=Ot(),v=(E,P)=>{const L=P.filter(N=>N.success).length,W=P.filter(N=>!N.success&&!N.skipped).length,F=P.filter(N=>N.skipped).length;return e("Export Completed",{export_type:E,success:L>0&&W===0,resource_count:P.length,success_count:L,error_count:W,skipped_count:F}),{successCount:L,errorCount:W,skippedCount:F}};l.useLayoutEffect(()=>{const E=w.get("multiExport"),P=w.get("exportType"),L=w.get("reauthorized");!P||!L||E!=="true"||(w.delete("multiExport"),w.delete("exportType"),w.delete("reauthorized"),y(w),e("Exported",{export_type:P,scope:"all",resumed:!0},{includeBlocks:!0}),C(P))},[w]);const j=E=>{const P=d();if(P.length<=1){e("Exported",{export_type:E},{includeBlocks:!0}),b({exportType:E,location:"header"});return}r({exportType:E,currentPacketTitle:f(),allPackets:P,onExportThis:()=>{e("Exported",{export_type:E,scope:"single"},{includeBlocks:!0}),b({exportType:E,location:"header"})},onExportAll:()=>{e("Exported",{export_type:E,scope:"all"},{includeBlocks:!0}),C(E)}})}
64,k=()=>{p.current=!0},C=async E=>{p.current=!1,u(E);const P=d(),L=P.filter(({packet:O})=>os(E,O?.orientation||"8.5x11"));if(L.length===0){const O=P.map(({packet:T})=>({packetId:T.id,title:T.title,skipped:!0,skipReason:"orientation"})),_=v(E,O);a({exportType:E,results:O,..._});return}if(i({current:0,total:L.length,currentTitle:"Starting exports..."}),!$n.has(E)){const{willReroute:O}=await x({exportType:E,additionalParams:{multiExport:"true"}});if(O)return}const W=g(),F=[];let N=0;for(const{packet:O}of P){const _=O.title;if(!os(E,O?.orientation||"8.5x11")){F.push(Promise.resolve({packetId:O.id,title:_,skipped:!0,skipReason:"orientation"}));continue}const A=h({exportType:E,packet:O,packetTitle:_}).then(X=>(N++,i({current:N,total:L.length,currentTitle:`${N} of ${L.length} completed`}),X?.success?{packetId:O.id,title:_,success:!0,googleId:X.googleId}:{packetId:O.id,title:_,success:!1,error:X?.error||"Export failed"})).catch(X=>(N++,i({current:N,total:L.length,currentTitle:`${N} of ${L.length} completed`}),console.error(`Error exporting packet ${O.id}:`,X),{packetId:O.id,title:_,success:!1,error:X.message||"Export failed"}));F.push(A)}const R=await Promise.all(F);W&&g()!==W&&m(W),i(null);const M=v(E,R);a({exportType:E,results:R,...M})},D=t.jsxs(t.Fragment,{children:[s&&t.jsx(tl,{onClose:()=>r(null),config:s}),n&&t.jsx(ul,{isOpen:!0,progress:n,exportType:c,onCancel:k}),o&&t.jsx(hl,{isOpen:!0,results:o,onClose:()=>a(null)})]});return{handleExportClick:j,multiExportModals:D}},xl=100,bl=1500,yl=e=>{const[s,r]=l.useState(null),[n,i]=l.useState(null);return e!==n&&(i(e),r(e??null)),l.useLayoutEffect(()=>{if(!s)return;if(!Bn()){r(null);return}let o;const c=Un(u=>{clearTimeout(o),u||(o=setTimeout(()=>r(null),xl))});return()=>{c(),clearTimeout(o)}},[s]),l.useEffect(()=>{if(!s)return;const o=setTimeout(()=>r(null),bl);return()=>clearTimeout(o)},[s]),s!==null},Ml=()=>t.jsx(wn,{children:t.jsx(vl,{})}),wl=()=>t.jsx("div",{className:"flex w-screen items-center justify-center px-4 pt-6 md:px-0 md:pt-20",children:t.jsx(ut,{})}),vl=()=>{const{isLoading:e,getActivePacketData:s,getProject:r,getProjectId:n,getPackets:i,getIsOwner:o,refreshProject:a,markPacketUpdated:c,isViewingVersion:u,versionUnavailable:p}=ge(),d=s(),f=n(),{packetId:m}=yt(),g=vn(),[b]=Ot(),{isLDidentified:h}=Ue(),x=l.useRef(null),w=l.useRef(null);l.useEffect(()=>{if(!h||e||!f||!d||r()?.id!==f)return;const j=!!b.get("stream_id"),k=x.current!==f;k&&(x.current=f,Se.track("Project Loaded",{project_id:f,packet_id:d.id,packet_title:d.title,packet_source:d.source,resource_count:i().length,is_owner:o(),is_version_view:u,is_streaming:j}),kn("ViewContent"),jn("contents_viewed"));const C=`${f}:${d.id}`;w.current!==C&&(w.current=C,Se.track("Resource Viewed",{project_id:f,packet_id:d.id,packet_title:d.title,packet_source:d.source,view_source:k?"project_load":"tab_switch",is_version_view:u}))},[h,e,f,d,r,i,o,u,b]),l.useEffect(()=>{if(!u||p||e)return;const v=i();if(v.length===0)return;if(!v.find(k=>k.packet.id===m)){const C=[...v].sort((D,E)=>(D.position??0)-(E.position??0))[0].packet.id;g(_n(f,C,b),{replace:!0})}},[u,p,e,m,f,g,b,i]);const y=l.useCallback(async(v,j)=>{try{Se.track("Resource Added To Project",{project_id:f,packet_id:v,title:j,method:j?.includes("Version")?"relevel_translate":"manual"}),await Sn(f,v,j),await a(),c(v)}catch(k){console.error("Failed to add packet to project:",k),window.location.href=`/p/${v}`}},[f,a,c]);return e?t.jsx(wl,{}):p?t.jsx(t.Fragment,{children:"Version unavailable"}):d?t.jsx(mo,{children:t.jsx(Nn,{children:t.jsx(Cn,{children:t.jsx(Wn,{children:t.jsx(Hn,{onModifySuccess:y,children:t.jsxs(Vn,{children:[t.jsx(jl,{}),t.jsx(kl,{}),t.jsx(_l,{})]})})})})})}):t.jsx("div",{className:"flex w-screen items-center justify-center pt-20",children:t.jsx("p",{className:"text-gray-500",children:"This project has no resources yet."})})},kl=()=>{const{getBlocks:e,getPacket:s,canUndo:r,canRedo:n,undo:i,redo:o,getPacketTitle:a,getPacketOrientation:c}=Fe(),{getProjectTitle:u,getProjectId:p,getIsOwner:d,getActivePacketId:f,isStreaming:m,isViewingVersion:g,cloneProjectAndRedirect:b}=ge(),{breakpoint:h}=qs(),x=l.useRef(null),w=s()?.id,y=e([]);
64let v,j;if(m){v=[];for(let z=0;z<y.length&&!y[z].canonical_id?.startsWith("loading");z++)v.push(y[z]);j=v.length<y.length}else v=y,j=!1;const k=!m||!j,[C,D]=l.useState(!m),E=f(),P=l.useRef(null);l.useEffect(()=>(v.length>0&&!C&&(P.current=requestAnimationFrame(()=>D(!0))),()=>{P.current&&cancelAnimationFrame(P.current)}),[v.length,C]),l.useEffect(()=>{v.length===0&&m&&D(!1)},[E,k]);const L=yl(w),{isSignedIn:W,isLoaded:F}=Dt(),[N]=Ot(),R=N.get("from_share")==="1",{setShowSignInModal:M}=Be(),{focusedSubresource:O}=Gn(),{chatModalOpen:_,setChatModalOpen:T}=Be(),{shareExportDialog:A}=Ke(),{isDiffitBot:X,isLDidentified:se}=Ue(),ne=X(),Y=l.useCallback((z,V={})=>{Se.track(z,{...V,project_id:p()})},[p]),{handleExportClick:G,multiExportModals:J}=gl(Y);l.useEffect(()=>{const z=new URLSearchParams(window.location.search);z.get("utm_source")==="claude"&&Y("MCP Resource Opened",{still_generating:!!z.get("stream_id")})},[]),l.useEffect(()=>{const z=u(),V=a(),K=z||V;return K&&(document.title=`${K} - Diffit`),()=>{document.title="Diffit For Teachers"}},[u,a]),l.useEffect(()=>{!R||W||!F||!M||M({open:!0,type:rs.SIGN_UP})},[F]);const q=l.useRef(!1);l.useEffect(()=>{!W||!se||!R||d()||!k||q.current||(q.current=!0,b(void 0))},[W,se,R,k]),Wi({canUndo:r,canRedo:n,undo:i,redo:o,trackEvent:Y}),Hi({getPacketOrientation:c,isDiffitBotUser:ne,trackEvent:Y}),Vi({focusedSubresource:O,trackEvent:Y});const H=_&&!g;return se?["xs","sm"].includes(h)?t.jsxs("div",{className:"bg-gray-50 print:bg-white",children:[t.jsx(cl,{children:!g&&(A?t.jsx($s,{trackEvent:Y,pill:!0,disabled:!k,onExportClick:G}):t.jsx(Bs,{trackEvent:Y,pill:!0,disabled:!k,onExportClick:G}))}),t.jsx(la,{}),t.jsx($i,{blocks:y,documentRef:x}),J]}):t.jsxs(t.Fragment,{children:[t.jsx(ra,{}),t.jsx(Yi,{scrollKey:L?null:w,resourceWidth:c()==="16x9"?sr:ds,isChatOpen:H,onToggleChat:g?void 0:()=>T(!_),chatHeader:t.jsx(Zi,{titleComponent:t.jsx(sa,{readOnly:!W||g,trackProjectEvent:Y}),rightContent:null}),resourceHeader:t.jsx(Qi,{children:t.jsx(na,{trackProjectEvent:Y,addButton:(d()||!W)&&!g?t.jsx(da,{}):null,undoButton:t.jsx(qn,{trackEvent:Y,isOwner:d()}),redoButton:t.jsx(zn,{trackEvent:Y,isOwner:d()}),presentButton:!g&&t.jsx(ll,{trackEvent:Y,disabled:!k}),exportButton:!g&&(A?t.jsx($s,{trackEvent:Y,pill:!0,disabled:!k,onExportClick:G}):t.jsx(Bs,{trackEvent:Y,pill:!0,disabled:!k,onExportClick:G}))})}),chatContent:t.jsx(ta,{isOpen:H,setOpen:T}),resourceContent:t.jsxs("div",{className:"flex flex-col items-center pb-4",children:[L&&k&&t.jsx("div",{className:"sticky top-0 z-10 h-0 w-full",children:t.jsx("div",{className:"absolute inset-x-0 top-0 flex justify-center",children:t.jsx(ut,{orientation:c()==="16x9"?"16x9":"portrait",offsetTop:!0})})}),v.length>0&&t.jsx("div",{style:{visibility:L?"hidden":void 0},className:`transition-opacity duration-500 print:visible ${C?"opacity-100":"opacity-0"}`,children:t.jsx(ua,{blocks:v,documentRef:x,isStreaming:m||j})}),!k&&t.jsx(ut,{orientation:c()==="16x9"?"16x9":"portrait",offsetTop:!0})]})}),J]}):["xs","sm"].includes(h)?t.jsx("div",{className:"flex flex-col items-center w-full px-4 pt-6",children:t.jsx(ut,{})}):t.jsx(t.Fragment,{})},jl=()=>{const{isLoading:e}=Fe(),{isSignedIn:s}=Dt(),{setShowSignInModal:r}=Be(),{getProjectId:n}=ge();return l.useEffect(()=>{const i=o=>{o.target.closest("[data-allow-click-when-logged-out]")||o.target.closest('[aria-modal="true"]')||(Se.track("Logged Out Project Clicked",{project_id:n()}),o.stopPropagation(),o.preventDefault(),r({open:!0,type:Xn()?rs.SIGN_UP:rs.SIGN_IN}))};return!s&&!e?document.addEventListener("click",i,!0):document.removeEventListener("click",i,!0),()=>{document.removeEventListener("click",i,!0)}},[s,e,r,n]),t.jsx(t.Fragment,{})},_l=()=>{const{getRemoveResourceConfirmation:e,clearRemoveResourceConfirmation:s}=ge(),r=e();return t.jsx(t.Fragment,{children:r&&t.jsx(ha,{onClose:s,config:r})})};export{Ml as Project};
65//# sourceMappingURL=project-0Kp9CxMz.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.