@remit/web-client-dist 0.0.116 → 0.0.118

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/assets/{ComposeBody-DbQicvPt.js → ComposeBody-DeSszvhh.js} +1 -1
  2. package/assets/{ErrorState-B7ruzpcU.js → ErrorState-BfxaQNmH.js} +1 -1
  3. package/assets/{OnboardingWizard-DVd5POJ9.js → OnboardingWizard-xvwCvrY5.js} +1 -1
  4. package/assets/{account-form-helpers-D8h3kmi5.js → account-form-helpers-CxtNxlMH.js} +1 -1
  5. package/assets/{accounts-BKlHKRwy.js → accounts-96Nt-7HF.js} +1 -1
  6. package/assets/{advanced-B8YgwMsP.js → advanced-DlUrcf2E.js} +1 -1
  7. package/assets/{appearance-C5g0EMDg.js → appearance-D0BXLAcK.js} +1 -1
  8. package/assets/{avatar-u2xv5ir0.js → avatar-C9A0tWly.js} +1 -1
  9. package/assets/{browser-ponyfill-Z3_yaJkZ.js → browser-ponyfill-CmMCz3_6.js} +1 -1
  10. package/assets/{filter-status-Cno2uEge.js → filter-status-GQG_QOmj.js} +1 -1
  11. package/assets/{filters-DpMD_2qb.js → filters-CZm3VcbQ.js} +1 -1
  12. package/assets/{flagged-DUaHc4QZ.js → flagged-CcI-V3h5.js} +1 -1
  13. package/assets/{folder-D9LdAj7g.js → folder-B24vOWVt.js} +1 -1
  14. package/assets/{folders-ZMmmt66-.js → folders-C34iHry2.js} +1 -1
  15. package/assets/{index-FEqTUkJz.js → index-BWkHHOCc.js} +4 -4
  16. package/assets/{index-1jPsSICV.js → index-BxLUgDD1.js} +1 -1
  17. package/assets/index-NKuGHf8d.js +1 -0
  18. package/assets/{kbd-Cocxki-7.js → kbd-Bql8Ucjm.js} +1 -1
  19. package/assets/{mail-N-zSB3pN.js → mail-Bcu7HbnV.js} +3 -3
  20. package/assets/{onboarding-CWiRsC6T.js → onboarding-V6yMtLvO.js} +1 -1
  21. package/assets/{select-CXiDtYIn.js → select-qDOWk-3K.js} +1 -1
  22. package/assets/{senders-D2JZQDD7.js → senders-DncJmsgU.js} +1 -1
  23. package/assets/settings-DqEixYGE.js +1 -0
  24. package/assets/{settings-screen-CqauHbQ0.js → settings-screen-BrQ9u_ut.js} +1 -1
  25. package/assets/{suggested-vips-ZYkzNXvT.js → suggested-vips-3dqmgGKZ.js} +1 -1
  26. package/assets/{useDebouncedValue-CDFJE7Bh.js → useDebouncedValue-CdUDVopg.js} +1 -1
  27. package/assets/{useMutation-DlslzhbR.js → useMutation-wcjpncqg.js} +1 -1
  28. package/assets/{useSignature-FvpR4-ot.js → useSignature-Mf8-UI7k.js} +1 -1
  29. package/index.html +1 -1
  30. package/package.json +1 -1
  31. package/assets/index-DPk71qb3.js +0 -1
  32. package/assets/settings-B0WJPyEF.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-DbQicvPt.js","assets/index-FEqTUkJz.js","assets/index-D6xwiajO.css","assets/useDebouncedValue-CDFJE7Bh.js","assets/avatar-u2xv5ir0.js","assets/kbd-Cocxki-7.js","assets/account-form-helpers-D8h3kmi5.js","assets/useMutation-DlslzhbR.js","assets/useSignature-FvpR4-ot.js","assets/ErrorState-B7ruzpcU.js","assets/format-B6Elex-n.js","assets/select-CXiDtYIn.js","assets/filter-status-Cno2uEge.js","assets/folder-D9LdAj7g.js"])))=>i.map(i=>d[i]);
2
- import{R as W,c as bd,r as c,a as ie,j as n,C as Et,X as We,b as H,B as G,d as tt,S as Rt,e as Yt,L as ra,f as vd,T as st,g as Gt,u as Bn,h as aa,i as Wi,I as Vi,p as Qi,k as oa,l as yd,D as Yi,m as Qs,O as wd,M as jd,A as Sd,F as Gi,n as kd,o as Cd,q as Nd,s as ia,t as la,v as ca,P as Ed,w as Id,x as ua,y as da,_ as St,z as Xi,E as Td,Q as fa,G as Rd,H as Md,J as Ad,K as zr,N as Dd,U as Od,V as ye,W as Pd,Y as Ld,Z as $d,$ as Fd,a0 as zd,a1 as _d,a2 as po,a3 as Bd,a4 as Kd,a5 as Ud,a6 as ma,a7 as Ji,a8 as Zi,a9 as Mt,aa as De,ab as Ve,ac as Ss,ad as pe,ae as ha,af as pa,ag as ga,ah as xa,ai as Kn,aj as xs,ak as Se,al as Ys,am as ce,an as el,ao as qd,ap as tl,aq as Hd,ar as Un,as as sl,at as gt,au as Ze,av as Wd,aw as ot,ax as nl,ay as Vt,az as qn,aA as Vd,aB as ba,aC as rl,aD as al,aE as Xt,aF as Hn,aG as Jt,aH as Qd,aI as Yd,aJ as bs,aK as Gd,aL as ol,aM as _r,aN as vs,aO as Xd,aP as va,aQ as Jd,aR as Zd,aS as il,aT as ya,aU as ks,aV as mt,aW as Br,aX as Kr,aY as ef,aZ as ll,a_ as tf,a$ as wa,b0 as cl,b1 as sf,b2 as nf,b3 as rf,b4 as af,b5 as of,b6 as lf,b7 as cf,b8 as uf,b9 as df,ba as ff,bb as mf,bc as hf,bd as pf,be as gf,bf as xf,bg as bf,bh as vf,bi as wt,bj as ft,bk as yf}from"./index-FEqTUkJz.js";import{S as Gs,u as ul}from"./useDebouncedValue-CDFJE7Bh.js";import{A as lt,M as ja,C as wf}from"./avatar-u2xv5ir0.js";import{K as hs}from"./kbd-Cocxki-7.js";import{L as xt,M as dl,a as jf}from"./account-form-helpers-D8h3kmi5.js";import{u as ve}from"./useMutation-DlslzhbR.js";import{R as Sf,u as kf}from"./useSignature-FvpR4-ot.js";import{E as At,f as fl}from"./ErrorState-B7ruzpcU.js";import{f as ml,a as Dt,b as hl,c as On,d as it,t as Cf}from"./format-B6Elex-n.js";import{C as Xs,S as Nf}from"./select-CXiDtYIn.js";import{b as pl,h as Ef,p as If,u as Tf}from"./filter-status-Cno2uEge.js";import{F as Rf}from"./folder-D9LdAj7g.js";function Ks(e){if(Mf())e.focus({preventScroll:!0});else{let t=Af(e);e.focus(),Df(t)}}let gn=null;function Mf(){if(gn==null){gn=!1;try{document.createElement("div").focus({get preventScroll(){return gn=!0,!0}})}catch{}}return gn}function Af(e){let t=e.parentNode,s=[],r=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==r;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return r instanceof HTMLElement&&s.push({element:r,scrollTop:r.scrollTop,scrollLeft:r.scrollLeft}),s}function Df(e){for(let{element:t,scrollTop:s,scrollLeft:r}of e)t.scrollTop=s,t.scrollLeft=r}const Ct=e=>e?.ownerDocument??document,It=e=>e&&"window"in e&&e.window===e?e:Ct(e).defaultView||window;function Of(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function Pf(e){return Of(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let Lf=!1;function gl(){return Lf}function rt(e,t){if(!gl())return t&&e?e.contains(t):!1;if(!e||!t)return!1;let s=t;for(;s!==null;){if(s===e)return!0;s.tagName==="SLOT"&&s.assignedSlot?s=s.assignedSlot.parentNode:Pf(s)?s=s.host:s=s.parentNode}return!1}function Te(e){if(gl()&&e.target instanceof Element&&e.target.shadowRoot){if("composedPath"in e)return e.composedPath()[0]??null;if("composedPath"in e.nativeEvent)return e.nativeEvent.composedPath()[0]??null}return e.target}const $f=typeof Element<"u"&&"checkVisibility"in Element.prototype;function Ff(e){const t=It(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:r}=e.style,a=s!=="none"&&r!=="hidden"&&r!=="collapse";if(a){const{getComputedStyle:o}=It(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function zf(e,t){return!e.hasAttribute("hidden")&&!e.hasAttribute("data-react-aria-prevent-focus")&&(e.nodeName==="DETAILS"&&t&&t.nodeName!=="SUMMARY"?e.hasAttribute("open"):!0)}function xl(e,t){return $f?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&Ff(e)&&zf(e,t)&&(!e.parentElement||xl(e.parentElement,e))}const bl=["input:not([disabled]):not([type=hidden])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable^="false"])',"permission"],_f=bl.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";bl.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function Bf(e,t){return e.matches(_f)&&!Kf(e)&&(t?.skipVisibilityCheck||xl(e))}function Kf(e){let t=e;for(;t!=null;){if(t instanceof It(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Sa=typeof document<"u"?W.useLayoutEffect:()=>{};function Uf(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function qf(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function Hf(e){for(;e&&!Bf(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=It(e),s=t.document.activeElement;if(!s||s===e)return;let r=!1,a=d=>{(Te(d)===s||r)&&d.stopImmediatePropagation()},o=d=>{(Te(d)===s||r)&&(d.stopImmediatePropagation(),!e&&!r&&(r=!0,Ks(s),u()))},i=d=>{(Te(d)===e||r)&&d.stopImmediatePropagation()},l=d=>{(Te(d)===e||r)&&(d.stopImmediatePropagation(),r||(r=!0,Ks(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(f),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),r=!1},f=requestAnimationFrame(u);return u}function Wn(e){if(typeof window>"u"||window.navigator==null)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(s=>e.test(s.brand))||e.test(window.navigator.userAgent)}function ka(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function Ot(e){let t=null;return()=>(t==null&&(t=e()),t)}const Pn=Ot(function(){return ka(/^Mac/i)}),Wf=Ot(function(){return ka(/^iPhone/i)}),vl=Ot(function(){return ka(/^iPad/i)||Pn()&&navigator.maxTouchPoints>1}),yl=Ot(function(){return Wf()||vl()}),Vf=Ot(function(){return Wn(/AppleWebKit/i)&&!Qf()}),Qf=Ot(function(){return Wn(/Chrome/i)}),wl=Ot(function(){return Wn(/Android/i)}),Yf=Ot(function(){return Wn(/Firefox/i)});function Gf(e){return e.pointerType===""&&e.isTrusted?!0:wl()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function Xf(e){return!wl()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function Us(e,t,s=!0){let{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}=t;Yf()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Pn()?r=!0:a=!0);let l=Vf()&&Pn()&&!vl()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});Us.isOpening=s,Ks(e),e.dispatchEvent(l),Us.isOpening=!1}Us.isOpening=!1;let kt=new Map,Ur=new Set;function go(){if(typeof window>"u")return;function e(r){return"propertyName"in r}let t=r=>{let a=Te(r);if(!e(r)||!a)return;let o=kt.get(a);o||(o=new Set,kt.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(r.propertyName)},s=r=>{let a=Te(r);if(!e(r)||!a)return;let o=kt.get(a);if(o&&(o.delete(r.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),kt.delete(a)),kt.size===0)){for(let i of Ur)i();Ur.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?go():document.addEventListener("DOMContentLoaded",go));function Jf(){for(const[e]of kt)"isConnected"in e&&!e.isConnected&&kt.delete(e)}function Zf(e){requestAnimationFrame(()=>{Jf(),kt.size===0?e():Ur.add(e)})}function jl(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let qr=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{qr.delete(e)});function em(e,t){if(e===t)return e;let s=qr.get(e);if(s)return s.forEach(a=>a.current=t),t;let r=qr.get(t);return r?(r.forEach(a=>a.current=e),e):t}function tm(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const r=e.map(a=>{const o=xo(a,t);return s||=typeof o=="function",o});if(s)return()=>{r.forEach((a,o)=>{typeof a=="function"?a():xo(e[o],null)})}}}function xo(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Js(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let r=e[s];for(let a in r){let o=t[a],i=r[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=jl(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=bd(o,i):a==="id"&&o&&i?t.id=em(o,i):a==="ref"&&o&&i?t.ref=tm(o,i):t[a]=i!==void 0?i:o}}return t}function sm(e,t){Sa(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const nm=W.useInsertionEffect??Sa;function br(e){const t=c.useRef(null);return nm(()=>{t.current=e},[e]),c.useCallback((...s)=>{const r=t.current;return r?.(...s)},[])}let fs="default",Hr="",Tn=new WeakMap;function rm(e){if(yl()){if(fs==="default"){const t=Ct(e);Hr=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}fs="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Tn.set(e,e.style[t]),e.style[t]="none"}}function bo(e){if(yl()){if(fs!=="disabled")return;fs="restoring",setTimeout(()=>{Zf(()=>{if(fs==="restoring"){const t=Ct(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=Hr||""),Hr="",fs="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Tn.has(e)){let t=Tn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Tn.delete(e)}}function vo(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let vr=new WeakMap;function am(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return vo(t);if(vr.has(t))return vr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),r=s&&s instanceof It(s).HTMLMetaElement&&(s.nonce||s.content)||vo(t)||void 0;return r!==void 0&&vr.set(t,r),r}const Sl=W.createContext({register:()=>{}});Sl.displayName="PressResponderContext";function kl(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...f)=>{e.current.delete(i),i(...f)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),r=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>r,[r]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:r}}function om(e){let t=c.useContext(Sl);if(t){let{register:s,ref:r,...a}=t;e=Js(a,e),s()}return sm(t,e.ref),e}class xn{#s;constructor(t,s,r,a){this.#s=!0;const i=(a?.target??r.currentTarget)?.getBoundingClientRect();let l,u=0,f,d=null;r.clientX!=null&&r.clientY!=null&&(f=r.clientX,d=r.clientY),i&&(f!=null&&d!=null?(l=f-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=r.currentTarget,this.shiftKey=r.shiftKey,this.metaKey=r.metaKey,this.ctrlKey=r.ctrlKey,this.altKey=r.altKey,this.x=l,this.y=u,this.key=r.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const yo=Symbol("linkClicked"),wo="react-aria-pressable-style",jo="data-react-aria-pressable";function im(e){let{onPress:t,onPressChange:s,onPressStart:r,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:f,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:m,ref:h,...x}=om(e),[b,p]=c.useState(!1),v=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:g,removeAllGlobalListeners:y}=kl(),w=c.useCallback((j,I)=>{let L=v.current;if(l||L.didFirePressStart)return!1;let T=!0;if(L.isTriggeringEvent=!0,r){let F=new xn("pressstart",I,j);r(F),T=F.shouldStopPropagation}return s&&s(!0),L.isTriggeringEvent=!1,L.didFirePressStart=!0,p(!0),T},[l,r,s]),S=c.useCallback((j,I,L=!0)=>{let T=v.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let F=!0;if(a){let M=new xn("pressend",I,j);a(M),F=M.shouldStopPropagation}if(s&&s(!1),p(!1),t&&L&&!l){let M=new xn("press",I,j);t(M),F&&=M.shouldStopPropagation}return T.isTriggeringEvent=!1,F},[l,a,s,t]),N=br(S),R=c.useCallback((j,I)=>{let L=v.current;if(l)return!1;if(o){L.isTriggeringEvent=!0;let T=new xn("pressup",I,j);return o(T),L.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[l,o]),C=br(R),k=c.useCallback(j=>{let I=v.current;if(I.isPressed&&I.target){I.didFirePressStart&&I.pointerType!=null&&S(Ut(I.target,j),I.pointerType,!1),I.isPressed=!1,I.isOverTarget=!1,I.activePointerId=null,I.pointerType=null,y(),m||bo(I.target);for(let L of I.disposables)L();I.disposables=[]}},[m,y,S]),D=br(k);c.useEffect(()=>{l&&v.current.isPressed&&D({currentTarget:v.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let O=c.useCallback(j=>{d&&k(j)},[d,k]),A=c.useCallback(j=>{l||i?.(j)},[l,i]),P=c.useCallback((j,I)=>{if(!l&&i){let L=new MouseEvent("click",j);qf(L,I),i(Uf(L))}},[l,i]),E=c.useMemo(()=>{let j=v.current,I={onKeyDown(T){if(yr(T.nativeEvent,T.currentTarget)&&rt(T.currentTarget,Te(T))){So(Te(T),T.key)&&T.preventDefault();let F=!0;!j.isPressed&&!T.repeat&&(j.target=T.currentTarget,j.isPressed=!0,j.pointerType="keyboard",F=w(T,"keyboard"));let M=T.currentTarget,$=K=>{yr(K,M)&&!K.repeat&&rt(M,Te(K))&&j.target&&C(Ut(j.target,K),"keyboard")};g(Ct(T.currentTarget),"keyup",jl($,L),!0),F&&T.stopPropagation(),T.metaKey&&Pn()&&j.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(j.metaKeyEvents=new Map)},onClick(T){if(!(T&&!rt(T.currentTarget,Te(T)))&&T&&T.button===0&&!j.isTriggeringEvent&&!Us.isOpening){let F=!0;if(l&&T.preventDefault(),!j.ignoreEmulatedMouseEvents&&!j.isPressed&&(j.pointerType==="virtual"||Gf(T.nativeEvent))){let M=w(T,"virtual"),$=C(T,"virtual"),K=N(T,"virtual");A(T),F=M&&$&&K}else if(j.isPressed&&j.pointerType!=="keyboard"){let M=j.pointerType||T.nativeEvent.pointerType||"virtual",$=C(Ut(T.currentTarget,T),M),K=N(Ut(T.currentTarget,T),M,!0);F=$&&K,j.isOverTarget=!1,A(T),D(T)}j.ignoreEmulatedMouseEvents=!1,F&&T.stopPropagation()}}},L=T=>{if(j.isPressed&&j.target&&yr(T,j.target)){So(Te(T),T.key)&&T.preventDefault();let F=Te(T),M=rt(j.target,F);N(Ut(j.target,T),"keyboard",M),M&&P(T,j.target),y(),T.key!=="Enter"&&Ca(j.target)&&rt(j.target,F)&&!T[yo]&&(T[yo]=!0,Us(j.target,T,!1)),j.isPressed=!1,j.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&j.metaKeyEvents?.size){let F=j.metaKeyEvents;j.metaKeyEvents=void 0;for(let M of F.values())j.target?.dispatchEvent(new KeyboardEvent("keyup",M))}};if(typeof PointerEvent<"u"){I.onPointerDown=M=>{if(M.button!==0||!rt(M.currentTarget,Te(M)))return;if(Xf(M.nativeEvent)){j.pointerType="virtual";return}j.pointerType=M.pointerType;let $=!0;if(!j.isPressed){j.isPressed=!0,j.isOverTarget=!0,j.activePointerId=M.pointerId,j.target=M.currentTarget,m||rm(j.target),$=w(M,j.pointerType);let K=Te(M);"releasePointerCapture"in K&&("hasPointerCapture"in K?K.hasPointerCapture(M.pointerId)&&K.releasePointerCapture(M.pointerId):K.releasePointerCapture(M.pointerId)),g(Ct(M.currentTarget),"pointerup",T,!1),g(Ct(M.currentTarget),"pointercancel",F,!1)}$&&M.stopPropagation()},I.onMouseDown=M=>{if(rt(M.currentTarget,Te(M))&&M.button===0){if(f){let $=Hf(M.target);$&&j.disposables.push($)}M.stopPropagation()}},I.onPointerUp=M=>{!rt(M.currentTarget,Te(M))||j.pointerType==="virtual"||M.button===0&&!j.isPressed&&C(M,j.pointerType||M.pointerType)},I.onPointerEnter=M=>{M.pointerId===j.activePointerId&&j.target&&!j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!0,w(Ut(j.target,M),j.pointerType))},I.onPointerLeave=M=>{M.pointerId===j.activePointerId&&j.target&&j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!1,N(Ut(j.target,M),j.pointerType,!1),O(M))};let T=M=>{if(M.pointerId===j.activePointerId&&j.isPressed&&M.button===0&&j.target){if(rt(j.target,Te(M))&&j.pointerType!=null){let $=!1,K=setTimeout(()=>{j.isPressed&&j.target instanceof HTMLElement&&($?D(M):(Ks(j.target),j.target.click()))},80);g(M.currentTarget,"click",()=>$=!0,!0),j.disposables.push(()=>clearTimeout(K))}else D(M);j.isOverTarget=!1}},F=M=>{D(M)};I.onDragStart=M=>{rt(M.currentTarget,Te(M))&&D(M)}}return I},[g,l,f,y,m,O,w,A,P]);return c.useEffect(()=>{if(!h)return;const j=Ct(h.current);if(!j||!j.head||j.getElementById(wo))return;const I=j.createElement("style");I.id=wo;let L=am(j);L&&(I.nonce=L),I.textContent=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-DeSszvhh.js","assets/index-BWkHHOCc.js","assets/index-D6xwiajO.css","assets/useDebouncedValue-CdUDVopg.js","assets/avatar-C9A0tWly.js","assets/kbd-Bql8Ucjm.js","assets/account-form-helpers-CxtNxlMH.js","assets/useMutation-wcjpncqg.js","assets/useSignature-Mf8-UI7k.js","assets/ErrorState-BfxaQNmH.js","assets/format-B6Elex-n.js","assets/select-qDOWk-3K.js","assets/filter-status-GQG_QOmj.js","assets/folder-B24vOWVt.js"])))=>i.map(i=>d[i]);
2
+ import{R as W,c as bd,r as c,a as ie,j as n,C as Et,X as We,b as H,B as G,d as tt,S as Rt,e as Yt,L as ra,f as vd,T as st,g as Gt,u as Bn,h as aa,i as Wi,I as Vi,p as Qi,k as oa,l as yd,D as Yi,m as Qs,O as wd,M as jd,A as Sd,F as Gi,n as kd,o as Cd,q as Nd,s as ia,t as la,v as ca,P as Ed,w as Id,x as ua,y as da,_ as St,z as Xi,E as Td,Q as fa,G as Rd,H as Md,J as Ad,K as zr,N as Dd,U as Od,V as ye,W as Pd,Y as Ld,Z as $d,$ as Fd,a0 as zd,a1 as _d,a2 as po,a3 as Bd,a4 as Kd,a5 as Ud,a6 as ma,a7 as Ji,a8 as Zi,a9 as Mt,aa as De,ab as Ve,ac as Ss,ad as pe,ae as ha,af as pa,ag as ga,ah as xa,ai as Kn,aj as xs,ak as Se,al as Ys,am as ce,an as el,ao as qd,ap as tl,aq as Hd,ar as Un,as as sl,at as gt,au as Ze,av as Wd,aw as ot,ax as nl,ay as Vt,az as qn,aA as Vd,aB as ba,aC as rl,aD as al,aE as Xt,aF as Hn,aG as Jt,aH as Qd,aI as Yd,aJ as bs,aK as Gd,aL as ol,aM as _r,aN as vs,aO as Xd,aP as va,aQ as Jd,aR as Zd,aS as il,aT as ya,aU as ks,aV as mt,aW as Br,aX as Kr,aY as ef,aZ as ll,a_ as tf,a$ as wa,b0 as cl,b1 as sf,b2 as nf,b3 as rf,b4 as af,b5 as of,b6 as lf,b7 as cf,b8 as uf,b9 as df,ba as ff,bb as mf,bc as hf,bd as pf,be as gf,bf as xf,bg as bf,bh as vf,bi as wt,bj as ft,bk as yf}from"./index-BWkHHOCc.js";import{S as Gs,u as ul}from"./useDebouncedValue-CdUDVopg.js";import{A as lt,M as ja,C as wf}from"./avatar-C9A0tWly.js";import{K as hs}from"./kbd-Bql8Ucjm.js";import{L as xt,M as dl,a as jf}from"./account-form-helpers-CxtNxlMH.js";import{u as ve}from"./useMutation-wcjpncqg.js";import{R as Sf,u as kf}from"./useSignature-Mf8-UI7k.js";import{E as At,f as fl}from"./ErrorState-BfxaQNmH.js";import{f as ml,a as Dt,b as hl,c as On,d as it,t as Cf}from"./format-B6Elex-n.js";import{C as Xs,S as Nf}from"./select-qDOWk-3K.js";import{b as pl,h as Ef,p as If,u as Tf}from"./filter-status-GQG_QOmj.js";import{F as Rf}from"./folder-B24vOWVt.js";function Ks(e){if(Mf())e.focus({preventScroll:!0});else{let t=Af(e);e.focus(),Df(t)}}let gn=null;function Mf(){if(gn==null){gn=!1;try{document.createElement("div").focus({get preventScroll(){return gn=!0,!0}})}catch{}}return gn}function Af(e){let t=e.parentNode,s=[],r=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==r;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return r instanceof HTMLElement&&s.push({element:r,scrollTop:r.scrollTop,scrollLeft:r.scrollLeft}),s}function Df(e){for(let{element:t,scrollTop:s,scrollLeft:r}of e)t.scrollTop=s,t.scrollLeft=r}const Ct=e=>e?.ownerDocument??document,It=e=>e&&"window"in e&&e.window===e?e:Ct(e).defaultView||window;function Of(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function Pf(e){return Of(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let Lf=!1;function gl(){return Lf}function rt(e,t){if(!gl())return t&&e?e.contains(t):!1;if(!e||!t)return!1;let s=t;for(;s!==null;){if(s===e)return!0;s.tagName==="SLOT"&&s.assignedSlot?s=s.assignedSlot.parentNode:Pf(s)?s=s.host:s=s.parentNode}return!1}function Te(e){if(gl()&&e.target instanceof Element&&e.target.shadowRoot){if("composedPath"in e)return e.composedPath()[0]??null;if("composedPath"in e.nativeEvent)return e.nativeEvent.composedPath()[0]??null}return e.target}const $f=typeof Element<"u"&&"checkVisibility"in Element.prototype;function Ff(e){const t=It(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:r}=e.style,a=s!=="none"&&r!=="hidden"&&r!=="collapse";if(a){const{getComputedStyle:o}=It(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function zf(e,t){return!e.hasAttribute("hidden")&&!e.hasAttribute("data-react-aria-prevent-focus")&&(e.nodeName==="DETAILS"&&t&&t.nodeName!=="SUMMARY"?e.hasAttribute("open"):!0)}function xl(e,t){return $f?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&Ff(e)&&zf(e,t)&&(!e.parentElement||xl(e.parentElement,e))}const bl=["input:not([disabled]):not([type=hidden])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable^="false"])',"permission"],_f=bl.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";bl.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function Bf(e,t){return e.matches(_f)&&!Kf(e)&&(t?.skipVisibilityCheck||xl(e))}function Kf(e){let t=e;for(;t!=null;){if(t instanceof It(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Sa=typeof document<"u"?W.useLayoutEffect:()=>{};function Uf(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function qf(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function Hf(e){for(;e&&!Bf(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=It(e),s=t.document.activeElement;if(!s||s===e)return;let r=!1,a=d=>{(Te(d)===s||r)&&d.stopImmediatePropagation()},o=d=>{(Te(d)===s||r)&&(d.stopImmediatePropagation(),!e&&!r&&(r=!0,Ks(s),u()))},i=d=>{(Te(d)===e||r)&&d.stopImmediatePropagation()},l=d=>{(Te(d)===e||r)&&(d.stopImmediatePropagation(),r||(r=!0,Ks(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(f),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),r=!1},f=requestAnimationFrame(u);return u}function Wn(e){if(typeof window>"u"||window.navigator==null)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(s=>e.test(s.brand))||e.test(window.navigator.userAgent)}function ka(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function Ot(e){let t=null;return()=>(t==null&&(t=e()),t)}const Pn=Ot(function(){return ka(/^Mac/i)}),Wf=Ot(function(){return ka(/^iPhone/i)}),vl=Ot(function(){return ka(/^iPad/i)||Pn()&&navigator.maxTouchPoints>1}),yl=Ot(function(){return Wf()||vl()}),Vf=Ot(function(){return Wn(/AppleWebKit/i)&&!Qf()}),Qf=Ot(function(){return Wn(/Chrome/i)}),wl=Ot(function(){return Wn(/Android/i)}),Yf=Ot(function(){return Wn(/Firefox/i)});function Gf(e){return e.pointerType===""&&e.isTrusted?!0:wl()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function Xf(e){return!wl()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function Us(e,t,s=!0){let{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}=t;Yf()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Pn()?r=!0:a=!0);let l=Vf()&&Pn()&&!vl()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});Us.isOpening=s,Ks(e),e.dispatchEvent(l),Us.isOpening=!1}Us.isOpening=!1;let kt=new Map,Ur=new Set;function go(){if(typeof window>"u")return;function e(r){return"propertyName"in r}let t=r=>{let a=Te(r);if(!e(r)||!a)return;let o=kt.get(a);o||(o=new Set,kt.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(r.propertyName)},s=r=>{let a=Te(r);if(!e(r)||!a)return;let o=kt.get(a);if(o&&(o.delete(r.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),kt.delete(a)),kt.size===0)){for(let i of Ur)i();Ur.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?go():document.addEventListener("DOMContentLoaded",go));function Jf(){for(const[e]of kt)"isConnected"in e&&!e.isConnected&&kt.delete(e)}function Zf(e){requestAnimationFrame(()=>{Jf(),kt.size===0?e():Ur.add(e)})}function jl(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let qr=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{qr.delete(e)});function em(e,t){if(e===t)return e;let s=qr.get(e);if(s)return s.forEach(a=>a.current=t),t;let r=qr.get(t);return r?(r.forEach(a=>a.current=e),e):t}function tm(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const r=e.map(a=>{const o=xo(a,t);return s||=typeof o=="function",o});if(s)return()=>{r.forEach((a,o)=>{typeof a=="function"?a():xo(e[o],null)})}}}function xo(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Js(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let r=e[s];for(let a in r){let o=t[a],i=r[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=jl(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=bd(o,i):a==="id"&&o&&i?t.id=em(o,i):a==="ref"&&o&&i?t.ref=tm(o,i):t[a]=i!==void 0?i:o}}return t}function sm(e,t){Sa(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const nm=W.useInsertionEffect??Sa;function br(e){const t=c.useRef(null);return nm(()=>{t.current=e},[e]),c.useCallback((...s)=>{const r=t.current;return r?.(...s)},[])}let fs="default",Hr="",Tn=new WeakMap;function rm(e){if(yl()){if(fs==="default"){const t=Ct(e);Hr=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}fs="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Tn.set(e,e.style[t]),e.style[t]="none"}}function bo(e){if(yl()){if(fs!=="disabled")return;fs="restoring",setTimeout(()=>{Zf(()=>{if(fs==="restoring"){const t=Ct(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=Hr||""),Hr="",fs="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Tn.has(e)){let t=Tn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Tn.delete(e)}}function vo(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let vr=new WeakMap;function am(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return vo(t);if(vr.has(t))return vr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),r=s&&s instanceof It(s).HTMLMetaElement&&(s.nonce||s.content)||vo(t)||void 0;return r!==void 0&&vr.set(t,r),r}const Sl=W.createContext({register:()=>{}});Sl.displayName="PressResponderContext";function kl(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...f)=>{e.current.delete(i),i(...f)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),r=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>r,[r]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:r}}function om(e){let t=c.useContext(Sl);if(t){let{register:s,ref:r,...a}=t;e=Js(a,e),s()}return sm(t,e.ref),e}class xn{#s;constructor(t,s,r,a){this.#s=!0;const i=(a?.target??r.currentTarget)?.getBoundingClientRect();let l,u=0,f,d=null;r.clientX!=null&&r.clientY!=null&&(f=r.clientX,d=r.clientY),i&&(f!=null&&d!=null?(l=f-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=r.currentTarget,this.shiftKey=r.shiftKey,this.metaKey=r.metaKey,this.ctrlKey=r.ctrlKey,this.altKey=r.altKey,this.x=l,this.y=u,this.key=r.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const yo=Symbol("linkClicked"),wo="react-aria-pressable-style",jo="data-react-aria-pressable";function im(e){let{onPress:t,onPressChange:s,onPressStart:r,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:f,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:m,ref:h,...x}=om(e),[b,p]=c.useState(!1),v=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:g,removeAllGlobalListeners:y}=kl(),w=c.useCallback((j,I)=>{let L=v.current;if(l||L.didFirePressStart)return!1;let T=!0;if(L.isTriggeringEvent=!0,r){let F=new xn("pressstart",I,j);r(F),T=F.shouldStopPropagation}return s&&s(!0),L.isTriggeringEvent=!1,L.didFirePressStart=!0,p(!0),T},[l,r,s]),S=c.useCallback((j,I,L=!0)=>{let T=v.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let F=!0;if(a){let M=new xn("pressend",I,j);a(M),F=M.shouldStopPropagation}if(s&&s(!1),p(!1),t&&L&&!l){let M=new xn("press",I,j);t(M),F&&=M.shouldStopPropagation}return T.isTriggeringEvent=!1,F},[l,a,s,t]),N=br(S),R=c.useCallback((j,I)=>{let L=v.current;if(l)return!1;if(o){L.isTriggeringEvent=!0;let T=new xn("pressup",I,j);return o(T),L.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[l,o]),C=br(R),k=c.useCallback(j=>{let I=v.current;if(I.isPressed&&I.target){I.didFirePressStart&&I.pointerType!=null&&S(Ut(I.target,j),I.pointerType,!1),I.isPressed=!1,I.isOverTarget=!1,I.activePointerId=null,I.pointerType=null,y(),m||bo(I.target);for(let L of I.disposables)L();I.disposables=[]}},[m,y,S]),D=br(k);c.useEffect(()=>{l&&v.current.isPressed&&D({currentTarget:v.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let O=c.useCallback(j=>{d&&k(j)},[d,k]),A=c.useCallback(j=>{l||i?.(j)},[l,i]),P=c.useCallback((j,I)=>{if(!l&&i){let L=new MouseEvent("click",j);qf(L,I),i(Uf(L))}},[l,i]),E=c.useMemo(()=>{let j=v.current,I={onKeyDown(T){if(yr(T.nativeEvent,T.currentTarget)&&rt(T.currentTarget,Te(T))){So(Te(T),T.key)&&T.preventDefault();let F=!0;!j.isPressed&&!T.repeat&&(j.target=T.currentTarget,j.isPressed=!0,j.pointerType="keyboard",F=w(T,"keyboard"));let M=T.currentTarget,$=K=>{yr(K,M)&&!K.repeat&&rt(M,Te(K))&&j.target&&C(Ut(j.target,K),"keyboard")};g(Ct(T.currentTarget),"keyup",jl($,L),!0),F&&T.stopPropagation(),T.metaKey&&Pn()&&j.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(j.metaKeyEvents=new Map)},onClick(T){if(!(T&&!rt(T.currentTarget,Te(T)))&&T&&T.button===0&&!j.isTriggeringEvent&&!Us.isOpening){let F=!0;if(l&&T.preventDefault(),!j.ignoreEmulatedMouseEvents&&!j.isPressed&&(j.pointerType==="virtual"||Gf(T.nativeEvent))){let M=w(T,"virtual"),$=C(T,"virtual"),K=N(T,"virtual");A(T),F=M&&$&&K}else if(j.isPressed&&j.pointerType!=="keyboard"){let M=j.pointerType||T.nativeEvent.pointerType||"virtual",$=C(Ut(T.currentTarget,T),M),K=N(Ut(T.currentTarget,T),M,!0);F=$&&K,j.isOverTarget=!1,A(T),D(T)}j.ignoreEmulatedMouseEvents=!1,F&&T.stopPropagation()}}},L=T=>{if(j.isPressed&&j.target&&yr(T,j.target)){So(Te(T),T.key)&&T.preventDefault();let F=Te(T),M=rt(j.target,F);N(Ut(j.target,T),"keyboard",M),M&&P(T,j.target),y(),T.key!=="Enter"&&Ca(j.target)&&rt(j.target,F)&&!T[yo]&&(T[yo]=!0,Us(j.target,T,!1)),j.isPressed=!1,j.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&j.metaKeyEvents?.size){let F=j.metaKeyEvents;j.metaKeyEvents=void 0;for(let M of F.values())j.target?.dispatchEvent(new KeyboardEvent("keyup",M))}};if(typeof PointerEvent<"u"){I.onPointerDown=M=>{if(M.button!==0||!rt(M.currentTarget,Te(M)))return;if(Xf(M.nativeEvent)){j.pointerType="virtual";return}j.pointerType=M.pointerType;let $=!0;if(!j.isPressed){j.isPressed=!0,j.isOverTarget=!0,j.activePointerId=M.pointerId,j.target=M.currentTarget,m||rm(j.target),$=w(M,j.pointerType);let K=Te(M);"releasePointerCapture"in K&&("hasPointerCapture"in K?K.hasPointerCapture(M.pointerId)&&K.releasePointerCapture(M.pointerId):K.releasePointerCapture(M.pointerId)),g(Ct(M.currentTarget),"pointerup",T,!1),g(Ct(M.currentTarget),"pointercancel",F,!1)}$&&M.stopPropagation()},I.onMouseDown=M=>{if(rt(M.currentTarget,Te(M))&&M.button===0){if(f){let $=Hf(M.target);$&&j.disposables.push($)}M.stopPropagation()}},I.onPointerUp=M=>{!rt(M.currentTarget,Te(M))||j.pointerType==="virtual"||M.button===0&&!j.isPressed&&C(M,j.pointerType||M.pointerType)},I.onPointerEnter=M=>{M.pointerId===j.activePointerId&&j.target&&!j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!0,w(Ut(j.target,M),j.pointerType))},I.onPointerLeave=M=>{M.pointerId===j.activePointerId&&j.target&&j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!1,N(Ut(j.target,M),j.pointerType,!1),O(M))};let T=M=>{if(M.pointerId===j.activePointerId&&j.isPressed&&M.button===0&&j.target){if(rt(j.target,Te(M))&&j.pointerType!=null){let $=!1,K=setTimeout(()=>{j.isPressed&&j.target instanceof HTMLElement&&($?D(M):(Ks(j.target),j.target.click()))},80);g(M.currentTarget,"click",()=>$=!0,!0),j.disposables.push(()=>clearTimeout(K))}else D(M);j.isOverTarget=!1}},F=M=>{D(M)};I.onDragStart=M=>{rt(M.currentTarget,Te(M))&&D(M)}}return I},[g,l,f,y,m,O,w,A,P]);return c.useEffect(()=>{if(!h)return;const j=Ct(h.current);if(!j||!j.head||j.getElementById(wo))return;const I=j.createElement("style");I.id=wo;let L=am(j);L&&(I.nonce=L),I.textContent=`
3
3
  @layer {
4
4
  [${jo}] {
5
5
  touch-action: pan-x pan-y pinch-zoom;
@@ -113,6 +113,6 @@ a, a:visited {
113
113
  .block-interactivity-`.concat(e,` {pointer-events: none;}
114
114
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
115
115
  `)},ox=0,cs=[];function ix(e){var t=c.useRef([]),s=c.useRef([0,0]),r=c.useRef(),a=c.useState(ox++)[0],o=c.useState(dc)[0],i=c.useRef(e);c.useEffect(function(){i.current=e},[e]),c.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=Td([e.lockRef.current],(e.shards||[]).map(ui),!0).filter(Boolean);return p.forEach(function(v){return v.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=c.useCallback(function(p,v){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var g=kn(p),y=s.current,w="deltaX"in p?p.deltaX:y[0]-g[0],S="deltaY"in p?p.deltaY:y[1]-g[1],N,R=p.target,C=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in p&&C==="h"&&R.type==="range")return!1;var k=window.getSelection(),D=k&&k.anchorNode,O=D?D===R||D.contains(R):!1;if(O)return!1;var A=li(C,R);if(!A)return!0;if(A?N=C:(N=C==="v"?"h":"v",A=li(C,R)),!A)return!1;if(!r.current&&"changedTouches"in p&&(w||S)&&(r.current=N),!N)return!0;var P=r.current||N;return nx(P,v,p,P==="h"?w:S)},[]),u=c.useCallback(function(p){var v=p;if(!(!cs.length||cs[cs.length-1]!==o)){var g="deltaY"in v?ci(v):kn(v),y=t.current.filter(function(N){return N.name===v.type&&(N.target===v.target||v.target===N.shadowParent)&&rx(N.delta,g)})[0];if(y&&y.should){v.cancelable&&v.preventDefault();return}if(!y){var w=(i.current.shards||[]).map(ui).filter(Boolean).filter(function(N){return N.contains(v.target)}),S=w.length>0?l(v,w[0]):!i.current.noIsolation;S&&v.cancelable&&v.preventDefault()}}},[]),f=c.useCallback(function(p,v,g,y){var w={name:p,delta:v,target:g,should:y,shadowParent:lx(g)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(S){return S!==w})},1)},[]),d=c.useCallback(function(p){s.current=kn(p),r.current=void 0},[]),m=c.useCallback(function(p){f(p.type,ci(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){f(p.type,kn(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return cs.push(o),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:h}),document.addEventListener("wheel",u,ls),document.addEventListener("touchmove",u,ls),document.addEventListener("touchstart",d,ls),function(){cs=cs.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,ls),document.removeEventListener("touchmove",u,ls),document.removeEventListener("touchstart",d,ls)}},[]);var x=e.removeScrollBar,b=e.inert;return c.createElement(c.Fragment,null,b?c.createElement(o,{styles:ax(a)}):null,x?c.createElement(Gg,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function lx(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const cx=$g(uc,ix);var pc=c.forwardRef(function(e,t){return c.createElement(Gn,St({},e,{ref:t,sideCar:cx}))});pc.classNames=Gn.classNames;var ux=class extends fa{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,r=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:l}=r,u=s.fetchMeta?.fetchMore?.direction,f=i&&u==="forward",d=a&&u==="forward",m=i&&u==="backward",h=a&&u==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Md(t,s.data),hasPreviousPage:Rd(t,s.data),isFetchNextPageError:f,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:h,isRefetchError:l&&!f&&!m,isRefetching:o&&!d&&!h}}};function di(e,t){const s=new Set(t);return e.filter(r=>!s.has(r))}function dx(e,t,s){const r=e.slice(0);return r[t]=s,r}var fx=class extends Ad{#s;#e;#a;#r;#t;#n;#o;#i;#l;#c=[];constructor(e,t,s){super(),this.#s=e,this.#r=s,this.#a=[],this.#t=[],this.#e=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#t.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#t.forEach(e=>{e.destroy()})}setQueries(e,t){this.#a=e,this.#r=t,zr.batch(()=>{const s=this.#t,r=this.#f(this.#a);r.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=r.map(d=>d.observer),o=a.map(d=>d.getCurrentResult()),i=s.length!==a.length,l=a.some((d,m)=>d!==s[m]),u=i||l,f=u?!0:o.some((d,m)=>{const h=this.#e[m];return!h||!Dd(d,h)});!u&&!f||(u&&(this.#c=r,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(di(s,a).forEach(d=>{d.destroy()}),di(a,s).forEach(d=>{d.subscribe(m=>{this.#m(d,m)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const s=this.#f(e),r=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[r,o=>this.#d(o??r,t,a),()=>this.#u(r,s)]}#u(e,t){return t.map((s,r)=>{const a=e[r];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const r=this.#l,a=s!==void 0&&r!==void 0&&(r.length!==s.length||s.some((o,i)=>o!==r[i]));return(!this.#n||this.#e!==this.#i||a||t!==this.#o)&&(this.#o=t,this.#i=this.#e,s!==void 0&&(this.#l=s),this.#n=Od(this.#n,t(e))),this.#n}return e}#p(){return this.#r?.combine!==void 0&&this.#t.some((e,t)=>e.options.suspense&&this.#e[t]?.data===void 0)}#f(e){const t=new Map;this.#t.forEach(r=>{const a=r.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(r):t.set(a,[r])});const s=[];return e.forEach(r=>{const a=this.#s.defaultQueryOptions(r),i=t.get(a.queryHash)?.shift()??new fa(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=dx(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,r=t?s:this.#d(e,this.#r?.combine);(t||s!==r)&&zr.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function Pt({queries:e,...t},s){const r=ye(),a=Pd(),o=Ld(),i=c.useMemo(()=>e.map(p=>{const v=r.defaultQueryOptions(p);return v._optimisticResults=a?"isRestoring":"optimistic",v}),[e,r,a]);i.forEach(p=>{$d(p);const v=r.getQueryCache().get(p.queryHash);Fd(p,o,v)}),zd(o);const[l]=c.useState(()=>new fx(r,i,t)),[u,f,d]=l.getOptimisticResult(i,t.combine),m=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>m?l.subscribe(zr.batchCalls(p)):_d,[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const x=u.some((p,v)=>po(i[v],p))?u.flatMap((p,v)=>{const g=i[v];if(g&&po(g,p)){const y=new fa(r,g);return Bd(g,y,o)}return[]}):[];if(x.length>0)throw Promise.all(x);const b=u.find((p,v)=>{const g=i[v];return g&&Kd({result:p,errorResetBoundary:o,throwOnError:g.throwOnError,query:r.getQueryCache().get(g.queryHash),suspense:g.suspense})});if(b?.error)throw b.error;return f(d())}function gc(e,t){return Ud(e,ux)}function mx(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const s=!!(e.condition??!0),r=e.blockerFn;return{shouldBlockFn:async()=>s&&r!==void 0?await r():s,enableBeforeUnload:s,withResolver:r===void 0}}function hx(e,t){const{shouldBlockFn:s,enableBeforeUnload:r=!0,disabled:a=!1,withResolver:o=!1}=mx(e),i=ma(),{history:l}=i,[u,f]=c.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return c.useEffect(()=>{const d=async m=>{function h(g){const y=i.parseLocation(g),w=i.getMatchedRoutes(y.pathname);return w.foundRoute===void 0?{routeId:"__notFound__",fullPath:y.pathname,pathname:y.pathname,params:w.routeParams,search:i.options.parseSearch(g.search)}:{routeId:w.foundRoute.id,fullPath:w.foundRoute.fullPath,pathname:y.pathname,params:w.routeParams,search:i.options.parseSearch(g.search)}}const x=h(m.currentLocation),b=h(m.nextLocation);if(x.routeId==="__notFound__"&&b.routeId!=="__notFound__")return!1;const p=await s({action:m.action,current:x,next:b});if(!o)return p;if(!p)return!1;const v=await new Promise(g=>{f({status:"blocked",current:x,next:b,action:m.action,proceed:()=>g(!1),reset:()=>g(!0)})});return f({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),v};return a?void 0:l.block({blockerFn:d,enableBeforeUnload:r})},[s,r,a,o,l,i]),u}function ht(e){const t=ma({warn:e?.router===void 0}),s=e?.router||t;return Ji(s.stores.__store,Zi(e,s))}function Xn(e){const t=ma();return Ji(t.stores.location,Zi(e,t))}const px=new Set(["outbox","flagged"]),gx=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!px.has(s)};function xx(e){const t=Pt({queries:e.map(s=>({...Ve({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,r]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Ss(r.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function xc(e){const{openCompose:t}=Mt(),s=De(),r=Xn(),a=xx(e);return c.useCallback(()=>{if(gx(r.pathname)){c.startTransition(()=>{t({mode:"new"})});return}a&&(c.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,r.pathname,a])}const bx=e=>e.startsWith("/mail")||e.startsWith("/settings"),vx=({accounts:e})=>{const{state:t}=Mt(),s=Xn(),r=xc(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!bx(s.pathname)||t.isOpen||o?null:n.jsx("button",{type:"button",onClick:r,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:n.jsx(Sm,{className:"size-6"})})},bc=({trigger:e,children:t,align:s="right"})=>{const[r,a]=c.useState(!1),o=c.useRef(null),i=c.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),l=c.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return c.useEffect(()=>(r&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",l)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",l)}),[r,i,l]),n.jsxs("div",{ref:o,className:"relative",children:[n.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!r)},className:pe("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),r&&n.jsx("div",{className:pe("absolute z-50 mt-1 min-w-[180px] py-1","bg-surface border border-line rounded-md shadow-lg",s==="right"?"right-0":"left-0"),children:t})]})},ms=({onClick:e,disabled:t,destructive:s,children:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:pe("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:r}),Yr=()=>n.jsx("div",{className:"my-1 h-px bg-line"}),vc=({children:e})=>{const{Account:t}=ha();return n.jsx(t,{children:e})},yx=({email:e,onSignOut:t})=>{const s=De(),r=e??"Account";return n.jsxs(bc,{trigger:n.jsx(lt,{name:r,email:e??void 0,size:"sm"}),align:"right",children:[e&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),n.jsx(Yr,{})]}),n.jsxs(ms,{onClick:()=>s({to:"/settings/accounts"}),children:[n.jsx(Ia,{className:"size-4"}),"Settings"]}),n.jsx(Yr,{}),n.jsxs(ms,{onClick:t,children:[n.jsx(Dl,{className:"size-4"}),"Sign out"]})]})},wx=()=>n.jsx(vc,{children:({email:e,signOut:t})=>n.jsx(yx,{email:e,onSignOut:t})}),fi=()=>{const e=pa(),t=ga(e);window.open(t,"_blank","noopener,noreferrer")};function yc({variant:e="icon"}){return e==="drawer"?n.jsxs("button",{type:"button",onClick:fi,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(ko,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]}):n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(ko,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:fi})}const wc="/mail/",Pa="/mail/$mailboxId",jc="/mail/outbox",Sc="/mail/flagged";function La(e){return e.some(t=>t.routeId===wc)}function sn(e){return e.some(t=>t.routeId===Sc)}function Jn(e){return e.some(t=>t.routeId===jc)}function kc(e){return e.some(t=>t.routeId===Pa)}function jx(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Pa}:${t}`:sn(e)?Sc:Jn(e)?jc:La(e)?wc:""}const An="search-scope";function Sx(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function Cc(e){return sn(e)||Jn(e)||kc(e)}function Nc(e){return e.find(t=>t.routeId===Pa)?.params?.mailboxId}function kx(e){const t=Nc(e.matches);return t||(Cc(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function Cx(e,t){return La(e)?{kind:"global"}:sn(e)?{kind:"scoped",chip:{id:An,label:"is:starred"}}:Jn(e)?{kind:"scoped",chip:{id:An,label:"in:outbox"}}:kc(e)?t?{kind:"scoped",chip:{id:An,label:Sx(t)}}:{kind:"pending"}:{kind:"global"}}function Nx(e,t,s){return t.kind==="global"?{kind:"global"}:sn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const Ec=({accounts:e})=>{const t=xa({strict:!1}),s=Xn(),r=t.mailboxId,{t:a}=Kn("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=Pt({queries:e.map(l=>({...Ve({path:{accountId:l.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!r)return null;for(let l=0;l<e.length;l++){const u=i[l]?.data?.items;if(!u)continue;const f=u.find(m=>m.mailboxId===r);if(!f)continue;const d=Ss(e[l].folderAppointments);return xs(f,d.get(r),o)}return null},Ex=({accounts:e})=>{const s=xa({strict:!1}).mailboxId,r=Pt({queries:e.map(a=>({...Ve({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of r){const o=a.data?.items;if(!o)continue;const i=o.find(l=>l.mailboxId===s);if(i)return i.unseenCount}return null};function Ic(e){const t=De(),{searchInput:s}=Se(),r=Ec({accounts:e}),a=ht({select:l=>l.matches}),o=Cx(a,r),i=c.useCallback(l=>{l===An&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const Tc=[{title:"Navigation",hints:[{action:"focusNext",keys:["j"],description:"Focus next message"},{action:"focusPrevious",keys:["k"],description:"Focus previous message"},{action:"focusNext",keys:["↓"],description:"Focus next message"},{action:"focusPrevious",keys:["↑"],description:"Focus previous message"},{action:"focusFirst",keys:["Home"],description:"Focus first"},{action:"focusLast",keys:["End"],description:"Focus last"},{action:"openFocused",keys:["Enter"],description:"Open focused thread"},{action:"back",keys:["Esc"],description:"Back / close overlay"}]},{title:"Selection",hints:[{action:"toggleSelect",keys:["x"],description:"Toggle select"},{action:"toggleSelect",keys:["Space"],description:"Toggle select"},{action:"extendSelectDown",keys:["Shift","j"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","k"],description:"Extend selection up"},{action:"extendSelectDown",keys:["Shift","↓"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","↑"],description:"Extend selection up"},{action:"selectAll",keys:["⌘","A"],description:"Select all"}]},{title:"Actions",hints:[{action:"reply",keys:["r"],description:"Reply"},{action:"replyAll",keys:["a"],description:"Reply all"},{action:"forward",keys:["f"],description:"Forward"},{action:"delete",keys:["#"],description:"Delete"},{action:"toggleStar",keys:["s"],description:"Star / unstar"},{action:"toggleRead",keys:["u"],description:"Toggle read / unread"}]},{title:"Sender",hints:[{action:"muteSender",keys:["m"],description:"Mute sender"},{action:"blockSender",keys:["b"],description:"Block sender"},{action:"vipSender",keys:["v"],description:"VIP sender"},{action:"markJunk",keys:["!"],description:"Mark junk"}]},{title:"Go to",hints:[{action:"goBrief",keys:["g","b"],description:"Daily brief"},{action:"goInbox",keys:["g","i"],description:"Inbox"},{action:"goSent",keys:["g","s"],description:"Sent"},{action:"goFlagged",keys:["g","f"],description:"Starred"},{action:"goSettings",keys:["g",","],description:"Settings"}]},{title:"View & global",hints:[{action:"toggleIntelligence",keys:["i"],description:"Toggle intelligence"},{action:"toggleDensity",keys:["d"],description:"Toggle density"},{action:"focusSearch",keys:["/"],description:"Focus search"},{action:"compose",keys:["c"],description:"Compose"},{action:"compose",keys:["⌘","N"],description:"Compose"},{action:"help",keys:["?"],description:"Shortcut help"}]}];function Ix(e){for(const t of Tc){const s=t.hints.find(r=>r.action===e);if(s)return s.keys}}function ds(e){const t=Ix(e);return!t||t.length===0?"":t.length===1?`(${t[0]})`:t[0]==="g"?`(${t.join(" then ")})`:`(${t.join("")})`}const Tx={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function Rx({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:r,onSearchClearQuery:a}=Se(),o=xc(e),{scope:i,clearScope:l}=Ic(e),u=i.kind==="scoped"?[{id:i.chip.id,label:i.chip.label,tone:"scope"}]:void 0,f=Tx[i.kind];return n.jsx(Oh,{search:n.jsx(Ra,{value:t,onChange:s,onClear:r,onClearQuery:a,chips:u,onRemoveChip:l,placeholder:f,size:"lg"}),actions:n.jsxs(n.Fragment,{children:[n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Em,{className:"size-4"}),title:`Compose ${ds("compose")}`,"aria-label":"Compose",onClick:o}),n.jsx(yc,{}),n.jsx(wx,{})]})})}const $a=({isOpen:e,onClose:t,children:s,ariaLabel:r="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=c.useRef(null),l=c.useRef(null);if(c.useEffect(()=>{if(!e)return;l.current=document.activeElement;const f=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",f),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const m=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",f),document.body.style.overflow=m,l.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return n.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":r,children:[n.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),n.jsxs("div",{ref:i,className:pe("absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[n.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:n.jsx(We,{className:"size-5"})})}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},Mx=e=>{const t=e.filter(a=>!a.isMultipart&&a.disposition!=="attachment"&&a.mediaType==="TEXT"&&a.contentUrl.length>0),s=t.find(a=>a.mediaSubtype.toUpperCase()==="HTML");if(s)return{kind:"html",contentUrl:s.contentUrl};const r=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return r?{kind:"text",contentUrl:r.contentUrl}:null},Gr={all:["messages"],detail:e=>[...Gr.all,"detail",e],body:e=>[...Gr.detail(e),"body"]};class Ht extends Error{reason;status;retryAfterSeconds;constructor(t,s,r,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=r,this.retryAfterSeconds=a}}const Ax=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},Dx=8,Ox="x-remit-403-reason",Px=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},Lx=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,$x=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},Fx=async(e,t,s=async()=>null)=>{const r={},a=await s();a&&(r.Authorization=`Bearer ${a}`);const o=await qd(e,{headers:r});if(o.status===202)throw new Ht("not-ready","Message body is still syncing",202,Ax(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(Ox),f=Px(o.status,u);throw new Ht(f,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if($x(t,i))throw new Ht("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(Lx(l,i))throw new Ht("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},zx=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),Rc=({messageId:e,bodyParts:t,enabled:s=!0})=>{const r=t?Mx(t):null,a=Ys(),{getToken:o}=ha(),i=c.useRef(null),l=ye(),u=c.useRef(!1),f=c.useRef(null),d=e&&r?`${e}:${r.contentUrl}`:null;f.current!==d&&(f.current=d,u.current=!1);const m=ce({queryKey:e?[...Gr.body(e),r?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!r)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const b=u.current;return u.current=!1,zx({fetchContent:(p,v)=>Fx(p,v,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:el({path:{messageId:e}})})},{contentUrl:r.contentUrl,kind:r.kind,isRetryAfterNotReady:b})},enabled:s&&!!e&&!!r,staleTime:300*1e3,gcTime:1800*1e3,retry:(b,p)=>p instanceof Ht&&p.reason==="not-ready"?b<Dx:b<1,retryDelay:(b,p)=>p instanceof Ht&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=m.isLoading&&!!r;c.useEffect(()=>{h&&(i.current=performance.now())},[h]),c.useEffect(()=>{m.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[m.isSuccess,a]);const x=m.data&&r?{kind:r.kind,body:m.data}:void 0;return{picked:r,data:x,isLoading:h,isError:m.isError,error:m.error,refetch:m.refetch}},_x=({outboxMessageId:e,onDraftCreated:t})=>{const[s,r]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=ye(),u=ve(tl()),f=ve(Hd()),d=c.useCallback(async b=>{if(r("saving"),o(null),e){const v=await f.mutateAsync({path:{outboxMessageId:e},body:{toAddresses:b.toAddresses,ccAddresses:b.ccAddresses,bccAddresses:b.bccAddresses,subject:b.subject,textBody:b.textBody,htmlBody:b.htmlBody,inReplyTo:b.inReplyTo,references:b.references}});return r("saved"),v}const p=await u.mutateAsync({body:{...b,sendImmediately:!1}});return t(p.outboxMessageId),r("saved"),l.invalidateQueries({queryKey:Un().queryKey}),p},[e,u,f,t,l]),m=c.useCallback(b=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{d(b).catch(p=>{o(p),r("error")})},2e3)},[d]),h=c.useCallback(b=>(i.current&&clearTimeout(i.current),d(b)),[d]),x=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:m,saveImmediately:h,cancelAutoSave:x}},Mc=e=>"text"in e&&!("children"in e),Ac=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),Bx=e=>{let t=Ac(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},Dc=e=>{const t=e.children.map(s=>Mc(s)?Bx(s):Dc(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${Ac(s)}">${t}</a>`}default:return`<p>${t}</p>`}},mi=e=>e.map(Dc).join(""),Oc=e=>Mc(e)?e.text:e.children.map(Oc).join(""),Xr=e=>e.map(Oc).join(`
116
- `),Kx=e=>e.displayName?`${e.displayName} <${e.normalizedEmail}>`:e.normalizedEmail,hi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),Ux=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const r=s[1].trim(),a=s[2].trim();if(hi(a))return{email:a,displayName:r}}if(hi(t))return{email:t}},Mr=({label:e,addresses:t,onChange:s,placeholder:r})=>{const[a,o]=c.useState(""),[i,l]=c.useState(-1),[u,f]=c.useState(!1),d=c.useRef(null),m=c.useRef(null),h=ul(a,200),{data:x}=ce({...sl({query:{q:h,limit:8}}),enabled:h.length>=2}),b=x?.items??[],p=new Set(t.map(C=>C.email.toLowerCase())),v=b.filter(C=>!p.has(C.normalizedEmail.toLowerCase()));c.useEffect(()=>{l(-1),f(v.length>0&&a.length>=2)},[v.length,a.length]);const g=c.useCallback(C=>{p.has(C.email.toLowerCase())||(s([...t,C]),o(""),f(!1))},[t,p,s]),y=c.useCallback(C=>{s(t.filter((k,D)=>D!==C))},[t,s]),w=c.useCallback(C=>{g({email:C.normalizedEmail,displayName:C.displayName}),d.current?.focus()},[g]),S=c.useCallback(()=>{const C=Ux(a);C&&g(C)},[a,g]),N=c.useCallback(C=>{if(C.key==="Backspace"&&a===""&&t.length>0){y(t.length-1);return}if(C.key==="Enter"||C.key==="Tab"||C.key===","){if(i>=0&&v[i]){C.preventDefault(),w(v[i]);return}a.trim()&&(C.preventDefault(),S());return}if(C.key==="ArrowDown"&&u){C.preventDefault(),l(k=>k<v.length-1?k+1:0);return}if(C.key==="ArrowUp"&&u){C.preventDefault(),l(k=>k>0?k-1:v.length-1);return}C.key==="Escape"&&(f(!1),l(-1))},[a,t.length,i,v,u,y,w,S]),R=c.useCallback(()=>{setTimeout(()=>{S(),f(!1)},150)},[S]);return n.jsxs("div",{className:"relative",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),n.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>d.current?.focus(),onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&d.current?.focus()},children:[t.map((C,k)=>n.jsx(Mm,{email:C.email,displayName:C.displayName,onRemove:()=>y(k)},C.email)),n.jsx("input",{ref:d,id:`address-field-${e}`,type:"text",value:a,onChange:C=>o(C.target.value),onKeyDown:N,onBlur:R,placeholder:t.length===0?r:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5"})]})]}),u&&v.length>0&&n.jsx("ul",{ref:m,className:"absolute left-12 right-0 mt-1 bg-surface border border-line rounded-md shadow-lg z-50 max-h-[200px] overflow-auto",children:v.map((C,k)=>n.jsx("li",{className:pe("px-3 py-2 text-sm cursor-pointer transition-colors",k===i&&"bg-accent-2-soft"),onMouseDown:D=>{D.preventDefault(),w(C)},onMouseEnter:()=>l(k),children:Kx(C)},C.addressId))})]})},qx=({accountId:e})=>{const t=De();return n.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[n.jsx(ca,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),n.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",n.jsx(hm,{className:"size-3","aria-hidden":"true"})]})]})]})},Jr=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia(e),a=o=>s(o.matches);return s(r.matches),r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[e]),t},Lt=()=>Jr("(min-width: 1024px)"),pi=150,Hx=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>pi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,r=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>pi})};return r(),s.addEventListener("resize",r),()=>s.removeEventListener("resize",r)},[]),e},Wx=({selectedAccountId:e,onSelect:t})=>{const{data:s}=ce({...gt(),staleTime:1/0}),r=s?.accounts??[];if(c.useEffect(()=>{!e&&r.length===1&&r[0]&&t(r[0])},[e,r,t]),r.length<=1){const a=r[0];return a?n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=r.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:r.map(a=>n.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},Vx=({value:e,onChange:t})=>n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),n.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),Qx=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],Yx=["href"],Gx=e=>Qi.sanitize(e,{ALLOWED_TAGS:Qx,ALLOWED_ATTR:Yx}),Xx=c.lazy(()=>Vd(()=>import("./ComposeBody-DbQicvPt.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(e=>({default:e.ComposeBody}))),Jx=()=>n.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[n.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),n.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),Pc=[{type:"p",children:[{text:""}]}],Zx=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],eb=e=>e?[...Zx,{type:"p",children:[{text:e}]}]:Pc,tb=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",sb=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",nb=(e,t,s)=>{const{envelope:r}=e,o=(r.replyTo.length>0?r.replyTo:r.from).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(f=>f.email.toLowerCase())),u=[...r.to,...r.cc].filter(f=>f.normalizedEmail.toLowerCase()!==i&&!l.has(f.normalizedEmail.toLowerCase())).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));return{to:o,cc:u}},rb=e=>{const t=e.envelope.messageIdValue,r=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!r.includes(t)&&r.push(t),{inReplyTo:t,references:r}},ab=(e,t,s,r,a)=>e.length===0&&t.length===0&&s.length===0&&r.trim()===""&&Xr(a).trim()==="",ob=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:r,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:f,showBcc:d,setShowBcc:m,subject:h,setSubject:x})=>{const b=Lt(),{isKeyboardOpen:p}=Hx();if(!b&&p){const g=[];return s.length>0&&g.push(`To: ${s.map(y=>y.displayName??y.email).join(", ")}`),a.length>0&&g.push(`Cc: ${a.length}`),i.length>0&&g.push(`Bcc: ${i.length}`),h&&g.push(h),n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[n.jsx("span",{className:"truncate text-xs text-fg-muted",children:g.length>0?g.join(" · "):"…"}),n.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return n.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[n.jsx(Wx,{selectedAccountId:e,onSelect:t}),n.jsx(Mr,{label:"To",addresses:s,onChange:r,placeholder:"Recipients"}),u?n.jsx(Mr,{label:"Cc",addresses:a,onChange:o}):n.jsxs("div",{className:"flex gap-2 pl-14",children:[n.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&n.jsx("div",{className:"pl-14",children:n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&n.jsx(Mr,{label:"Bcc",addresses:i,onChange:l}),n.jsx(Vx,{value:h,onChange:x})]})},Fa=({mode:e,account:t,sourceMessage:s,onClose:r,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Mt(),{pushError:u}=Ze(),{outboxMessageId:f}=o,[d,m]=c.useState([]),[h,x]=c.useState([]),[b,p]=c.useState([]),[v,g]=c.useState(""),[y,w]=c.useState(!1),[S,N]=c.useState(!1),[R,C]=c.useState(t?.accountId),[k,D]=c.useState(!1),O=c.useRef(f);c.useEffect(()=>{O.current!==f&&(O.current=f,f&&(m([]),x([]),p([]),g(""),w(!1),N(!1),E(Pc),D(!1)))},[f]);const{signature:A}=kf(R),[P,E]=c.useState(()=>eb(A.plainText)),{data:j}=ce({...Wd({path:{outboxMessageId:f??""}}),enabled:!!f&&!k});c.useEffect(()=>{!j||k||(m(j.toAddresses.map(J=>({email:J,displayName:void 0}))),j.ccAddresses&&j.ccAddresses.length>0&&(x(j.ccAddresses.map(J=>({email:J,displayName:void 0}))),w(!0)),j.bccAddresses&&j.bccAddresses.length>0&&(p(j.bccAddresses.map(J=>({email:J,displayName:void 0}))),N(!0)),j.subject&&g(j.subject),j.textBody&&E([{type:"p",children:[{text:j.textBody}]}]),C(j.accountId),D(!0))},[j,k]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:J,cc:ae}=nb(s,e,t?.email);m(J),x(ae),ae.length>0&&w(!0),g(tb(s.envelope.subject))}e==="forward"&&g(sb(s.envelope.subject))}},[e,s,t?.email]);const I=e==="reply"||e==="reply_all"||e==="forward",{data:L}=Rc({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:I&&!!s}),T=L?.kind==="text"?L.body:"",F=L?.kind==="html"?Gx(L.body):void 0,M=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:$,saveError:K,saveDraft:_,cancelAutoSave:X}=_x({outboxMessageId:f,onDraftCreated:i});c.useEffect(()=>{K&&u({title:"Couldn't save draft",detail:ot(K)??"Saving the draft failed.",error:K})},[K,u]);const ee=ve(tl()),Y=ve(nl()),me=ve({...qn(),onError:J=>{u(Vt("Couldn't discard draft","The draft wasn't discarded.",J))}}),{data:ue}=ce({...gt(),staleTime:1/0}),te=ue?.accounts.find(J=>J.accountId===R),q=te?jf(te):!1,U=ee.isPending||Y.isPending,re=d.length>0&&!!R&&!q;c.useEffect(()=>{if(!R||f&&!k||ab(d,h,b,v,P))return;const J=Xr(P),ae=mi(P);_({accountId:R,toAddresses:d.map(de=>de.email),ccAddresses:h.length>0?h.map(de=>de.email):void 0,bccAddresses:b.length>0?b.map(de=>de.email):void 0,subject:v||void 0,textBody:J||void 0,htmlBody:ae||void 0})},[R,f,k,d,h,b,v,P,_]);const Pe=c.useCallback(async()=>{if(!R||d.length===0)return;X();const J=s&&(e==="reply"||e==="reply_all")?rb(s):{};let ae=f,de=!1;if(!ae){const Qe=Xr(P),Le=mi(P),ge=await ee.mutateAsync({body:{accountId:R,toAddresses:d.map(we=>we.email),ccAddresses:h.length>0?h.map(we=>we.email):void 0,bccAddresses:b.length>0?b.map(we=>we.email):void 0,subject:v||void 0,textBody:Qe||void 0,htmlBody:Le||void 0,sendImmediately:!0,...J}}).catch(we=>(u({title:"Couldn't send message",detail:ot(we)??"Saving the draft failed.",error:we}),null));if(ge===null)return;ae=ge.outboxMessageId,de=!0,i(ae)}await Y.mutateAsync({path:{outboxMessageId:ae}}).catch(Qe=>(u({title:"Couldn't send message",detail:ot(Qe)??(de?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:Qe}),null))!==null&&(l(ae),r())},[R,d,h,b,v,P,e,s,f,ee,Y,X,l,i,u,r]),Re=c.useCallback(()=>{X(),f&&me.mutate({path:{outboxMessageId:f}}),r()},[X,f,me,r]),V=c.useCallback(J=>{C(J.accountId),a?.(J)},[a]);return n.jsx(qh,{banner:te&&q?n.jsx(qx,{accountId:te.accountId}):void 0,header:n.jsx(ob,{selectedAccountId:R,onAccountChange:V,toAddresses:d,setToAddresses:m,ccAddresses:h,setCcAddresses:x,bccAddresses:b,setBccAddresses:p,showCc:y,setShowCc:w,showBcc:S,setShowBcc:N,subject:v,setSubject:g}),quoted:T||F?n.jsx(hp,{text:T,html:F,senderName:M}):void 0,actionBar:n.jsx(Uh,{onSend:Pe,onDiscard:Re,sending:U,canSend:re,saveStatus:$,unavailableReason:q?"SMTP not configured":void 0,onUnavailable:J=>u({title:"Can't send yet",detail:J})}),children:n.jsx(c.Suspense,{fallback:n.jsx(Jx,{}),children:n.jsx(Xx,{value:P,onChange:E,onSubmit:Pe,autoFocus:e==="new"})})})},gi=({mode:e,account:t,sourceMessage:s,onClose:r})=>n.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:n.jsx(Fa,{mode:e,account:t,sourceMessage:s,onClose:r})}),Lc=({message:e,icon:t})=>n.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&n.jsx("div",{className:"mb-4 text-fg-muted",children:t}),n.jsx("p",{className:"text-fg-muted",children:e})]}),za=({enabled:e=!0,bindings:t,capture:s=!1})=>{const r=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const f=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(f&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",r,s),()=>window.removeEventListener("keydown",r,s)},[e,r,s])},$c=e=>{const{data:t,isLoading:s}=ce({...gt(),staleTime:1/0}),r=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=Pt({queries:r.map(l=>({...Ve({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<r.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return r[l]}},[e,r,a]),isLoading:o}},ib=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),lb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Fc=(e,t)=>e===void 0?e:ib(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:lb(e)?{...e,items:t(e.items)}:e,$t=e=>{const t=[];for(const s of new Set(e))t.push(ba({path:{mailboxId:s}})),t.push(rl({path:{mailboxId:s}}));return t.push(al()),t},nn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),rn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,r])=>({queryKey:s,data:r})),an=(e,t,s)=>{const r=a=>Fc(a,s);for(const a of t)e.setQueriesData({queryKey:a},r)},on=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},Ft=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},cb=3e3,ub=(e,t,s)=>{if(e.length===0)return()=>{};const r=setTimeout(()=>s(e),t);return()=>clearTimeout(r)},_a=(e,t,s)=>{const r=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(r.get(o)??s);return[...a]},Ln=(e,t,s)=>e.map(r=>t.has(r.messageId)?{...r,isRead:s}:r),db=(e,t,s,r)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!r.has(a.messageId)).map(a=>a.messageId),fb=({messages:e,expandedIds:t,threadId:s,mailboxId:r,accountId:a})=>{const o=ye(),{pushError:i}=Ze(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:f}=ve({...Hn(),onMutate:async h=>{const x=new Set(h.body.messageIds??[]),b=h.body.isRead??!0,p=Jt({path:{threadId:s}}),v=$t(_a(x,e,r));await Promise.all([o.cancelQueries({queryKey:p}),nn(o,v)]);const g=o.getQueriesData({queryKey:p}).filter(w=>w[1]!==void 0).map(([w,S])=>({queryKey:w,data:S})),y=rn(o,v);return o.setQueriesData({queryKey:p},w=>w&&{...w,items:Ln(w.items,x,b)}),an(o,v,w=>Ln(w,x,b)),{threadMessagesPrefix:p,listPrefixes:v,previousThreadMessages:g,previousThreadsList:y}},onSuccess:(h,x)=>{const b=x.body.messageIds??[];for(const p of b)l.current.add(p),u.current.delete(p)},onError:(h,x,b)=>{const p=x.body.messageIds??[];for(const g of p)u.current.delete(g);if(b){for(const g of b.previousThreadMessages)o.setQueryData(g.queryKey,g.data);on(o,b.previousThreadsList)}const v=x.body.isRead??!0;i({title:v?"Couldn't mark as read":"Couldn't mark as unread",detail:ot(h),error:h})},onSettled:(h,x,b,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),Ft(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:Xt({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const x=h.filter(b=>!l.current.has(b)&&!u.current.has(b));if(x.length!==0){for(const b of x)u.current.add(b);f({body:{messageIds:x,isRead:!0}})}},[f]),m=c.useMemo(()=>db(e,t,l.current,u.current),[e,t]);c.useEffect(()=>ub(m,cb,d),[m,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},Zn=e=>{const{mailboxId:t,accountId:s,messages:r}=e,a=ye(),{pushError:o}=Ze(),{mutate:i,isPending:l}=ve({...Hn(),onError:(f,d)=>{const m=d.body.isRead??!0;o({title:m?"Couldn't mark as read":"Couldn't mark as unread",detail:ot(f),error:f})},onSettled:(f,d,m)=>{Ft(a,$t(_a(m.body.messageIds??[],r??[],t))),s&&a.invalidateQueries({queryKey:Xt({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,isRead:d}})},[i]),isPending:l}},mb=60,hb=1.5,pb=(e,t,s)=>{const r=Math.abs(e),a=Math.abs(t);return r<s?{direction:null}:r<a*hb?{direction:null}:{direction:e<0?"left":"right"}},gb=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=mb})=>{const r=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){r.current=null;return}r.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const f=r.current;if(r.current=null,!f)return;const{direction:d}=pb(u.clientX-f.x,u.clientY-f.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{r.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},xb=(e,t,s)=>t?.find(r=>r.messageId===e)?.mailboxId??s,xi=(e,t,s)=>e.map(r=>r.messageId===t?{...r,hasStars:s}:r),Ba=({threadId:e,mailboxId:t,messages:s})=>{const r=ye(),{pushError:a}=Ze(),{mutate:o,isPending:i,variables:l}=ve({...Qd(),onMutate:async f=>{const d=f.path.messageId,m=f.body.isStarred??!1,h=Jt({path:{threadId:e}}),x=$t([xb(d,s,t)]);await Promise.all([r.cancelQueries({queryKey:h}),nn(r,x)]);const b=r.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,g])=>({queryKey:v,data:g})),p=rn(r,x);return r.setQueriesData({queryKey:h},v=>Fc(v,g=>xi(g,d,m))),an(r,x,v=>xi(v,d,m)),{threadMessagesPrefix:h,listPrefixes:x,previousThreadMessages:b,previousThreadsList:p}},onError:(f,d,m)=>{if(m){for(const x of m.previousThreadMessages)r.setQueryData(x.queryKey,x.data);on(r,m.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:ot(f),error:f})},onSettled:(f,d,m,h)=>{h&&(r.invalidateQueries({queryKey:h.threadMessagesPrefix}),Ft(r,h.listPrefixes))}});return{toggleStar:(f,d)=>{o({path:{messageId:f},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function er(e){return e===void 0?"uncategorized":e}const at={uncategorized:"uncategorized",personal:"personal",newsletter:"newsletter",marketing:"marketing",automated:"automated",transactional:"transactional",social:"social"},bi={MoveToInbox:"MoveToInbox",MoveToJunk:"MoveToJunk"},bb={inbox:"Inbox",junk:"Junk"},Ka=e=>e.destinationMailboxId!==void 0,vb=(e,t)=>{if(Ka(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${bb[s]??"another folder"} by Remit`},yb=(e,t)=>{if(e===bi.MoveToInbox)return t.inboxMailboxId;if(e===bi.MoveToJunk)return t.junkMailboxId},wb=(e,t,s)=>{if(!e||!t)return!1;const r=Ka(e)?e.destinationMailboxId:yb(e.action,s);return r!==void 0&&r===t},jb=(e,t)=>{if(e){if(Ka(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},tr=(e,t)=>{const{data:s,isLoading:r}=ce({...gt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:r}},Sb=e=>{const{mailboxId:t,isLoading:s}=tr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},kb=e=>{const{mailboxId:t,isLoading:s}=tr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},Ua=e=>{const{mailboxId:t,isLoading:s}=tr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},sr=e=>{const{mailboxId:t,isLoading:s}=tr(e,"Junk");return{junkMailboxId:t,isLoading:s}},zc=e=>{const{data:t}=ce({...gt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},vi=(e,t)=>e.filter(s=>!t.has(s.messageId)),Tt=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=ye(),{pushError:o}=Ze(),{mutate:i,isPending:l}=ve({...Yd(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),m=t?Jt({path:{threadId:t}}):[],h=$t([e,f.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:m})]:[],nn(a,h)]);const x=t?a.getQueriesData({queryKey:m}).filter(p=>p[1]!==void 0).map(([p,v])=>({queryKey:p,data:v})):[],b=rn(a,h);return t&&a.setQueriesData({queryKey:m},p=>p&&{...p,items:vi(p.items,d)}),an(a,h,p=>vi(p,d)),r?.(Array.from(d)),{threadMessagesPrefix:m,listPrefixes:h,previousThreadMessages:x,previousThreadsList:b}},onError:(f,d,m)=>{if(m){for(const x of m.previousThreadMessages)a.setQueryData(x.queryKey,x.data);on(a,m.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:ot(f),error:f})},onSettled:(f,d,m,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),Ft(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:Xt({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,destinationMailboxId:d}})},[i]),isPending:l}},Cb=({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a})=>{const{inboxMailboxId:o}=Ua(e),{junkMailboxId:i}=sr(e),{moveMessages:l,isPending:u}=Tt({mailboxId:r,threadId:s,accountId:e}),{data:f}=ce({...Ve({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},m=wb(a,r,d),h=jb(a,d),x=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!m||!a)return{show:!1,label:"",isUndoing:!1};const b=a.fromMailboxId?f?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>bs(p.fullPath))[0]:void 0;return{show:!0,label:vb(a,b),onUndo:h?x:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function _c({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a,size:o="sm"}){const i=Cb({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a});return i.show?n.jsx(Ph,{label:i.label,size:o,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:o==="md"?i.filtersHref:void 0}):null}const yi=(e,t)=>e.filter(s=>!t.has(s.messageId)),Nb=e=>e.filter(t=>t.isDeleted!==!0),Qt=({mailboxId:e,threadId:t,accountId:s,messages:r,onAfterOptimisticRemove:a})=>{const o=ye(),{pushError:i}=Ze(),{mutate:l,isPending:u}=ve({...Gd(),onMutate:async d=>{const m=new Set(d.body.messageIds??[]),h=t?Jt({path:{threadId:t}}):[],x=$t(_a(m,r??[],e));await Promise.all([o.cancelQueries({queryKey:h}),nn(o,x)]);const b=t?o.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,g])=>({queryKey:v,data:g})):[],p=rn(o,x);return t&&o.setQueriesData({queryKey:h},v=>v&&{...v,items:yi(v.items,m)}),an(o,x,v=>yi(v,m)),a?.(Array.from(m)),{threadMessagesPrefix:h,listPrefixes:x,previousThreadMessages:b,previousThreadsList:p}},onError:(d,m,h)=>{if(h){for(const b of h.previousThreadMessages)o.setQueryData(b.queryKey,b.data);on(o,h.previousThreadsList)}const x=m.body.messageIds?.length??0;i({title:x>1?`Couldn't delete ${x} messages`:"Couldn't delete this message",detail:ot(d),error:d})},onSettled:(d,m,h,x)=>{x&&(t&&o.invalidateQueries({queryKey:x.threadMessagesPrefix}),Ft(o,x.listPrefixes),s&&o.invalidateQueries({queryKey:Xt({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&l({body:{messageIds:d}})},[l]),isPending:u}},Bc=(e,t=Date.now())=>({value:e,setAt:t}),Eb=(e,t,s,r)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Bc(!0,r):delete a.trusted,{...e,flags:a}},Ib=(e,t,s,r)=>{const a=o=>o.map(i=>Eb(i,t,s,r));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},qa=({messageId:e})=>{const t=ye(),{pushError:s}=Ze(),{mutate:r,isPending:a,error:o,reset:i}=ve({...ol(),onMutate:async u=>{const f=u.path.addressId,m=u.body.flags?.trusted?.value===!0,h=el({path:{messageId:e}});await t.cancelQueries({queryKey:h});const x=t.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,p])=>({queryKey:b,data:p}));return t.setQueriesData({queryKey:h},b=>b&&Ib(b,f,m)),{describePrefix:h,previous:x}},onError:(u,f,d)=>{if(d)for(const m of d.previous)t.setQueryData(m.queryKey,m.data);s(Vt("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,f,d,m)=>{m&&t.invalidateQueries({queryKey:m.describePrefix})}});return{toggleTrusted:(u,f)=>{r({path:{addressId:u},body:{flags:{trusted:Bc(!f)}}})},isPending:a,error:o,reset:i}};var nr="Dialog",[Kc]=Fp(nr),[Tb,nt]=Kc(nr),Uc=e=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[f,d]=Bp({prop:r,defaultProp:a??!1,onChange:o,caller:nr});return n.jsx(Tb,{scope:t,triggerRef:l,contentRef:u,contentId:Nr(),titleId:Nr(),descriptionId:Nr(),open:f,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),modal:i,children:s})};Uc.displayName=nr;var qc="DialogTrigger",Rb=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt(qc,s),o=Zt(t,a.triggerRef);return n.jsx(bt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Wa(a.open),...r,ref:o,onClick:Nt(e.onClick,a.onOpenToggle)})});Rb.displayName=qc;var Ha="DialogPortal",[Mb,Hc]=Kc(Ha,{forceMount:void 0}),Wc=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,o=nt(Ha,t);return n.jsx(Mb,{scope:t,forceMount:s,children:c.Children.map(r,i=>n.jsx(Yn,{present:s||o.open,children:n.jsx(ic,{asChild:!0,container:a,children:i})}))})};Wc.displayName=Ha;var $n="DialogOverlay",Vc=c.forwardRef((e,t)=>{const s=Hc($n,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=nt($n,e.__scopeDialog);return o.modal?n.jsx(Yn,{present:r||o.open,children:n.jsx(Db,{...a,ref:t})}):null});Vc.displayName=$n;var Ab=Da("DialogOverlay.RemoveScroll"),Db=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt($n,s),o=og(),i=Zt(t,o);return n.jsx(pc,{as:Ab,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(bt.div,{"data-state":Wa(a.open),...r,ref:i,style:{pointerEvents:"auto",...r.style}})})}),js="DialogContent",Qc=c.forwardRef((e,t)=>{const s=Hc(js,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=nt(js,e.__scopeDialog);return n.jsx(Yn,{present:r||o.open,children:o.modal?n.jsx(Ob,{...a,ref:t}):n.jsx(Pb,{...a,ref:t})})});Qc.displayName=js;var Ob=c.forwardRef((e,t)=>{const s=nt(js,e.__scopeDialog),r=c.useRef(null),a=Zt(t,s.contentRef,r);return c.useEffect(()=>{const o=r.current;if(o)return Ig(o)},[]),n.jsx(Yc,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Nt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Nt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Nt(e.onFocusOutside,o=>o.preventDefault())})}),Pb=c.forwardRef((e,t)=>{const s=nt(js,e.__scopeDialog),r=c.useRef(!1),a=c.useRef(!1);return n.jsx(Yc,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||s.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),Yc=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=nt(js,s);return ug(),n.jsx(n.Fragment,{children:n.jsx(ac,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:o,children:n.jsx(nc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Wa(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),Gc="DialogTitle",Xc=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt(Gc,s);return n.jsx(bt.h2,{id:a.titleId,...r,ref:t})});Xc.displayName=Gc;var Jc="DialogDescription",Lb=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt(Jc,s);return n.jsx(bt.p,{id:a.descriptionId,...r,ref:t})});Lb.displayName=Jc;var Zc="DialogClose",$b=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt(Zc,s);return n.jsx(bt.button,{type:"button",...r,ref:t,onClick:Nt(e.onClick,()=>a.onOpenChange(!1))})});$b.displayName=Zc;function Wa(e){return e?"open":"closed"}function Fb(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}const eu=W.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),ln=()=>{const e=W.useContext(eu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};Fb(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
116
+ `),Kx=e=>e.displayName?`${e.displayName} <${e.normalizedEmail}>`:e.normalizedEmail,hi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),Ux=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const r=s[1].trim(),a=s[2].trim();if(hi(a))return{email:a,displayName:r}}if(hi(t))return{email:t}},Mr=({label:e,addresses:t,onChange:s,placeholder:r})=>{const[a,o]=c.useState(""),[i,l]=c.useState(-1),[u,f]=c.useState(!1),d=c.useRef(null),m=c.useRef(null),h=ul(a,200),{data:x}=ce({...sl({query:{q:h,limit:8}}),enabled:h.length>=2}),b=x?.items??[],p=new Set(t.map(C=>C.email.toLowerCase())),v=b.filter(C=>!p.has(C.normalizedEmail.toLowerCase()));c.useEffect(()=>{l(-1),f(v.length>0&&a.length>=2)},[v.length,a.length]);const g=c.useCallback(C=>{p.has(C.email.toLowerCase())||(s([...t,C]),o(""),f(!1))},[t,p,s]),y=c.useCallback(C=>{s(t.filter((k,D)=>D!==C))},[t,s]),w=c.useCallback(C=>{g({email:C.normalizedEmail,displayName:C.displayName}),d.current?.focus()},[g]),S=c.useCallback(()=>{const C=Ux(a);C&&g(C)},[a,g]),N=c.useCallback(C=>{if(C.key==="Backspace"&&a===""&&t.length>0){y(t.length-1);return}if(C.key==="Enter"||C.key==="Tab"||C.key===","){if(i>=0&&v[i]){C.preventDefault(),w(v[i]);return}a.trim()&&(C.preventDefault(),S());return}if(C.key==="ArrowDown"&&u){C.preventDefault(),l(k=>k<v.length-1?k+1:0);return}if(C.key==="ArrowUp"&&u){C.preventDefault(),l(k=>k>0?k-1:v.length-1);return}C.key==="Escape"&&(f(!1),l(-1))},[a,t.length,i,v,u,y,w,S]),R=c.useCallback(()=>{setTimeout(()=>{S(),f(!1)},150)},[S]);return n.jsxs("div",{className:"relative",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),n.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>d.current?.focus(),onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&d.current?.focus()},children:[t.map((C,k)=>n.jsx(Mm,{email:C.email,displayName:C.displayName,onRemove:()=>y(k)},C.email)),n.jsx("input",{ref:d,id:`address-field-${e}`,type:"text",value:a,onChange:C=>o(C.target.value),onKeyDown:N,onBlur:R,placeholder:t.length===0?r:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5"})]})]}),u&&v.length>0&&n.jsx("ul",{ref:m,className:"absolute left-12 right-0 mt-1 bg-surface border border-line rounded-md shadow-lg z-50 max-h-[200px] overflow-auto",children:v.map((C,k)=>n.jsx("li",{className:pe("px-3 py-2 text-sm cursor-pointer transition-colors",k===i&&"bg-accent-2-soft"),onMouseDown:D=>{D.preventDefault(),w(C)},onMouseEnter:()=>l(k),children:Kx(C)},C.addressId))})]})},qx=({accountId:e})=>{const t=De();return n.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[n.jsx(ca,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),n.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",n.jsx(hm,{className:"size-3","aria-hidden":"true"})]})]})]})},Jr=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia(e),a=o=>s(o.matches);return s(r.matches),r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[e]),t},Lt=()=>Jr("(min-width: 1024px)"),pi=150,Hx=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>pi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,r=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>pi})};return r(),s.addEventListener("resize",r),()=>s.removeEventListener("resize",r)},[]),e},Wx=({selectedAccountId:e,onSelect:t})=>{const{data:s}=ce({...gt(),staleTime:1/0}),r=s?.accounts??[];if(c.useEffect(()=>{!e&&r.length===1&&r[0]&&t(r[0])},[e,r,t]),r.length<=1){const a=r[0];return a?n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=r.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:r.map(a=>n.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},Vx=({value:e,onChange:t})=>n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),n.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),Qx=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],Yx=["href"],Gx=e=>Qi.sanitize(e,{ALLOWED_TAGS:Qx,ALLOWED_ATTR:Yx}),Xx=c.lazy(()=>Vd(()=>import("./ComposeBody-DeSszvhh.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(e=>({default:e.ComposeBody}))),Jx=()=>n.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[n.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),n.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),Pc=[{type:"p",children:[{text:""}]}],Zx=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],eb=e=>e?[...Zx,{type:"p",children:[{text:e}]}]:Pc,tb=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",sb=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",nb=(e,t,s)=>{const{envelope:r}=e,o=(r.replyTo.length>0?r.replyTo:r.from).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(f=>f.email.toLowerCase())),u=[...r.to,...r.cc].filter(f=>f.normalizedEmail.toLowerCase()!==i&&!l.has(f.normalizedEmail.toLowerCase())).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));return{to:o,cc:u}},rb=e=>{const t=e.envelope.messageIdValue,r=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!r.includes(t)&&r.push(t),{inReplyTo:t,references:r}},ab=(e,t,s,r,a)=>e.length===0&&t.length===0&&s.length===0&&r.trim()===""&&Xr(a).trim()==="",ob=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:r,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:f,showBcc:d,setShowBcc:m,subject:h,setSubject:x})=>{const b=Lt(),{isKeyboardOpen:p}=Hx();if(!b&&p){const g=[];return s.length>0&&g.push(`To: ${s.map(y=>y.displayName??y.email).join(", ")}`),a.length>0&&g.push(`Cc: ${a.length}`),i.length>0&&g.push(`Bcc: ${i.length}`),h&&g.push(h),n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[n.jsx("span",{className:"truncate text-xs text-fg-muted",children:g.length>0?g.join(" · "):"…"}),n.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return n.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[n.jsx(Wx,{selectedAccountId:e,onSelect:t}),n.jsx(Mr,{label:"To",addresses:s,onChange:r,placeholder:"Recipients"}),u?n.jsx(Mr,{label:"Cc",addresses:a,onChange:o}):n.jsxs("div",{className:"flex gap-2 pl-14",children:[n.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&n.jsx("div",{className:"pl-14",children:n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&n.jsx(Mr,{label:"Bcc",addresses:i,onChange:l}),n.jsx(Vx,{value:h,onChange:x})]})},Fa=({mode:e,account:t,sourceMessage:s,onClose:r,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Mt(),{pushError:u}=Ze(),{outboxMessageId:f}=o,[d,m]=c.useState([]),[h,x]=c.useState([]),[b,p]=c.useState([]),[v,g]=c.useState(""),[y,w]=c.useState(!1),[S,N]=c.useState(!1),[R,C]=c.useState(t?.accountId),[k,D]=c.useState(!1),O=c.useRef(f);c.useEffect(()=>{O.current!==f&&(O.current=f,f&&(m([]),x([]),p([]),g(""),w(!1),N(!1),E(Pc),D(!1)))},[f]);const{signature:A}=kf(R),[P,E]=c.useState(()=>eb(A.plainText)),{data:j}=ce({...Wd({path:{outboxMessageId:f??""}}),enabled:!!f&&!k});c.useEffect(()=>{!j||k||(m(j.toAddresses.map(J=>({email:J,displayName:void 0}))),j.ccAddresses&&j.ccAddresses.length>0&&(x(j.ccAddresses.map(J=>({email:J,displayName:void 0}))),w(!0)),j.bccAddresses&&j.bccAddresses.length>0&&(p(j.bccAddresses.map(J=>({email:J,displayName:void 0}))),N(!0)),j.subject&&g(j.subject),j.textBody&&E([{type:"p",children:[{text:j.textBody}]}]),C(j.accountId),D(!0))},[j,k]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:J,cc:ae}=nb(s,e,t?.email);m(J),x(ae),ae.length>0&&w(!0),g(tb(s.envelope.subject))}e==="forward"&&g(sb(s.envelope.subject))}},[e,s,t?.email]);const I=e==="reply"||e==="reply_all"||e==="forward",{data:L}=Rc({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:I&&!!s}),T=L?.kind==="text"?L.body:"",F=L?.kind==="html"?Gx(L.body):void 0,M=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:$,saveError:K,saveDraft:_,cancelAutoSave:X}=_x({outboxMessageId:f,onDraftCreated:i});c.useEffect(()=>{K&&u({title:"Couldn't save draft",detail:ot(K)??"Saving the draft failed.",error:K})},[K,u]);const ee=ve(tl()),Y=ve(nl()),me=ve({...qn(),onError:J=>{u(Vt("Couldn't discard draft","The draft wasn't discarded.",J))}}),{data:ue}=ce({...gt(),staleTime:1/0}),te=ue?.accounts.find(J=>J.accountId===R),q=te?jf(te):!1,U=ee.isPending||Y.isPending,re=d.length>0&&!!R&&!q;c.useEffect(()=>{if(!R||f&&!k||ab(d,h,b,v,P))return;const J=Xr(P),ae=mi(P);_({accountId:R,toAddresses:d.map(de=>de.email),ccAddresses:h.length>0?h.map(de=>de.email):void 0,bccAddresses:b.length>0?b.map(de=>de.email):void 0,subject:v||void 0,textBody:J||void 0,htmlBody:ae||void 0})},[R,f,k,d,h,b,v,P,_]);const Pe=c.useCallback(async()=>{if(!R||d.length===0)return;X();const J=s&&(e==="reply"||e==="reply_all")?rb(s):{};let ae=f,de=!1;if(!ae){const Qe=Xr(P),Le=mi(P),ge=await ee.mutateAsync({body:{accountId:R,toAddresses:d.map(we=>we.email),ccAddresses:h.length>0?h.map(we=>we.email):void 0,bccAddresses:b.length>0?b.map(we=>we.email):void 0,subject:v||void 0,textBody:Qe||void 0,htmlBody:Le||void 0,sendImmediately:!0,...J}}).catch(we=>(u({title:"Couldn't send message",detail:ot(we)??"Saving the draft failed.",error:we}),null));if(ge===null)return;ae=ge.outboxMessageId,de=!0,i(ae)}await Y.mutateAsync({path:{outboxMessageId:ae}}).catch(Qe=>(u({title:"Couldn't send message",detail:ot(Qe)??(de?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:Qe}),null))!==null&&(l(ae),r())},[R,d,h,b,v,P,e,s,f,ee,Y,X,l,i,u,r]),Re=c.useCallback(()=>{X(),f&&me.mutate({path:{outboxMessageId:f}}),r()},[X,f,me,r]),V=c.useCallback(J=>{C(J.accountId),a?.(J)},[a]);return n.jsx(qh,{banner:te&&q?n.jsx(qx,{accountId:te.accountId}):void 0,header:n.jsx(ob,{selectedAccountId:R,onAccountChange:V,toAddresses:d,setToAddresses:m,ccAddresses:h,setCcAddresses:x,bccAddresses:b,setBccAddresses:p,showCc:y,setShowCc:w,showBcc:S,setShowBcc:N,subject:v,setSubject:g}),quoted:T||F?n.jsx(hp,{text:T,html:F,senderName:M}):void 0,actionBar:n.jsx(Uh,{onSend:Pe,onDiscard:Re,sending:U,canSend:re,saveStatus:$,unavailableReason:q?"SMTP not configured":void 0,onUnavailable:J=>u({title:"Can't send yet",detail:J})}),children:n.jsx(c.Suspense,{fallback:n.jsx(Jx,{}),children:n.jsx(Xx,{value:P,onChange:E,onSubmit:Pe,autoFocus:e==="new"})})})},gi=({mode:e,account:t,sourceMessage:s,onClose:r})=>n.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:n.jsx(Fa,{mode:e,account:t,sourceMessage:s,onClose:r})}),Lc=({message:e,icon:t})=>n.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&n.jsx("div",{className:"mb-4 text-fg-muted",children:t}),n.jsx("p",{className:"text-fg-muted",children:e})]}),za=({enabled:e=!0,bindings:t,capture:s=!1})=>{const r=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const f=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(f&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",r,s),()=>window.removeEventListener("keydown",r,s)},[e,r,s])},$c=e=>{const{data:t,isLoading:s}=ce({...gt(),staleTime:1/0}),r=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=Pt({queries:r.map(l=>({...Ve({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<r.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return r[l]}},[e,r,a]),isLoading:o}},ib=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),lb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Fc=(e,t)=>e===void 0?e:ib(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:lb(e)?{...e,items:t(e.items)}:e,$t=e=>{const t=[];for(const s of new Set(e))t.push(ba({path:{mailboxId:s}})),t.push(rl({path:{mailboxId:s}}));return t.push(al()),t},nn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),rn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,r])=>({queryKey:s,data:r})),an=(e,t,s)=>{const r=a=>Fc(a,s);for(const a of t)e.setQueriesData({queryKey:a},r)},on=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},Ft=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},cb=3e3,ub=(e,t,s)=>{if(e.length===0)return()=>{};const r=setTimeout(()=>s(e),t);return()=>clearTimeout(r)},_a=(e,t,s)=>{const r=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(r.get(o)??s);return[...a]},Ln=(e,t,s)=>e.map(r=>t.has(r.messageId)?{...r,isRead:s}:r),db=(e,t,s,r)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!r.has(a.messageId)).map(a=>a.messageId),fb=({messages:e,expandedIds:t,threadId:s,mailboxId:r,accountId:a})=>{const o=ye(),{pushError:i}=Ze(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:f}=ve({...Hn(),onMutate:async h=>{const x=new Set(h.body.messageIds??[]),b=h.body.isRead??!0,p=Jt({path:{threadId:s}}),v=$t(_a(x,e,r));await Promise.all([o.cancelQueries({queryKey:p}),nn(o,v)]);const g=o.getQueriesData({queryKey:p}).filter(w=>w[1]!==void 0).map(([w,S])=>({queryKey:w,data:S})),y=rn(o,v);return o.setQueriesData({queryKey:p},w=>w&&{...w,items:Ln(w.items,x,b)}),an(o,v,w=>Ln(w,x,b)),{threadMessagesPrefix:p,listPrefixes:v,previousThreadMessages:g,previousThreadsList:y}},onSuccess:(h,x)=>{const b=x.body.messageIds??[];for(const p of b)l.current.add(p),u.current.delete(p)},onError:(h,x,b)=>{const p=x.body.messageIds??[];for(const g of p)u.current.delete(g);if(b){for(const g of b.previousThreadMessages)o.setQueryData(g.queryKey,g.data);on(o,b.previousThreadsList)}const v=x.body.isRead??!0;i({title:v?"Couldn't mark as read":"Couldn't mark as unread",detail:ot(h),error:h})},onSettled:(h,x,b,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),Ft(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:Xt({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const x=h.filter(b=>!l.current.has(b)&&!u.current.has(b));if(x.length!==0){for(const b of x)u.current.add(b);f({body:{messageIds:x,isRead:!0}})}},[f]),m=c.useMemo(()=>db(e,t,l.current,u.current),[e,t]);c.useEffect(()=>ub(m,cb,d),[m,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},Zn=e=>{const{mailboxId:t,accountId:s,messages:r}=e,a=ye(),{pushError:o}=Ze(),{mutate:i,isPending:l}=ve({...Hn(),onError:(f,d)=>{const m=d.body.isRead??!0;o({title:m?"Couldn't mark as read":"Couldn't mark as unread",detail:ot(f),error:f})},onSettled:(f,d,m)=>{Ft(a,$t(_a(m.body.messageIds??[],r??[],t))),s&&a.invalidateQueries({queryKey:Xt({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,isRead:d}})},[i]),isPending:l}},mb=60,hb=1.5,pb=(e,t,s)=>{const r=Math.abs(e),a=Math.abs(t);return r<s?{direction:null}:r<a*hb?{direction:null}:{direction:e<0?"left":"right"}},gb=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=mb})=>{const r=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){r.current=null;return}r.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const f=r.current;if(r.current=null,!f)return;const{direction:d}=pb(u.clientX-f.x,u.clientY-f.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{r.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},xb=(e,t,s)=>t?.find(r=>r.messageId===e)?.mailboxId??s,xi=(e,t,s)=>e.map(r=>r.messageId===t?{...r,hasStars:s}:r),Ba=({threadId:e,mailboxId:t,messages:s})=>{const r=ye(),{pushError:a}=Ze(),{mutate:o,isPending:i,variables:l}=ve({...Qd(),onMutate:async f=>{const d=f.path.messageId,m=f.body.isStarred??!1,h=Jt({path:{threadId:e}}),x=$t([xb(d,s,t)]);await Promise.all([r.cancelQueries({queryKey:h}),nn(r,x)]);const b=r.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,g])=>({queryKey:v,data:g})),p=rn(r,x);return r.setQueriesData({queryKey:h},v=>Fc(v,g=>xi(g,d,m))),an(r,x,v=>xi(v,d,m)),{threadMessagesPrefix:h,listPrefixes:x,previousThreadMessages:b,previousThreadsList:p}},onError:(f,d,m)=>{if(m){for(const x of m.previousThreadMessages)r.setQueryData(x.queryKey,x.data);on(r,m.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:ot(f),error:f})},onSettled:(f,d,m,h)=>{h&&(r.invalidateQueries({queryKey:h.threadMessagesPrefix}),Ft(r,h.listPrefixes))}});return{toggleStar:(f,d)=>{o({path:{messageId:f},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function er(e){return e===void 0?"uncategorized":e}const at={uncategorized:"uncategorized",personal:"personal",newsletter:"newsletter",marketing:"marketing",automated:"automated",transactional:"transactional",social:"social"},bi={MoveToInbox:"MoveToInbox",MoveToJunk:"MoveToJunk"},bb={inbox:"Inbox",junk:"Junk"},Ka=e=>e.destinationMailboxId!==void 0,vb=(e,t)=>{if(Ka(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${bb[s]??"another folder"} by Remit`},yb=(e,t)=>{if(e===bi.MoveToInbox)return t.inboxMailboxId;if(e===bi.MoveToJunk)return t.junkMailboxId},wb=(e,t,s)=>{if(!e||!t)return!1;const r=Ka(e)?e.destinationMailboxId:yb(e.action,s);return r!==void 0&&r===t},jb=(e,t)=>{if(e){if(Ka(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},tr=(e,t)=>{const{data:s,isLoading:r}=ce({...gt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:r}},Sb=e=>{const{mailboxId:t,isLoading:s}=tr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},kb=e=>{const{mailboxId:t,isLoading:s}=tr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},Ua=e=>{const{mailboxId:t,isLoading:s}=tr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},sr=e=>{const{mailboxId:t,isLoading:s}=tr(e,"Junk");return{junkMailboxId:t,isLoading:s}},zc=e=>{const{data:t}=ce({...gt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},vi=(e,t)=>e.filter(s=>!t.has(s.messageId)),Tt=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=ye(),{pushError:o}=Ze(),{mutate:i,isPending:l}=ve({...Yd(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),m=t?Jt({path:{threadId:t}}):[],h=$t([e,f.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:m})]:[],nn(a,h)]);const x=t?a.getQueriesData({queryKey:m}).filter(p=>p[1]!==void 0).map(([p,v])=>({queryKey:p,data:v})):[],b=rn(a,h);return t&&a.setQueriesData({queryKey:m},p=>p&&{...p,items:vi(p.items,d)}),an(a,h,p=>vi(p,d)),r?.(Array.from(d)),{threadMessagesPrefix:m,listPrefixes:h,previousThreadMessages:x,previousThreadsList:b}},onError:(f,d,m)=>{if(m){for(const x of m.previousThreadMessages)a.setQueryData(x.queryKey,x.data);on(a,m.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:ot(f),error:f})},onSettled:(f,d,m,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),Ft(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:Xt({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,destinationMailboxId:d}})},[i]),isPending:l}},Cb=({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a})=>{const{inboxMailboxId:o}=Ua(e),{junkMailboxId:i}=sr(e),{moveMessages:l,isPending:u}=Tt({mailboxId:r,threadId:s,accountId:e}),{data:f}=ce({...Ve({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},m=wb(a,r,d),h=jb(a,d),x=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!m||!a)return{show:!1,label:"",isUndoing:!1};const b=a.fromMailboxId?f?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>bs(p.fullPath))[0]:void 0;return{show:!0,label:vb(a,b),onUndo:h?x:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function _c({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a,size:o="sm"}){const i=Cb({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a});return i.show?n.jsx(Ph,{label:i.label,size:o,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:o==="md"?i.filtersHref:void 0}):null}const yi=(e,t)=>e.filter(s=>!t.has(s.messageId)),Nb=e=>e.filter(t=>t.isDeleted!==!0),Qt=({mailboxId:e,threadId:t,accountId:s,messages:r,onAfterOptimisticRemove:a})=>{const o=ye(),{pushError:i}=Ze(),{mutate:l,isPending:u}=ve({...Gd(),onMutate:async d=>{const m=new Set(d.body.messageIds??[]),h=t?Jt({path:{threadId:t}}):[],x=$t(_a(m,r??[],e));await Promise.all([o.cancelQueries({queryKey:h}),nn(o,x)]);const b=t?o.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,g])=>({queryKey:v,data:g})):[],p=rn(o,x);return t&&o.setQueriesData({queryKey:h},v=>v&&{...v,items:yi(v.items,m)}),an(o,x,v=>yi(v,m)),a?.(Array.from(m)),{threadMessagesPrefix:h,listPrefixes:x,previousThreadMessages:b,previousThreadsList:p}},onError:(d,m,h)=>{if(h){for(const b of h.previousThreadMessages)o.setQueryData(b.queryKey,b.data);on(o,h.previousThreadsList)}const x=m.body.messageIds?.length??0;i({title:x>1?`Couldn't delete ${x} messages`:"Couldn't delete this message",detail:ot(d),error:d})},onSettled:(d,m,h,x)=>{x&&(t&&o.invalidateQueries({queryKey:x.threadMessagesPrefix}),Ft(o,x.listPrefixes),s&&o.invalidateQueries({queryKey:Xt({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&l({body:{messageIds:d}})},[l]),isPending:u}},Bc=(e,t=Date.now())=>({value:e,setAt:t}),Eb=(e,t,s,r)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Bc(!0,r):delete a.trusted,{...e,flags:a}},Ib=(e,t,s,r)=>{const a=o=>o.map(i=>Eb(i,t,s,r));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},qa=({messageId:e})=>{const t=ye(),{pushError:s}=Ze(),{mutate:r,isPending:a,error:o,reset:i}=ve({...ol(),onMutate:async u=>{const f=u.path.addressId,m=u.body.flags?.trusted?.value===!0,h=el({path:{messageId:e}});await t.cancelQueries({queryKey:h});const x=t.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,p])=>({queryKey:b,data:p}));return t.setQueriesData({queryKey:h},b=>b&&Ib(b,f,m)),{describePrefix:h,previous:x}},onError:(u,f,d)=>{if(d)for(const m of d.previous)t.setQueryData(m.queryKey,m.data);s(Vt("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,f,d,m)=>{m&&t.invalidateQueries({queryKey:m.describePrefix})}});return{toggleTrusted:(u,f)=>{r({path:{addressId:u},body:{flags:{trusted:Bc(!f)}}})},isPending:a,error:o,reset:i}};var nr="Dialog",[Kc]=Fp(nr),[Tb,nt]=Kc(nr),Uc=e=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[f,d]=Bp({prop:r,defaultProp:a??!1,onChange:o,caller:nr});return n.jsx(Tb,{scope:t,triggerRef:l,contentRef:u,contentId:Nr(),titleId:Nr(),descriptionId:Nr(),open:f,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),modal:i,children:s})};Uc.displayName=nr;var qc="DialogTrigger",Rb=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt(qc,s),o=Zt(t,a.triggerRef);return n.jsx(bt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Wa(a.open),...r,ref:o,onClick:Nt(e.onClick,a.onOpenToggle)})});Rb.displayName=qc;var Ha="DialogPortal",[Mb,Hc]=Kc(Ha,{forceMount:void 0}),Wc=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,o=nt(Ha,t);return n.jsx(Mb,{scope:t,forceMount:s,children:c.Children.map(r,i=>n.jsx(Yn,{present:s||o.open,children:n.jsx(ic,{asChild:!0,container:a,children:i})}))})};Wc.displayName=Ha;var $n="DialogOverlay",Vc=c.forwardRef((e,t)=>{const s=Hc($n,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=nt($n,e.__scopeDialog);return o.modal?n.jsx(Yn,{present:r||o.open,children:n.jsx(Db,{...a,ref:t})}):null});Vc.displayName=$n;var Ab=Da("DialogOverlay.RemoveScroll"),Db=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt($n,s),o=og(),i=Zt(t,o);return n.jsx(pc,{as:Ab,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(bt.div,{"data-state":Wa(a.open),...r,ref:i,style:{pointerEvents:"auto",...r.style}})})}),js="DialogContent",Qc=c.forwardRef((e,t)=>{const s=Hc(js,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=nt(js,e.__scopeDialog);return n.jsx(Yn,{present:r||o.open,children:o.modal?n.jsx(Ob,{...a,ref:t}):n.jsx(Pb,{...a,ref:t})})});Qc.displayName=js;var Ob=c.forwardRef((e,t)=>{const s=nt(js,e.__scopeDialog),r=c.useRef(null),a=Zt(t,s.contentRef,r);return c.useEffect(()=>{const o=r.current;if(o)return Ig(o)},[]),n.jsx(Yc,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Nt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Nt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Nt(e.onFocusOutside,o=>o.preventDefault())})}),Pb=c.forwardRef((e,t)=>{const s=nt(js,e.__scopeDialog),r=c.useRef(!1),a=c.useRef(!1);return n.jsx(Yc,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||s.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),Yc=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=nt(js,s);return ug(),n.jsx(n.Fragment,{children:n.jsx(ac,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:o,children:n.jsx(nc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Wa(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),Gc="DialogTitle",Xc=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt(Gc,s);return n.jsx(bt.h2,{id:a.titleId,...r,ref:t})});Xc.displayName=Gc;var Jc="DialogDescription",Lb=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt(Jc,s);return n.jsx(bt.p,{id:a.descriptionId,...r,ref:t})});Lb.displayName=Jc;var Zc="DialogClose",$b=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=nt(Zc,s);return n.jsx(bt.button,{type:"button",...r,ref:t,onClick:Nt(e.onClick,()=>a.onOpenChange(!1))})});$b.displayName=Zc;function Wa(e){return e?"open":"closed"}function Fb(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}const eu=W.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),ln=()=>{const e=W.useContext(eu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};Fb(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
117
117
  [data-state=closed]
118
118
  ){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function zb(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function _b(){return Va(/^Mac/)}function Bb(){return Va(/^iPhone/)}function wi(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Kb(){return Va(/^iPad/)||_b()&&navigator.maxTouchPoints>1}function tu(){return Bb()||Kb()}function Va(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const Ub=24,qb=typeof window<"u"?c.useLayoutEffect:c.useEffect;function ji(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const Ar=typeof document<"u"&&window.visualViewport;function Si(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function su(e){for(Si(e)&&(e=e.parentElement);e&&!Si(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Hb=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Cn=0,Dr;function Wb(e={}){let{isDisabled:t}=e;qb(()=>{if(!t)return Cn++,Cn===1&&tu()&&(Dr=Vb()),()=>{Cn--,Cn===0&&Dr?.()}},[t])}function Vb(){let e,t=0,s=m=>{e=su(m.target),!(e===document.documentElement&&e===document.body)&&(t=m.changedTouches[0].pageY)},r=m=>{if(!e||e===document.documentElement||e===document.body){m.preventDefault();return}let h=m.changedTouches[0].pageY,x=e.scrollTop,b=e.scrollHeight-e.clientHeight;b!==0&&((x<=0&&h>t||x>=b&&h<t)&&m.preventDefault(),t=h)},a=m=>{let h=m.target;Zr(h)&&h!==document.activeElement&&(m.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=m=>{let h=m.target;Zr(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",Ar&&(Ar.height<window.innerHeight?requestAnimationFrame(()=>{ki(h)}):Ar.addEventListener("resize",()=>ki(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,f=ji(Qb(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=ji(Os(document,"touchstart",s,{passive:!1,capture:!0}),Os(document,"touchmove",r,{passive:!1,capture:!0}),Os(document,"touchend",a,{passive:!1,capture:!0}),Os(document,"focus",o,!0),Os(window,"scroll",i));return()=>{f(),d(),window.scrollTo(l,u)}}function Qb(e,t,s){let r=e.style[t];return e.style[t]=s,()=>{e.style[t]=r}}function Os(e,t,s,r){return e.addEventListener(t,s,r),()=>{e.removeEventListener(t,s,r)}}function ki(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=su(e);if(s!==document.documentElement&&s!==document.body&&s!==e){let r=s.getBoundingClientRect().top,a=e.getBoundingClientRect().top,o=e.getBoundingClientRect().bottom;const i=s.getBoundingClientRect().bottom+Ub;o>i&&(s.scrollTop+=a-r)}e=s.parentElement}}function Zr(e){return e instanceof HTMLInputElement&&!Hb.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function Yb(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function Gb(...e){return t=>e.forEach(s=>Yb(s,t))}function nu(...e){return c.useCallback(Gb(...e),e)}const ru=new WeakMap;function Ne(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let r={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}r[a]=e.style[a],e.style[a]=o}),!s&&ru.set(e,r)}function Xb(e,t){if(!e||!(e instanceof HTMLElement))return;let s=ru.get(e);s&&(e.style[t]=s[t])}const je=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function Nn(e,t){if(!e)return null;const s=window.getComputedStyle(e),r=s.transform||s.webkitTransform||s.mozTransform;let a=r.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[je(t)?13:12]):(a=r.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[je(t)?5:4]):null)}function Jb(e){return 8*(Math.log(e+1)-2)}function Or(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function Zb(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const be={DURATION:.5,EASE:[.32,.72,0,1]},au=.4,ev=.25,tv=100,ou=8,qt=16,ea=26,Pr="vaul-dragging";function iu(e){const t=W.useRef(e);return W.useEffect(()=>{t.current=e}),W.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function sv({defaultProp:e,onChange:t}){const s=W.useState(e),[r]=s,a=W.useRef(r),o=iu(t);return W.useEffect(()=>{a.current!==r&&(o(r),a.current=r)},[r,a,o]),s}function lu({prop:e,defaultProp:t,onChange:s=()=>{}}){const[r,a]=sv({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:r,l=iu(s),u=W.useCallback(f=>{if(o){const m=typeof f=="function"?f(e):f;m!==e&&l(m)}else a(f)},[o,e,a,l]);return[i,u]}function nv({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:r,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:f}){const[d,m]=lu({prop:e,defaultProp:s?.[0],onChange:t}),[h,x]=W.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);W.useEffect(()=>{function C(){x({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[]);const b=W.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=W.useMemo(()=>{var C;return(C=s?.findIndex(k=>k===d))!=null?C:null},[s,d]),v=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,g=W.useMemo(()=>{const C=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var k;return(k=s?.map(D=>{const O=typeof D=="string";let A=0;if(O&&(A=parseInt(D,10)),je(l)){const E=O?A:h?D*C.height:0;return h?l==="bottom"?C.height-E:-C.height+E:E}const P=O?A:h?D*C.width:0;return h?l==="right"?C.width-P:-C.width+P:P}))!=null?k:[]},[s,h,u]),y=W.useMemo(()=>p!==null?g?.[p]:null,[g,p]),w=W.useCallback(C=>{var k;const D=(k=g?.findIndex(O=>O===C))!=null?k:null;i(D),Ne(r.current,{transition:`transform ${be.DURATION}s cubic-bezier(${be.EASE.join(",")})`,transform:je(l)?`translate3d(0, ${C}px, 0)`:`translate3d(${C}px, 0, 0)`}),g&&D!==g.length-1&&o!==void 0&&D!==o&&D<o?Ne(a.current,{transition:`opacity ${be.DURATION}s cubic-bezier(${be.EASE.join(",")})`,opacity:"0"}):Ne(a.current,{transition:`opacity ${be.DURATION}s cubic-bezier(${be.EASE.join(",")})`,opacity:"1"}),m(s?.[Math.max(D,0)])},[r.current,s,g,o,a,m]);W.useEffect(()=>{if(d||e){var C;const k=(C=s?.findIndex(D=>D===e||D===d))!=null?C:-1;g&&k!==-1&&typeof g[k]=="number"&&w(g[k])}},[d,e,s,g,w]);function S({draggedDistance:C,closeDrawer:k,velocity:D,dismissible:O}){if(o===void 0)return;const A=l==="bottom"||l==="right"?(y??0)-C:(y??0)+C,P=p===o-1,E=p===0,j=C>0;if(P&&Ne(a.current,{transition:`opacity ${be.DURATION}s cubic-bezier(${be.EASE.join(",")})`}),!f&&D>2&&!j){O?k():w(g[0]);return}if(!f&&D>2&&j&&g&&s){w(g[s.length-1]);return}const I=g?.reduce((T,F)=>typeof T!="number"||typeof F!="number"?T:Math.abs(F-A)<Math.abs(T-A)?F:T),L=je(l)?window.innerHeight:window.innerWidth;if(D>au&&Math.abs(C)<L*.4){const T=j?1:-1;if(T>0&&b&&s){w(g[s.length-1]);return}if(E&&T<0&&O&&k(),p===null)return;w(g[p+T]);return}w(I)}function N({draggedDistance:C}){if(y===null)return;const k=l==="bottom"||l==="right"?y-C:y+C;(l==="bottom"||l==="right")&&k<g[g.length-1]||(l==="top"||l==="left")&&k>g[g.length-1]||Ne(r.current,{transform:je(l)?`translate3d(0, ${k}px, 0)`:`translate3d(${k}px, 0, 0)`})}function R(C,k){if(!s||typeof p!="number"||!g||o===void 0)return null;const D=p===o-1;if(p>=o&&k)return 0;if(D&&!k)return 1;if(!v&&!D)return null;const A=D?p+1:p-1,P=D?g[A]-g[A-1]:g[A+1]-g[A],E=C/Math.abs(P);return D?1-E:E}return{isLastSnapPoint:b,activeSnapPoint:d,shouldFade:v,getPercentageDragged:R,setActiveSnapPoint:m,activeSnapPointIndex:p,onRelease:S,onDrag:N,snapPointsOffset:g}}const rv=()=>()=>{};function av(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:r,noBodyStyles:a}=ln(),o=W.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-ea)/window.innerWidth}W.useEffect(()=>{if(t&&s){o.current&&clearTimeout(o.current);const u=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!u)return;Zb(r&&!a?Or(document.body,{background:"black"}):rv,Or(u,{transformOrigin:je(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${be.DURATION}s`,transitionTimingFunction:`cubic-bezier(${be.EASE.join(",")})`}));const f=Or(u,{borderRadius:`${ou}px`,overflow:"hidden",...je(e)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{f(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},be.DURATION*1e3)}}},[t,s,i])}let Ps=null;function ov({isOpen:e,modal:t,nested:s,hasBeenOpened:r,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=W.useState(()=>typeof window<"u"?window.location.href:""),u=W.useRef(0),f=W.useCallback(()=>{if(wi()&&Ps===null&&e&&!o){Ps={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:m,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-m}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const x=h-window.innerHeight;x&&u.current>=h&&(document.body.style.top=`${-(u.current+x)}px`)}),300)}},[e]),d=W.useCallback(()=>{if(wi()&&Ps!==null&&!o){const m=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Ps),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,m)}),Ps=null}},[i]);return W.useEffect(()=>{function m(){u.current=window.scrollY}return m(),window.addEventListener("scroll",m),()=>{window.removeEventListener("scroll",m)}},[]),W.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),W.useEffect(()=>{s||!r||(e?(!window.matchMedia("(display-mode: standalone)").matches&&f(),t||window.setTimeout(()=>{d()},500)):d())},[e,r,i,t,s,f,d]),{restorePositionSetting:d}}function iv({open:e,onOpenChange:t,children:s,onDrag:r,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=ev,scrollLockTimeout:f=tv,dismissible:d=!0,handleOnly:m=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:x,setActiveSnapPoint:b,fixed:p,modal:v=!0,onClose:g,nested:y,noBodyStyles:w=!1,direction:S="bottom",defaultOpen:N=!1,disablePreventScroll:R=!0,snapToSequentialPoint:C=!1,preventScrollRestoration:k=!1,repositionInputs:D=!0,onAnimationEnd:O,container:A,autoFocus:P=!1}){var E,j;const[I=!1,L]=lu({defaultProp:N,prop:e,onChange:Z=>{t?.(Z),!Z&&!y&&Fe(),setTimeout(()=>{O?.(Z)},be.DURATION*1e3),Z&&!v&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),Z||(document.body.style.pointerEvents="auto")}}),[T,F]=W.useState(!1),[M,$]=W.useState(!1),[K,_]=W.useState(!1),X=W.useRef(null),ee=W.useRef(null),Y=W.useRef(null),me=W.useRef(null),ue=W.useRef(null),te=W.useRef(!1),q=W.useRef(null),U=W.useRef(0),re=W.useRef(!1),Pe=W.useRef(!N),Re=W.useRef(0),V=W.useRef(null),J=W.useRef(((E=V.current)==null?void 0:E.getBoundingClientRect().height)||0),ae=W.useRef(((j=V.current)==null?void 0:j.getBoundingClientRect().width)||0),de=W.useRef(0),B=W.useCallback(Z=>{o&&Z===Ye.length-1&&(ee.current=new Date)},[]),{activeSnapPoint:Qe,activeSnapPointIndex:Le,setActiveSnapPoint:ge,onRelease:we,snapPointsOffset:Ye,onDrag:es,shouldFade:$e,getPercentageDragged:et}=nv({snapPoints:o,activeSnapPointProp:x,setActiveSnapPointProp:b,drawerRef:V,fadeFromIndex:h,overlayRef:X,onSnapPointChange:B,direction:S,container:A,snapToSequentialPoint:C});Wb({isDisabled:!I||M||!v||K||!T||!D||!R});const{restorePositionSetting:Fe}=ov({isOpen:I,modal:v,nested:y??!1,hasBeenOpened:T,preventScrollRestoration:k,noBodyStyles:w});function ze(){return(window.innerWidth-ea)/window.innerWidth}function ct(Z){var le,ne;!d&&!o||V.current&&!V.current.contains(Z.target)||(J.current=((le=V.current)==null?void 0:le.getBoundingClientRect().height)||0,ae.current=((ne=V.current)==null?void 0:ne.getBoundingClientRect().width)||0,$(!0),Y.current=new Date,tu()&&window.addEventListener("touchend",()=>te.current=!1,{once:!0}),Z.target.setPointerCapture(Z.pointerId),U.current=je(S)?Z.pageY:Z.pageX)}function Ee(Z,le){var ne;let oe=Z;const fe=(ne=window.getSelection())==null?void 0:ne.toString(),he=V.current?Nn(V.current,S):null,xe=new Date;if(oe.tagName==="SELECT"||oe.hasAttribute("data-vaul-no-drag")||oe.closest("[data-vaul-no-drag]"))return!1;if(S==="right"||S==="left")return!0;if(ee.current&&xe.getTime()-ee.current.getTime()<500)return!1;if(he!==null&&(S==="bottom"?he>0:he<0))return!0;if(fe&&fe.length>0)return!1;if(ue.current&&xe.getTime()-ue.current.getTime()<f&&he===0||le)return ue.current=xe,!1;for(;oe;){if(oe.scrollHeight>oe.clientHeight){if(oe.scrollTop!==0)return ue.current=new Date,!1;if(oe.getAttribute("role")==="dialog")return!0}oe=oe.parentNode}return!0}function ts(Z){if(V.current&&M){const le=S==="bottom"||S==="right"?1:-1,ne=(U.current-(je(S)?Z.pageY:Z.pageX))*le,oe=ne>0,fe=o&&!d&&!oe;if(fe&&Le===0)return;const he=Math.abs(ne),xe=document.querySelector("[data-vaul-drawer-wrapper]"),Ke=S==="bottom"||S==="top"?J.current:ae.current;let Me=he/Ke;const Ue=et(he,oe);if(Ue!==null&&(Me=Ue),fe&&Me>=1||!te.current&&!Ee(Z.target,oe))return;if(V.current.classList.add(Pr),te.current=!0,Ne(V.current,{transition:"none"}),Ne(X.current,{transition:"none"}),o&&es({draggedDistance:ne}),oe&&!o){const Ie=Jb(ne),Ge=Math.min(Ie*-1,0)*le;Ne(V.current,{transform:je(S)?`translate3d(0, ${Ge}px, 0)`:`translate3d(${Ge}px, 0, 0)`});return}const Ae=1-Me;if(($e||h&&Le===h-1)&&(r?.(Z,Me),Ne(X.current,{opacity:`${Ae}`,transition:"none"},!0)),xe&&X.current&&i){const Ie=Math.min(ze()+Me*(1-ze()),1),Ge=8-Me*8,Ce=Math.max(0,14-Me*14);Ne(xe,{borderRadius:`${Ge}px`,transform:je(S)?`scale(${Ie}) translate3d(0, ${Ce}px, 0)`:`scale(${Ie}) translate3d(${Ce}px, 0, 0)`,transition:"none"},!0)}if(!o){const Ie=he*le;Ne(V.current,{transform:je(S)?`translate3d(0, ${Ie}px, 0)`:`translate3d(${Ie}px, 0, 0)`})}}}W.useEffect(()=>{window.requestAnimationFrame(()=>{Pe.current=!0})},[]),W.useEffect(()=>{var Z;function le(){if(!V.current||!D)return;const ne=document.activeElement;if(Zr(ne)||re.current){var oe;const fe=((oe=window.visualViewport)==null?void 0:oe.height)||0,he=window.innerHeight;let xe=he-fe;const Ke=V.current.getBoundingClientRect().height||0,Me=Ke>he*.8;de.current||(de.current=Ke);const Ue=V.current.getBoundingClientRect().top;if(Math.abs(Re.current-xe)>60&&(re.current=!re.current),o&&o.length>0&&Ye&&Le){const Ae=Ye[Le]||0;xe+=Ae}if(Re.current=xe,Ke>fe||re.current){const Ae=V.current.getBoundingClientRect().height;let Ie=Ae;Ae>fe&&(Ie=fe-(Me?Ue:ea)),p?V.current.style.height=`${Ae-Math.max(xe,0)}px`:V.current.style.height=`${Math.max(Ie,fe-Ue)}px`}else zb()||(V.current.style.height=`${de.current}px`);o&&o.length>0&&!re.current?V.current.style.bottom="0px":V.current.style.bottom=`${Math.max(xe,0)}px`}}return(Z=window.visualViewport)==null||Z.addEventListener("resize",le),()=>{var ne;return(ne=window.visualViewport)==null?void 0:ne.removeEventListener("resize",le)}},[Le,o,Ye]);function _e(Z){ke(),g?.(),Z||L(!1),setTimeout(()=>{o&&ge(o[0])},be.DURATION*1e3)}function zt(){if(!V.current)return;const Z=document.querySelector("[data-vaul-drawer-wrapper]"),le=Nn(V.current,S);Ne(V.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${be.DURATION}s cubic-bezier(${be.EASE.join(",")})`}),Ne(X.current,{transition:`opacity ${be.DURATION}s cubic-bezier(${be.EASE.join(",")})`,opacity:"1"}),i&&le&&le>0&&I&&Ne(Z,{borderRadius:`${ou}px`,overflow:"hidden",...je(S)?{transform:`scale(${ze()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${ze()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${be.DURATION}s`,transitionTimingFunction:`cubic-bezier(${be.EASE.join(",")})`},!0)}function ke(){!M||!V.current||(V.current.classList.remove(Pr),te.current=!1,$(!1),me.current=new Date)}function Be(Z){if(!M||!V.current)return;V.current.classList.remove(Pr),te.current=!1,$(!1),me.current=new Date;const le=Nn(V.current,S);if(!Z||!Ee(Z.target,!1)||!le||Number.isNaN(le)||Y.current===null)return;const ne=me.current.getTime()-Y.current.getTime(),oe=U.current-(je(S)?Z.pageY:Z.pageX),fe=Math.abs(oe)/ne;if(fe>.05&&(_(!0),setTimeout(()=>{_(!1)},200)),o){we({draggedDistance:oe*(S==="bottom"||S==="right"?1:-1),closeDrawer:_e,velocity:fe,dismissible:d}),a?.(Z,!0);return}if(S==="bottom"||S==="right"?oe>0:oe<0){zt(),a?.(Z,!0);return}if(fe>au){_e(),a?.(Z,!1);return}var he;const xe=Math.min((he=V.current.getBoundingClientRect().height)!=null?he:0,window.innerHeight);var Ke;const Me=Math.min((Ke=V.current.getBoundingClientRect().width)!=null?Ke:0,window.innerWidth),Ue=S==="left"||S==="right";if(Math.abs(le)>=(Ue?Me:xe)*u){_e(),a?.(Z,!1);return}a?.(Z,!0),zt()}W.useEffect(()=>(I&&(Ne(document.documentElement,{scrollBehavior:"auto"}),ee.current=new Date),()=>{Xb(document.documentElement,"scrollBehavior")}),[I]);function ut(Z){const le=Z?(window.innerWidth-qt)/window.innerWidth:1,ne=Z?-qt:0;q.current&&window.clearTimeout(q.current),Ne(V.current,{transition:`transform ${be.DURATION}s cubic-bezier(${be.EASE.join(",")})`,transform:je(S)?`scale(${le}) translate3d(0, ${ne}px, 0)`:`scale(${le}) translate3d(${ne}px, 0, 0)`}),!Z&&V.current&&(q.current=setTimeout(()=>{const oe=Nn(V.current,S);Ne(V.current,{transition:"none",transform:je(S)?`translate3d(0, ${oe}px, 0)`:`translate3d(${oe}px, 0, 0)`})},500))}function ss(Z,le){if(le<0)return;const ne=(window.innerWidth-qt)/window.innerWidth,oe=ne+le*(1-ne),fe=-qt+le*qt;Ne(V.current,{transform:je(S)?`scale(${oe}) translate3d(0, ${fe}px, 0)`:`scale(${oe}) translate3d(${fe}px, 0, 0)`,transition:"none"})}function _t(Z,le){const ne=je(S)?window.innerHeight:window.innerWidth,oe=le?(ne-qt)/ne:1,fe=le?-qt:0;le&&Ne(V.current,{transition:`transform ${be.DURATION}s cubic-bezier(${be.EASE.join(",")})`,transform:je(S)?`scale(${oe}) translate3d(0, ${fe}px, 0)`:`scale(${oe}) translate3d(${fe}px, 0, 0)`})}return W.useEffect(()=>{v||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[v]),W.createElement(Uc,{defaultOpen:N,onOpenChange:Z=>{!d&&!Z||(Z?F(!0):_e(!0),L(Z))},open:I},W.createElement(eu.Provider,{value:{activeSnapPoint:Qe,snapPoints:o,setActiveSnapPoint:ge,drawerRef:V,overlayRef:X,onOpenChange:t,onPress:ct,onRelease:Be,onDrag:ts,dismissible:d,shouldAnimate:Pe,handleOnly:m,isOpen:I,isDragging:M,shouldFade:$e,closeDrawer:_e,onNestedDrag:ss,onNestedOpenChange:ut,onNestedRelease:_t,keyboardIsOpen:re,modal:v,snapPointsOffset:Ye,activeSnapPointIndex:Le,direction:S,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:w,container:A,autoFocus:P}},s))}const cu=W.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:r,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=ln(),f=nu(t,s),d=r&&r.length>0;if(!l)return null;const m=W.useCallback(h=>a(h),[a]);return W.createElement(Vc,{onMouseUp:m,ref:f,"data-vaul-overlay":"","data-vaul-snap-points":i&&d?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});cu.displayName="Drawer.Overlay";const uu=W.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...r},a){const{drawerRef:o,onPress:i,onRelease:l,onDrag:u,keyboardIsOpen:f,snapPointsOffset:d,activeSnapPointIndex:m,modal:h,isOpen:x,direction:b,snapPoints:p,container:v,handleOnly:g,shouldAnimate:y,autoFocus:w}=ln(),[S,N]=W.useState(!1),R=nu(a,o),C=W.useRef(null),k=W.useRef(null),D=W.useRef(!1),O=p&&p.length>0;av();const A=(E,j,I=0)=>{if(D.current)return!0;const L=Math.abs(E.y),T=Math.abs(E.x),F=T>L,M=["bottom","right"].includes(j)?1:-1;if(j==="left"||j==="right"){if(!(E.x*M<0)&&T>=0&&T<=I)return F}else if(!(E.y*M<0)&&L>=0&&L<=I)return!F;return D.current=!0,!0};W.useEffect(()=>{O&&window.requestAnimationFrame(()=>{N(!0)})},[]);function P(E){C.current=null,D.current=!1,l(E)}return W.createElement(Qc,{"data-vaul-drawer-direction":b,"data-vaul-drawer":"","data-vaul-delayed-snap-points":S?"true":"false","data-vaul-snap-points":x&&O?"true":"false","data-vaul-custom-container":v?"true":"false","data-vaul-animate":y?.current?"true":"false",...r,ref:R,style:d&&d.length>0?{"--snap-point-height":`${d[m??0]}px`,...t}:t,onPointerDown:E=>{g||(r.onPointerDown==null||r.onPointerDown.call(r,E),C.current={x:E.pageX,y:E.pageY},i(E))},onOpenAutoFocus:E=>{s?.(E),w||E.preventDefault()},onPointerDownOutside:E=>{if(e?.(E),!h||E.defaultPrevented){E.preventDefault();return}f.current&&(f.current=!1)},onFocusOutside:E=>{if(!h){E.preventDefault();return}},onPointerMove:E=>{if(k.current=E,g||(r.onPointerMove==null||r.onPointerMove.call(r,E),!C.current))return;const j=E.pageY-C.current.y,I=E.pageX-C.current.x,L=E.pointerType==="touch"?10:2;A({x:I,y:j},b,L)?u(E):(Math.abs(I)>L||Math.abs(j)>L)&&(C.current=null)},onPointerUp:E=>{r.onPointerUp==null||r.onPointerUp.call(r,E),C.current=null,D.current=!1,l(E)},onPointerOut:E=>{r.onPointerOut==null||r.onPointerOut.call(r,E),P(k.current)},onContextMenu:E=>{r.onContextMenu==null||r.onContextMenu.call(r,E),k.current&&P(k.current)}})});uu.displayName="Drawer.Content";const lv=250,cv=120,du=W.forwardRef(function({preventCycle:e=!1,children:t,...s},r){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:l,setActiveSnapPoint:u,dismissible:f,handleOnly:d,isOpen:m,onPress:h,onDrag:x}=ln(),b=W.useRef(null),p=W.useRef(!1);function v(){if(p.current){w();return}window.setTimeout(()=>{g()},cv)}function g(){if(o||e||p.current){w();return}if(w(),!i||i.length===0){f||a();return}if(l===i[i.length-1]&&f){a();return}const N=i.findIndex(C=>C===l);if(N===-1)return;const R=i[N+1];u(R)}function y(){b.current=window.setTimeout(()=>{p.current=!0},lv)}function w(){b.current&&window.clearTimeout(b.current),p.current=!1}return W.createElement("div",{onClick:v,onPointerCancel:w,onPointerDown:S=>{d&&h(S),y()},onPointerMove:S=>{d&&x(S)},ref:r,"data-vaul-drawer-visible":m?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},W.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});du.displayName="Drawer.Handle";function uv(e){const t=ln(),{container:s=t.container,...r}=e;return W.createElement(Wc,{container:s,...r})}const Je={Root:iv,Content:uu,Overlay:cu,Portal:uv,Handle:du,Title:Xc},dv=new Set(["outbox","postvak uit","boîte d'envoi","postausgang","buzón de salida","posta in uscita","送信トレイ","送件匣","发件箱","skrzynka nadawcza"]),fv=e=>{const t=bs(e.fullPath).trim().toLowerCase();return dv.has(t)},Ci=_r.length,rr=(e,t=[])=>{const s=Ss(t);return[...e.filter(a=>{const o=s.get(a.mailboxId);return o==="drafts"||o==="sent"?!1:!fv(a)})].sort((a,o)=>{const i=s.has(a.mailboxId)?_r.indexOf(s.get(a.mailboxId)??"inbox"):Ci,l=s.has(o.mailboxId)?_r.indexOf(s.get(o.mailboxId)??"inbox"):Ci;return i!==l?i-l:bs(a.fullPath).localeCompare(bs(o.fullPath),void 0,{sensitivity:"base",numeric:!0})})},fu="inline-flex items-center justify-center transition-colors",mv=pe(fu,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),hv=pe(fu,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),cn=({accountId:e,currentMailboxId:t,onMove:s,disabled:r=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),f=Lt(),d=c.useRef(null),m=i??"Move to folder",h=c.useId(),{t:x}=Kn("mail",{useSuspense:!1}),b=c.useCallback((O,A)=>x(O,{defaultValue:A}),[x]),{data:p,isLoading:v,isError:g,error:y,refetch:w}=ce({...Ve({path:{accountId:e}}),staleTime:1/0,enabled:l}),S=zc(e),N=c.useMemo(()=>{const O=rr(p?.items??[],S),A=Ss(S);return O.map(P=>({id:P.mailboxId,label:xs(P,A.get(P.mailboxId),b),searchValue:P.fullPath,isCurrent:P.mailboxId===t}))},[p?.items,S,t,b]),R=c.useCallback(O=>{u(!1),s(O)},[s]);c.useEffect(()=>{if(!l||!f)return;const O=P=>{d.current&&!d.current.contains(P.target)&&u(!1)},A=P=>{P.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",O),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("keydown",A)}},[l,f]);const C=r||!!a,k=n.jsxs("button",{type:"button",onClick:O=>{O.stopPropagation(),!C&&u(A=>!A)},"aria-label":m,"aria-haspopup":f?"listbox":"dialog","aria-expanded":l,"aria-controls":l?h:void 0,title:a,className:o==="icon-only"?mv:hv,children:[n.jsx(Ml,{className:"size-4"}),o==="compact"&&n.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),D=v?n.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):g?n.jsx("div",{className:"p-3",children:n.jsx(At,{variant:"inline",title:"Couldn't load folders",error:y,onRetry:()=>w()})}):n.jsx(ec,{mailboxes:N,onSelect:R,onCancel:()=>u(!1),autoFocus:!f,labels:{searchPlaceholder:x("move_picker_placeholder",{defaultValue:"Move to…"}),searchAriaLabel:x("move_picker_filter_label",{defaultValue:"Filter folders"}),optionLabel:O=>`Move to ${O}`,currentSuffix:"(current folder)",currentTag:"current",emptyMessage:O=>`No folders match "${O}"`}});return f?n.jsxs("div",{ref:d,className:"relative inline-block",children:[k,l&&n.jsx("div",{id:h,className:pe("absolute right-0 mt-1 z-50 w-72 max-h-96 flex flex-col","bg-surface border border-line rounded-md shadow-lg"),children:D})]}):n.jsxs(n.Fragment,{children:[k,n.jsx(Je.Root,{open:l,onOpenChange:u,children:n.jsxs(Je.Portal,{children:[n.jsx(Je.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Je.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{maxHeight:"85dvh"},id:h,children:[n.jsx(Je.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),n.jsx(Je.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),n.jsx("div",{className:"flex-1 overflow-hidden",children:D})]})]})})]})},pv=({messageId:e,threadId:t,mailboxId:s,isRead:r,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const f=ye(),d=De(),{pushError:m}=Ze(),{selectedMessageId:h}=vs({strict:!1}),{mutate:x,isPending:b}=ve({...Hn(),onMutate:async I=>{const L=I.body.isRead??!0,T=new Set(I.body.messageIds??[]),F=Jt({path:{threadId:t}}),M=$t([s]);await Promise.all([f.cancelQueries({queryKey:F}),nn(f,M)]);const $=f.getQueriesData({queryKey:F}).filter(_=>_[1]!==void 0).map(([_,X])=>({queryKey:_,data:X})),K=rn(f,M);return f.setQueriesData({queryKey:F},_=>_&&{..._,items:Ln(_.items,T,L)}),an(f,M,_=>Ln(_,T,L)),{threadMessagesPrefix:F,listPrefixes:M,previousThreadMessages:$,previousThreadsList:K}},onError:(I,L,T)=>{if(T){for(const M of T.previousThreadMessages)f.setQueryData(M.queryKey,M.data);on(f,T.previousThreadsList)}const F=L.body.isRead??!0;m({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:ot(I),error:I})},onSettled:(I,L,T,F)=>{F&&(f.invalidateQueries({queryKey:F.threadMessagesPrefix}),Ft(f,F.listPrefixes))}}),p=c.useCallback(I=>{h&&I.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:L=>({...L,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:v,isPending:g}=Qt({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:y,isPending:w}=Tt({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:S,isPending:N,error:R,reset:C}=qa({messageId:e}),k=()=>{x({body:{messageIds:[e],isRead:!1}})},D=()=>{v([e])},O=()=>{o&&S(o,i)},A=b||g||w||N,P=A||!o,E=c.useCallback(I=>{y([e],I)},[y,e]),j=o?void 0:"Sender has no parseable address";return n.jsxs("div",{className:"flex flex-col items-end gap-1",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[a&&n.jsx(cn,{accountId:a,currentMailboxId:s,onMove:E,disabled:A,label:"Move this message"}),n.jsxs(bc,{trigger:n.jsx(Rl,{className:"size-4"}),children:[n.jsxs(ms,{onClick:O,disabled:P,children:[i?n.jsx(Vn,{className:"size-4 text-positive"}):n.jsx(Xs,{className:"size-4 opacity-0"}),n.jsx("span",{title:j,children:"Trusted sender"})]}),r&&n.jsxs(ms,{onClick:k,disabled:A,children:[n.jsx(Cs,{className:"size-4"}),"Mark as unread"]}),u&&n.jsxs(ms,{onClick:u,children:[n.jsx(Tl,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),n.jsx(Yr,{}),n.jsxs(ms,{onClick:D,disabled:A,destructive:!0,children:[n.jsx(st,{className:"size-4"}),"Delete"]})]})]}),R&&n.jsx("div",{className:"w-64",children:n.jsx(At,{variant:"inline",title:"Couldn't update trust",error:R,onRetry:()=>{C(),O()}})})]})},gv=()=>{const[e,t]=c.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return c.useEffect(()=>{const s=document.documentElement,r=new MutationObserver(()=>{t(s.classList.contains("dark"))});return r.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>r.disconnect()},[]),e},xv=({blockedImageCount:e,canAlwaysTrust:t,isTrustPending:s,onLoadOnce:r,onAlwaysTrust:a})=>n.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-md bg-surface-sunken/50 px-3 py-2 text-sm",children:[n.jsxs("span",{className:"text-fg-muted",children:[e," image",e>1?"s":""," blocked for privacy"]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:r,className:"text-accent hover:underline",children:"Load once"}),t&&n.jsx("button",{type:"button",onClick:a,"aria-busy":s,className:"text-accent hover:underline aria-busy:opacity-50",children:s?"Trusting…":"Always trust"})]})]}),bv=(e,t)=>{switch(e){case"auth":return{title:"Your session expired",detail:"Sign in again to reload the message body. Other parts of the app may also stop responding until you do."};case"body-missing":return{title:"Message body is missing in storage",detail:"A sync failure may have left this message without its body bytes. Contact support, or run the reconcile script to refetch from the upstream IMAP server."};case"content-type-mismatch":return{title:"Couldn't load message body",detail:"The server returned an unexpected content type for this part. The message body has not been rendered to keep you safe."};case"spa-shell-leak":return{title:"Couldn't load message body",detail:"The server returned the app shell instead of the message body. This is an infrastructure bug — please report it."};case"not-ready":return{title:"Message body is still syncing",detail:"This message's body hasn't finished downloading from the mail server yet. It should appear shortly — reopen the message to try again."};default:return{title:"Couldn't load message body",detail:t}}},vv=e=>e instanceof Ht?e.reason:"generic",yv=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",wv=({error:e,onRetry:t})=>{const s=vv(e),r=yv(e),{title:a,detail:o}=bv(s,r),[i,l]=c.useState(!1),{Account:u}=ha();return i?null:n.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[n.jsx(Yt,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"font-medium text-danger",children:a}),n.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&n.jsx(u,{children:({signOut:f})=>n.jsx("button",{type:"button",onClick:()=>f(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&n.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),n.jsx("button",{type:"button",onClick:()=>l(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:n.jsx(We,{className:"size-4","aria-hidden":"true"})})]})]})},jv=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),Ni=()=>n.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),mu=({bodyParts:e,html:t,text:s,isTrusted:r=!1,messageId:a,fromAddressId:o,category:i,className:l})=>{const[u,f]=c.useState(!1),d=r||u,m=gv(),{toggleTrusted:h,isPending:x}=qa({messageId:a??""}),b=!!e&&e.length>0,{picked:p,data:v,isLoading:g,isError:y,error:w,refetch:S}=Rc({messageId:a,bodyParts:e,enabled:b}),N=c.useMemo(()=>eh(e??[]),[e]),R=b&&v?.kind==="html"?v.body:t,C=b&&v?.kind==="text"?v.body:s;if(b){if(g)return n.jsx("div",{className:pe("message-body",l),children:n.jsx(jv,{})});if(y)return n.jsx("div",{className:pe("message-body",l),children:n.jsx(wv,{error:w,onRetry:()=>S()})});if(!p)return n.jsx("div",{className:pe("message-body",l),children:n.jsx(Ni,{})})}else if(!t&&!s)return n.jsx("div",{className:pe("message-body",l),children:n.jsx(Ni,{})});const k=!!(o&&a),D=()=>{!o||x||(f(!0),h(o,!1))};return n.jsx(Vl,{className:l,html:R,text:C,isDark:m,category:i,allowImages:d,resolveCid:N,renderBlockedNotice:O=>n.jsx(xv,{blockedImageCount:O,canAlwaysTrust:k,isTrustPending:x,onLoadOnce:()=>f(!0),onAlwaysTrust:D})})},Sv=({messageId:e,threadId:t,mailboxId:s,accountId:r,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:l,isTrusted:u,showRaw:f,onToggleRaw:d,onReply:m,onReplyAll:h,onForward:x})=>{const b=ye(),{deleteMessages:p}=Qt({mailboxId:s,threadId:t}),{moveMessages:v}=Tt({mailboxId:s,threadId:t,accountId:r}),{toggleTrusted:g}=qa({messageId:e}),{mutate:y}=ve({...Hn(),onSettled:()=>{b.invalidateQueries({queryKey:Jt({path:{threadId:t}})}),Ft(b,$t([s]))}}),w=c.useCallback(C=>{v([e],C)},[v,e]),S=c.useCallback(()=>{p([e])},[p,e]),N=c.useCallback(()=>{y({body:{messageIds:[e],isRead:!a}})},[y,e,a]),R=[];return l&&R.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?n.jsx(Vn,{className:"size-4 text-positive"}):n.jsx(Xs,{className:"size-4"}),onSelect:()=>g(l,u)}),d&&R.push({key:"raw",label:f?"Show formatted":"Show raw email",icon:n.jsx(Tl,{className:"size-4"}),onSelect:d}),n.jsx(Wl,{hasThread:!0,onReply:m,onReplyAll:h,onForward:x,isStarred:o,onToggleStar:i,onDelete:S,isRead:a,onToggleRead:N,overflowItems:R,moveSlot:r?n.jsx(cn,{accountId:r,currentMailboxId:s,onMove:w,label:"Move this message"}):void 0})},kv=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading raw email",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"})]}),Cv=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:r,isError:a,error:o,refetch:i}=ce({...Xd({path:{messageId:e}}),enabled:t});if(r)return n.jsx("div",{className:"message-body",children:n.jsx(kv,{})});if(a)return n.jsx("div",{className:"message-body",children:n.jsx(At,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const l=s?.raw??"";return l===""?n.jsx("div",{className:"message-body",children:n.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):n.jsx("div",{className:"message-body",children:n.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:l})})},Nv=()=>n.jsx(Vn,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),hu=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),pu=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:pe("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":pe("text-fg-subtle hover:text-warning",r&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:n.jsx(Rt,{className:pe("size-3.5",e&&"fill-current")})}),Ev=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:r,isStarPending:a})=>{const o=ml(e.sentDate,"datetime"),i=hu(e,o);return n.jsx(Ql,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:n.jsxs(n.Fragment,{children:[e.hasAttachment&&n.jsx(Qn,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx(pu,{isStarred:e.hasStars,onToggleStar:r,isStarPending:a,hoverReveal:!0}),n.jsx("span",{"data-testid":"message-date",className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:o})]})})},Iv=({threadMessage:e,messageData:t,isLoading:s,isError:r,error:a,onRetry:o,isFocused:i,onToggle:l,onToggleStar:u,isStarPending:f,accountId:d,showRaw:m,onToggleRaw:h,mobile:x,onReply:b,onReplyAll:p,onForward:v})=>{const g=ml(e.sentDate,"long"),y=!e.isRead,w=t?.envelope.from[0]?.flags?.trusted?.value===!0,S=t?.envelope.from[0]?.addressId,N=hu(e,g),R=e.autoMoved?n.jsx(_c,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"md"}):null;return n.jsx(Yl,{message:N,isFocused:x?!1:i,onHeaderClick:l,senderBadge:w?n.jsx(Nv,{}):void 0,trailing:n.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:g}),to:t?n.jsx(Rm,{label:"To",addresses:t.envelope.to}):null,indicators:R||!x?n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[R,!x&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n.jsx(pu,{isStarred:e.hasStars,onToggleStar:u,isStarPending:f}),e.hasAttachment&&n.jsx("span",{className:"text-fg-subtle p-0.5",children:n.jsx(Qn,{className:"size-3.5"})})]}),y&&n.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:x?void 0:n.jsx(pv,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:S,isTrusted:w,showRaw:m,onToggleRaw:h}),actionBar:x?n.jsx(Sv,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:S,isTrusted:w,showRaw:m,onToggleRaw:h,onReply:b,onReplyAll:p,onForward:v}):void 0,body:s?n.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):r&&Jd(a)?n.jsx("div",{className:"mt-3",children:n.jsx(Lc,{message:"This message has been deleted"})}):r?n.jsx("div",{className:"mt-3",children:n.jsx(At,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):m?n.jsx("div",{className:"mt-3",children:n.jsx(Cv,{messageId:e.messageId})}):n.jsx("div",{className:"mt-3",children:n.jsx(mu,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:w,category:er(e.category)})})})},Tv=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,mobile:l,onReply:u,onReplyAll:f,onForward:d})=>{const[m,h]=c.useState(!1),{data:x,isLoading:b,isError:p,error:v,refetch:g}=ce({...va({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?n.jsx(Iv,{threadMessage:e,messageData:x,isLoading:b,isError:p,error:v,onRetry:()=>g(),isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,showRaw:m,onToggleRaw:()=>h(y=>!y),mobile:l,onReply:u,onReplyAll:f,onForward:d}):n.jsx(Ev,{threadMessage:e,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o})},Rv=()=>n.jsxs("div",{className:"animate-pulse p-4",children:[n.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),n.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>n.jsxs("div",{className:"flex gap-3 py-3",children:[n.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function Ei({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?n.jsxs("div",{className:"flex items-start gap-2 rounded-none border-b border-danger/20 bg-danger-soft px-5 py-2.5 text-sm",children:[n.jsx(Ns,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",n.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&n.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const Is=({threadId:e,mailboxId:t,subject:s,selectedMessageId:r,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:l,onComposeClose:u,onSwipeNext:f,onSwipePrevious:d,mobileIntelligenceOpen:m})=>{const h=Lt(),{handlers:x}=gb({onSwipeLeft:f,onSwipeRight:d}),{accountId:b}=$c(t),{data:p,isLoading:v,isError:g,error:y,refetch:w}=ce({...Zd({path:{threadId:e}})}),S=c.useMemo(()=>p?.items??[],[p?.items]),N=S[S.length-1],R=c.useRef(new Map),[C,k]=c.useState(new Set),[D,O]=c.useState(null),[A,P]=c.useState(0);c.useEffect(()=>{if(S.length>0&&e!==D){O(e);const J=new Set([S[S.length-1].threadMessageId]);if(r){const ae=S.find(de=>de.messageId===r);ae&&J.add(ae.threadMessageId)}k(J),P(S.length-1)}},[e,S,D,r]);const E=c.useCallback(J=>{k(ae=>{const de=new Set(ae);return de.has(J)?de.delete(J):de.add(J),de})},[]),j=c.useCallback(J=>{const ae=S[J];if(!ae)return;R.current.get(ae.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[S]),I=c.useCallback(()=>{if(S.length===0)return;const J=Math.min(A+1,S.length-1);P(J),j(J)},[S.length,A,j]),L=c.useCallback(()=>{if(S.length===0)return;const J=Math.max(A-1,0);P(J),j(J)},[S.length,A,j]),T=c.useCallback(()=>{const J=S[A];J&&E(J.threadMessageId)},[S,A,E]),{data:F}=ce({...gt(),staleTime:1/0}),M=F?.accounts?.[0],$=!!M?.smtpHost;fb({messages:S,expandedIds:C,threadId:e,mailboxId:t,accountId:M?.accountId});const{toggleStar:K,isPending:_,pendingMessageId:X}=Ba({threadId:e,mailboxId:t,messages:S}),[ee,Y]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(Y(l),u?.())},[l,u]);const{data:me}=ce({...va({path:{messageId:N?.messageId??""}}),enabled:!!N&&ee!==null}),ue=c.useCallback(()=>{Y("reply")},[]),te=c.useCallback(()=>{Y("reply_all")},[]),q=c.useCallback(()=>{Y("forward")},[]),U=c.useCallback(()=>{Y(null),u?.()},[u]);if(za({enabled:!v&&S.length>0&&ee===null,bindings:[{key:"j",handler:I,preventDefault:!0},{key:"ArrowDown",handler:I,preventDefault:!0},{key:"k",handler:L,preventDefault:!0},{key:"ArrowUp",handler:L,preventDefault:!0},{key:"Enter",handler:T,preventDefault:!0},{key:"o",handler:T,preventDefault:!0},...$?[{key:"r",handler:ue,preventDefault:!0},{key:"R",handler:te,noModifiers:!1,preventDefault:!0},{key:"f",handler:q,preventDefault:!0}]:[]]}),v)return n.jsx(Rv,{});if(g)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(At,{title:"Couldn't load this conversation",error:y,onRetry:()=>w()})});if(S.length===0)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(Lc,{message:"No messages in this thread"})});const re=s||S[0]?.subject||"(No subject)",Pe=S.length,Re=J=>n.jsx("div",{children:S.map((ae,de)=>n.jsx("div",{ref:B=>{B&&R.current.set(ae.threadMessageId,B)},children:n.jsx(Tv,{threadMessage:ae,isExpanded:C.has(ae.threadMessageId),isFocused:de===A,onToggle:()=>E(ae.threadMessageId),onToggleStar:()=>K(ae.messageId,ae.hasStars),isStarPending:_&&X===ae.messageId,accountId:b,mobile:J,onReply:J&&$?ue:void 0,onReplyAll:J&&$?te:void 0,onForward:J&&$?q:void 0})},ae.threadMessageId))}),V=n.jsxs("header",{className:"border-b border-line px-5 pt-5 pb-3",children:[n.jsx("h1",{className:"max-w-2xl text-lg font-semibold leading-snug text-fg",children:re}),n.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Pe," ",Pe===1?"message":"messages"]})]});return h?n.jsxs("article",{className:"h-full flex flex-col",children:[V,a?.dkimMismatch&&n.jsx(Ei,{authenticity:a,onOpenIntelligence:o}),n.jsx("div",{className:"flex-1 overflow-auto",children:Re(!1)}),ee!==null&&n.jsx(gi,{mode:ee,account:M,sourceMessage:me,onClose:U})]}):n.jsxs(Ch,{thread:{subject:re,messages:[]},onBack:i??(()=>{}),intelligenceOpen:m,onToggleIntelligence:o,touchHandlers:x,children:[a?.dkimMismatch&&n.jsx(Ei,{authenticity:a,onOpenIntelligence:o}),Re(!0),ee!==null&&n.jsx(gi,{mode:ee,account:M,sourceMessage:me,onClose:U})]})};function Ts(){const{mailboxNameIndex:e,accountNameIndex:t}=Se();return{...ht({select:r=>Cc(r.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Qa=e=>e.trim().toLocaleLowerCase(),Mv=/^\d{4}-\d{2}-\d{2}$/;function Ii(e,t,s){if(!Mv.test(s))return;const r=Date.parse(`${s}T00:00:00Z`);if(!Number.isNaN(r))return{type:e,raw:t,value:s,epochSeconds:Math.floor(r/1e3)}}function Av(e,t){const s=e.toLowerCase();if(s.startsWith("from:")&&e.length>5)return{type:"from",raw:e,value:e.slice(5)};if(s==="has:attachment")return{type:"hasAttachment",raw:e};if(s==="is:unread")return{type:"isUnread",raw:e};if(s.startsWith("before:")&&e.length>7)return Ii("before",e,e.slice(7));if(s.startsWith("after:")&&e.length>6)return Ii("after",e,e.slice(6));if(s.startsWith("in:")&&e.length>3){const r=e.slice(3),a=t.mailboxesByName?.get(r.toLowerCase());return a?{type:"in",raw:e,value:r,mailboxId:a}:void 0}if(s.startsWith("account:")&&e.length>8){const r=e.slice(8),a=t.accountsByName?.get(r.toLowerCase());return a?{type:"account",raw:e,value:r,accountId:a}:void 0}}function Rs(e,t={}){const s=e.split(/\s+/).filter(o=>o.length>0),r=[],a=[];for(const o of s){const i=Av(o,t);i?r.push(i):a.push(o)}return{freeText:a.join(" "),tokens:r}}function Dv(e,t){return e.split(/\s+/).filter(s=>s.length>0&&s!==t.raw).join(" ")}function Ov(e){switch(e.type){case"from":return`From: ${e.value}`;case"hasAttachment":return"Has attachment";case"isUnread":return"Unread";case"before":return`Before ${e.value}`;case"after":return`After ${e.value}`;case"in":return`In: ${e.value}`;case"account":return`Account: ${e.value}`}}const Pv=20,Lv=new Set(Object.values(at)),$v=e=>e!==void 0&&Lv.has(e)?e:void 0;function gu({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Se(),r=Ts(),a=ht({select:y=>y.matches}),o=Qa(s),{freeText:i,tokens:l}=Rs(o,r),u=i.length>0,f=$v(t),d=l.some(y=>y.type==="hasAttachment")?!0:void 0,m=l.some(y=>y.type==="isUnread")?!1:void 0,h=l.find(y=>y.type==="after"),x=l.find(y=>y.type==="before"),b=l.find(y=>y.type==="in"),p=kx({matches:a,callerMailboxId:e,inTokenMailboxId:b?.mailboxId}),{data:v,isLoading:g}=ce({...il({query:{query:i,mailboxId:p,limit:Pv,...f!==void 0?{category:f}:{},...d!==void 0?{hasAttachment:d}:{},...m!==void 0?{isRead:m}:{},...h?{sentDateFrom:h.epochSeconds}:{},...x?{sentDateTo:x.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:v?.items??[],isLoading:u&&g}}const Fv=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),zv=e=>[...e].sort(Fv);function ta(e){const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId??e.accountConfigId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Dt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:er(e.category),suspicious:t}}function _v(e,t){const s=new Set,r=[];for(const a of[...e,...t])s.has(a.id)||(s.add(a.id),r.push(a));return r.sort((a,o)=>(o.sentDate??0)-(a.sentDate??0))}const Ti=[{id:"personal",label:"Personal",category:at.personal},{id:"transactional",label:"Transactional",category:at.transactional},{id:"newsletter",label:"Newsletter",category:at.newsletter},{id:"marketing",label:"Marketing",category:at.marketing},{id:"social",label:"Social",category:at.social},{id:"automated",label:"Automated",category:at.automated},{id:"uncategorized",label:"Unclassified",category:at.uncategorized}];function Bv(e){const t=new Map(Ti.map(r=>[r.category,[]]));for(const r of e){const a=r.category??at.uncategorized;(t.get(a)??t.get(at.uncategorized))?.push(r)}const s=[];for(const r of Ti){const a=t.get(r.category);a&&a.length>0&&s.push({id:r.id,label:r.label,threads:a})}return s}function xu(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function bu(e,t){return t.every(s=>{switch(s.type){case"from":{const r=s.value.toLowerCase();return e.fromEmail.toLowerCase().includes(r)||e.fromName.toLowerCase().includes(r)}case"hasAttachment":return e.hasAttachment===!0;case"isUnread":return!e.isRead;case"after":return e.sentDate!=null&&e.sentDate>=s.epochSeconds*1e3;case"before":return e.sentDate!=null&&e.sentDate<s.epochSeconds*1e3;case"in":return e.mailboxId===s.mailboxId;case"account":return e.accountId===s.accountId;default:return!1}})}const Kv={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function Uv(e){return Kv[e]??e}function qv(e,t){const{folder:s}=ya(t,[e.mailboxId]);return{id:e.messageId,sender:e.fromName??e.fromEmail??"Unknown",subject:e.subject??"(No subject)",snippet:e.snippet??"",date:Dt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function vu(e,t){const{folder:s}=ya(t,e.mailboxId?[e.mailboxId]:[]);return{id:e.id,sender:e.fromName,subject:e.subject,snippet:e.snippet,date:e.timeLabel,unread:!e.isRead,flagged:e.starred===!0,...e.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function Hv(e,t){const{mailboxId:s,folder:r}=ya(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?Dt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:Uv(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...r?{folder:r}:{}}}function yu(e,t,s){const r=new Set(t),a=[];for(const o of[...e].sort((i,l)=>l.score-i.score))r.has(o.threadId)||(r.add(o.threadId),a.push(Hv(o,s)));return a}const Wv=768,Vv=1024,wu=e=>e!=="desktop",ar=()=>{const e=Jr(`(min-width: ${Wv}px)`);return Jr(`(min-width: ${Vv}px)`)?"desktop":e?"tablet":"phone"},ju="remit.recentSearches",Qv=5;function sa(){try{const e=localStorage.getItem(ju);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Ri(e){const t=e.trim();if(!t)return sa();const s=[t,...sa().filter(r=>r!==t)].slice(0,Qv);try{localStorage.setItem(ju,JSON.stringify(s))}catch{return s}return s}const Yv=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function Gv(e){const{spam:t}=Jl([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let r;for(const[a,o]of s)(!r||o>r.count)&&(r={mailboxId:a,count:o});return r}function Su({title:e,unreadCount:t,children:s,footer:r,searchFilter:a,searchResults:o,searchLoading:i,relatedResults:l,relatedLoading:u,onSelectSearchResult:f,searchResultsLabel:d="Top matches",relatedResultsLabel:m="Related",searchResultsInBody:h=!1}){const{accounts:x,resultFolderIndex:b,searchQuery:p,searchInput:v,onSearchChange:g,onSearchClear:y,searchViewKey:w}=Se(),S=Ts(),N=De(),R=ks(),C=ar(),[k,D]=c.useState(!1),[O,A]=c.useState(sa),P=c.useRef(w);c.useEffect(()=>{P.current!==w&&(P.current=w,D(!1))},[w]);const E=v.trim().length>0,j=Rs(v,S).tokens.map(U=>({label:Ov(U),onRemove:()=>g(Dv(v,U))})),I=o??[],L=l??[],T=E?[{id:"top",label:d,results:I},{id:"related",label:m,results:L}]:[],M=!(I.length+L.length>0)&&(i===!0||u===!0),{scope:$}=Ic(x),K=ht({select:U=>U.matches}),_=Nc(K),X=Nx(K,$,_?b.get(_)?.role:void 0),ee=X.kind==="global"?Gv([...I,...L]):void 0,Y=ee?{kind:"global",onScopeToSpam:()=>N({to:"/mail/$mailboxId",params:{mailboxId:ee.mailboxId},search:{q:p||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:X;if(C==="phone"&&k){const U=re=>{A(Ri(v)),D(!1),f?.(re)};return n.jsx(ap,{value:v,onChange:g,onClear:y,onCancel:()=>{D(!1),y()},filter:a,recentSearches:O,onPickRecent:g,sections:T,loading:M,onSelectResult:U,tokens:j,scope:Y})}const me=Yv({tier:C,hasLiveInput:E,hasCommittedQuery:p.trim().length>0,bodyRendersCommittedResults:h}),ue=U=>{A(Ri(v)),f?.(U)},te=n.jsx(Zl,{value:v,sections:T,loading:M,onSelectResult:ue,tokens:j,scope:Y}),q=me?a?n.jsx(ia,{...a,children:te}):n.jsx("div",{className:"h-full overflow-y-auto",children:te}):s;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsx(Gh,{title:e,unreadCount:t,isDesktop:!1,showSearch:wu(C),onMenuClick:()=>R?.openNav(),searchValue:v,onSearchChange:g,onSearchClear:y,searchOpen:k,onSearchOpenChange:D}),n.jsx("div",{className:"min-h-0 flex-1",children:q}),r]})}const Ya=({isOpen:e,title:t,description:s,confirmLabel:r,cancelLabel:a="Cancel",destructive:o=!1,isBusy:i=!1,onConfirm:l,onCancel:u})=>{const f=c.useRef(null),d=c.useCallback(m=>{m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),m.stopImmediatePropagation(),u())},[u]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[e,d]),c.useEffect(()=>{e&&f.current?.focus()},[e]),e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm","aria-hidden":"true",onClick:u}),n.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":t,className:pe("relative z-10 w-full max-w-sm","bg-surface border border-line rounded-sm shadow-lg","p-6"),onClick:m=>m.stopPropagation(),onKeyDown:m=>m.stopPropagation(),children:[n.jsx("h2",{className:"text-lg font-semibold",children:t}),s&&n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:s}),n.jsxs("div",{className:"mt-6 flex items-center justify-end gap-2",children:[n.jsx("button",{ref:f,type:"button",onClick:u,className:pe("min-h-11 inline-flex items-center justify-center px-4 rounded text-sm font-medium transition-colors","border border-line hover:bg-surface-raised"),children:a}),n.jsx("button",{type:"button",onClick:l,disabled:i,className:pe("min-h-11 inline-flex items-center justify-center px-4 rounded text-sm font-medium transition-colors",o?"bg-danger text-canvas hover:bg-danger/90":"bg-accent text-accent-fg hover:bg-accent-hover","disabled:opacity-50 disabled:cursor-not-allowed"),children:r})]})]})]}):null},Xv=(e,t,s)=>{const r=e.indexOf(s);if(r===-1)return[];const a=t===void 0?-1:e.indexOf(t);if(a===-1)return[s];const o=Math.min(a,r),i=Math.max(a,r);return e.slice(o,i+1)},Jv=(e,t,s,r)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:r,Zv=(e,t)=>{const s=new Set(t),r=new Set;for(const a of e)s.has(a)&&r.add(a);return r},ku=(e,t,s)=>{if(e.length===0)return;const r=t===void 0?-1:e.indexOf(t);if(r===-1)return s>0?e[0]:e[e.length-1];const a=Math.min(Math.max(r+s,0),e.length-1);return e[a]},Cu=e=>{const[t,s]=c.useState(new Set),[r,a]=c.useState(void 0),o=c.useCallback(p=>t.has(p),[t]),i=c.useCallback(p=>{a(p),s(v=>{const g=new Set(v);return g.has(p)?g.delete(p):g.add(p),g})},[]),l=c.useCallback(p=>{a(p),s(v=>{if(v.has(p))return v;const g=new Set(v);return g.add(p),g})},[]),u=c.useCallback(p=>{s(v=>{if(!v.has(p))return v;const g=new Set(v);return g.delete(p),g})},[]),f=c.useCallback(p=>{s(new Set(p))},[]),d=c.useCallback(()=>{a(void 0),s(new Set)},[]),m=c.useCallback(p=>{s(v=>p.every(y=>v.has(y))?new Set:new Set(p))},[]),h=c.useCallback(p=>{a(p)},[]),x=c.useCallback(p=>{s(v=>{if(v.size===0)return v;const g=Zv(v,p);return g.size===v.size?v:g})},[]),b=c.useCallback((p,v,g)=>{const y=Jv(p,r,g,v);s(w=>{const S=Xv(p,y,v);if(S.length===0)return w;const N=new Set(w);for(const R of S)N.add(R);return N}),a(y)},[r]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:l,deselect:u,selectAll:f,clearSelection:d,toggleAll:m,selectRange:b,setAnchor:h,anchorId:r,intersectWith:x}},Nu=(e,t)=>!t&&e>0,ey=(e,t)=>e==="BACK"&&t,ty=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:r})=>{const[a,o]=c.useState(s),i=Cu(),{selectedCount:l,toggle:u,clearSelection:f,selectRange:d,setAnchor:m,selectAll:h}=i,x=Nu(l,t),b=c.useRef(null),p=c.useRef(!1),v=c.useCallback(()=>{r?.(),f()},[f,r]),g=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),y=c.useCallback(E=>{if(E<0||E>=e.length)return;const j=e[E];if(x){u(j);return}b.current=j,p.current=!1,o(j)},[e,x,u]),w=c.useCallback(()=>{e.length!==0&&y(g<0?0:Math.min(g+1,e.length-1))},[e.length,g,y]),S=c.useCallback(()=>{e.length!==0&&y(g<=0?0:g-1)},[e.length,g,y]),N=c.useCallback(()=>y(0),[y]),R=c.useCallback(()=>y(e.length-1),[y,e.length]),C=c.useCallback(()=>{a&&u(a)},[a,u]),k=c.useCallback((E,j)=>j.shiftKey?(d(e,E,a),!0):j.metaKey||j.ctrlKey?(u(E),!0):(v(),m(E),!1),[e,a,d,u,v,m]),D=c.useCallback(E=>{const j=ku(e,a,E);j!==void 0&&(d(e,j),b.current=j,p.current=!1,o(j))},[e,a,d]),O=c.useCallback(()=>D(-1),[D]),A=c.useCallback(()=>D(1),[D]),P=c.useCallback(()=>{e.length>0&&h(e)},[e,h]);return{focusedMessageId:a,setFocusedMessageId:o,focusIndex:g,pendingDomFocusRef:b,cursorMovedByPointerRef:p,selection:i,isMultiSelectMode:x,exitSelection:v,moveFocusToIndex:y,focusNext:w,focusPrevious:S,focusFirst:N,focusLast:R,toggleFocusedSelection:C,extendRangeUp:O,extendRangeDown:A,selectAllLoaded:P,handleRowSelect:k}};function Eu(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Iu=({selectedCount:e,onDelete:t,onClearSelection:s,onMarkAsRead:r,onMove:a,onOrganize:o,isDeleting:i=!1,isMoving:l=!1,accountId:u,currentMailboxId:f,moveDisabledHint:d,selectAll:m,statusLabel:h,isCounting:x=!1,progress:b,notice:p})=>{if(e===0)return null;const v=b!==void 0,g=i||l||v,y=!v&&!x,w=!!a&&!!u&&!!f,S=!!o&&!!u&&!!f&&!d&&!h,N=m?.checked?`All ${e} loaded selected`:`${e} ${e===1?"message":"messages"} selected`;return n.jsxs("div",{className:"sticky top-0 z-10 flex flex-col bg-surface-sunken border-b border-line",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:s,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded hover:bg-surface-raised transition-colors","aria-label":"Clear selection",children:n.jsx(We,{className:"size-4 text-fg-muted"})}),m&&n.jsx("label",{className:"flex size-11 shrink-0 cursor-pointer items-center justify-center",children:n.jsx(tn,{"aria-label":"Select all",checked:m.checked,indeterminate:m.indeterminate,onChange:m.onChange})}),n.jsx("span",{className:"text-sm font-medium",children:h??N}),d&&!p&&n.jsx("span",{className:"text-xs text-fg-muted",role:"status","aria-live":"polite",children:d})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[S&&o&&n.jsxs("button",{type:"button",onClick:g?void 0:o,className:"min-h-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Organize similar messages",children:[n.jsx(pt,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:"Organize"})]}),y&&r&&n.jsx("button",{type:"button",onClick:g?void 0:r,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Mark as read","aria-busy":g,children:n.jsx(Cs,{className:"size-4"})}),y&&w&&a&&u&&f&&n.jsx(cn,{accountId:u,currentMailboxId:f,onMove:g?()=>{}:a,disabledHint:d,variant:"icon-only",label:"Move selected messages"}),y&&n.jsxs("button",{type:"button",onClick:g?void 0:t,className:pe("min-h-11 min-w-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors","bg-danger text-canvas hover:bg-danger/90"),"aria-label":"Delete selected messages","aria-busy":i,children:[i?n.jsx(xt,{className:"size-4 animate-spin"}):n.jsx(st,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:i?"Deleting...":"Delete"})]})]})]}),b&&n.jsx("div",{className:"px-3 pb-2",children:n.jsx(Ta,{value:b.value,max:b.max,tone:b.tone})}),p&&n.jsx(Gt,{tone:p.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-3 mb-2",children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[p.text&&n.jsx("span",{children:p.text}),p.action&&n.jsx("button",{type:"button",onClick:p.action.onClick,className:"-my-1 min-h-11 shrink-0 inline-flex items-center px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised",children:p.action.label})]})})]})},Ga=c.createContext(null),sy=e=>{const t=c.useContext(Ga);return t?t.rowInteraction(e):null},ny=()=>{const e=c.useContext(Ga);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},ry="[data-message-id]",ay=e=>Array.from(e.querySelectorAll(ry)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),oy=(e,t)=>e.length===t.length&&e.every((s,r)=>s===t[r]),iy=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const r=e.current;if(!r)return;const a=()=>{const i=ay(r);s(l=>oy(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(r,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function Tu({selectedMessageId:e,onOpen:t,onDeleteMessages:s,isDeleting:r=!1,commandsRef:a,onTriageContextChange:o,children:i}){const l=Lt(),u=c.useRef(null),f=iy(u),d=ty({orderedIds:f,isDesktop:l,initialFocusedId:e}),{focusedMessageId:m,setFocusedMessageId:h,pendingDomFocusRef:x,cursorMovedByPointerRef:b,selection:p,isMultiSelectMode:v,exitSelection:g,handleRowSelect:y}=d,{selectedIds:w,selectedCount:S,isSelected:N,toggle:R,select:C}=p,{intersectWith:k}=p;c.useEffect(()=>{k(f)},[k,f]),c.useEffect(()=>{const Y=x.current;Y!==null&&(x.current=null,u.current?.querySelector(`[data-message-id="${Y}"]`)?.focus())});const D=c.useCallback(Y=>{b.current=!0,h(Y)},[b,h]),O=c.useCallback(Y=>{l||C(Y)},[l,C]),A=c.useCallback(()=>{m&&t(m)},[m,t]),[P,E]=c.useState(null),j=c.useCallback(Y=>!s||Y.length===0?!1:(E(Y),!0),[s]),I=c.useCallback(()=>{j(Array.from(w))},[j,w]),L=c.useCallback(()=>P!==null?!0:S>0?j(Array.from(w)):m?j([m]):!1,[P,S,w,m,j]),T=c.useCallback(()=>{P!==null&&(s?.(P),E(null),g())},[P,s,g]),F=c.useCallback(()=>E(null),[]),M=c.useCallback(()=>S===0?!1:(g(),!0),[S,g]),$=f.length>0;c.useEffect(()=>{if(a){if(!$){a.current=null;return}return a.current={focusNext:d.focusNext,focusPrevious:d.focusPrevious,focusFirst:d.focusFirst,focusLast:d.focusLast,openFocused:A,toggleSelect:d.toggleFocusedSelection,extendSelectDown:d.extendRangeDown,extendSelectUp:d.extendRangeUp,selectAll:d.selectAllLoaded,clearSelection:M,requestDelete:L,toggleDensity:()=>{}},()=>{a.current=null}}},[a,$,d.focusNext,d.focusPrevious,d.focusFirst,d.focusLast,d.toggleFocusedSelection,d.extendRangeDown,d.extendRangeUp,d.selectAllLoaded,A,M,L]);const K=c.useMemo(()=>Array.from(w),[w]),_=P!==null;c.useEffect(()=>{o?.({focusedMessageId:m,selectedIds:K,orderedIds:f,hasList:$,blocksKeyboard:_})},[o,m,K,f,$,_]);const X=Eu(f,m),ee=c.useMemo(()=>({selectedIds:w,selectedCount:S,exitSelection:g,requestDeleteSelection:I,rowInteraction:Y=>({focused:Y===m,isTabStop:Y===X,isDesktop:l,onFocusRow:D,selection:{isChecked:N(Y),onToggleCheck:R,onRowSelect:y,isMultiSelectMode:v,onLongPress:O}})}),[w,S,g,I,m,X,l,D,N,R,y,v,O]);return n.jsxs(Ga.Provider,{value:ee,children:[n.jsx("div",{ref:u,className:"contents",children:i}),n.jsx(Ya,{isOpen:_,title:hl(P?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:r,onConfirm:T,onCancel:F})]})}function Ru({onMarkAsRead:e,isDeleting:t}){const{selectedIds:s,selectedCount:r,exitSelection:a,requestDeleteSelection:o}=ny(),i=c.useCallback(()=>{e?.(Array.from(s)),a()},[e,s,a]);return n.jsx(Iu,{selectedCount:r,onDelete:o,onClearSelection:a,onMarkAsRead:e?i:void 0,isDeleting:t})}const ly=({thread:e,active:t=!1,focused:s,isTabStop:r,density:a="comfortable",isDesktop:o,badge:i,selection:l,inListbox:u=!1,linkMailboxId:f,onClick:d,onFocusRow:m})=>{const h=ye(),x=e.id,b=sy(x),p=s??b?.focused??!1,v=r??b?.isTabStop??!1,g=l??b?.selection,y=m??b?.onFocusRow,w=o??b?.isDesktop??!0,S=g?.isChecked??!1,N=g?.isMultiSelectMode??!1,R=g?.onToggleCheck,C=g?.onRowSelect,k=g?.onLongPress,D=c.useCallback(M=>{M.preventDefault(),M.stopPropagation(),R?.(x)},[R,x]),O=c.useCallback(M=>{if(!w){if(N){M.preventDefault(),M.stopPropagation(),R?.(x);return}d?.();return}const $={shiftKey:M.shiftKey,metaKey:M.metaKey,ctrlKey:M.ctrlKey};if(C?.(x,$)){M.preventDefault(),M.stopPropagation(),$.shiftKey&&window.getSelection()?.removeAllRanges();return}d?.()},[w,N,R,C,d,x]),A=c.useCallback(M=>{w&&M.shiftKey&&M.preventDefault()},[w]),P=c.useCallback(()=>{k?.(x)},[k,x]),{longPressProps:E}=Ul({onLongPress:P,delayMs:500,accessibilityDescription:S?"Deselect message":"Select message"}),j=c.useCallback(()=>{h.prefetchQuery(va({path:{messageId:x}}))},[h,x]),I=c.useCallback(()=>{j(),y?.(x)},[j,y,x]),L=Js({"data-list-row":"","data-message-row":!0,"data-message-id":x,...u?{role:"option","aria-selected":S}:{},tabIndex:v?0:-1,onClick:O,onMouseDown:A,onMouseEnter:j,onFocus:I},w||!g?{}:E),T=pe(a==="compact"?_l({active:t,focused:p}):pe("group",en({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",S&&"bg-accent-soft",!w&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?n.jsx(Bl,{thread:e}):n.jsx(Kl,{thread:e,badge:i,selection:g?{checked:S,alwaysVisible:N,onToggle:D}:void 0});return f===void 0?n.jsx("button",{type:"button",...L,className:T,children:F}):n.jsx(mt,{to:"/mail/$mailboxId",params:{mailboxId:f},search:M=>({...M,selectedMessageId:x}),...L,className:T,children:F})},Xa=c.memo(ly),cy=200,uy={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0,contacts:e=>e.trust==="vip"||e.trust==="wellknown",today:e=>e.sentDate!=null&&new Date(e.sentDate).toDateString()===new Date().toDateString()},Mi=()=>n.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>n.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[n.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsxs("div",{className:"flex justify-between gap-2",children:[n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),dy=({accountEmail:e})=>{const t=De();return n.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[n.jsx(Yt,{className:"size-3.5 shrink-0"}),n.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),n.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})};function fy({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:r,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i,onMarkMessagesRead:l}){const{searchQuery:u,resultFolderIndex:f}=Se(),d=Ts(),m=Lt(),h=c.useMemo(()=>zv(e.filter(q=>!q.muted?.value)),[e]),[x,b]=c.useState("all"),[p,v]=c.useState("all"),[g,y]=c.useState(new Set),[w,S]=c.useState(!1),N=c.useCallback(q=>{y(U=>{const re=new Set(U);return re.has(q)?re.delete(q):re.add(q),re})},[]),{data:R,isLoading:C,isError:k,refetch:D}=ce({...Br(),staleTime:6e4}),O=Pt({queries:h.map(q=>({...Ve({path:{accountId:q.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),A=c.useMemo(()=>{const q=new Map;for(let U=0;U<h.length;U++){const re=h[U].accountId,Re=(O[U]?.data?.items??[]).reduce((V,J)=>V+(J.unseenCount??0),0);q.set(re,Re)}return q},[h,O]),P=c.useMemo(()=>h.filter((q,U)=>{const re=O[U];return re?.isError?!Kr(re.error):!1}),[h,O]),{freeText:E,tokens:j}=Rs(u.trim().toLowerCase(),d),{data:I,isFetching:L}=ce({...Br({query:{query:E,limit:cy}}),enabled:E.length>0,staleTime:3e4}),T=c.useMemo(()=>{const q=(R?.items??[]).map(ta);return(E?_v(q.filter(re=>xu(re,E)),(I?.items??[]).map(ta)):q).filter(re=>(x==="all"||re.accountId===x)&&bu(re,j))},[R,I,x,E,j]),F=c.useMemo(()=>Bv(T),[T]),M=c.useMemo(()=>h.length<=1?[]:[{id:"all",label:"All",active:x==="all"},...h.map(q=>({id:q.accountId,label:q.email.split("@")[0]??q.email,count:A.get(q.accountId),active:x===q.accountId}))],[h,A,x]),$=c.useMemo(()=>e.filter(q=>q.muted?.value).length,[e]),K=c.useMemo(()=>Array.from(A.values()).reduce((q,U)=>q+U,0),[A]),_=c.useMemo(()=>{const q=Array.from(g).map(U=>uy[U]).filter(U=>U!=null);return T.filter(U=>(p==="all"||U.category===p)&&q.every(re=>re(U))).map(U=>vu(U,f))},[T,p,g,f]),{hits:X,isLoading:ee}=gu(),Y=c.useMemo(()=>{const q=new Map;for(const re of R?.items??[])q.set(re.messageId,re.threadId);const U=_.map(re=>q.get(re.id)).filter(re=>re!=null);return yu(X,U,f)},[X,_,R,f]),me=c.useMemo(()=>{const q=Op(M.map(U=>({id:U.id,label:U.label,count:U.count,active:U.active})));return{categories:q.categories,filters:q.filters,sources:q.sources,sourcesNote:$>0?`+${$} muted`:void 0,selectedCategory:p,activeFilters:g,expanded:w,onExpandedChange:S,onSelectCategory:U=>v(U),onSelectSource:b,onToggleFilter:N,onClear:()=>{v("all"),b("all"),y(new Set)}}},[M,$,p,g,w,N]),ue=F.length===0&&x==="all"&&E.length===0,te=C?n.jsxs("div",{className:"h-full overflow-y-auto",children:[n.jsx(Mi,{}),n.jsx(Mi,{})]}):k?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[n.jsx(Yt,{className:"size-8 text-danger"}),n.jsx("p",{children:"Couldn't load your messages"}),n.jsxs("button",{type:"button",onClick:()=>D(),className:"flex items-center gap-1 text-accent underline text-xs",children:[n.jsx(Ol,{className:"size-3.5"}),"Try again"]})]}):ue?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[n.jsx(pt,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"You're caught up"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Nothing needs attention."})]}):n.jsx(Tu,{selectedMessageId:t,onOpen:q=>s?.(q),onDeleteMessages:i,commandsRef:a,onTriageContextChange:o,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[i?n.jsx(Ru,{onMarkAsRead:l}):null,n.jsx("div",{className:"min-h-0 flex-1",children:n.jsx(Wi,{sections:F,Row:Xa,manageFocus:!1,briefCategory:p,onSelectBriefCategory:v,sources:M,sourcesNote:$>0?`+${$} muted`:void 0,onSelectSource:b,selectedThreadId:t,onSelectThread:s})})]})});return n.jsx(Su,{title:"Daily brief",unreadCount:K,footer:m?n.jsx(Fl,{}):void 0,searchFilter:me,searchResults:_,searchLoading:C||L,relatedResults:Y,relatedLoading:ee,onSelectSearchResult:r,children:n.jsxs("div",{className:"flex h-full flex-col",children:[P.map(q=>n.jsx(dy,{accountEmail:q.email,accountId:q.accountId},q.accountId)),n.jsx("div",{className:"min-h-0 flex-1",children:te})]})})}const my=10,Mu=e=>({q:e?.toLowerCase()??"",limit:my}),hy=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(r=>r.normalizedEmail===s)};function py(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":On(t,{month:"short",year:"numeric"})}function Au(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const gy="We can't verify the sender of this email, which could mean it's from an insecure source.",xy="We couldn't read this sender's address, so we can't confirm who really sent this message.";function by(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?py(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Au(e.fromEmail)}}function vy(e){return e?.flags?{vip:e.flags.vip?.value===!0,muted:e.flags.muted?.value===!0,blocked:e.flags.blocked?.value===!0,unsubscribed:e.flags.unsubscribed?.value===!0}:{}}function yy(e,t){const s=t>0?t:void 0;if(Au(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:xy,similarCount:s};const r=e.authenticity;if(!r)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:gy};if(!r.dkimMismatch)return{verdict:"aligned",fromDomain:r.fromDomain,dkimDomain:r.dkimDomain,summary:r.dkimDomain?`We verified this message was really sent by ${r.fromDomain}.`:"Nothing looks unusual about this sender."};const a=r.fromDomain,o=r.dkimDomain,i=e.fromName&&e.fromName!==e.fromEmail?e.fromName:void 0,l=i?`The display name claims "${i}", but this message was actually sent from ${o??"another sender"} — not ${a}. Real senders use their own address.`:`This message claims to be from ${a}, but it was actually sent from ${o??"a different sender"}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:l,similarCount:s}}function Du(e,t){const s=e?.fromEmail??null,r=e?.subject??"",{data:a,error:o}=ce({...sl({query:Mu(s??void 0)}),enabled:!!s,staleTime:3e4}),i=hy(a?.items,s??void 0),l=[r,s].filter(Boolean).join(" "),{data:u,isLoading:f,error:d}=ce({...il({query:{query:l,limit:5}}),enabled:!!(e&&l.length>3),staleTime:6e4,retry:1});return{data:c.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(g=>g.messageId!==e.messageId).map(g=>({id:g.messageId,mailboxId:t!=null&&g.mailboxIds.includes(t)?t:g.mailboxIds[0]??"",fromName:g.fromName??"",subject:g.subject??"(No subject)",timeLabel:g.sentDate!=null?Dt(g.sentDate*1e3):"",matched:g.matchedChunkType})),x=by(e,i),b=yy(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},v=vy(i);return{sender:x,authenticity:b,category:p,flags:v,similar:h}},[e,i,u,t]),isSimilarLoading:f,similarError:d,similarErrorIsFatal:Kr(d),addressErrorIsFatal:Kr(o),addressId:i?.addressId,address:i}}function wy(e,t){const s={...e??{}};for(const[r,a]of Object.entries(t))a==null?delete s[r]:s[r]={...a,setAt:a.setAt??Date.now()};return s}function Ou({addressId:e,senderEmail:t}){const s=ye(),{pushError:r}=Ze(),a=ef({query:Mu(t)}),{mutate:o,isPending:i}=ve({...ol(),onMutate:async u=>{const f=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,m=>m&&{...m,items:m.items.map(h=>h.addressId===u.path.addressId?{...h,flags:wy(h.flags,f)}:h)}),{previous:d}},onError:(u,f,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),r({title:"Couldn't update sender preference",detail:ot(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){ll(new Error(`Quick action fired but the sender's address record did not resolve (sender: ${t??"unknown"}). This should never happen — the address row exists.`));return}o({path:{addressId:e},body:{flags:u}})},[e,o,t]),isPending:i}}const jy=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Pu=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function Sy(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function ky(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function Cy(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Lu(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const Ny=["personal","newsletter","marketing","automated","transactional","social"],Ey=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:r}=e;return t?s&&t===s?r?"notSpam":null:s?"markSpam":null:null},Iy=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:r}=e;return t&&!s?"error":r?"loading":"ready"};function Ty(){return n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(pt,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"h-8 rounded bg-surface"})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>n.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function Ry({isOpen:e,current:t,onSelect:s,onCancel:r}){return e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:r,children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),n.jsx("div",{className:"mt-4 flex flex-col gap-1",children:Ny.map(a=>n.jsxs("button",{type:"button",onClick:()=>s(a),className:`flex min-h-11 items-center justify-between rounded px-3 text-left text-sm capitalize transition-colors hover:bg-surface-raised ${a===t?"font-semibold text-accent":"text-fg"}`,children:[a,a===t&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"current"})]},a))}),n.jsx("div",{className:"mt-6 flex justify-end",children:n.jsx("button",{type:"button",onClick:r,className:"inline-flex min-h-11 items-center justify-center rounded border border-line px-4 text-sm font-medium transition-colors hover:bg-surface-raised",children:"Cancel"})})]})]}):null}function My({thread:e,onClose:t,mailboxId:s,accountId:r,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:f}=Du(e,s),[d,m]=c.useState(!1),[h,x]=c.useState(!1),b=e.fromEmail??void 0,{updateFlags:p,isPending:v}=Ou({addressId:i,senderEmail:b}),{junkMailboxId:g}=sr(r),{inboxMailboxId:y}=Ua(r),{moveMessages:w}=Tt({mailboxId:s??"",threadId:e.threadId,accountId:r}),S=Ys(),N=Ey({mailboxId:s,junkMailboxId:g,inboxMailboxId:y}),R=c.useCallback(()=>{y&&w([e.messageId],y)},[y,w,e.messageId]),C=c.useCallback(()=>{g&&(Lu(S,{count:1,senderTrust:e.senderTrust,wasRescuable:Pu(e)}),w([e.messageId],g))},[g,w,e,S]),k=c.useCallback(()=>{},[]),D=c.useCallback(()=>{const M=o?.flags?.vip!==!0;p({vip:{value:M}})},[o?.flags?.vip,p]),O=c.useCallback(()=>{const M=o?.flags?.muted!==!0;p({muted:{value:M}})},[o?.flags?.muted,p]),A=c.useCallback(()=>{o?.flags?.blocked===!0?p({blocked:{value:!1}}):m(!0)},[o?.flags?.blocked,p]),P=c.useCallback(()=>{m(!1),p({blocked:{value:!0}})},[p]),E=c.useCallback(()=>{const M=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:M}})},[o?.flags?.unsubscribed,p]),j=c.useCallback(M=>{x(!1),p({category:{value:M}})},[p]),I=i!==void 0,L={onToggleVip:I?D:void 0,onToggleMute:I?O:void 0,onToggleBlock:I?A:void 0,onToggleUnsubscribe:I?E:void 0,onReclassify:I?()=>x(!0):void 0,onNotSpam:N==="notSpam"?R:void 0,onMarkSpam:N==="markSpam"?C:void 0},T=({mailboxId:M,messageId:$,className:K,ariaLabel:_,children:X})=>n.jsx(mt,{to:"/mail/$mailboxId",params:{mailboxId:M},search:ee=>({...ee,selectedMessageId:$}),className:K,"aria-label":_,children:X});if(!o)return n.jsx(Ty,{});const F=Iy({similarError:u,similarErrorIsFatal:f,isSimilarLoading:l});return n.jsxs(n.Fragment,{children:[n.jsx($l,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:k,actions:L,similarState:F,similarLinkComponent:T,className:"border-l-0 h-full w-full"}),n.jsx(Ya,{isOpen:d,title:"Block this sender?",description:`Messages from ${b??"this sender"} will never load images and will be flagged. You can undo this in Settings → Senders.`,confirmLabel:"Block sender",destructive:!0,isBusy:v,onConfirm:P,onCancel:()=>m(!1)}),n.jsx(Ry,{isOpen:h,current:o.category.value,onSelect:j,onCancel:()=>x(!1)})]})}const Ms=({onClose:e,thread:t,mailboxId:s,accountId:r,hideCloseButton:a})=>t?n.jsx(My,{thread:t,onClose:e,mailboxId:s,accountId:r,hideCloseButton:a}):n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(pt,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[n.jsx(pt,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),Lr="Open a message first",Ja=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:r,onReply:a,onReplyAll:o,onForward:i,onDelete:l,canDelete:u,onToggleStar:f,isStarred:d,moveContext:m})=>{const[h,x]=c.useState(null),b=u??e,p=v=>()=>x(v);return n.jsx(Xm,{hasThread:e,isStarred:d,onUnavailable:v=>x(Lr),unavailableHint:h,replyTitle:`Reply ${ds("reply")}`,replyAllTitle:`Reply all ${ds("replyAll")}`,forwardTitle:`Forward ${ds("forward")}`,deleteTitle:`Move to Trash ${ds("delete")}`,flagTitle:`Star ${ds("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:b?l:p(Lr),onToggleStar:f,onMove:p(Lr),moveSlot:m?n.jsx(cn,{accountId:m.accountId,currentMailboxId:m.currentMailboxId,onMove:m.onMove,label:"Move to mailbox"}):void 0,children:n.jsx(Gm,{open:t,enabled:s,onToggle:r})})},$u=()=>{const e=ye();return c.useCallback(t=>{const s=Jt({path:{threadId:t.threadId}}),a=e.getQueriesData({queryKey:s}).flatMap(([,o])=>o?.items.map(i=>i.messageId)??[]);return a.length>0?a:[t.messageId]},[e])},Vs=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=t??e?.mailboxId,o=s??e?.accountConfigId,i=$u(),{deleteMessages:l}=Qt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{moveMessages:u}=Tt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{toggleStar:f}=Ba({threadId:e?.threadId??"",mailboxId:a??""}),d=c.useCallback(()=>{e&&l(i(e))},[e,i,l]),m=c.useCallback(v=>{e&&u(i(e),v)},[e,i,u]),h=c.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[x,b]=c.useState(null),p=c.useCallback(()=>b(null),[]);return{mailboxId:a,accountId:o,isStarred:e?.hasStars,deleteThread:d,moveThread:m,toggleStar:h,composeRequest:x,requestCompose:b,clearComposeRequest:p}},Ls={action:null,nextPrefix:null,preventDefault:!1},Ay={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},Dy={j:{action:"focusNext"},k:{action:"focusPrevious"},arrowdown:{action:"focusNext"},arrowup:{action:"focusPrevious"},home:{action:"focusFirst"},end:{action:"focusLast"},enter:{action:"openFocused"}," ":{action:"toggleSelect"},delete:{action:"delete"},backspace:{action:"delete"},u:{action:"toggleRead"},x:{action:"toggleSelect"},r:{action:"reply"},a:{action:"replyAll"},f:{action:"forward"},"#":{action:"delete"},s:{action:"toggleStar"},m:{action:"muteSender"},b:{action:"blockSender"},v:{action:"vipSender"},"!":{action:"markJunk"},i:{action:"toggleIntelligence"},d:{action:"toggleDensity"},"/":{action:"focusSearch"},c:{action:"compose"},"?":{action:"help"}};function Oy(e,t){const s=e.key.toLowerCase(),r=e.metaKey||e.ctrlKey;if(e.inEditable)return{...Ls,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...Ls,nextPrefix:t==="g"?null:t};if(r&&s==="n")return{action:"compose",nextPrefix:null,preventDefault:!0};if(r&&s==="a")return{action:"selectAll",nextPrefix:null,preventDefault:!0};if(r)return{...Ls,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=Ay[s===","?",":s]??null;return{action:i,nextPrefix:null,preventDefault:i!==null}}if(s==="g"&&!e.shiftKey)return{action:null,nextPrefix:"g",preventDefault:!0};if(e.shiftKey){const o=s==="j"||s==="arrowdown";if(o||(s==="k"||s==="arrowup"))return{action:o?"extendSelectDown":"extendSelectUp",nextPrefix:null,preventDefault:!0}}const a=Dy[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?Ls:{action:a.action,nextPrefix:null,preventDefault:!0}}return Ls}function Py(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const Ly="data-message-row",$y='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function Fy(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest($y);return t?!t.hasAttribute(Ly):!1}function zy({handlers:e,enabled:t=!0,sequenceTimeoutMs:s=1e3}){const r=c.useRef(e);r.current=e;const a=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{if(!t)return;const i=()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},l=u=>{const f=Oy({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:Py(u.target),onControl:Fy(u.target)},a.current);if(i(),a.current=f.nextPrefix,f.nextPrefix!==null&&(o.current=setTimeout(()=>{a.current=null,o.current=null},s)),f.action===null)return;const d=r.current[f.action];d&&(f.preventDefault&&u.preventDefault(),d())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l),i(),a.current=null}},[t,s])}const Ai=(e,t,s)=>{if(!t)return null;const r=e.indexOf(t);if(r===-1)return null;const a=s==="next"?r+1:r-1;return a<0||a>=e.length?null:e[a]},Za=()=>{const[e,t]=c.useState(void 0),[s,r]=c.useState([]),[a,o]=c.useState([]),i=c.useRef(null),[l,u]=c.useState(!1),[f,d]=c.useState(!1),m=c.useCallback(h=>{t(h.focusedMessageId),r(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:m,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:l,blocksKeyboard:f}},eo=({context:e,orderedIds:t,selectedMessageId:s,enabled:r=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:l,blocksKeyboard:u}=e,f=c.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return zy({enabled:r&&!u,handlers:{...l?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:f,...o}}),{goBack:f,nextMessageId:Ai(t,s,"next")??void 0,previousMessageId:Ai(t,s,"previous")??void 0}};function _y(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function Fu(e,t){if(e)return _y(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const zu=c.createContext(null);function or(){const e=c.useContext(zu);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function By({selectedMessageId:e,children:t}){const s=De(),{searchInput:r}=Se(),{selectedThreadId:a,selectedMailboxId:o}=vs({strict:!1}),{data:i}=ce({...Br(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(O=>O.messageId===e)},[i,e]),u=c.useMemo(()=>Fu(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),f=c.useCallback(O=>{s({to:"/mail",search:A=>({...A,selectedMessageId:O,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),d=c.useCallback(O=>{s({to:"/mail",search:A=>({...A,q:r||void 0,selectedMessageId:O.id,selectedThreadId:O.threadId,selectedMailboxId:O.mailboxId})})},[s,r]),m=c.useCallback(O=>{e&&O.includes(e)&&s({to:"/mail",search:A=>({...A,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=Vs({thread:l,onAfterOptimisticRemove:m}),x=c.useCallback(()=>{s({to:"/mail",search:O=>({...O,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),b=Za(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:v}=Qt({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:m}),{toggleReadFor:g}=Zn({mailboxId:l?.mailboxId??"",messages:p}),y=c.useCallback(O=>g(O,!0),[g]),w=b.focusedMessageId,N=c.useMemo(()=>i?.items.find(O=>O.messageId===w),[i,w])??l,R=Vs({thread:N}),{nextMessageId:C,previousMessageId:k}=eo({context:b,orderedIds:b.orderedIds,selectedMessageId:e,onClose:x,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{b.listCommandsRef.current?.requestDelete()||R.deleteThread()},toggleStar:R.toggleStar,toggleRead:()=>{const O=b.selectedIds.length>0?b.selectedIds:N?[N.messageId]:[];O.length!==0&&g(O,!(N?.isRead??!1))},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),D={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:f,onSelectSearchResult:d,onCloseThread:x,actions:h,triage:b,onDeleteMessages:v,onMarkMessagesRead:y,nextMessageId:C,previousMessageId:k};return n.jsx(zu.Provider,{value:D,children:t})}function _u(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:r,onDeleteMessages:a,onMarkMessagesRead:o}=or(),{accounts:i}=Se();return n.jsx(fy,{accounts:i,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:r.listCommandsRef,onTriageContextChange:r.onTriageContextChange,onDeleteMessages:a,onMarkMessagesRead:o})}function Ky(){const{conversation:e,actions:t}=or(),{intelligenceOpen:s,onToggleIntelligence:r}=Se(),a=ks()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(Ja,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Es,{})})]})}function Uy(){const{selectedThread:e}=or(),{onToggleIntelligence:t}=Se();return n.jsx(Ms,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function qy(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:r,nextMessageId:a,previousMessageId:o}=or(),{intelligenceOpen:i,onToggleIntelligence:l}=Se();return t?n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:r,onOpenIntelligence:l,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:i}),n.jsx($a,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:l,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(_u,{})})}const $s=Object.assign(By,{List:_u,Reading:Ky,Intelligence:Uy,Phone:qy}),Hy=()=>al({query:{starred:!0,order:"desc"}});function Bu(){const{data:e,isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=gc({queryKey:Hy(),queryFn:async({pageParam:f})=>{const{data:d}=await tf({query:{starred:!0,order:"desc",continuationToken:f},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:f=>f.continuationToken,staleTime:6e4});return{threads:c.useMemo(()=>(e?.pages??[]).flatMap(f=>f.items??[]),[e]),isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}}const Wy=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function Ku({title:e,unreadCount:t,preset:s,selectedCategory:r,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:l,onClearFilters:u,children:f,footer:d,searchResults:m,searchLoading:h,relatedResults:x,relatedLoading:b,onSelectSearchResult:p,searchResultsLabel:v,relatedResultsLabel:g,searchResultsInBody:y}){const[w,S]=c.useState(!1),N={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:r,activeFilters:a,expanded:w,onExpandedChange:S,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return n.jsx(Su,{title:e,unreadCount:t,footer:d,searchFilter:N,searchResults:m,searchLoading:h,relatedResults:x,relatedLoading:b,onSelectSearchResult:p,searchResultsLabel:v,relatedResultsLabel:g,searchResultsInBody:y,children:n.jsx(ia,{...N,children:f})})}const Vy={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function Qy({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:r,onDeleteMessages:a,onMarkMessagesRead:o}){const{searchQuery:i,resultFolderIndex:l}=Se(),u=Ts(),f=Lt(),[d,m]=c.useState("all"),[h,x]=c.useState(new Set),b=c.useCallback(T=>{x(F=>{const M=new Set(F);return M.has(T)?M.delete(T):M.add(T),M})},[]),p=c.useCallback(()=>{m("all"),x(new Set)},[]),{threads:v,isLoading:g,isError:y,error:w,refetch:S,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:C}=Bu(),{freeText:k,tokens:D}=Rs(i.trim().toLowerCase(),u),O=c.useMemo(()=>{const T=Array.from(h).map(F=>Vy[F]).filter(F=>F!=null);return Wy(v).map(ta).filter(F=>(d==="all"||F.category===d)&&T.every(M=>M(F))&&(!k||xu(F,k))&&bu(F,D))},[v,d,h,k,D]),A=c.useMemo(()=>Lp(),[]),P=c.useMemo(()=>O.map(T=>vu(T,l)),[O,l]),E=c.useMemo(()=>O.filter(T=>!T.isRead).length,[O]),j=g?"loading":y?"error":O.length===0?"empty":"ready",I=c.useCallback(()=>{const T=ga(pa());window.open(T,"_blank","noopener,noreferrer")},[]),L=n.jsx(Tu,{selectedMessageId:e,onOpen:T=>t?.(T),onDeleteMessages:a,commandsRef:s,onTriageContextChange:r,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a?n.jsx(Ru,{onMarkAsRead:o}):null,n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.jsx("div",{className:"divide-y divide-line",children:O.map(T=>n.jsx(Xa,{thread:T,active:T.id===e,onClick:()=>t?.(T.id)},T.id))}),R?n.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>N(),disabled:C,children:C?"Loading…":"Load more"}):null]})]})});return n.jsx(Ku,{title:"Starred",unreadCount:E,preset:A,selectedCategory:d,activeFilters:h,onSelectCategory:m,onToggleFilter:b,onClearFilters:p,searchResults:P,searchLoading:g,onSelectSearchResult:T=>t?.(T.id),children:n.jsx(Hl,{listTitle:"Starred",sections:[{id:"flagged",threads:O}],flatList:!0,hideHeader:!0,listState:j,searchQuery:k?i:void 0,errorMessage:y?fl(w):void 0,onRetry:()=>S(),onReportError:I,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:f,listBody:j==="ready"?L:void 0})})}const Uu=c.createContext(null);function ir(){const e=c.useContext(Uu);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function Yy({selectedMessageId:e,children:t}){const s=De(),{threads:r}=Bu(),a=c.useMemo(()=>{if(e)return r.find(S=>S.messageId===e)},[r,e]),o=c.useCallback(S=>{s({to:"/mail/flagged",search:N=>({...N,selectedMessageId:S})})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:S=>({...S,selectedMessageId:void 0})})},[s]),l=c.useCallback(S=>{e&&S.includes(e)&&i()},[e,i]),u=Vs({thread:a,onAfterOptimisticRemove:l}),f=Za(),{deleteMessages:d}=Qt({mailboxId:a?.mailboxId??"",messages:r,onAfterOptimisticRemove:l}),{toggleReadFor:m}=Zn({mailboxId:a?.mailboxId??"",messages:r}),h=c.useCallback(S=>m(S,!0),[m]),x=f.focusedMessageId,p=c.useMemo(()=>r.find(S=>S.messageId===x),[r,x])??a,v=Vs({thread:p}),{nextMessageId:g,previousMessageId:y}=eo({context:f,orderedIds:f.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{f.listCommandsRef.current?.requestDelete()||v.deleteThread()},toggleStar:v.toggleStar,toggleRead:()=>{const S=f.selectedIds.length>0?f.selectedIds:p?[p.messageId]:[];S.length!==0&&m(S,!(p?.isRead??!1))},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),w={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:f,onDeleteMessages:d,onMarkMessagesRead:h,nextMessageId:g,previousMessageId:y};return n.jsx(Uu.Provider,{value:w,children:t})}function qu(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:r,onMarkMessagesRead:a}=ir();return n.jsx(Qy,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:r,onMarkMessagesRead:a})}function Gy(){const{selectedThread:e,actions:t}=ir(),{intelligenceOpen:s,onToggleIntelligence:r}=Se(),a=ks()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(Ja,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Es,{})})]})}function Xy(){const{selectedThread:e}=ir(),{onToggleIntelligence:t}=Se();return n.jsx(Ms,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function Jy(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:r,previousMessageId:a}=ir(),{intelligenceOpen:o,onToggleIntelligence:i}=Se();return e?n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:i,onSwipeNext:r?()=>s(r):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:o}),n.jsx($a,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:i,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(qu,{})})}const Fs=Object.assign(Yy,{List:qu,Reading:Gy,Intelligence:Xy,Phone:Jy}),Zy={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},e0=()=>{const e=c.useRef(!1);return c.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector("[data-slate-editor]")?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},t0=()=>{const{state:e,closeCompose:t}=Mt(),s=e0(),[r,a]=c.useState(!1),{isError:o,error:i,refetch:l}=ce({...gt(),staleTime:1/0}),u=c.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),f=c.useCallback(()=>{a(!1),t()},[t]),d=c.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const m=Zy[e.mode]??"New Message";return n.jsxs(Je.Root,{open:e.isOpen,onOpenChange:u,children:[n.jsxs(Je.Portal,{children:[n.jsx(Je.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Je.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[n.jsx(Je.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),n.jsx(Je.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:m}),o?n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(At,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):n.jsx("div",{className:"flex-1 overflow-hidden",children:n.jsx(Fa,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),r&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50",children:n.jsxs("div",{className:"mx-4 w-full max-w-sm rounded-xl bg-canvas p-6 shadow-xl",children:[n.jsx("h3",{className:"text-lg font-semibold",children:"Discard draft?"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Your message has unsaved content. Are you sure you want to discard it?"}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:d,className:"rounded-md px-4 py-2 text-sm font-medium hover:bg-surface-raised transition-colors",children:"Keep editing"}),n.jsx("button",{type:"button",onClick:f,className:"rounded-md bg-danger px-4 py-2 text-sm font-medium text-canvas hover:bg-danger/90 transition-colors",children:"Discard"})]})]})})]})},s0={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Hu=()=>{const{state:e,closeCompose:t}=Mt(),s=Lt(),{isError:r,error:a,refetch:o}=ce({...gt(),staleTime:1/0});if(!s)return n.jsx(t0,{});if(!e.isOpen)return null;const i=s0[e.mode]??"New Message",l=n.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[n.jsx("div",{className:"flex items-center gap-2 min-w-0",children:n.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:n.jsx(We,{className:"size-5"})})]});return r?n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[l,n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(At,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[l,n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:n.jsx(Fa,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function n0(e){const t=e.toAddresses.join(", ");return{id:e.outboxMessageId,accountId:e.accountId,fromName:e.fromName??e.fromAddress??"Me",fromEmail:e.fromAddress??"",subject:e.subject??"(No subject)",snippet:t?`To: ${t}`:"(No recipients)",timeLabel:Dt(e.updatedAt),isRead:!0}}function r0(e){return{id:e.messageId,accountId:e.accountConfigId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Dt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function a0({outboxMessages:e,accountId:t,imapThreads:s}){const r=e.filter(i=>i.status==="draft"&&i.accountId===t).map(n0),a=s.map(r0),o=[];return r.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:r}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function to(){const e=ks();return!e||e.showNavPane?null:n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(ja,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const o0=({label:e,count:t})=>n.jsxs("div",{className:"sticky top-0 z-10 flex items-baseline justify-between border-b border-line bg-surface-sunken px-row-inset py-1",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:t})]}),i0=({row:e,isSelected:t,onOpen:s,onDelete:r,isDeleting:a})=>n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:H("group",en({active:t})),children:[n.jsx(Gi,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),n.jsx(qs,{thread:e}),n.jsx("div",{className:"flex items-center gap-1 shrink-0",children:n.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),r(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:n.jsx(st,{className:"size-3.5"})})})]}),l0=({row:e,isSelected:t,onOpen:s})=>{const r=!e.isRead;return n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:H("group",en({active:t})),children:[r&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx(lt,{name:e.fromName,email:e.fromEmail,size:"sm"}),n.jsx(qs,{thread:e})]})};function c0({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:r,title:a,unreadCount:o}){const{openCompose:i,state:l}=Mt(),u=De(),f=ye(),{data:d}=ce(Un()),m=c.useMemo(()=>a0({outboxMessages:d?.items??[],accountId:t,imapThreads:r}),[d?.items,t,r]),h=ve({...qn(),onSuccess:()=>{f.invalidateQueries({queryKey:wa()})}}),x=g=>{h.mutate({path:{outboxMessageId:g}})},b=g=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:g})},p=g=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:g}})},v=m.length===0;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(to,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:a}),(o??0)>0&&n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:[o," unread"]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:v?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[n.jsx(oa,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):m.map(g=>n.jsxs("div",{children:[g.label&&n.jsx(o0,{label:g.label,count:g.threads.length}),n.jsx("div",{className:"divide-y divide-line",children:g.threads.map(y=>g.id==="remit-drafts"?n.jsx(i0,{row:y,isSelected:l.isOpen&&y.id===l.outboxMessageId,onOpen:b,onDelete:x,isDeleting:h.isPending},y.id):n.jsx(l0,{row:y,isSelected:y.id===s,onOpen:p},y.id))})]},g.id))})]})}function u0(e,t,s){const r=new Array(e);return new Proxy(r,{get(a,o,i){if(typeof o=="string"){const l=o.charCodeAt(0);if(l>=48&&l<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let f=a[u];if(!f){const d=t[u*2];f=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return f}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function us(e,t,s){let r=s.initialDeps??[],a,o=!0;function i(){const l=e();return(l.length!==r.length||l.some((f,d)=>r[d]!==f))&&(r=l,a=t(...l),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=l=>{r=l},i}function Di(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const d0=(e,t)=>Math.abs(e-t)<1.01,f0=(e,t,s)=>{let r;return function(...a){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,a),s)}};let zs;const $r=()=>{if(zs!==void 0)return zs;if(typeof navigator>"u")return zs=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zs=!0;const e=navigator.maxTouchPoints;return zs=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Oi=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},m0=e=>e,h0=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,a=new Array(r);for(let o=0;o<r;o++)a[o]=t+o;return a},p0=(e,t)=>{const s=e.scrollElement;if(!s)return;const r=e.targetWindow;if(!r)return;const a=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(a(Oi(s)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u?.borderBoxSize){const f=u.borderBoxSize[0];if(f){a({width:f.inlineSize,height:f.blockSize});return}}a(Oi(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},Fn={passive:!0},g0=typeof window>"u"?!0:"onscrollend"in window,x0=(e,t,s)=>{const r=e.scrollElement;if(!r)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&g0;let i=0;const l=o?null:f0(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=m=>()=>{i=s(r),l?.(),t(i,m)},f=u(!0),d=u(!1);return r.addEventListener("scroll",f,Fn),o&&r.addEventListener("scrollend",d,Fn),()=>{r.removeEventListener("scroll",f),o&&r.removeEventListener("scrollend",d)}},b0=(e,t)=>x0(e,t,s=>{const{horizontal:r,isRtl:a}=e.options;return r?s.scrollLeft*(a&&-1||1):s.scrollTop}),v0=(e,t,s)=>{if(s.options.useCachedMeasurements){const r=s.indexFromElement(e),a=s.options.getItemKey(r);return s.itemSizeCache.get(a)??s.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[s.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=s.indexFromElement(e),a=s.options.getItemKey(r),o=s.itemSizeCache.get(a);if(o!==void 0)return o}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},y0=(e,{adjustments:t=0,behavior:s},r)=>{var a,o;(o=(a=r.scrollElement)==null?void 0:a.scrollTo)==null||o.call(a,{[r.options.horizontal?"left":"top"]:e+t,behavior:s})},w0=y0;class j0{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,r,a;return((a=(r=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:r.now)==null?void 0:a.call(r))??Date.now()},this.observer=(()=>{let s=null;const r=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const l=o.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[f,d]of this.elementsCache)if(d===l){this.elementsCache.delete(f);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=r())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=r())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=r())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var r,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:m0,rangeExtractor:h0,onChange:()=>{},measureElement:v0,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in s){const x=s[h];x!==void 0&&(o[h]=x)}const i=this.options;let l=null,u=null,f=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,x=o.count,b=this.getMeasurements(),p=h>0?((r=b[0])==null?void 0:r.key)??i.getItemKey(0):null,v=h>0?((a=b[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(x!==h||h>0&&x>0&&(o.getItemKey(0)!==p||o.getItemKey(x-1)!==v)){f=!0;const w=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??b[0]:null;w&&(l=[w.key,this.getScrollOffset()-w.start]);const S=o.followOnAppend===!0?"auto":o.followOnAppend||null;S&&x>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(x-1)!==v)&&(u=S)}}this.options=o,f&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,m=0;if(l&&this.scrollOffset!==null){const[h,x]=l,b=this.getMeasurements(),{count:p,getItemKey:v}=this.options;let g=0;for(;g<p&&v(g)!==h;)g++;if(g<p){const y=b[g];if(y){const w=y.start+x;w!==this.scrollOffset&&(m=w-this.scrollOffset,this.scrollOffset=w,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,u,m])},this.notify=s=>{var r,a;(a=(r=this.options).onChange)==null||a.call(r,this,s)},this.maybeNotify=us(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===o?this.scrollDirection:l<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!$r()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,Fn),o.addEventListener("touchend",l,Fn),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,l,u]=a;o!==null&&!l&&($r()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),r=this.getMaxScrollOffset();if(s<0||s>r)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=us(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,r,a,o,i,l,u,f)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f}),{key:!1}),this.getMeasurements=us(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f},d)=>{const m=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const g of this.laneAssignments.keys())g>=s&&this.laneAssignments.delete(g);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(g=>{this.itemSizeCache.set(g.key,g.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),l===1){const g=s*2;let y=this._flatMeasurements;if(!y||y.length<g){const N=new Float64Array(g);y&&h>0&&N.set(y.subarray(0,h*2)),y=N,this._flatMeasurements=y}let w;if(h===0)w=r+a;else{const N=h-1;w=y[N*2]+y[N*2+1]+f}for(let N=h;N<s;N++){const R=o(N),C=m.get(R),k=typeof C=="number"?C:this.options.estimateSize(N);y[N*2]=w,y[N*2+1]=k,w+=k+f}const S=u0(s,y,o);return this.measurementsCache=S,S}const x=this.measurementsCache.slice(0,h),b=new Array(l).fill(void 0),p=new Float64Array(l);let v=0;for(let g=0;g<h;g++){const y=x[g];y&&(b[y.lane]===void 0&&v++,b[y.lane]=g,p[y.lane]=y.end)}for(let g=h;g<s;g++){const y=o(g),w=this.laneAssignments.get(g);let S,N;const R=u==="estimate"||m.has(y);if(w!==void 0&&this.options.lanes>1){S=w;const O=b[S],A=O!==void 0?x[O]:void 0;N=A?A.end+f:r+a}else if(v===l){let O=0,A=p[0],P=b[0];for(let E=1;E<l;E++){const j=p[E];(j<A||j===A&&b[E]<P)&&(O=E,A=j,P=b[E])}S=O,N=A+f,R&&this.laneAssignments.set(g,S)}else S=g%this.options.lanes,N=r+a,R&&this.laneAssignments.set(g,S);const C=m.get(y),k=typeof C=="number"?C:this.options.estimateSize(g),D=N+k;x[g]={index:g,start:N,size:k,end:D,key:y,lane:S},b[S]===void 0&&v++,b[S]=g,p[S]=D}return this.measurementsCache=x,x},{key:!1,debug:()=>this.options.debug}),this.calculateRange=us(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,r,a,o)=>s.length===0||r===0?(this.range=null,null):(this.range=k0(s,r,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=us(()=>{let s=null,r=null;const a=this.calculateRange();return a&&(s=a.startIndex,r=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,r]},(s,r,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:r,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const r=this.options.indexAttribute,a=s.getAttribute(r);return a?parseInt(a,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),l=Math.min(this.options.count-1,a+o);return s>=i&&s<=l}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const r=this.indexFromElement(s),a=this.options.getItemKey(r),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,r)=>{var a,o;if(s<0||s>=this.options.count)return;let i,l,u;const f=this._flatMeasurements;if(this.options.lanes===1&&f!==null)u=this.options.getItemKey(s),l=f[s*2],i=f[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,l=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,m=r-d;if(m!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=h?this.getTotalSize():0,b=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:l,size:i,end:l+i,lane:0},m,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,r),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-x):b&&this.applyScrollAdjustment(m),this.notify(!1)}},this.getVirtualItems=us(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,r)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const l=s[o],u=r[l];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const r=this.getMeasurements();if(r.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=Wu(0,r.length-1,o?l=>a[l*2]:l=>Di(r[l]).start,s);return Di(r[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,r,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=s>=i+o?"end":"start"),r==="center"?s+=(a-o)/2:r==="end"&&(s-=o);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,r="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(r==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)r="end";else if(i.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,i.size),r]},this.scrollToOffset=(s,{align:r="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,r),i=this.now();this.scrollState={index:null,align:r,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:r="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,r);if(!o)return;const[i,l]=o,u=this.now();this.scrollState={index:s,align:l,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:r="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const r=this.getMeasurements();let a;if(r.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=r[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&o.some(l=>l===null);){const l=r[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}a=Math.max(...o.filter(l=>l!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const r=this.getMeasurements();for(const a of r)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:r,behavior:a})=>{this._intendedScrollOffset=s+(r??0),this.options.scrollToFn(s,{behavior:a,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&($r()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=r?r[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&d0(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),f=this.scrollState.behavior==="smooth"&&u>l;this.scrollState.lastTargetOffset=a,f||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:f?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Wu=(e,t,s,r)=>{for(;e<=t;){const a=(e+t)/2|0,o=s(a);if(o<r)e=a+1;else if(o>r)t=a-1;else return a}return e>0?e-1:0};function S0(e,t,s){let r=0;for(;r<=t;){const a=(r+t)/2|0,o=e[a*2];if(o<s)r=a+1;else if(o>s)t=a-1;else return a}return r>0?r-1:0}function k0(e,t,s,r,a){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&a!==null){const f=S0(a,o,s);let d=f;const m=s+t;for(;d<o&&a[d*2]+a[d*2+1]<m;)d++;return{startIndex:f,endIndex:d}}let l=Wu(0,o,f=>e[f].start,s),u=l;if(r===1)for(;u<o&&e[u].end<s+t;)u++;else if(r>1){const f=Array(r).fill(0);for(;u<o&&f.some(m=>m<s+t);){const m=e[u];f[m.lane]=m.end,u++}const d=Array(r).fill(s+t);for(;l>=0&&d.some(m=>m>=s);){const m=e[l];d[m.lane]=m.start,l--}l=Math.max(0,l-l%r),u=Math.min(o,u+(r-1-u%r))}return{startIndex:l,endIndex:u}}const Fr=typeof document<"u"?c.useLayoutEffect:c.useEffect;function C0({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...r}){const a=c.useReducer(f=>f+1,0)[1],o=c.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=f=>{const d=o.current;if(!d.enabled||!d.container)return;const m=f.getTotalSize();if(m!==d.lastSize){d.lastSize=m;const g=f.options.horizontal?"width":"height";d.container.style[g]=`${m}px`}const h=!!f.options.horizontal,x=d.mode==="transform",b=h?"left":"top",p=f.options.scrollMargin,v=f.getVirtualItems();for(const g of v){const y=g.start-p,w=f.elementsCache.get(g.key);w&&d.lastPositions.get(w)!==y&&(d.lastPositions.set(w,y),x?w.style.transform=h?`translate3d(${y}px, 0, 0)`:`translate3d(0, ${y}px, 0)`:w.style[b]=`${y}px`)}},l={...r,onChange:(f,d)=>{var m;const h=o.current;let x=!0;if(h.enabled){i(f);const b=f.range,p=h.prevRange;x=!p||p.isScrolling!==f.isScrolling||p.startIndex!==b?.startIndex||p.endIndex!==b?.endIndex,x&&(h.prevRange=b?{startIndex:b.startIndex,endIndex:b.endIndex,isScrolling:f.isScrolling}:null)}x&&(e&&d?da.flushSync(a):a()),(m=r.onChange)==null||m.call(r,f,d)}},[u]=c.useState(()=>{const f=new j0(l);return Object.assign(f,{containerRef:d=>{const m=o.current;if(m.container=d,m.lastSize=null,d&&m.enabled){const h=f.getTotalSize();m.lastSize=h;const x=f.options.horizontal?"width":"height";d.style[x]=`${h}px`}}})});return u.setOptions(l),Fr(()=>u._didMount(),[]),Fr(()=>u._willUpdate()),Fr(()=>{i(u)}),u}function N0(e){return C0({observeElementRect:p0,observeElementOffset:b0,scrollToFn:w0,...e})}const E0={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},Vu={delete:"moved to Trash",move:"moved",markRead:"marked as read"},Qu={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},I0={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},T0={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},R0=(e,t,s)=>E0[e](it(t),it(s)),Pi=(e,t)=>`${it(t)} ${Vu[e]}. Your mail server is still catching up.`,M0=(e,t,s)=>`${it(t)} ${Vu[e]}. ${it(s)} ${Qu[e]}.`,A0=(e,t)=>t>0?`Stopped after ${it(t)} — some messages ${Qu[e]}`:I0[e],D0=e=>T0[e],O0=e=>e==="delete"?"danger":"info",Yu=100,zn=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),P0=(e,t=Yu)=>{if(e.length===0)return[];const s=[];for(let r=0;r<e.length;r+=t)s.push(e.slice(r,r+t));return s},L0=async(e,t,s,r)=>{const a=P0(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(r())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const f=a[u],d=await zn(t(f));if(!d.ok)return l.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:l,cancelled:!1,error:d.error};i+=f.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},$0=async(e,t,s,r,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await zn(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const f=u.value;if(f.ids.length>0){const d=await zn(s(f.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=f.ids.length,r({done:o,total:t})}l=f.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},F0=e=>({done:e.done,total:Math.max(e.total,e.done)}),z0=async(e,t,s)=>{let r=0,a;do{if(s())return{total:r,cancelled:!0};const o=await zn(e(a));if(!o.ok)return{total:r,cancelled:!1,error:o.error};const i=o.value;r+=i.ids.length,t(r),a=i.continuationToken}while(a);return{total:r,cancelled:!1}},_0=e=>e.failedIds.length>0?{exit:!1,retryIds:e.failedIds}:e.cancelled||e.error?{exit:!1,retryIds:[]}:{exit:!0,retryIds:[]},B0=100,K0=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],U0=({mailboxId:e,accountId:t,enabled:s,predicateKey:r,searchQuery:a})=>{const[o,i]=c.useState({kind:"idle"}),[l,u]=c.useState(void 0),[f,d]=c.useState(void 0),m=c.useRef(!1),h=ye(),{pushError:x}=Ze();c.useEffect(()=>{m.current=!0,i({kind:"idle"})},[s,r]);const b=c.useRef(a);b.current=a;const p=c.useCallback(async R=>{const{data:C}=await cl({path:{mailboxId:e},query:{...b.current,continuationToken:R,limit:B0},throwOnError:!0});return{ids:(C.items??[]).map(k=>k.messageId),continuationToken:C.continuationToken}},[e]),v=c.useCallback(R=>async C=>{if(R.kind==="move"){const{data:D}=await sf({body:{messageIds:C,destinationMailboxId:R.destinationMailboxId},throwOnError:!0});return D}if(R.kind==="markRead"){const{data:D}=await nf({body:{messageIds:C,isRead:!0},throwOnError:!0});return D}const{data:k}=await rf({body:{messageIds:C},throwOnError:!0});return k},[]),g=c.useCallback(R=>{Ft(h,$t(K0(R,e))),t&&h.invalidateQueries({queryKey:Xt({path:{accountId:t}})})},[h,e,t]),y=c.useCallback(()=>{m.current=!1,i({kind:"counting",countSoFar:0}),z0(p,R=>i({kind:"counting",countSoFar:R}),()=>m.current).then(R=>{if(R.error){x(Vt("Couldn't count matching messages","The count didn't finish.",R.error)),i({kind:"idle"});return}if(R.cancelled){i({kind:"idle"});return}i({kind:"escalated",total:R.total})})},[p,x]),w=c.useCallback(()=>{m.current=!0},[]),S=c.useCallback(()=>{m.current=!0,i({kind:"idle"})},[]),N=c.useCallback(async(R,C)=>{m.current=!1,u(R);const k=A=>d(F0(A)),D=v(R),O=C!==void 0?await L0(C,D,k,()=>m.current):await $0(p,o.kind==="escalated"?o.total:0,D,k,()=>m.current);return u(void 0),d(void 0),i({kind:"idle"}),O.error&&x(Vt(A0(R.kind,O.done),D0(R.kind),O.error)),O.done>0&&g(R),O},[v,p,o,x,g]);return{phase:o,escalate:y,stop:w,clear:S,isRunning:l!==void 0,runningAction:l,progress:f,runAction:N}},Gu=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",q0=e=>`Select all ${Gu(e)}`,H0=(e,t)=>`All ${it(t)} ${Gu(e)} selected`,W0=e=>e.isRunning?"running":e.isCounting?"counting":e.isEscalated?"escalated":"idle",V0=2,Q0=(e,t,s=!1)=>e>=V0||t!=="idle"||s,Xu=e=>{const t=ve(af()),{mutate:s}=t;return{preview:c.useCallback(a=>{e&&s({path:{accountId:e},body:pl(a)})},[e,s]),reset:t.reset,matchedCount:t.data?.matchedCount,messageIds:t.data?.messageIds,semanticUnavailable:t.data?.semanticUnavailable??!1,isPending:t.isPending,isError:t.isError,error:t.error}},Y0=({entry:e,hasSeed:t,previewStatus:s,matchedCount:r})=>{if(e==="something-else"&&!t)return{kind:"something-else"};if(s==="error")return{kind:"error"};if(s!=="success")return{kind:"widening"};const a=r??0;return{kind:"organize",matchedCount:a,fallback:a===0}},G0=new Set(["Complete","Failed"]),Li=e=>e!==void 0&&G0.has(e),X0=1e3,J0=15e3,Z0=e=>{const t=Math.max(0,e),s=X0*2**t;return Math.min(s,J0)},ew=e=>{const[t,s]=c.useState(),r=ve({...of(),onSuccess:m=>s(m.organizeJobId)}),{mutate:a}=r,o=ce({...lf({path:{accountId:e??"",organizeJobId:t??""}}),enabled:!!e&&!!t,refetchInterval:m=>{const h=m.state.data?.state;return Li(h)?!1:Z0(m.state.dataUpdateCount)}}),i=c.useCallback(m=>{e&&(s(void 0),a({path:{accountId:e},body:pl(m)}))},[e,a]),l=o.data,u=l?.state??r.data?.state,f=Li(l?.state),d={state:u,matchedCount:l?.matchedCount??0,appliedCount:l?.appliedCount??0,failedCount:l?.failedCount??0,errorMessage:l?.errorMessage??""};return{start:i,progress:d,isStarting:r.isPending,isRunning:!!t&&!f,isDone:f,isError:r.isError||o.isError,error:r.error??o.error}},tw=({draft:e,scope:t,name:s,pickedDate:r})=>{if(!Ef(e))return"Pick a folder to move these into — labeling isn't available yet.";if((t==="standing"||t==="temporary")&&s.trim()==="")return"Name this filter so you can find it later.";if(t==="temporary"&&r==="")return"Pick the date this should stop on."},sw=(e,t)=>{switch(e){case"just-these":return`Move ${t} message${t===1?"":"s"}`;case"all-like-these":return`Organize ${t} message${t===1?"":"s"}`;case"standing":return"Always do this";case"temporary":return"Do this until then"}},nw=(e,t,s)=>e==="just-these"?t:s,rw=[{id:"just-these",label:"Just these",caption:"the ones you selected"},{id:"all-like-these",label:"All like these",caption:"including the similar ones found now"},{id:"standing",label:"These and new mail like this",caption:"keeps working on future mail"},{id:"temporary",label:"Until a date",caption:"stops on its own"}];function Ju({accountId:e,mailboxId:t,selectedMessageIds:s,anchorMessageId:r,matchedCount:a,initialScope:o,seedMailboxId:i,fallback:l=!1,semanticUnavailable:u=!1,onClose:f}){const d=l||u,[m,h]=c.useState(o??(d?"just-these":"all-like-these")),[x,b]=c.useState(i??""),[p,v]=c.useState(""),[g,y]=c.useState(""),{data:w}=ce({...Ve({path:{accountId:e}}),staleTime:1/0}),S=c.useMemo(()=>rr(w?.items??[]).map(I=>({id:I.mailboxId,label:bs(I.fullPath)})),[w?.items]),N=c.useMemo(()=>({anchorMessageId:r,matchOperator:"And",literalClauses:[],moveMailboxId:x||void 0,expiresAt:m==="temporary"?If(g):void 0}),[r,x,m,g]),{moveMessages:R}=Tt({mailboxId:t,accountId:e}),C=ew(e),k=Tf(e),D=s.length,O=nw(m,D,a),A=tw({draft:N,scope:m,name:p,pickedDate:g}),P=()=>{if(!A)switch(m){case"just-these":x&&R(s,x),f();return;case"all-like-these":C.start(N);return;case"standing":k.createFilter(N,"standing",p.trim());return;case"temporary":k.createFilter(N,"temporary",p.trim());return}};if(C.isRunning||C.isDone)return n.jsx(aw,{progress:C.progress,isDone:C.isDone,onClose:f});if(k.isSuccess)return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(Na,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Filter saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"You can see it, and when it expires, under Settings › Filters."}),n.jsx(G,{variant:"primary",onClick:f,className:"mt-2",children:"Done"})]});const E=m==="standing"||m==="temporary";return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"border-b border-line px-5 py-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg",children:"Organize"}),n.jsx("p",{className:"mt-0.5 text-xs text-fg-muted",children:u?`Finding similar mail isn't available on this server — organizing just your ${D} selected.`:l?`No similar messages found — organizing just your ${D} selected.`:`${a} similar message${a===1?"":"s"} found${D>0?` from ${D} selected`:""}.`})]}),n.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4",children:[n.jsxs("section",{className:"space-y-2 rounded-lg border border-line bg-surface-sunken p-3",children:[n.jsxs("p",{className:"text-sm leading-relaxed text-fg-muted",children:[m==="standing"&&n.jsx("span",{className:"font-semibold text-fg",children:"Always keep "}),m==="standing"?"":"Keep ",m==="just-these"?"these":"emails like these"," in"]}),n.jsxs(Nf,{"aria-label":"Destination folder",value:x,onChange:j=>b(j.target.value),children:[n.jsx("option",{value:"",children:"Choose a folder…"}),S.map(j=>n.jsx("option",{value:j.id,children:j.label},j.id))]}),n.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[n.jsx(tt,{tone:"neutral",children:"label them…"}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:"Labeling isn't available yet — arrives with mail-labeling (RFC 031)."})]})]}),n.jsx("section",{className:"space-y-1.5",children:rw.map(j=>{const I=m===j.id;return n.jsxs("button",{type:"button",onClick:()=>h(j.id),className:`flex w-full items-start gap-3 rounded-lg border px-3 py-2.5 text-left transition-colors ${I?"border-accent-2 bg-accent-2-soft":"border-line bg-surface hover:bg-surface-sunken"}`,children:[n.jsx("span",{className:`mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border ${I?"border-accent-2 bg-accent-2":"border-line bg-surface"}`,children:I&&n.jsx("span",{className:"size-1.5 rounded-full bg-white"})}),n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:`block text-sm font-medium ${I?"text-accent-2":"text-fg"}`,children:j.label}),n.jsx("span",{className:"block text-xs text-fg-subtle",children:j.caption})]})]},j.id)})}),E&&n.jsxs("section",{className:"space-y-2",children:[n.jsx(la,{value:p,onChange:j=>v(j.target.value),placeholder:"Name this filter (e.g. Travel)","aria-label":"Filter name"}),m==="temporary"&&n.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-muted",children:["Until",n.jsx("input",{type:"date",value:g,onChange:j=>y(j.target.value),"aria-label":"Expiry date",className:"rounded-md border border-line bg-surface-sunken px-2 py-1 text-sm text-fg"})]})]})]}),n.jsxs("div",{className:"space-y-2 border-t border-line px-5 py-3",children:[A&&n.jsx("p",{className:"text-xs text-fg-subtle",role:"status",children:A}),k.isError&&n.jsx("p",{className:"text-xs text-danger",role:"alert",children:"Couldn't save the filter. Please try again."}),n.jsx(G,{variant:"primary",onClick:P,disabled:!!A||k.isPending||C.isStarting,className:"w-full",children:k.isPending?"Saving…":sw(m,O)}),n.jsx(G,{variant:"ghost",onClick:f,className:"w-full",children:"Not now"})]})]})}function aw({progress:e,isDone:t,onClose:s}){const r=e.state==="Failed";return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[t?r?n.jsx("span",{className:"text-sm font-semibold text-danger",children:"Organize failed"}):n.jsx(Na,{className:"size-8 text-positive"}):n.jsx(xt,{className:"size-8 animate-spin text-accent-2"}),!t&&n.jsx("p",{className:"text-sm font-medium text-fg",children:"Organizing similar mail…"}),t&&!r&&n.jsxs("div",{className:"text-sm text-fg",children:[n.jsx("p",{className:"font-medium",children:"Done"}),n.jsxs("p",{className:"mt-1 text-xs text-fg-muted",children:[e.appliedCount," of ",e.matchedCount," moved",e.failedCount>0?` · ${e.failedCount} failed`:"","."]})]}),t&&r&&n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:e.errorMessage||"Something went wrong. Please try again."}),t&&n.jsx(G,{variant:"primary",onClick:s,className:"mt-2",children:"Done"})]})}const $i=(e,t)=>e.find(s=>s.label.toLowerCase()===t),ow=(e,t)=>{const s=[],r=$i(e,"inbox");r&&s.push({id:"keep-inbox",label:"Always keep in Inbox",seed:{moveMailboxId:r.id,scope:"standing"}});const a=$i(e,"archive");a&&s.push({id:"file-archive",label:"File in Archive",seed:{moveMailboxId:a.id}});const o=t?e.find(i=>i.id===t):void 0;return o&&s.push({id:"move-junk",label:`Move to ${o.label}`,seed:{moveMailboxId:o.id}}),s},iw=(e,t)=>{const s=e.toLowerCase(),r=t.find(o=>s.includes(o.label.toLowerCase())),a=/\b(always|keep|future|from now)\b/.test(s);return{moveMailboxId:r?.id,scope:a?"standing":void 0}};function lw({folderOptions:e,junkMailboxId:t,onSeed:s}){const[r,a]=c.useState(""),o=c.useMemo(()=>ow(e,t),[e,t]),i=()=>{const l=r.trim();l&&s(iw(l,e))};return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"border-b border-line px-5 py-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg",children:"What should Remit do?"}),n.jsx("p",{className:"mt-0.5 text-xs text-fg-muted",children:"Pick a shortcut or say it in your own words."})]}),n.jsx("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto px-5 py-4",children:o.map(l=>n.jsx(G,{variant:"secondary",onClick:()=>s(l.seed),className:"h-12 w-full justify-start px-4",children:l.label},l.id))}),n.jsxs("div",{className:"flex items-center gap-2 border-t border-line px-5 py-3",children:[n.jsx(la,{value:r,onChange:l=>a(l.target.value),onKeyDown:l=>l.key==="Enter"&&i(),placeholder:"Tell Remit what to do…","aria-label":"Tell Remit what to do",className:"flex-1"}),n.jsx(G,{variant:"primary","aria-label":"Send",onClick:i,disabled:!r.trim(),icon:n.jsx(pm,{className:"size-4"}),className:"size-9 shrink-0 px-0"})]})]})}const cw=(e,t,s)=>e?"error":t?"pending":s!==void 0?"success":"idle";function uw({entry:e,accountId:t,mailboxId:s,selectedMessageIds:r,junkMailboxId:a,onClose:o}){const i=r[0],[l,u]=c.useState(),{preview:f,matchedCount:d,semanticUnavailable:m,isPending:h,isError:x,error:b}=Xu(t);c.useEffect(()=>{i&&f({anchorMessageId:i,matchOperator:"And",literalClauses:[]})},[i,f]);const{data:p}=ce({...Ve({path:{accountId:t}}),staleTime:Number.POSITIVE_INFINITY}),v=c.useMemo(()=>rr(p?.items??[]).map(y=>({id:y.mailboxId,label:bs(y.fullPath)})),[p?.items]),g=Y0({entry:e,hasSeed:l!==void 0,previewStatus:cw(x,h,d),matchedCount:d});return n.jsxs(Gl,{open:!0,onClose:o,dismissLabel:"Dismiss organize",children:[g.kind==="something-else"&&n.jsx(lw,{folderOptions:v,junkMailboxId:a,onSeed:u}),g.kind==="widening"&&n.jsx(dw,{}),g.kind==="error"&&n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:b instanceof Error?b.message:"Please try again."}),n.jsx(G,{variant:"ghost",onClick:o,className:"mt-2",children:"Close"})]}),g.kind==="organize"&&n.jsx(Ju,{accountId:t,mailboxId:s,selectedMessageIds:r,anchorMessageId:i,matchedCount:g.matchedCount,initialScope:l?.scope,seedMailboxId:l?.moveMailboxId,fallback:g.fallback,semanticUnavailable:m,onClose:o})]})}function dw(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(xt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]})}function fw({open:e,accountId:t,mailboxId:s,selectedMessageIds:r,onClose:a}){const o=r[0],{preview:i,reset:l,matchedCount:u,semanticUnavailable:f,isPending:d,isError:m,error:h}=Xu(t);c.useEffect(()=>{!e||!o||i({anchorMessageId:o,matchOperator:"And",literalClauses:[]})},[e,o,i]);const x=()=>{l(),a()};return e?n.jsx(Yi,{open:e,onClose:x,title:"Organize similar mail",children:d||u===void 0?m?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:h instanceof Error?h.message:"Please try again."}),n.jsx(G,{variant:"ghost",onClick:x,className:"mt-2",children:"Close"})]}):n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(xt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]}):n.jsx(Ju,{accountId:t,mailboxId:s,selectedMessageIds:r,anchorMessageId:o,matchedCount:u,semanticUnavailable:f,onClose:x})}):null}const mw=(e,t)=>({id:e.messageId,accountId:e.accountConfigId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Dt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:er(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0}),hw=({thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,messageCount:d,isMultiSelectMode:m,onLongPress:h,isDesktop:x,density:b})=>n.jsx(Xa,{thread:mw(e,d),linkMailboxId:t,inListbox:!0,active:r,focused:a,isTabStop:o,density:b,isDesktop:x,onFocusRow:i,selection:{isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:m,onLongPress:h},badge:e.autoMoved?n.jsx(_c,{accountId:s,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"sm"}):void 0}),pw=c.memo(hw),gw=e=>{const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountConfigId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Dt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:er(e.category),suspicious:t}},xw=({thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:d,onLongPress:m,isDesktop:h,onDelete:x,onToggleRead:b,density:p})=>{const[v,g]=c.useState("none"),y=c.useCallback(N=>{navigator.vibrate?.(10),N==="trailing"?x(e.messageId):b(e.messageId,e.isRead),g("none")},[x,b,e.messageId,e.isRead]),w=c.useCallback(()=>{m(e.messageId)},[m,e.messageId]),S=c.useCallback(()=>{u(e.messageId)},[u,e.messageId]);return h||d?n.jsx(pw,{thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:d,onLongPress:m,isDesktop:h,density:p}):n.jsx(ql,{thread:gw(e),selectionMode:!1,checked:!1,active:r,peek:v,onPeek:g,onToggleCheck:S,onLongPress:w,onOpen:()=>{},onAct:y,linkComponent:({onOpenClick:N,children:R,...C})=>n.jsx(mt,{...C,to:"/mail/$mailboxId",params:{mailboxId:t},search:k=>({...k,selectedMessageId:e.messageId}),"data-message-row":!0,onClick:N,children:R})})},bw=72,vw=32,yw=5,Zu="remit:list-density",ww={kind:"delete"},Fi={kind:"markRead"},jw=()=>{try{const e=localStorage.getItem(Zu);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},Sw=({query:e,count:t})=>n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[n.jsx(Gs,{className:"size-4 text-fg-muted"}),n.jsxs("span",{className:"text-sm text-fg-muted",children:[t," ",t===1?"result":"results"," for “",e,"”"]})]}),kw=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:r,isError:a=!1,error:o,onRetry:i,searchQuery:l,searchPredicate:u,onDeleteMessages:f,onMoveMessages:d,isDeleting:m=!1,isMoving:h=!1,onLoadMore:x,hasMore:b=!1,isLoadingMore:p=!1,accountId:v,listTitle:g,listMeta:y,onTriageContextChange:w,commandsRef:S,hideHeader:N=!1})=>{const R=c.useRef(null),C=De(),k=Lt(),[D,O]=c.useState(!1),[A,P]=c.useState(null),E=!!l?.trim(),[j,I]=c.useState(s),[L,T]=c.useState(jw),F=c.useCallback(()=>{T(z=>{const se=z==="comfortable"?"compact":"comfortable";try{localStorage.setItem(Zu,se)}catch{}return se})},[]),{toggleReadFor:M}=Zn({mailboxId:e}),{junkMailboxId:$}=sr(v),{selectedIds:K,selectedCount:_,hasSelection:X,isSelected:ee,toggle:Y,select:me,clearSelection:ue,selectRange:te,setAnchor:q,selectAll:U,toggleAll:re,intersectWith:Pe}=Cu(),Re=Nu(_,k);c.useEffect(()=>{_===0&&P(null)},[_]);const[V,J]=c.useState(null),ae=E&&!!u,de=`${e}|${JSON.stringify(u??{})}`,B=U0({mailboxId:e,accountId:v,enabled:ae,predicateKey:de,searchQuery:u??{}}),Qe=B.phase.kind,Le=B.clear,ge=c.useCallback(()=>{Qe==="escalated"&&Le(),ue()},[ue,Le,Qe]),[we,Ye]=c.useState(null),[es,$e]=c.useState(null),et=c.useRef(null),Fe=c.useRef(!1),ze=c.useRef(null),ct=!r&&t.length>0,Ee=V!==null,ts=c.useCallback((z,se)=>{const{exit:yt,retryIds:Xe}=_0(se);if(yt){$e(Pi(z.kind,se.done)),Ye(null),ge();return}if(Xe.length>0){Ye({action:z,succeeded:se.done}),U(Xe);return}Ye(null)},[ge,U]),_e=N0({count:t.length,getScrollElement:()=>R.current,estimateSize:()=>L==="compact"?vw:bw,overscan:yw}),zt=s?t.findIndex(z=>z.messageId===s):-1,ke=j?t.findIndex(z=>z.messageId===j):-1,Be=c.useCallback(z=>{if(z<0||z>=t.length)return;const se=t[z];if(Re){Y(se.messageId);return}et.current=se.messageId,Fe.current=!1,I(se.messageId)},[t,Re,Y]),ut=c.useCallback(()=>{if(t.length===0)return;const z=ke<0?0:Math.min(ke+1,t.length-1);Be(z)},[t.length,ke,Be]),ss=c.useCallback(()=>{if(t.length===0)return;const z=ke<=0?0:ke-1;Be(z)},[t.length,ke,Be]),_t=c.useCallback(()=>Be(0),[Be]),Z=c.useCallback(()=>Be(t.length-1),[Be,t.length]),le=c.useCallback(()=>{j&&Y(j)},[j,Y]),ne=c.useMemo(()=>t.map(z=>z.messageId),[t]),oe=c.useCallback((z,se)=>se.shiftKey?(te(ne,z,j),!0):se.metaKey||se.ctrlKey?(Y(z),!0):(ge(),q(z),!1),[ne,j,te,Y,ge,q]),fe=c.useCallback(z=>{!f||z.length===0||(ze.current=j??null,J({source:"ids",ids:z}))},[f,j]),he=c.useCallback(()=>{B.phase.kind==="escalated"&&(ze.current=j??null,J({source:"predicate",total:B.phase.total}))},[B.phase,j]),xe=c.useCallback(z=>{const se=ku(ne,j,z);se!==void 0&&(te(ne,se),et.current=se,Fe.current=!1,I(se))},[ne,j,te]),Ke=c.useCallback(()=>xe(-1),[xe]),Me=c.useCallback(()=>xe(1),[xe]),Ue=c.useCallback(()=>{ne.length>0&&U(ne)},[ne,U]),Ae=c.useCallback(()=>V!==null?!0:f?_>0?(fe(Array.from(K)),!0):j?(fe([j]),!0):!1:!1,[V,f,_,K,j,fe]),Ie=c.useCallback(()=>{j&&C({to:"/mail/$mailboxId",params:{mailboxId:e},search:z=>({...z,selectedMessageId:j})})},[j,C,e]),Ge=c.useCallback(()=>{_>0&&fe(Array.from(K))},[fe,_,K]),Ce=c.useCallback(async(z,se)=>{const yt=await B.runAction(z,se);ts(z,yt)},[B,ts]),Bt=c.useCallback(async z=>{J(null),ze.current=null,await Ce(ww,z)},[Ce]),cr=c.useCallback(()=>{if(!V)return;if(V.source==="predicate"){Bt(void 0);return}const{ids:z}=V;if(z.length===0){J(null);return}if(z.length>Yu){Bt(z);return}const se=new Set(z),yt=t.findIndex(Oe=>se.has(Oe.messageId));let Xe;for(let Oe=yt+1;Oe<t.length;Oe++)if(!se.has(t[Oe].messageId)){Xe=t[Oe].messageId;break}if(Xe===void 0){for(let Oe=yt-1;Oe>=0;Oe--)if(!se.has(t[Oe].messageId)){Xe=t[Oe].messageId;break}}f?.(z),ge(),ze.current=null,J(null),Xe!==void 0&&(et.current=Xe,Fe.current=!1,I(Xe),k&&C({to:"/mail/$mailboxId",params:{mailboxId:e},search:Oe=>({...Oe,selectedMessageId:Xe}),replace:!0})),k||$e(Pi("delete",z.length))},[V,t,f,ge,C,e,k,Bt]),ur=c.useCallback(()=>{const z=ze.current;ze.current=null,J(null),z!==null&&(et.current=z,Fe.current=!1,I(z))},[]),dt=c.useCallback(()=>{if(B.phase.kind==="escalated"){Ce(Fi);return}_!==0&&Ce(Fi,Array.from(K))},[B.phase,Ce,_,K]),ns=c.useCallback(z=>{if(B.phase.kind==="escalated"){Ce({kind:"move",destinationMailboxId:z});return}!d||_===0||(d(Array.from(K),z),ge())},[B.phase,Ce,d,_,K,ge]),dr=c.useCallback(()=>{$&&ns($)},[$,ns]),Kt=c.useMemo(()=>{if(_===0)return;const z=new Set;for(const se of t)K.has(se.messageId)&&z.add(se.accountConfigId);if(z.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[_,K,t]),fr=c.useCallback(z=>{f?.([z])},[f]),mr=c.useCallback((z,se)=>{M([z],!se)},[M]),hr=c.useCallback(z=>{k||me(z)},[k,me]),un=c.useCallback(()=>{if(B.phase.kind==="escalated"){he();return}Ge()},[B.phase,he,Ge]),vt=c.useCallback(()=>{if(B.isRunning||B.phase.kind==="counting"){B.stop();return}ge()},[B,ge]),dn=c.useCallback(()=>{B.clear()},[B]),fn=c.useCallback(()=>{if(!we)return;const z=Array.from(K);if(we.action.kind==="delete"){Bt(z);return}Ce(we.action,z)},[we,Bt,Ce,K]);c.useEffect(()=>{if(Fe.current||!k&&s)return;const z=ke>=0?ke:zt;z>=0&&_e.scrollToIndex(z,{align:"auto"})},[ke,zt,_e,k,s]),c.useEffect(()=>{s&&(Fe.current=!1,I(s))},[s]),c.useEffect(()=>{j&&(t.some(z=>z.messageId===j)||I(t[0]?.messageId))},[t,j]),c.useEffect(()=>{w?.({focusedMessageId:j,selectedIds:Array.from(K),hasList:ct,blocksKeyboard:Ee})},[j,K,ct,Ee,w]);const mn=c.useRef(w);mn.current=w,c.useEffect(()=>()=>mn.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{B.phase.kind!=="idle"||B.isRunning||Pe(t.map(z=>z.messageId))},[t,Pe,B.phase,B.isRunning]);const hn=c.useRef(e);c.useEffect(()=>{hn.current!==e&&(hn.current=e,ge())},[e,ge]),hx({shouldBlockFn:({action:z})=>ey(z,X)?(ge(),!0):!1,enableBeforeUnload:!1,disabled:!X}),c.useEffect(()=>{const z=R.current;if(!z||!b||!x)return;const se=()=>{if(p)return;const{scrollTop:yt,scrollHeight:Xe,clientHeight:Oe}=z;yt+Oe>=Xe-200&&x()};return z.addEventListener("scroll",se,{passive:!0}),se(),()=>z.removeEventListener("scroll",se)},[b,p,x]),c.useEffect(()=>{const z=et.current;if(!z)return;const se=R.current?.querySelector(`[data-message-id="${z}"]`);se&&(et.current=null,se.focus({preventScroll:!0}))}),c.useEffect(()=>{if(S){if(!ct){S.current=null;return}return S.current={focusNext:ut,focusPrevious:ss,focusFirst:_t,focusLast:Z,openFocused:Ie,toggleSelect:le,extendSelectDown:Me,extendSelectUp:Ke,selectAll:Ue,clearSelection:()=>X?(ge(),!0):!1,requestDelete:Ae,toggleDensity:F},()=>{S.current=null}}},[S,ct,ut,ss,_t,Z,Ie,le,Me,Ke,Ue,X,ge,Ae,F]);const pn=r?"loading":a?"error":t.length===0?"empty":"ready",pr=a?fl(o):void 0,gr=c.useCallback(()=>{const z=ga(pa());window.open(z,"_blank","noopener,noreferrer")},[]),Q=[{id:"inbox",threads:[]}],qe=ne.length>0&&ne.every(z=>K.has(z)),He=ae&&b&&qe&&!m&&!h&&B.phase.kind==="idle"&&!B.isRunning,ud=m||h||B.isRunning,xr=B.phase.kind==="escalated"?B.phase.total:_,ro=B.runningAction?R0(B.runningAction.kind,B.progress?.done??0,B.progress?.total??0):B.phase.kind==="counting"?B.phase.countSoFar>=5e3?`Counting… ${it(B.phase.countSoFar)} so far. This is a big result set.`:`Counting… ${it(B.phase.countSoFar)} so far`:B.phase.kind==="escalated"?H0(u??{},B.phase.total):void 0,ao=B.phase.kind!=="escalated"&&ne.length>0?{checked:qe,indeterminate:_>0&&!qe,onChange:()=>re(ne)}:void 0,oo=B.runningAction&&B.progress?{value:B.progress.done,max:B.progress.total,tone:O0(B.runningAction.kind)}:void 0,io=B.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:B.stop}}:B.phase.kind==="escalated"&&!B.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:dn}}:He?{tone:"info",text:"",action:{label:q0(u??{}),onClick:B.escalate}}:we!==null&&_>0?{tone:"danger",text:M0(we.action.kind,we.succeeded,_),action:{label:`Retry ${it(_)}`,onClick:fn}}:void 0,lo=io??(Kt?{tone:"warning",text:Kt}:void 0),co=W0({isRunning:B.isRunning,isCounting:B.phase.kind==="counting",isEscalated:B.phase.kind==="escalated"}),uo=!k&&Re&&Q0(xr,co,lo!==void 0),dd=(d||B.phase.kind==="escalated")&&v&&e?n.jsx(cn,{accountId:v,currentMailboxId:e,onMove:m||h?()=>{}:ns,disabledHint:Kt,label:"Move selected messages"}):void 0,fo=A&&v&&!k&&_>0?n.jsx(uw,{entry:A,accountId:v,mailboxId:e,selectedMessageIds:Array.from(K),junkMailboxId:$,onClose:()=>{P(null),ge()}}):void 0,mo=uo?n.jsx(Mp,{count:xr,mode:co,onCancel:vt,onDelete:un,onJunk:$&&$!==e&&!Kt?dr:void 0,onMarkRead:dt,onSelectSimilar:v?()=>P("select-similar"):void 0,onSomethingElse:v?()=>P("something-else"):void 0,moveSlot:dd,isBusy:ud,selectAll:ao,statusLabel:ro,progress:oo,notice:lo}):void 0,fd=mo||fo?n.jsxs(n.Fragment,{children:[mo,fo]}):void 0,md=X&&k?n.jsx(Iu,{selectedCount:xr,onDelete:un,onClearSelection:vt,onMarkAsRead:dt,onMove:d?ns:void 0,onOrganize:()=>O(!0),isDeleting:m,isMoving:h,accountId:v,currentMailboxId:e,moveDisabledHint:Kt,selectAll:ae?ao:void 0,statusLabel:ro,isCounting:B.phase.kind==="counting",progress:oo,notice:io}):void 0,hd=Eu(ne,j),pd=c.useCallback(z=>{Fe.current=!0,I(z)},[]),gd=n.jsxs(n.Fragment,{children:[E&&l&&n.jsx(Sw,{query:l,count:t.length}),n.jsxs("div",{ref:R,role:"listbox","aria-multiselectable":!0,"aria-label":g,className:"flex-1 overflow-y-auto",style:uo?{paddingBottom:Bs}:void 0,children:[n.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${_e.getTotalSize()}px`},children:_e.getVirtualItems().map(z=>{const se=t[z.index];return n.jsx("div",{role:"presentation","data-index":z.index,ref:_e.measureElement,className:pe("absolute left-0 top-0 w-full border-b border-line",B.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${z.start}px)`},children:n.jsx(xw,{thread:se,mailboxId:e,accountId:v,isSelected:s===se.messageId,isFocused:j===se.messageId,isTabStop:hd===se.messageId,onFocusRow:pd,isChecked:ee(se.messageId),onToggleCheck:Y,onRowSelect:oe,isMultiSelectMode:Re,onLongPress:hr,isDesktop:k,onDelete:fr,onToggleRead:mr,density:L})},z.key)})}),p&&n.jsx("div",{className:"flex justify-center py-4",children:n.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-fg-muted border-t-transparent"})})]})]}),xd=V?V.source==="ids"?V.ids.length:V.total:0,ho=V?.source==="predicate";return n.jsxs(n.Fragment,{children:[es&&!k&&n.jsx(Gt,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>$e(null),children:es}),n.jsx(Hl,{listTitle:g,listMeta:y,sections:Q,flatList:!0,listState:pn,searchQuery:E?l:void 0,errorMessage:pr,onRetry:i,onReportError:gr,density:L,selectedThreadId:s,onSelectThread:z=>C({to:"/mail/$mailboxId",params:{mailboxId:e},search:se=>({...se,selectedMessageId:z})}),onSelectBriefCategory:()=>{},isDesktop:k,hideHeader:N,selectionBar:md,selectionSheet:fd,listBody:pn==="ready"?gd:void 0}),n.jsx(Ya,{isOpen:V!==null,title:hl(xd,ho),description:ho?"This count is a snapshot — new mail arriving during the delete won't be included. You can restore what's deleted from Trash later.":"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:m,onConfirm:cr,onCancel:ur}),D&&v&&n.jsx(fw,{open:D,accountId:v,mailboxId:e,selectedMessageIds:Array.from(K),onClose:()=>O(!1)})]})},Cw=e=>Xt({path:{accountId:e}}),Nw=e=>{const t=ye(),s=Ys(),r=ve({...cf(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:Cw(e)})}});return{trigger:()=>{r.mutate({path:{accountId:e}})},triggerAsync:()=>r.mutateAsync({path:{accountId:e}}),isPending:r.isPending,error:r.error,reset:r.reset}},Ew=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:r}=Nw(e);return n.jsx(mp,{onRefresh:s,isRefreshing:r,children:t})};function Iw({accountId:e,currentMailboxId:t,candidates:s,onMove:r,children:a}){const[o,i]=c.useState(!1),l=Ys(),{t:u}=Kn("mail",{useSuspense:!1}),f=c.useCallback((y,w)=>u(y,{defaultValue:w}),[u]),{inboxMailboxId:d}=Ua(e),m=zc(e),{data:h}=ce({...Ve({path:{accountId:e}}),staleTime:1/0}),x=c.useMemo(()=>{const y=rr(h?.items??[],m),w=Ss(m);return y.map(S=>({id:S.mailboxId,label:xs(S,w.get(S.mailboxId),f),searchValue:S.fullPath,isCurrent:S.mailboxId===t}))},[h?.items,m,t,f]),b=c.useMemo(()=>d||(x.find(w=>w.label.toLowerCase()==="inbox")?.id??x.find(w=>!w.isCurrent)?.id??""),[d,x]),p=c.useRef(!1);c.useEffect(()=>{p.current||(p.current=!0,Sy(l,s.length))},[l,s.length]);const v=c.useCallback(()=>{ky(l,s.length),i(!0)},[l,s.length]),g=c.useCallback((y,w)=>{Cy(l,{selected:y.length,total:s.length,toInbox:w===d}),r(y,w)},[l,s.length,d,r]);return n.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[n.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:n.jsx(gp,{count:s.length,onReview:v})}),n.jsx("div",{className:"min-h-0 flex-1",children:a}),n.jsx(Np,{open:o,candidates:s,defaultDestinationId:b,availableFolders:x,onConfirmMove:g,onCancel:()=>i(!1)})]})}const Tw="We can verify this sender";function Rw(e){const{data:t}=ce({...uf({path:{mailboxId:e??""},query:{senderTrust:["vip","wellknown"],dkimMismatch:!1,results:!0,limit:500}}),enabled:!!e,staleTime:6e4});return{candidates:(t?.items??[]).map(r=>({id:r.messageId,senderName:r.fromName||r.fromEmail||"Unknown sender",senderAddress:r.fromEmail??"",subject:r.subject||"(no subject)",snippet:r.snippet??"",trustReason:Tw,trustSubReason:jy(r.senderTrust),senderTrust:r.senderTrust}))}}const Mw=e=>{const t=new Set,s=[];for(const r of e)t.has(r.threadMessageId)||(t.add(r.threadMessageId),s.push(r));return s},ed="remit:intelligence-open";function Aw(){try{return localStorage.getItem(ed)!=="closed"}catch{return!0}}function zi(e){try{localStorage.setItem(ed,e?"open":"closed")}catch{}}const Dw=(e,t)=>e!==t,Ow=(e,t,s)=>{if(!(s||!t))return e.find(r=>r.messageId===t)},Pw={unread:e=>!e.isRead,flagged:e=>e.hasStars===!0,attachment:e=>!!e.hasAttachment};function Lw(e,t,s){const r=Array.from(s).map(a=>Pw[a]).filter(a=>a!=null);return t==="all"&&r.length===0?e:e.filter(a=>(t==="all"||a.category===t)&&r.every(o=>o(a)))}const td=c.createContext(null);function lr(){const e=c.useContext(td);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function $w({mailboxId:e,selectedMessageId:t,children:s}){const r=De(),o=ar()==="desktop",i=Ys(),{accounts:l,searchQuery:u,searchInput:f,intelligenceOpen:d,onToggleIntelligence:m,onSetIntelligenceOpen:h}=Se(),x=Ts(),b=Qa(u),p=b.length>0,{freeText:v,tokens:g}=Rs(b,x),y=g.find(Q=>Q.type==="from"),w={order:"desc",...v?{query:v}:{},...y?{from:y.value}:{},...g.some(Q=>Q.type==="hasAttachment")?{attachments:!0}:{},...g.some(Q=>Q.type==="isUnread")?{unread:!0}:{}},S=p?rl({path:{mailboxId:e},query:w}):ba({path:{mailboxId:e},query:{order:"desc"}}),{data:N,isLoading:R,isError:C,error:k,refetch:D,fetchNextPage:O,hasNextPage:A,isFetchingNextPage:P}=gc({queryKey:S,queryFn:async({pageParam:Q})=>{if(p){const{data:He}=await cl({path:{mailboxId:e},query:{...w,continuationToken:Q},throwOnError:!0});return He}const{data:qe}=await ff({path:{mailboxId:e},query:{order:"desc",continuationToken:Q},throwOnError:!0});return qe},initialPageParam:void 0,getNextPageParam:Q=>Q.continuationToken,enabled:p?b.length>0:!0,placeholderData:df}),E=c.useCallback(Q=>{t&&Q.includes(t)&&r({to:"/mail/$mailboxId",params:{mailboxId:e},search:qe=>({...qe,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,r]),{deleteMessages:j,isPending:I}=Qt({mailboxId:e,onAfterOptimisticRemove:E}),{accountId:L}=$c(e),T=Ec({accounts:l}),{moveMessages:F,isPending:M}=Tt({mailboxId:e,accountId:L,onAfterOptimisticRemove:E}),$=Nb(Mw(N?.pages.flatMap(Q=>Q.items??[])??[])),[K,_]=c.useState("all"),[X,ee]=c.useState(new Set),Y=c.useMemo(()=>Lw($,K,X),[$,K,X]),me=c.useCallback(Q=>{_(Q)},[]),ue=c.useCallback(Q=>{ee(qe=>{const He=new Set(qe);return He.has(Q)?He.delete(Q):He.add(Q),He})},[]),te=c.useCallback(()=>{_("all"),ee(new Set)},[]),q=Dw(f,u),U=Ow($,t,q),{selectedThreadId:re}=vs({strict:!1}),Pe=c.useMemo(()=>Fu(U,{messageId:t,threadId:q?void 0:re,mailboxId:e}),[U,t,re,q,e]),Re=Za(),{listCommandsRef:V,onTriageContextChange:J,focusedMessageId:ae,selectedIds:de}=Re,B=Y.find(Q=>Q.messageId===ae)??U,Qe=c.useRef(null);c.useEffect(()=>{const Q=U?.messageId??null;Q&&Qe.current!==Q&&U?.authenticity?.dkimMismatch&&(Qe.current=Q,d||m())},[U?.messageId,U?.authenticity?.dkimMismatch,d,m]);const Le=c.useRef(!1);c.useEffect(()=>{Le.current||o&&U?.messageId&&(Le.current=!0,Aw()&&!d&&h(!0))},[o,U?.messageId,d,h]);const we=Ex({accounts:l})??$.filter(Q=>!Q.isRead).length,Ye=ye(),{pushError:es}=Ze(),$e=Vs({thread:U,mailboxId:e,accountId:L,onAfterOptimisticRemove:E}),{draftsMailboxId:et}=kb(L),Fe=et!==void 0&&et===e,{archiveMailboxId:ze}=Sb(L),ct=$u(),{requestCompose:Ee}=$e,ts=c.useCallback(()=>{Ee("reply")},[Ee]),_e=c.useCallback(()=>{Ee("reply_all")},[Ee]),zt=c.useCallback(()=>{Ee("forward")},[Ee]),{state:ke,openCompose:Be,closeCompose:ut}=Mt(),ss=c.useCallback(()=>{Be({mode:"new"})},[Be]),_t=ve({...qn(),onError:Q=>{es(Vt("Couldn't discard draft","The draft wasn't deleted.",Q))}}),Z=c.useCallback(()=>{const Q=ke.outboxMessageId;Q&&(_t.mutate({path:{outboxMessageId:Q}}),Ye.invalidateQueries({queryKey:wa()}),ut())},[ke.outboxMessageId,_t,Ye,ut]),le=c.useCallback(()=>{r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Q=>({...Q,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,r]),ne=c.useCallback(Q=>Q?ct(Q):[],[ct]),{toggleStar:oe}=Ba({threadId:B?.threadId??"",mailboxId:e}),{toggleReadFor:fe}=Zn({mailboxId:e,accountId:L}),{junkMailboxId:he}=sr(L),xe=he!=null&&he===e,{candidates:Ke}=Rw(xe?he:void 0),{moveMessages:Me}=Tt({mailboxId:e,threadId:B?.threadId,accountId:L,onAfterOptimisticRemove:E}),{deleteMessages:Ue}=Qt({mailboxId:e,threadId:B?.threadId,onAfterOptimisticRemove:E}),{addressId:Ae,address:Ie}=Du(B),{updateFlags:Ge}=Ou({addressId:Ae,senderEmail:B?.fromEmail??void 0}),Ce=c.useCallback(()=>t||!ae?!1:(r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Q=>({...Q,selectedMessageId:ae})}),!0),[t,ae,e,r]),Bt=c.useCallback(()=>{Ce()||U&&Ee("reply")},[Ce,U,Ee]),cr=c.useCallback(()=>{Ce()||U&&Ee("reply_all")},[Ce,U,Ee]),ur=c.useCallback(()=>{Ce()||U&&Ee("forward")},[Ce,U,Ee]),dt=c.useCallback(()=>de.length>0?de:ne(B),[de,ne,B]),ns=c.useCallback(()=>{if(V.current?.requestDelete())return;const Q=dt();Q.length>0&&Ue(Q)},[V,dt,Ue]),dr=c.useCallback(()=>{if(!he)return;const Q=dt();Q.length!==0&&(Lu(i,{count:Q.length,senderTrust:B?.senderTrust??"unknown",wasRescuable:B?Pu(B):!1}),Me(Q,he))},[he,dt,Me,i,B]),Kt=c.useCallback(()=>{if(de.length>0){const Q=!(B?.hasStars??!1),qe=new Set(de);for(const He of Y)qe.has(He.messageId)&&He.hasStars!==Q&&oe(He.messageId,He.hasStars);return}B&&oe(B.messageId,B.hasStars)},[de,Y,B,oe]),fr=c.useCallback(()=>{const Q=dt();if(Q.length===0)return;const qe=!(B?.isRead??!1);fe(Q,qe)},[dt,B,fe]),mr=c.useCallback(()=>{if(!Ae)return;const Q=Ie?.flags?.muted?.value!==!0;Ge({muted:{value:Q}})},[Ae,Ie,Ge]),hr=c.useCallback(()=>{if(!Ae)return;const Q=Ie?.flags?.vip?.value!==!0;Ge({vip:{value:Q}})},[Ae,Ie,Ge]),un=c.useCallback(()=>{d||m()},[d,m]),vt=c.useCallback(Q=>{r({to:Q})},[r]),dn=Fe?"drafts":ze===e?"archive":he===e?"junk":"inbox",fn=c.useRef("");c.useEffect(()=>{const Q=fn.current;fn.current=b,b.length>0&&Q.length===0&&i.recordEvent("search.submitted",{mailboxType:dn})},[b,dn,i]);const mn=Fe&&ke.isOpen&&!!ke.outboxMessageId&&!U,{goBack:hn,nextMessageId:pn,previousMessageId:pr}=eo({context:Re,orderedIds:Y.map(Q=>Q.messageId),selectedMessageId:t,enabled:!ke.isOpen,onClose:le,handlers:{reply:Bt,replyAll:cr,forward:ur,delete:ns,toggleStar:Kt,toggleRead:fr,muteSender:mr,blockSender:un,vipSender:hr,markJunk:dr,toggleIntelligence:U?m:void 0,compose:ss,goBrief:()=>vt("/mail"),goInbox:()=>vt("/mail"),goSent:()=>vt("/mail"),goFlagged:()=>vt("/mail/flagged"),goSettings:()=>vt("/settings")}});za({enabled:ke.isOpen,bindings:[{key:"Escape",handler:ut,preventDefault:!0}]});const gr={mailboxId:e,selectedMessageId:t,selectedThread:U,conversation:Pe,threads:Y,isLoading:R,isError:C,error:k,mailboxAccountId:L,mailboxName:T,unreadCount:we,isDraftsMailbox:Fe,isSpamFolder:xe,rescueCandidates:Ke,filterCategory:K,filterAttributes:X,onSelectFilterCategory:me,onToggleFilterAttribute:ue,onClearFilters:te,intelligenceOpen:d,onToggleIntelligence:m,searchPredicate:p?w:void 0,onDeleteMessages:j,onMoveMessages:F,isDeleting:I,isMoving:M,onLoadMore:O,hasMore:A,isLoadingMore:P,onTriageContextChange:J,listCommandsRef:V,onRetry:()=>D(),toolbarComposeRequest:$e.composeRequest,onToolbarReply:ts,onToolbarReplyAll:_e,onToolbarForward:zt,onClearComposeRequest:$e.clearComposeRequest,onToolbarDelete:$e.deleteThread,onToolbarStar:$e.toggleStar,onToolbarDiscardDraft:Z,onToolbarMove:$e.moveThread,composeState:ke,closeCompose:ut,hasRemitDraftOpen:mn,onBack:hn,nextMessageId:pn,previousMessageId:pr};return n.jsx(td.Provider,{value:gr,children:s})}function sd(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:r,isError:a,error:o,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,mailboxAccountId:x,mailboxName:b,unreadCount:p,isDraftsMailbox:v,isSpamFolder:g,rescueCandidates:y,onTriageContextChange:w,listCommandsRef:S,onRetry:N,filterCategory:R,filterAttributes:C,onSelectFilterCategory:k,onToggleFilterAttribute:D,onClearFilters:O,searchPredicate:A}=lr(),{searchQuery:P,searchInput:E,accounts:j,resultFolderIndex:I}=Se(),L=ar(),T=De(),F=b??"Inbox",M=c.useMemo(()=>Pp(),[]),$=c.useMemo(()=>s.map(q=>qv(q,I)),[s,I]),{hits:K,isLoading:_}=gu({mailboxId:e,filterCategory:R}),X=c.useMemo(()=>yu(K,s.map(q=>q.threadId),I),[K,s,I]),ee=c.useCallback(q=>T({to:"/mail/$mailboxId",params:{mailboxId:q.mailboxId??e},search:U=>({...U,q:E||void 0,selectedMessageId:q.id,selectedThreadId:q.threadId})}),[e,T,E]);if(v&&x)return n.jsx(c0,{mailboxId:e,accountId:x,selectedMessageId:t,imapThreads:s,title:b??"Drafts",unreadCount:p??void 0});const Y=n.jsx(kw,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:r,isError:a,error:o,onRetry:N,searchQuery:P,searchPredicate:A,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,accountId:x,listTitle:F,hideHeader:!0,onTriageContextChange:w,commandsRef:S}),me=j[0]?.accountId,ue=L==="phone"&&me?n.jsx(Ew,{accountId:me,children:Y}):Y,te=g&&y.length>0&&x?n.jsx(Iw,{accountId:x,currentMailboxId:e,candidates:y,onMove:l,children:ue}):ue;return n.jsx(Ku,{title:F,unreadCount:p,preset:M,selectedCategory:R,activeFilters:C,onSelectCategory:k,onToggleFilter:D,onClearFilters:O,searchResults:$,searchLoading:r,relatedResults:X,relatedLoading:_,onSelectSearchResult:ee,searchResultsInBody:!0,children:te})}function Fw(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:r,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:l,onToolbarReply:u,onToolbarReplyAll:f,onToolbarForward:d,onClearComposeRequest:m,onToolbarDelete:h,onToolbarStar:x,onToolbarDiscardDraft:b,onToolbarMove:p,composeState:v}=lr(),g=ks()?.showIntelligencePane??!1,y=!!r,w=g&&y,S=v.isOpen&&!r?n.jsx(Hu,{}):r?n.jsx(Is,{threadId:r.threadId,mailboxId:r.mailboxId,subject:r.subject,selectedMessageId:r.messageId,authenticity:r.authenticity,onOpenIntelligence:r.authenticity?.dkimMismatch?i:void 0,composeRequest:l,onComposeClose:m}):n.jsx(Es,{});return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(Ja,{hasThread:y,intelligenceOpen:w&&o,canToggleIntelligence:w,onToggleIntelligence:i,onReply:y?u:void 0,onReplyAll:y?f:void 0,onForward:y?d:void 0,canDelete:y||a,onDelete:y?h:a?b:void 0,onToggleStar:y?x:void 0,isStarred:s?.hasStars,moveContext:y&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:S})]})}function zw(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:r}=lr();return n.jsx(Ms,{onClose:r,thread:s,mailboxId:e,accountId:t})}function _w(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:r,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=lr(),f=De();if(s){const d=m=>f({to:"/mail/$mailboxId",params:{mailboxId:e},search:h=>({...h,selectedMessageId:m,selectedThreadId:void 0})});return n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:s.threadId,mailboxId:s.mailboxId,subject:s.subject,selectedMessageId:s.messageId,authenticity:s.authenticity,onBack:o,onOpenIntelligence:a,onSwipeNext:i?()=>d(i):void 0,onSwipePrevious:l?()=>d(l):void 0,mobileIntelligenceOpen:r}),n.jsx($a,{isOpen:r,onClose:a,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?n.jsx("div",{className:"h-full",children:n.jsx(Hu,{})}):n.jsx(sd,{})}const _s=Object.assign($w,{List:sd,Reading:Fw,Intelligence:zw,Phone:_w}),nd=e=>e==="failed"||e==="blocked",rd=e=>e!=="draft"&&e!=="sent",so="remit.savedSearches",Bw=25;function _n(){try{const e=localStorage.getItem(so);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Kw(e){const t=e.trim();if(!t)return _n();const s=[t,..._n().filter(r=>r!==t)].slice(0,Bw);try{localStorage.setItem(so,JSON.stringify(s))}catch{return s}return s}function Uw(e){const t=_n().filter(s=>s!==e);try{localStorage.setItem(so,JSON.stringify(t))}catch{return t}return t}const _i=e=>/^\d/.test(e),qw=(e,t)=>{const s=_i(e),r=_i(t);return s&&!r?-1:!s&&r?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function Hw(e,t,s){const r=[],a=[];for(const o of e)t.has(o.mailboxId)?r.push(o):a.push(o);return a.sort((o,i)=>qw(xs(o,void 0,s),xs(i,void 0,s))),{system:r,labels:a}}function Ww(e,t,s){const r=mf(t)&&e.unseenCount>0;return{id:e.mailboxId,name:xs(e,t,s),unseen:r?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function Vw(){const e=Xn(),t=xa({strict:!1});return e.pathname.startsWith("/settings")?"settings":e.pathname.startsWith("/mail/outbox")?"outbox":e.pathname.startsWith("/mail/flagged")?"flagged":t.mailboxId?t.mailboxId:e.pathname==="/mail"||e.pathname==="/mail/"?"brief":""}function Bi({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const r=ye(),a=De(),o=Vw(),{searchInput:i,onSearchChange:l}=Se(),[u,f]=c.useState(_n),{t:d}=Kn("mail",{useSuspense:!1}),m=c.useCallback((k,D)=>d(k,{defaultValue:D}),[d]),h=Pt({queries:e.map(k=>({...Ve({path:{accountId:k.accountId}}),staleTime:1/0}))}),{data:x}=ce(Un()),b=c.useMemo(()=>(x?.items??[]).filter(k=>rd(k.status)).length,[x?.items]),p=c.useMemo(()=>e.map((k,D)=>{const O=h[D],A=O?.data?.items??[],P=Ss(k.folderAppointments),{system:E,labels:j}=Hw(A,P,m),I=O?.isError?"error":O?.isLoading?"loading":"ready";return{id:k.accountId,label:k.email,email:k.email,muted:!!k.muted,outboxPending:b,status:I,onRetry:()=>O?.refetch(),mailboxes:[...E,...j].map(L=>Ww(L,P.get(L.mailboxId),m))}}),[e,h,b,m]),v=k=>{r.invalidateQueries({queryKey:ba({path:{mailboxId:k},query:{order:"desc"}})})},g=({navId:k,className:D,ariaLabel:O,title:A,children:P,onClick:E})=>k==="brief"?n.jsx(mt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>E?.(),className:D,"aria-label":O,title:A,children:P}):k==="outbox"?n.jsx(mt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>E?.(),className:D,"aria-label":O,title:A,children:P}):k==="flagged"?n.jsx(mt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>E?.(),className:D,"aria-label":O,title:A,children:P}):k==="settings"?n.jsx(mt,{to:"/settings/accounts",onClick:()=>E?.(),className:D,"aria-label":O,title:A,children:P}):n.jsx(mt,{to:"/mail/$mailboxId",params:{mailboxId:k},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{v(k),E?.()},className:D,"aria-label":O,title:A,children:P}),y=()=>{l(""),t?.()},w=i.trim(),S=w.length>0&&!u.includes(w)?w:void 0,N=c.useCallback(()=>{S&&f(Kw(S))},[S]),R=c.useCallback(k=>{f(Uw(k))},[]),C=c.useCallback(k=>{l(k),a({to:"/mail",search:{q:k,selectedMessageId:void 0}}),t?.()},[l,a,t]);return n.jsx(Dh,{accounts:p,selectedNavId:o,onSelectNav:y,linkComponent:g,variant:s,savedSearches:u,saveableQuery:S,onSaveCurrentSearch:N,onSelectSavedSearch:C,onRemoveSavedSearch:R})}function Qw({accounts:e,onMailboxSelect:t}){return ks()?.showNavPane??!0?n.jsx(Bi,{accounts:e}):n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(Bi,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),n.jsxs("div",{className:"border-t border-line px-2 py-2",children:[n.jsxs(mt,{to:"/settings/accounts",onClick:t,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(Ia,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),n.jsx(yc,{variant:"drawer"}),n.jsx(vc,{children:({signOut:a})=>n.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[n.jsx(Dl,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function Yw(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const r=[e.subject,e.fromAddress,e.fromName,...e.toAddresses??[],...e.ccAddresses??[]].filter(a=>typeof a=="string").join(" ").toLowerCase();return s.split(/\s+/).every(a=>a.length===0||r.includes(a))}function Gw(e){return e.tokens.length>0&&e.freeText.trim().length===0}const ad={queued:{icon:Ea,label:"Queued",className:"text-warning"},sending:{icon:xt,label:"Sending…",className:"text-accent-2"},sent:{icon:Il,label:"Sent",className:"text-positive"},failed:{icon:Yt,label:"Failed",className:"text-danger"},blocked:{icon:ca,label:"Blocked",className:"text-warning"}},Xw=e=>Cf(e).toDateString()===new Date().toDateString()?On(e,{hour:"numeric",minute:"2-digit"}):On(e,{month:"short",day:"numeric"}),Ki=e=>On(e,{dateStyle:"medium",timeStyle:"short"}),Jw=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},od=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",id=c.createContext(null);function no(){const e=c.useContext(id);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function Zw({children:e}){const t=De(),{selectedOutboxMessageId:s}=vs({strict:!1}),{data:r,isLoading:a}=ce(Un()),{searchQuery:o}=Se(),i=Ts(),l=Qa(o),u=Rs(l,i),f=l.length>0,d=Gw(u),m=c.useMemo(()=>d?[]:(r?.items??[]).filter(p=>rd(p.status)).filter(p=>Yw(p,u.freeText)),[r,u.freeText,d]),h=c.useMemo(()=>m.find(p=>p.outboxMessageId===s),[m,s]),x=c.useCallback(p=>{t({to:"/mail/outbox",search:v=>({...v,selectedOutboxMessageId:p})})},[t]),b={messages:m,hasQuery:f,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:x};return n.jsx(id.Provider,{value:b,children:e})}function ld({message:e,isSelected:t,onSelect:s}){const r=ye(),{openCompose:a}=Mt(),{pushError:o}=Ze(),i=c.useCallback(()=>{r.invalidateQueries({queryKey:wa()})},[r]),l=ve({...nl(),onSuccess:i,onError:m=>{o(Vt("Couldn't resend message","The message wasn't sent.",m))}}),u=ve({...qn(),onSuccess:i,onError:m=>{o(Vt("Couldn't delete message","The message wasn't deleted.",m))}}),f=e.status;if(!ad[f])return null;const d=nd(e.status);return n.jsx(dp,{recipients:Jw(e),subject:e.subject||"",time:Xw(e.sentAt??e.updatedAt),status:f,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:f==="failed"?()=>l.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:l.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function cd({message:e,onBack:t}){const s=e.status,r=ad[s],a=r?.icon??Qs,o=e.sentAt?Ki(e.sentAt):Ki(e.updatedAt);return n.jsxs("div",{className:"h-full overflow-y-auto bg-canvas",children:[n.jsxs("div",{className:"border-b border-line p-4",children:[t&&n.jsxs("button",{type:"button",onClick:t,className:"mb-3 inline-flex items-center gap-1 text-sm text-fg-muted hover:text-fg",children:[n.jsx(Nl,{className:"size-4"}),n.jsx("span",{children:"Back"})]}),n.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),n.jsxs("div",{className:"space-y-1 text-sm",children:[n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),n.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),n.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),n.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),n.jsx("span",{className:"text-fg",children:o})]}),r&&n.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[n.jsx(a,{className:pe("size-4",r.className,s==="sending"&&"animate-spin")}),n.jsx("span",{className:pe("text-xs font-medium",r.className),children:r.label}),nd(e.status)&&e.lastError&&n.jsxs("span",{className:"text-xs text-fg-muted",children:["— ",e.lastError]})]})]})]}),n.jsx("div",{className:"p-4",children:n.jsx(mu,{html:e.htmlBody,text:e.textBody})})]})}function ej(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,onSelectMessage:o}=no(),i=c.useRef(null);return Bn({containerRef:i,itemSelector:aa}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Es,{message:od(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(to,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(l=>n.jsx(ld,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function tj(){const{selectedMessage:e}=no();return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx("header",{className:"flex h-pane-header shrink-0 items-center border-b border-line px-3"}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(cd,{message:e}):n.jsx(Es,{message:"Select a message to read",showHints:!1})})]})}function sj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=no(),l=c.useRef(null);return Bn({containerRef:l,itemSelector:aa}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?n.jsx(cd,{message:o,onBack:()=>i(void 0)}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Es,{message:od(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(to,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:l,className:"flex-1 overflow-y-auto",children:e.map(u=>n.jsx(ld,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const En=Object.assign(Zw,{List:ej,Reading:tj,Phone:sj}),nj=({isOpen:e,onClose:t})=>{const s=c.useCallback(r=>{r.key==="Escape"&&(r.preventDefault(),t())},[t]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:t,onKeyDown:r=>r.key==="Escape"&&t(),children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{className:pe("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),onClick:r=>r.stopPropagation(),onKeyDown:r=>{r.key!=="Escape"&&r.stopPropagation()},children:[n.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),n.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:n.jsx(We,{className:"size-5"})})]}),n.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:Tc.map(r=>n.jsxs("div",{children:[n.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:r.title}),n.jsx("div",{className:"space-y-2",children:r.hints.map(a=>n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsx("span",{className:"text-sm",children:a.description}),n.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>n.jsxs(c.Fragment,{children:[i>0&&a.keys[0]==="g"&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),n.jsx(hs,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},r.title))}),n.jsx("div",{className:"mt-6 border-t border-line pt-4",children:n.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",n.jsx(hs,{children:"Esc"})," to close"]})})]})]}):null};function rj(e){const t=new Map;for(const s of e){const r=s.email.toLowerCase(),a=r.split("@")[0];a&&!t.has(a)&&t.set(a,s.accountId),t.has(r)||t.set(r,s.accountId)}return t}function aj(e){const t=new Map;for(const s of e)for(const r of s){const a=r.fullPath?.toLowerCase();if(!a)continue;const o=a.split("/").pop();t.has(a)||t.set(a,r.mailboxId),o&&!t.has(o)&&t.set(o,r.mailboxId)}return t}function oj(e){const t=Pt({queries:e.map(s=>({...Ve({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>aj(t.map(s=>s.data?.items??[])),[t])}const ij=e=>e.map(t=>t.data?.items??[]);function lj(e){const t=Pt({queries:e.map(s=>({...Ve({path:{accountId:s.accountId}}),staleTime:1/0})),combine:ij});return c.useMemo(()=>hf(e.map((s,r)=>({folderAppointments:s.folderAppointments,mailboxes:t[r]??[]}))),[e,t])}var In={exports:{}},Ui;function cj(){if(Ui)return In.exports;Ui=1;const e=(t,s,r)=>new Promise((a,o)=>{if(r=Object.assign({concurrency:1/0},r),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=r;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const l=[],u=t[Symbol.iterator]();let f=!1,d=!1,m=0,h=0;const x=()=>{if(f)return;const b=u.next(),p=h;if(h++,b.done){d=!0,m===0&&a(l);return}m++,Promise.resolve(b.value).then(v=>s(v,p)).then(v=>{l[p]=v,m--,x()},v=>{f=!0,o(v)})};for(let b=0;b<i&&(x(),!d);b++);});return In.exports=e,In.exports.default=e,In.exports}var uj=cj();const dj=pf(uj),fj=900*1e3,mj=300,hj=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},pj=60*1e3,gj=e=>Math.max(hj(e,mj)*1e3,pj),Dn=gj(bf().mailboxPollIntervalSeconds),xj=5,na=new Set,bj=(e,t,s=fj)=>e.filter(r=>{const a=r.lastSyncAt;return a==null?!0:t-a>s}).map(r=>r.accountId),vj=(e,t,s=Dn)=>e-t>=s,yj=(e,t)=>e.filter(s=>!t.has(s)),qi=(e,t)=>{if(na.delete(e),xf(t,{softError:!0})){ll(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},Hi=(e,t)=>gf({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:Xt({path:{accountId:e}})})}),wj=e=>{const t=ye(),s=c.useRef(e);s.current=e;const r=e.map(a=>a.accountId).join(",");c.useEffect(()=>{const a=Date.now(),i=bj(s.current,a).filter(l=>!na.has(l));if(i.length!==0)for(const l of i)na.add(l),Hi(l,t).catch(u=>{qi(l,u)})},[r,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const d=yj(s.current.map(m=>m.accountId),i);for(const m of d)i.add(m);dj(d,m=>Hi(m,t).catch(h=>{qi(m,h)}).finally(()=>{i.delete(m)}),{concurrency:xj})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,Dn);return}},f=()=>{document.visibilityState==="visible"&&vj(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,Dn))};return o=setTimeout(u,Dn),document.addEventListener("visibilitychange",f),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",f)}},[r,t])};function jj(e,t,s){if(e!==t)return s}function Sj(e,t){return e===""?"":t}function kj(e,t,s){return t!==e?!1:t!==s}function Cj(){const{q:e=""}=vs({from:"/mail"}),t=De(),s=ar(),r=wu(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,f]=c.useState(!1),d=c.useCallback(te=>{f(te),zi(te)},[]),[m,h]=c.useState(e),x=ul(m,200),b=Sj(m,x),p=c.useRef(e);p.current=e;const v=ht({select:te=>jx(te.matches)}),[g,y]=c.useState(v);if(g!==v){const te=jj(g,v,e);y(v),te!==void 0&&h(te)}c.useEffect(()=>{kj(m,b,p.current)&&t({to:".",search:te=>{const q=te.q===b;return{...te,q:b||void 0,...b&&!q?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[m,b,t]);const{data:w,isLoading:S,isError:N,error:R,refetch:C}=ce({...gt(),staleTime:1/0}),k=!!(w&&(w.accounts?.length??0)===0);c.useEffect(()=>{k&&t({to:"/onboarding",replace:!0})},[k,t]),za({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const D=c.useCallback(te=>{h(te)},[]),O=c.useCallback(()=>{h("")},[]),A=c.useCallback(()=>{h("")},[]),P=c.useCallback(()=>{f(te=>{const q=!te;return zi(q),q})},[]),E=w?.accounts??[],j=oj(E),I=lj(E),L=c.useMemo(()=>rj(E),[E]),T=ht({select:te=>te.matches.find(U=>"mailboxId"in U.params)?.params.mailboxId}),{selectedMessageId:F}=vs({strict:!1}),M=ht({select:te=>La(te.matches)}),$=ht({select:te=>sn(te.matches)}),K=ht({select:te=>Jn(te.matches)});wj(E);const _=c.useCallback(()=>{l(!1)},[]),X={accounts:E,mailboxNameIndex:j,accountNameIndex:L,resultFolderIndex:I,searchQuery:b,searchInput:m,searchViewKey:v,onSearchChange:D,onSearchClear:O,onSearchClearQuery:A,intelligenceOpen:u,onToggleIntelligence:P,onSetIntelligenceOpen:d},ee=n.jsx(Qw,{accounts:E,onMailboxSelect:_}),Y=r?n.jsx(vx,{accounts:E}):void 0,me=r?void 0:n.jsx(Rx,{accounts:E}),ue={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return n.jsxs(vf.Provider,{value:X,children:[N?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:n.jsx(At,{title:"Couldn't load your account",error:R,onRetry:()=>{C()}})}):M?n.jsx($s,{selectedMessageId:F,children:r?n.jsx(wt,{nav:ee,list:n.jsx($s.Phone,{}),intelligenceOpen:u,overlay:Y,skeleton:n.jsx(ft,{}),isLoading:S||k,...ue}):n.jsx(wt,{nav:ee,topBar:me,list:n.jsx($s.List,{}),reading:n.jsx($s.Reading,{}),intelligence:n.jsx($s.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:Y,skeleton:n.jsx(ft,{}),isLoading:S||k,...ue})}):$?n.jsx(Fs,{selectedMessageId:F,children:r?n.jsx(wt,{nav:ee,list:n.jsx(Fs.Phone,{}),intelligenceOpen:u,overlay:Y,skeleton:n.jsx(ft,{}),isLoading:S||k,...ue}):n.jsx(wt,{nav:ee,topBar:me,list:n.jsx(Fs.List,{}),reading:n.jsx(Fs.Reading,{}),intelligence:n.jsx(Fs.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:Y,skeleton:n.jsx(ft,{}),isLoading:S||k,...ue})}):T?n.jsx(_s,{mailboxId:T,selectedMessageId:F,children:r?n.jsx(wt,{nav:ee,list:n.jsx(_s.Phone,{}),intelligenceOpen:u,overlay:Y,skeleton:n.jsx(ft,{}),isLoading:S||k,...ue}):n.jsx(wt,{nav:ee,topBar:me,list:n.jsx(_s.List,{}),reading:n.jsx(_s.Reading,{}),intelligence:n.jsx(_s.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:Y,skeleton:n.jsx(ft,{}),isLoading:S||k,...ue})}):K?n.jsx(En,{children:r?n.jsx(wt,{nav:ee,list:n.jsx(En.Phone,{}),intelligenceOpen:!1,overlay:Y,skeleton:n.jsx(ft,{}),isLoading:S||k,...ue}):n.jsx(wt,{nav:ee,topBar:me,list:n.jsx(En.List,{}),reading:n.jsx(En.Reading,{}),intelligenceOpen:!1,overlay:Y,skeleton:n.jsx(ft,{}),isLoading:S||k,...ue})}):n.jsx(ft,{}),n.jsx(nj,{isOpen:a,onClose:()=>o(!1)}),n.jsx(yf,{})]})}const Bj=Object.freeze(Object.defineProperty({__proto__:null,component:Cj,useMailContext:Se},Symbol.toStringTag,{value:"Module"}));export{_j as S,Im as U,Bj as m};