@remit/web-client-dist 0.0.194 → 0.0.196

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 (38) hide show
  1. package/assets/{ComposeBody-BYDXbvpM.js → ComposeBody-PaioGRCf.js} +1 -1
  2. package/assets/{ConfirmDialog-BBJ9XhWo.js → ConfirmDialog-DZRbTR_Q.js} +1 -1
  3. package/assets/{ErrorState-DAQZTqVj.js → ErrorState-B1m0Htkw.js} +1 -1
  4. package/assets/{OnboardingWizard-CqjaKY40.js → OnboardingWizard-CWaVbxbx.js} +1 -1
  5. package/assets/{account-form-helpers-Bb5Mzx-W.js → account-form-helpers-Dw8IX5ad.js} +1 -1
  6. package/assets/{accounts-DNMv22Ld.js → accounts-X1ShI88H.js} +1 -1
  7. package/assets/{advanced-7Cb_OYvP.js → advanced-BmGalmey.js} +1 -1
  8. package/assets/{appearance-PzGNfpZ3.js → appearance-C6Sr9VRe.js} +1 -1
  9. package/assets/{avatar-T5lzsM7Y.js → avatar-BFql-Wf3.js} +1 -1
  10. package/assets/{browser-ponyfill-fygSgvhd.js → browser-ponyfill-CIc2O2ss.js} +1 -1
  11. package/assets/{circle-check-DkRP515Q.js → circle-check-BzcLYagA.js} +1 -1
  12. package/assets/{download-DuchNXsv.js → download-D3vX661x.js} +1 -1
  13. package/assets/{filters-DTIN3swS.js → filters-BNIvedmO.js} +1 -1
  14. package/assets/{flagged-CCW2SHDY.js → flagged-CiFVGUbQ.js} +1 -1
  15. package/assets/{folders-BTYmh297.js → folders-CALbsNI3.js} +1 -1
  16. package/assets/index-C0v7_T0F.js +1 -0
  17. package/assets/{index-CH_b9XR8.js → index-CKFUe2Hf.js} +4 -4
  18. package/assets/{index-CT5X-uh9.js → index-c7-N9vnh.js} +1 -1
  19. package/assets/{kbd-573nWHcn.js → kbd-BlUZIvOx.js} +1 -1
  20. package/assets/{labels-ZYU612BI.js → labels-7OoO6vj3.js} +1 -1
  21. package/assets/{mail-DbuDzs6e.js → mail-CPS9KUT6.js} +3 -3
  22. package/assets/{move-mailbox-picker-Bg1rm2gg.js → move-mailbox-picker-aWLZRXnO.js} +1 -1
  23. package/assets/{move-targets-DZ4ZYhsX.js → move-targets-BznNJwIY.js} +1 -1
  24. package/assets/{onboarding-nbQ5S-kq.js → onboarding-DbR84ysV.js} +1 -1
  25. package/assets/{search-55AsdJdg.js → search-B2bPE-iK.js} +1 -1
  26. package/assets/{senders-BELBmhfY.js → senders-B6P4l5Pi.js} +1 -1
  27. package/assets/settings-Cu83jD12.js +1 -0
  28. package/assets/{settings-screen-MGFNwOof.js → settings-screen-CLOXT-9K.js} +1 -1
  29. package/assets/{shield-check-Ds-LwrMW.js → shield-check-DpuRrVB8.js} +1 -1
  30. package/assets/{suggested-vips-C0m4_Iuy.js → suggested-vips-DfHKQsjf.js} +1 -1
  31. package/assets/{useDebouncedValue-DnNOfVqb.js → useDebouncedValue-oa1RpC9E.js} +1 -1
  32. package/assets/{useLabels-DFyrrw4J.js → useLabels-Cvsyvf4k.js} +1 -1
  33. package/assets/{useRulePreview-BoH4YPfl.js → useRulePreview-CNVWuuDh.js} +1 -1
  34. package/assets/{useSignature-D4u_dE4_.js → useSignature-BRr_qVQ8.js} +1 -1
  35. package/index.html +1 -1
  36. package/package.json +1 -1
  37. package/assets/index-D5-LTXZg.js +0 -1
  38. package/assets/settings-B93B-K1V.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-BYDXbvpM.js","assets/index-CH_b9XR8.js","assets/index-CptAZLJ2.css","assets/search-55AsdJdg.js","assets/avatar-T5lzsM7Y.js","assets/kbd-573nWHcn.js","assets/shield-check-Ds-LwrMW.js","assets/account-form-helpers-Bb5Mzx-W.js","assets/useSignature-D4u_dE4_.js","assets/useDebouncedValue-DnNOfVqb.js","assets/useRulePreview-BoH4YPfl.js","assets/ErrorState-DAQZTqVj.js","assets/format-B6Elex-n.js","assets/move-targets-DZ4ZYhsX.js","assets/move-mailbox-picker-Bg1rm2gg.js","assets/circle-check-DkRP515Q.js","assets/ConfirmDialog-BBJ9XhWo.js","assets/useLabels-DFyrrw4J.js"])))=>i.map(i=>d[i]);
2
- import{R as U,c as _d,r as c,a as me,j as n,C as Ot,X as We,b as q,B as V,d as ut,S as Pt,e as ft,f as Zt,L as et,g as da,h as zd,i as Bd,k as en,T as at,l as es,u as qn,m as fa,n as el,I as ma,p as tl,o as ha,q as Kd,D as pa,s as tn,O as Ud,M as qd,A as Hd,F as sl,t as Wd,v as Vd,w as Qd,x as Yd,y as ga,z as xa,P as Gd,E as Xd,G as ba,H as va,_ as Tt,J as nl,K as Jd,Q as ya,N as Zd,U as ef,V as tf,W as Wr,Y as sf,Z as nf,$ as ye,a0 as rf,a1 as af,a2 as of,a3 as lf,a4 as cf,a5 as uf,a6 as So,a7 as df,a8 as ff,a9 as mf,aa as wa,ab as rl,ac as al,ad as Lt,ae as Me,af as Ue,ag as sn,ah as be,ai as ja,aj as Sa,ak as ka,al as Ca,am as Hn,an as ys,ao as Ce,ap as nn,aq as fe,ar as ol,as as hf,at as ve,au as il,av as pf,aw as Wn,ax as ll,ay as vt,az as Ve,aA as gf,aB as rt,aC as cl,aD as Yt,aE as Vn,aF as xf,aG as Na,aH as ul,aI as dl,aJ as ts,aK as Qn,aL as ss,aM as bf,aN as vf,aO as Yn,aP as yf,aQ as fl,aR as ws,aS as wf,aT as Ea,aU as jf,aV as Sf,aW as ml,aX as Ia,aY as hl,aZ as pl,a_ as ks,a$ as kf,b0 as ko,b1 as Cf,b2 as Nf,b3 as xt,b4 as Vr,b5 as Qr,b6 as Ef,b7 as gl,b8 as If,b9 as Ta,ba as xl,bb as Tf,bc as Rf,bd as Mf,be as Af,bf as Of,bg as Df,bh as Pf,bi as Lf,bj as $f,bk as Ff,bl as _f,bm as zf,bn as Bf,bo as Kf,bp as Et,bq as gt,br as Uf}from"./index-CH_b9XR8.js";import{S as Gn}from"./search-55AsdJdg.js";import{A as mt,M as Ra,C as qf}from"./avatar-T5lzsM7Y.js";import{K as xs}from"./kbd-573nWHcn.js";import{S as rn,C as Ma,R as Hf}from"./shield-check-Ds-LwrMW.js";import{M as bl,a as Wf}from"./account-form-helpers-Bb5Mzx-W.js";import{R as Vf,u as Qf}from"./useSignature-D4u_dE4_.js";import{u as vl}from"./useDebouncedValue-DnNOfVqb.js";import{B as yl,u as $t,a as Co,b as Yr,n as Yf,S as Aa,c as wl,r as Oa,d as jl,e as Sl,f as kl,g as Gf,h as Xf,i as Jf,j as Zf,k as em}from"./useRulePreview-BoH4YPfl.js";import{E as Ft,f as Cl}from"./ErrorState-DAQZTqVj.js";import{f as Nl,a as _t,b as El,c as $n,d as dt,t as tm}from"./format-B6Elex-n.js";import{P as No,u as Il,b as an,M as nt}from"./move-targets-DZ4ZYhsX.js";import{F as Da,a as sm,M as Tl}from"./move-mailbox-picker-Bg1rm2gg.js";import{C as Xn}from"./circle-check-DkRP515Q.js";import{C as Pa}from"./ConfirmDialog-BBJ9XhWo.js";import{u as Rl,a as nm}from"./useLabels-DFyrrw4J.js";function Qs(e){if(rm())e.focus({preventScroll:!0});else{let t=am(e);e.focus(),om(t)}}let vn=null;function rm(){if(vn==null){vn=!1;try{document.createElement("div").focus({get preventScroll(){return vn=!0,!0}})}catch{}}return vn}function am(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 om(e){for(let{element:t,scrollTop:s,scrollLeft:r}of e)t.scrollTop=s,t.scrollLeft=r}const Mt=e=>e?.ownerDocument??document,Dt=e=>e&&"window"in e&&e.window===e?e:Mt(e).defaultView||window;function im(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function lm(e){return im(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let cm=!1;function Ml(){return cm}function ct(e,t){if(!Ml())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:lm(s)?s=s.host:s=s.parentNode}return!1}function Te(e){if(Ml()&&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 um=typeof Element<"u"&&"checkVisibility"in Element.prototype;function dm(e){const t=Dt(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}=Dt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function fm(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 Al(e,t){return um?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&dm(e)&&fm(e,t)&&(!e.parentElement||Al(e.parentElement,e))}const Ol=["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"],mm=Ol.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";Ol.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function hm(e,t){return e.matches(mm)&&!pm(e)&&(t?.skipVisibilityCheck||Al(e))}function pm(e){let t=e;for(;t!=null;){if(t instanceof Dt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const La=typeof document<"u"?U.useLayoutEffect:()=>{};function gm(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function xm(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function bm(e){for(;e&&!hm(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Dt(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,Qs(s),u()))},i=d=>{(Te(d)===e||r)&&d.stopImmediatePropagation()},l=d=>{(Te(d)===e||r)&&(d.stopImmediatePropagation(),r||(r=!0,Qs(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 Jn(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 $a(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function zt(e){let t=null;return()=>(t==null&&(t=e()),t)}const Fn=zt(function(){return $a(/^Mac/i)}),vm=zt(function(){return $a(/^iPhone/i)}),Dl=zt(function(){return $a(/^iPad/i)||Fn()&&navigator.maxTouchPoints>1}),Pl=zt(function(){return vm()||Dl()}),ym=zt(function(){return Jn(/AppleWebKit/i)&&!wm()}),wm=zt(function(){return Jn(/Chrome/i)}),Ll=zt(function(){return Jn(/Android/i)}),jm=zt(function(){return Jn(/Firefox/i)});function Sm(e){return e.pointerType===""&&e.isTrusted?!0:Ll()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function km(e){return!Ll()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function Ys(e,t,s=!0){let{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}=t;jm()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Fn()?r=!0:a=!0);let l=ym()&&Fn()&&!Dl()?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});Ys.isOpening=s,Qs(e),e.dispatchEvent(l),Ys.isOpening=!1}Ys.isOpening=!1;let Rt=new Map,Gr=new Set;function Eo(){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=Rt.get(a);o||(o=new Set,Rt.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=Rt.get(a);if(o&&(o.delete(r.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Rt.delete(a)),Rt.size===0)){for(let i of Gr)i();Gr.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?Eo():document.addEventListener("DOMContentLoaded",Eo));function Cm(){for(const[e]of Rt)"isConnected"in e&&!e.isConnected&&Rt.delete(e)}function Nm(e){requestAnimationFrame(()=>{Cm(),Rt.size===0?e():Gr.add(e)})}function $l(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let Xr=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{Xr.delete(e)});function Em(e,t){if(e===t)return e;let s=Xr.get(e);if(s)return s.forEach(a=>a.current=t),t;let r=Xr.get(t);return r?(r.forEach(a=>a.current=e),e):t}function Im(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const r=e.map(a=>{const o=Io(a,t);return s||=typeof o=="function",o});if(s)return()=>{r.forEach((a,o)=>{typeof a=="function"?a():Io(e[o],null)})}}}function Io(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Cs(...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]=$l(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=_d(o,i):a==="id"&&o&&i?t.id=Em(o,i):a==="ref"&&o&&i?t.ref=Im(o,i):t[a]=i!==void 0?i:o}}return t}function Tm(e,t){La(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const Rm=U.useInsertionEffect??La;function Cr(e){const t=c.useRef(null);return Rm(()=>{t.current=e},[e]),c.useCallback((...s)=>{const r=t.current;return r?.(...s)},[])}let ps="default",Jr="",An=new WeakMap;function Mm(e){if(Pl()){if(ps==="default"){const t=Mt(e);Jr=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}ps="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";An.set(e,e.style[t]),e.style[t]="none"}}function To(e){if(Pl()){if(ps!=="disabled")return;ps="restoring",setTimeout(()=>{Nm(()=>{if(ps==="restoring"){const t=Mt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=Jr||""),Jr="",ps="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&An.has(e)){let t=An.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),An.delete(e)}}function Ro(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Nr=new WeakMap;function Am(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return Ro(t);if(Nr.has(t))return Nr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),r=s&&s instanceof Dt(s).HTMLMetaElement&&(s.nonce||s.content)||Ro(t)||void 0;return r!==void 0&&Nr.set(t,r),r}const Fl=U.createContext({register:()=>{}});Fl.displayName="PressResponderContext";function _l(){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(Fl);if(t){let{register:s,ref:r,...a}=t;e=Cs(a,e),s()}return Tm(t,e.ref),e}class yn{#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 Mo=Symbol("linkClicked"),Ao="react-aria-pressable-style",Oo="data-react-aria-pressable";function Dm(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,...g}=Om(e),[v,p]=c.useState(!1),x=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:y}=_l(),j=c.useCallback((S,O)=>{let L=x.current;if(l||L.didFirePressStart)return!1;let T=!0;if(L.isTriggeringEvent=!0,r){let $=new yn("pressstart",O,S);r($),T=$.shouldStopPropagation}return s&&s(!0),L.isTriggeringEvent=!1,L.didFirePressStart=!0,p(!0),T},[l,r,s]),w=c.useCallback((S,O,L=!0)=>{let T=x.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let $=!0;if(a){let R=new yn("pressend",O,S);a(R),$=R.shouldStopPropagation}if(s&&s(!1),p(!1),t&&L&&!l){let R=new yn("press",O,S);t(R),$&&=R.shouldStopPropagation}return T.isTriggeringEvent=!1,$},[l,a,s,t]),E=Cr(w),N=c.useCallback((S,O)=>{let L=x.current;if(l)return!1;if(o){L.isTriggeringEvent=!0;let T=new yn("pressup",O,S);return o(T),L.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[l,o]),k=Cr(N),C=c.useCallback(S=>{let O=x.current;if(O.isPressed&&O.target){O.didFirePressStart&&O.pointerType!=null&&w(Ht(O.target,S),O.pointerType,!1),O.isPressed=!1,O.isOverTarget=!1,O.activePointerId=null,O.pointerType=null,y(),m||To(O.target);for(let L of O.disposables)L();O.disposables=[]}},[m,y,w]),M=Cr(C);c.useEffect(()=>{l&&x.current.isPressed&&M({currentTarget:x.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let A=c.useCallback(S=>{d&&C(S)},[d,C]),D=c.useCallback(S=>{l||i?.(S)},[l,i]),P=c.useCallback((S,O)=>{if(!l&&i){let L=new MouseEvent("click",S);xm(L,O),i(gm(L))}},[l,i]),I=c.useMemo(()=>{let S=x.current,O={onKeyDown(T){if(Er(T.nativeEvent,T.currentTarget)&&ct(T.currentTarget,Te(T))){Do(Te(T),T.key)&&T.preventDefault();let $=!0;!S.isPressed&&!T.repeat&&(S.target=T.currentTarget,S.isPressed=!0,S.pointerType="keyboard",$=j(T,"keyboard"));let R=T.currentTarget,F=Q=>{Er(Q,R)&&!Q.repeat&&ct(R,Te(Q))&&S.target&&k(Ht(S.target,Q),"keyboard")};b(Mt(T.currentTarget),"keyup",$l(F,L),!0),$&&T.stopPropagation(),T.metaKey&&Fn()&&S.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(S.metaKeyEvents=new Map)},onClick(T){if(!(T&&!ct(T.currentTarget,Te(T)))&&T&&T.button===0&&!S.isTriggeringEvent&&!Ys.isOpening){let $=!0;if(l&&T.preventDefault(),!S.ignoreEmulatedMouseEvents&&!S.isPressed&&(S.pointerType==="virtual"||Sm(T.nativeEvent))){let R=j(T,"virtual"),F=k(T,"virtual"),Q=E(T,"virtual");D(T),$=R&&F&&Q}else if(S.isPressed&&S.pointerType!=="keyboard"){let R=S.pointerType||T.nativeEvent.pointerType||"virtual",F=k(Ht(T.currentTarget,T),R),Q=E(Ht(T.currentTarget,T),R,!0);$=F&&Q,S.isOverTarget=!1,D(T),M(T)}S.ignoreEmulatedMouseEvents=!1,$&&T.stopPropagation()}}},L=T=>{if(S.isPressed&&S.target&&Er(T,S.target)){Do(Te(T),T.key)&&T.preventDefault();let $=Te(T),R=ct(S.target,$);E(Ht(S.target,T),"keyboard",R),R&&P(T,S.target),y(),T.key!=="Enter"&&Fa(S.target)&&ct(S.target,$)&&!T[Mo]&&(T[Mo]=!0,Ys(S.target,T,!1)),S.isPressed=!1,S.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&S.metaKeyEvents?.size){let $=S.metaKeyEvents;S.metaKeyEvents=void 0;for(let R of $.values())S.target?.dispatchEvent(new KeyboardEvent("keyup",R))}};if(typeof PointerEvent<"u"){O.onPointerDown=R=>{if(R.button!==0||!ct(R.currentTarget,Te(R)))return;if(km(R.nativeEvent)){S.pointerType="virtual";return}S.pointerType=R.pointerType;let F=!0;if(!S.isPressed){S.isPressed=!0,S.isOverTarget=!0,S.activePointerId=R.pointerId,S.target=R.currentTarget,m||Mm(S.target),F=j(R,S.pointerType);let Q=Te(R);"releasePointerCapture"in Q&&("hasPointerCapture"in Q?Q.hasPointerCapture(R.pointerId)&&Q.releasePointerCapture(R.pointerId):Q.releasePointerCapture(R.pointerId)),b(Mt(R.currentTarget),"pointerup",T,!1),b(Mt(R.currentTarget),"pointercancel",$,!1)}F&&R.stopPropagation()},O.onMouseDown=R=>{if(ct(R.currentTarget,Te(R))&&R.button===0){if(f){let F=bm(R.target);F&&S.disposables.push(F)}R.stopPropagation()}},O.onPointerUp=R=>{!ct(R.currentTarget,Te(R))||S.pointerType==="virtual"||R.button===0&&!S.isPressed&&k(R,S.pointerType||R.pointerType)},O.onPointerEnter=R=>{R.pointerId===S.activePointerId&&S.target&&!S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!0,j(Ht(S.target,R),S.pointerType))},O.onPointerLeave=R=>{R.pointerId===S.activePointerId&&S.target&&S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!1,E(Ht(S.target,R),S.pointerType,!1),A(R))};let T=R=>{if(R.pointerId===S.activePointerId&&S.isPressed&&R.button===0&&S.target){if(ct(S.target,Te(R))&&S.pointerType!=null){let F=!1,Q=setTimeout(()=>{S.isPressed&&S.target instanceof HTMLElement&&(F?M(R):(Qs(S.target),S.target.click()))},80);b(R.currentTarget,"click",()=>F=!0,!0),S.disposables.push(()=>clearTimeout(Q))}else M(R);S.isOverTarget=!1}},$=R=>{M(R)};O.onDragStart=R=>{ct(R.currentTarget,Te(R))&&M(R)}}return O},[b,l,f,y,m,A,j,D,P]);return c.useEffect(()=>{if(!h)return;const S=Mt(h.current);if(!S||!S.head||S.getElementById(Ao))return;const O=S.createElement("style");O.id=Ao;let L=Am(S);L&&(O.nonce=L),O.textContent=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-PaioGRCf.js","assets/index-CKFUe2Hf.js","assets/index-CptAZLJ2.css","assets/search-B2bPE-iK.js","assets/avatar-BFql-Wf3.js","assets/kbd-BlUZIvOx.js","assets/shield-check-DpuRrVB8.js","assets/account-form-helpers-Dw8IX5ad.js","assets/useSignature-BRr_qVQ8.js","assets/useDebouncedValue-oa1RpC9E.js","assets/useRulePreview-CNVWuuDh.js","assets/ErrorState-B1m0Htkw.js","assets/format-B6Elex-n.js","assets/move-targets-BznNJwIY.js","assets/move-mailbox-picker-aWLZRXnO.js","assets/circle-check-BzcLYagA.js","assets/ConfirmDialog-DZRbTR_Q.js","assets/useLabels-Cvsyvf4k.js"])))=>i.map(i=>d[i]);
2
+ import{R as U,c as _d,r as c,a as me,j as n,C as Ot,X as We,b as q,B as V,d as ut,S as Pt,e as ft,f as Zt,L as et,g as da,h as zd,i as Bd,k as en,T as at,l as es,u as qn,m as fa,n as el,I as ma,p as tl,o as ha,q as Kd,D as pa,s as tn,O as Ud,M as qd,A as Hd,F as sl,t as Wd,v as Vd,w as Qd,x as Yd,y as ga,z as xa,P as Gd,E as Xd,G as ba,H as va,_ as Tt,J as nl,K as Jd,Q as ya,N as Zd,U as ef,V as tf,W as Wr,Y as sf,Z as nf,$ as ye,a0 as rf,a1 as af,a2 as of,a3 as lf,a4 as cf,a5 as uf,a6 as So,a7 as df,a8 as ff,a9 as mf,aa as wa,ab as rl,ac as al,ad as Lt,ae as Me,af as Ue,ag as sn,ah as be,ai as ja,aj as Sa,ak as ka,al as Ca,am as Hn,an as ys,ao as Ce,ap as nn,aq as fe,ar as ol,as as hf,at as ve,au as il,av as pf,aw as Wn,ax as ll,ay as vt,az as Ve,aA as gf,aB as rt,aC as cl,aD as Yt,aE as Vn,aF as xf,aG as Na,aH as ul,aI as dl,aJ as ts,aK as Qn,aL as ss,aM as bf,aN as vf,aO as Yn,aP as yf,aQ as fl,aR as ws,aS as wf,aT as Ea,aU as jf,aV as Sf,aW as ml,aX as Ia,aY as hl,aZ as pl,a_ as ks,a$ as kf,b0 as ko,b1 as Cf,b2 as Nf,b3 as xt,b4 as Vr,b5 as Qr,b6 as Ef,b7 as gl,b8 as If,b9 as Ta,ba as xl,bb as Tf,bc as Rf,bd as Mf,be as Af,bf as Of,bg as Df,bh as Pf,bi as Lf,bj as $f,bk as Ff,bl as _f,bm as zf,bn as Bf,bo as Kf,bp as Et,bq as gt,br as Uf}from"./index-CKFUe2Hf.js";import{S as Gn}from"./search-B2bPE-iK.js";import{A as mt,M as Ra,C as qf}from"./avatar-BFql-Wf3.js";import{K as xs}from"./kbd-BlUZIvOx.js";import{S as rn,C as Ma,R as Hf}from"./shield-check-DpuRrVB8.js";import{M as bl,a as Wf}from"./account-form-helpers-Dw8IX5ad.js";import{R as Vf,u as Qf}from"./useSignature-BRr_qVQ8.js";import{u as vl}from"./useDebouncedValue-oa1RpC9E.js";import{B as yl,u as $t,a as Co,b as Yr,n as Yf,S as Aa,c as wl,r as Oa,d as jl,e as Sl,f as kl,g as Gf,h as Xf,i as Jf,j as Zf,k as em}from"./useRulePreview-CNVWuuDh.js";import{E as Ft,f as Cl}from"./ErrorState-B1m0Htkw.js";import{f as Nl,a as _t,b as El,c as $n,d as dt,t as tm}from"./format-B6Elex-n.js";import{P as No,u as Il,b as an,M as nt}from"./move-targets-BznNJwIY.js";import{F as Da,a as sm,M as Tl}from"./move-mailbox-picker-aWLZRXnO.js";import{C as Xn}from"./circle-check-BzcLYagA.js";import{C as Pa}from"./ConfirmDialog-DZRbTR_Q.js";import{u as Rl,a as nm}from"./useLabels-Cvsyvf4k.js";function Qs(e){if(rm())e.focus({preventScroll:!0});else{let t=am(e);e.focus(),om(t)}}let vn=null;function rm(){if(vn==null){vn=!1;try{document.createElement("div").focus({get preventScroll(){return vn=!0,!0}})}catch{}}return vn}function am(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 om(e){for(let{element:t,scrollTop:s,scrollLeft:r}of e)t.scrollTop=s,t.scrollLeft=r}const Mt=e=>e?.ownerDocument??document,Dt=e=>e&&"window"in e&&e.window===e?e:Mt(e).defaultView||window;function im(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function lm(e){return im(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let cm=!1;function Ml(){return cm}function ct(e,t){if(!Ml())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:lm(s)?s=s.host:s=s.parentNode}return!1}function Te(e){if(Ml()&&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 um=typeof Element<"u"&&"checkVisibility"in Element.prototype;function dm(e){const t=Dt(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}=Dt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function fm(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 Al(e,t){return um?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&dm(e)&&fm(e,t)&&(!e.parentElement||Al(e.parentElement,e))}const Ol=["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"],mm=Ol.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";Ol.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function hm(e,t){return e.matches(mm)&&!pm(e)&&(t?.skipVisibilityCheck||Al(e))}function pm(e){let t=e;for(;t!=null;){if(t instanceof Dt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const La=typeof document<"u"?U.useLayoutEffect:()=>{};function gm(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function xm(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function bm(e){for(;e&&!hm(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Dt(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,Qs(s),u()))},i=d=>{(Te(d)===e||r)&&d.stopImmediatePropagation()},l=d=>{(Te(d)===e||r)&&(d.stopImmediatePropagation(),r||(r=!0,Qs(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 Jn(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 $a(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function zt(e){let t=null;return()=>(t==null&&(t=e()),t)}const Fn=zt(function(){return $a(/^Mac/i)}),vm=zt(function(){return $a(/^iPhone/i)}),Dl=zt(function(){return $a(/^iPad/i)||Fn()&&navigator.maxTouchPoints>1}),Pl=zt(function(){return vm()||Dl()}),ym=zt(function(){return Jn(/AppleWebKit/i)&&!wm()}),wm=zt(function(){return Jn(/Chrome/i)}),Ll=zt(function(){return Jn(/Android/i)}),jm=zt(function(){return Jn(/Firefox/i)});function Sm(e){return e.pointerType===""&&e.isTrusted?!0:Ll()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function km(e){return!Ll()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function Ys(e,t,s=!0){let{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}=t;jm()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Fn()?r=!0:a=!0);let l=ym()&&Fn()&&!Dl()?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});Ys.isOpening=s,Qs(e),e.dispatchEvent(l),Ys.isOpening=!1}Ys.isOpening=!1;let Rt=new Map,Gr=new Set;function Eo(){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=Rt.get(a);o||(o=new Set,Rt.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=Rt.get(a);if(o&&(o.delete(r.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Rt.delete(a)),Rt.size===0)){for(let i of Gr)i();Gr.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?Eo():document.addEventListener("DOMContentLoaded",Eo));function Cm(){for(const[e]of Rt)"isConnected"in e&&!e.isConnected&&Rt.delete(e)}function Nm(e){requestAnimationFrame(()=>{Cm(),Rt.size===0?e():Gr.add(e)})}function $l(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let Xr=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{Xr.delete(e)});function Em(e,t){if(e===t)return e;let s=Xr.get(e);if(s)return s.forEach(a=>a.current=t),t;let r=Xr.get(t);return r?(r.forEach(a=>a.current=e),e):t}function Im(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const r=e.map(a=>{const o=Io(a,t);return s||=typeof o=="function",o});if(s)return()=>{r.forEach((a,o)=>{typeof a=="function"?a():Io(e[o],null)})}}}function Io(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Cs(...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]=$l(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=_d(o,i):a==="id"&&o&&i?t.id=Em(o,i):a==="ref"&&o&&i?t.ref=Im(o,i):t[a]=i!==void 0?i:o}}return t}function Tm(e,t){La(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const Rm=U.useInsertionEffect??La;function Cr(e){const t=c.useRef(null);return Rm(()=>{t.current=e},[e]),c.useCallback((...s)=>{const r=t.current;return r?.(...s)},[])}let ps="default",Jr="",An=new WeakMap;function Mm(e){if(Pl()){if(ps==="default"){const t=Mt(e);Jr=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}ps="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";An.set(e,e.style[t]),e.style[t]="none"}}function To(e){if(Pl()){if(ps!=="disabled")return;ps="restoring",setTimeout(()=>{Nm(()=>{if(ps==="restoring"){const t=Mt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=Jr||""),Jr="",ps="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&An.has(e)){let t=An.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),An.delete(e)}}function Ro(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Nr=new WeakMap;function Am(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return Ro(t);if(Nr.has(t))return Nr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),r=s&&s instanceof Dt(s).HTMLMetaElement&&(s.nonce||s.content)||Ro(t)||void 0;return r!==void 0&&Nr.set(t,r),r}const Fl=U.createContext({register:()=>{}});Fl.displayName="PressResponderContext";function _l(){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(Fl);if(t){let{register:s,ref:r,...a}=t;e=Cs(a,e),s()}return Tm(t,e.ref),e}class yn{#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 Mo=Symbol("linkClicked"),Ao="react-aria-pressable-style",Oo="data-react-aria-pressable";function Dm(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,...g}=Om(e),[v,p]=c.useState(!1),x=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:y}=_l(),j=c.useCallback((S,O)=>{let L=x.current;if(l||L.didFirePressStart)return!1;let T=!0;if(L.isTriggeringEvent=!0,r){let $=new yn("pressstart",O,S);r($),T=$.shouldStopPropagation}return s&&s(!0),L.isTriggeringEvent=!1,L.didFirePressStart=!0,p(!0),T},[l,r,s]),w=c.useCallback((S,O,L=!0)=>{let T=x.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let $=!0;if(a){let R=new yn("pressend",O,S);a(R),$=R.shouldStopPropagation}if(s&&s(!1),p(!1),t&&L&&!l){let R=new yn("press",O,S);t(R),$&&=R.shouldStopPropagation}return T.isTriggeringEvent=!1,$},[l,a,s,t]),E=Cr(w),N=c.useCallback((S,O)=>{let L=x.current;if(l)return!1;if(o){L.isTriggeringEvent=!0;let T=new yn("pressup",O,S);return o(T),L.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[l,o]),k=Cr(N),C=c.useCallback(S=>{let O=x.current;if(O.isPressed&&O.target){O.didFirePressStart&&O.pointerType!=null&&w(Ht(O.target,S),O.pointerType,!1),O.isPressed=!1,O.isOverTarget=!1,O.activePointerId=null,O.pointerType=null,y(),m||To(O.target);for(let L of O.disposables)L();O.disposables=[]}},[m,y,w]),M=Cr(C);c.useEffect(()=>{l&&x.current.isPressed&&M({currentTarget:x.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let A=c.useCallback(S=>{d&&C(S)},[d,C]),D=c.useCallback(S=>{l||i?.(S)},[l,i]),P=c.useCallback((S,O)=>{if(!l&&i){let L=new MouseEvent("click",S);xm(L,O),i(gm(L))}},[l,i]),I=c.useMemo(()=>{let S=x.current,O={onKeyDown(T){if(Er(T.nativeEvent,T.currentTarget)&&ct(T.currentTarget,Te(T))){Do(Te(T),T.key)&&T.preventDefault();let $=!0;!S.isPressed&&!T.repeat&&(S.target=T.currentTarget,S.isPressed=!0,S.pointerType="keyboard",$=j(T,"keyboard"));let R=T.currentTarget,F=Q=>{Er(Q,R)&&!Q.repeat&&ct(R,Te(Q))&&S.target&&k(Ht(S.target,Q),"keyboard")};b(Mt(T.currentTarget),"keyup",$l(F,L),!0),$&&T.stopPropagation(),T.metaKey&&Fn()&&S.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(S.metaKeyEvents=new Map)},onClick(T){if(!(T&&!ct(T.currentTarget,Te(T)))&&T&&T.button===0&&!S.isTriggeringEvent&&!Ys.isOpening){let $=!0;if(l&&T.preventDefault(),!S.ignoreEmulatedMouseEvents&&!S.isPressed&&(S.pointerType==="virtual"||Sm(T.nativeEvent))){let R=j(T,"virtual"),F=k(T,"virtual"),Q=E(T,"virtual");D(T),$=R&&F&&Q}else if(S.isPressed&&S.pointerType!=="keyboard"){let R=S.pointerType||T.nativeEvent.pointerType||"virtual",F=k(Ht(T.currentTarget,T),R),Q=E(Ht(T.currentTarget,T),R,!0);$=F&&Q,S.isOverTarget=!1,D(T),M(T)}S.ignoreEmulatedMouseEvents=!1,$&&T.stopPropagation()}}},L=T=>{if(S.isPressed&&S.target&&Er(T,S.target)){Do(Te(T),T.key)&&T.preventDefault();let $=Te(T),R=ct(S.target,$);E(Ht(S.target,T),"keyboard",R),R&&P(T,S.target),y(),T.key!=="Enter"&&Fa(S.target)&&ct(S.target,$)&&!T[Mo]&&(T[Mo]=!0,Ys(S.target,T,!1)),S.isPressed=!1,S.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&S.metaKeyEvents?.size){let $=S.metaKeyEvents;S.metaKeyEvents=void 0;for(let R of $.values())S.target?.dispatchEvent(new KeyboardEvent("keyup",R))}};if(typeof PointerEvent<"u"){O.onPointerDown=R=>{if(R.button!==0||!ct(R.currentTarget,Te(R)))return;if(km(R.nativeEvent)){S.pointerType="virtual";return}S.pointerType=R.pointerType;let F=!0;if(!S.isPressed){S.isPressed=!0,S.isOverTarget=!0,S.activePointerId=R.pointerId,S.target=R.currentTarget,m||Mm(S.target),F=j(R,S.pointerType);let Q=Te(R);"releasePointerCapture"in Q&&("hasPointerCapture"in Q?Q.hasPointerCapture(R.pointerId)&&Q.releasePointerCapture(R.pointerId):Q.releasePointerCapture(R.pointerId)),b(Mt(R.currentTarget),"pointerup",T,!1),b(Mt(R.currentTarget),"pointercancel",$,!1)}F&&R.stopPropagation()},O.onMouseDown=R=>{if(ct(R.currentTarget,Te(R))&&R.button===0){if(f){let F=bm(R.target);F&&S.disposables.push(F)}R.stopPropagation()}},O.onPointerUp=R=>{!ct(R.currentTarget,Te(R))||S.pointerType==="virtual"||R.button===0&&!S.isPressed&&k(R,S.pointerType||R.pointerType)},O.onPointerEnter=R=>{R.pointerId===S.activePointerId&&S.target&&!S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!0,j(Ht(S.target,R),S.pointerType))},O.onPointerLeave=R=>{R.pointerId===S.activePointerId&&S.target&&S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!1,E(Ht(S.target,R),S.pointerType,!1),A(R))};let T=R=>{if(R.pointerId===S.activePointerId&&S.isPressed&&R.button===0&&S.target){if(ct(S.target,Te(R))&&S.pointerType!=null){let F=!1,Q=setTimeout(()=>{S.isPressed&&S.target instanceof HTMLElement&&(F?M(R):(Qs(S.target),S.target.click()))},80);b(R.currentTarget,"click",()=>F=!0,!0),S.disposables.push(()=>clearTimeout(Q))}else M(R);S.isOverTarget=!1}},$=R=>{M(R)};O.onDragStart=R=>{ct(R.currentTarget,Te(R))&&M(R)}}return O},[b,l,f,y,m,A,j,D,P]);return c.useEffect(()=>{if(!h)return;const S=Mt(h.current);if(!S||!S.head||S.getElementById(Ao))return;const O=S.createElement("style");O.id=Ao;let L=Am(S);L&&(O.nonce=L),O.textContent=`
3
3
  @layer {
4
4
  [${Oo}] {
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
  `)},Px=0,fs=[];function Lx(e){var t=c.useRef([]),s=c.useRef([0,0]),r=c.useRef(),a=c.useState(Px++)[0],o=c.useState(Cc)[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=Jd([e.lockRef.current],(e.shards||[]).map(vi),!0).filter(Boolean);return p.forEach(function(x){return x.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=c.useCallback(function(p,x){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var b=En(p),y=s.current,j="deltaX"in p?p.deltaX:y[0]-b[0],w="deltaY"in p?p.deltaY:y[1]-b[1],E,N=p.target,k=Math.abs(j)>Math.abs(w)?"h":"v";if("touches"in p&&k==="h"&&N.type==="range")return!1;var C=window.getSelection(),M=C&&C.anchorNode,A=M?M===N||M.contains(N):!1;if(A)return!1;var D=xi(k,N);if(!D)return!0;if(D?E=k:(E=k==="v"?"h":"v",D=xi(k,N)),!D)return!1;if(!r.current&&"changedTouches"in p&&(j||w)&&(r.current=E),!E)return!0;var P=r.current||E;return Ax(P,x,p,P==="h"?j:w)},[]),u=c.useCallback(function(p){var x=p;if(!(!fs.length||fs[fs.length-1]!==o)){var b="deltaY"in x?bi(x):En(x),y=t.current.filter(function(E){return E.name===x.type&&(E.target===x.target||x.target===E.shadowParent)&&Ox(E.delta,b)})[0];if(y&&y.should){x.cancelable&&x.preventDefault();return}if(!y){var j=(i.current.shards||[]).map(vi).filter(Boolean).filter(function(E){return E.contains(x.target)}),w=j.length>0?l(x,j[0]):!i.current.noIsolation;w&&x.cancelable&&x.preventDefault()}}},[]),f=c.useCallback(function(p,x,b,y){var j={name:p,delta:x,target:b,should:y,shadowParent:$x(b)};t.current.push(j),setTimeout(function(){t.current=t.current.filter(function(w){return w!==j})},1)},[]),d=c.useCallback(function(p){s.current=En(p),r.current=void 0},[]),m=c.useCallback(function(p){f(p.type,bi(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){f(p.type,En(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return fs.push(o),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:h}),document.addEventListener("wheel",u,ds),document.addEventListener("touchmove",u,ds),document.addEventListener("touchstart",d,ds),function(){fs=fs.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,ds),document.removeEventListener("touchmove",u,ds),document.removeEventListener("touchstart",d,ds)}},[]);var g=e.removeScrollBar,v=e.inert;return c.createElement(c.Fragment,null,v?c.createElement(o,{styles:Dx(a)}):null,g?c.createElement(Cx,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function $x(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Fx=fx(kc,Lx);var Tc=c.forwardRef(function(e,t){return c.createElement(sr,Tt({},e,{ref:t,sideCar:Fx}))});Tc.classNames=sr.classNames;var _x=class extends ya{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:ef(t,s.data),hasPreviousPage:Zd(t,s.data),isFetchNextPageError:f,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:h,isRefetchError:l&&!f&&!m,isRefetching:o&&!d&&!h}}};function yi(e,t){const s=new Set(t);return e.filter(r=>!s.has(r))}function zx(e,t,s){const r=e.slice(0);return r[t]=s,r}var Bx=class extends tf{#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,Wr.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||!sf(d,h)});!u&&!f||(u&&(this.#c=r,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(yi(s,a).forEach(d=>{d.destroy()}),yi(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=nf(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 ya(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=zx(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)&&Wr.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function Bt({queries:e,...t},s){const r=ye(),a=rf(),o=af(),i=c.useMemo(()=>e.map(p=>{const x=r.defaultQueryOptions(p);return x._optimisticResults=a?"isRestoring":"optimistic",x}),[e,r,a]);i.forEach(p=>{of(p);const x=r.getQueryCache().get(p.queryHash);lf(p,o,x)}),cf(o);const[l]=c.useState(()=>new Bx(r,i,t)),[u,f,d]=l.getOptimisticResult(i,t.combine),m=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>m?l.subscribe(Wr.batchCalls(p)):uf,[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const g=u.some((p,x)=>So(i[x],p))?u.flatMap((p,x)=>{const b=i[x];if(b&&So(b,p)){const y=new ya(r,b);return df(b,y,o)}return[]}):[];if(g.length>0)throw Promise.all(g);const v=u.find((p,x)=>{const b=i[x];return b&&ff({result:p,errorResetBoundary:o,throwOnError:b.throwOnError,query:r.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(v?.error)throw v.error;return f(d())}function Rc(e,t){return mf(e,_x)}function Kx(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 Ux(e,t){const{shouldBlockFn:s,enableBeforeUnload:r=!0,disabled:a=!1,withResolver:o=!1}=Kx(e),i=wa(),{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(b){const y=i.parseLocation(b),j=i.getMatchedRoutes(y.pathname);return j.foundRoute===void 0?{routeId:"__notFound__",fullPath:y.pathname,pathname:y.pathname,params:j.routeParams,search:i.options.parseSearch(b.search)}:{routeId:j.foundRoute.id,fullPath:j.foundRoute.fullPath,pathname:y.pathname,params:j.routeParams,search:i.options.parseSearch(b.search)}}const g=h(m.currentLocation),v=h(m.nextLocation);if(g.routeId==="__notFound__"&&v.routeId!=="__notFound__")return!1;const p=await s({action:m.action,current:g,next:v});if(!o)return p;if(!p)return!1;const x=await new Promise(b=>{f({status:"blocked",current:g,next:v,action:m.action,proceed:()=>b(!1),reset:()=>b(!0)})});return f({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),x};return a?void 0:l.block({blockerFn:d,enableBeforeUnload:r})},[s,r,a,o,l,i]),u}function bt(e){const t=wa({warn:e?.router===void 0}),s=e?.router||t;return rl(s.stores.__store,al(e,s))}function nr(e){const t=wa();return rl(t.stores.location,al(e,t))}const qx=new Set(["outbox","flagged"]),Hx=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!qx.has(s)};function Wx(e){const t=Bt({queries:e.map(s=>({...Ue({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=sn(r.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function Mc(e){const{openCompose:t}=Lt(),s=Me(),r=nr(),a=Wx(e);return c.useCallback(()=>{if(Hx(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 Vx=e=>e.startsWith("/mail")||e.startsWith("/settings"),Qx=({accounts:e})=>{const{state:t}=Lt(),s=nr(),r=Mc(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!Vx(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(Gm,{className:"size-6"})})},Ac=({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:be("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:be("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})]})},gs=({onClick:e,disabled:t,destructive:s,children:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:be("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}),sa=()=>n.jsx("div",{className:"my-1 h-px bg-line"}),Oc=({children:e})=>{const{Account:t}=ja();return n.jsx(t,{children:e})},Yx=({email:e,onSignOut:t})=>{const s=Me(),r=e??"Account";return n.jsxs(Ac,{trigger:n.jsx(mt,{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(sa,{})]}),n.jsxs(gs,{onClick:()=>s({to:"/settings/accounts"}),children:[n.jsx(_a,{className:"size-4"}),"Settings"]}),n.jsx(sa,{}),n.jsxs(gs,{onClick:t,children:[n.jsx(Vl,{className:"size-4"}),"Sign out"]})]})},Gx=()=>n.jsx(Oc,{children:({email:e,signOut:t})=>n.jsx(Yx,{email:e,onSignOut:t})}),wi=()=>{const e=Sa(),t=ka(e);window.open(t,"_blank","noopener,noreferrer")};function Dc({variant:e="icon"}){return e==="drawer"?n.jsxs("button",{type:"button",onClick:wi,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(Po,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]}):n.jsx(V,{variant:"ghost",size:"sm",icon:n.jsx(Po,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:wi})}const Pc="/mail/",Wa="/mail/$mailboxId",Lc="/mail/outbox",$c="/mail/flagged";function Va(e){return e.some(t=>t.routeId===Pc)}function cn(e){return e.some(t=>t.routeId===$c)}function rr(e){return e.some(t=>t.routeId===Lc)}function Fc(e){return e.some(t=>t.routeId===Wa)}function Xx(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Wa}:${t}`:cn(e)?$c:rr(e)?Lc:Va(e)?Pc:""}const Pn="search-scope";function Jx(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function _c(e){return cn(e)||rr(e)||Fc(e)}function zc(e){return e.find(t=>t.routeId===Wa)?.params?.mailboxId}function Zx(e){const t=zc(e.matches);return t||(_c(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function eb(e,t){return Va(e)?{kind:"global"}:cn(e)?{kind:"scoped",chip:{id:Pn,label:"is:starred"}}:rr(e)?{kind:"scoped",chip:{id:Pn,label:"in:outbox"}}:Fc(e)?t?{kind:"scoped",chip:{id:Pn,label:Jx(t)}}:{kind:"pending"}:{kind:"global"}}function tb(e,t,s){return t.kind==="global"?{kind:"global"}:cn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const Bc=({accounts:e})=>{const t=Ca({strict:!1}),s=nr(),r=t.mailboxId,{t:a}=Hn("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=Bt({queries:e.map(l=>({...Ue({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=sn(e[l].folderAppointments);return ys(f,d.get(r),o)}return null},sb=({accounts:e})=>{const s=Ca({strict:!1}).mailboxId,r=Bt({queries:e.map(a=>({...Ue({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 Kc(e){const t=Me(),{searchInput:s}=Ce(),r=Bc({accounts:e}),a=bt({select:l=>l.matches}),o=eb(a,r),i=c.useCallback(l=>{l===Pn&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const Uc=[{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 nb(e){for(const t of Uc){const s=t.hints.find(r=>r.action===e);if(s)return s.keys}}function hs(e){const t=nb(e);return!t||t.length===0?"":t.length===1?`(${t[0]})`:t[0]==="g"?`(${t.join(" then ")})`:`(${t.join("")})`}const rb={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function ab({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:r,onSearchClearQuery:a}=Ce(),o=Mc(e),{scope:i,clearScope:l}=Kc(e),u=i.kind==="scoped"?[{id:i.chip.id,label:i.chip.label,tone:"scope"}]:void 0,f=rb[i.kind];return n.jsx(up,{search:n.jsx(Ba,{value:t,onChange:s,onClear:r,onClearQuery:a,chips:u,onRemoveChip:l,placeholder:f,size:"lg"}),actions:n.jsxs(n.Fragment,{children:[n.jsx(V,{variant:"ghost",size:"sm",icon:n.jsx(Zm,{className:"size-4"}),title:`Compose ${hs("compose")}`,"aria-label":"Compose",onClick:o}),n.jsx(Dc,{}),n.jsx(Gx,{})]})})}const Qa=({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:be("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})]})]})},ob=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},na={all:["messages"],detail:e=>[...na.all,"detail",e],body:e=>[...na.detail(e),"body"]};class Vt 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 ib=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},lb=8,cb="x-remit-403-reason",ub=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},db=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,fb=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},mb=async(e,t,s=async()=>null)=>{const r={},a=await s();a&&(r.Authorization=`Bearer ${a}`);const o=await hf(e,{headers:r});if(o.status===202)throw new Vt("not-ready","Message body is still syncing",202,ib(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(cb),f=ub(o.status,u);throw new Vt(f,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(fb(t,i))throw new Vt("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(db(l,i))throw new Vt("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},hb=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),qc=({messageId:e,bodyParts:t,enabled:s=!0})=>{const r=t?ob(t):null,a=nn(),{getToken:o}=ja(),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=fe({queryKey:e?[...na.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 v=u.current;return u.current=!1,hb({fetchContent:(p,x)=>mb(p,x,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:ol({path:{messageId:e}})})},{contentUrl:r.contentUrl,kind:r.kind,isRetryAfterNotReady:v})},enabled:s&&!!e&&!!r,staleTime:300*1e3,gcTime:1800*1e3,retry:(v,p)=>p instanceof Vt&&p.reason==="not-ready"?v<lb:v<1,retryDelay:(v,p)=>p instanceof Vt&&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 g=m.data&&r?{kind:r.kind,body:m.data}:void 0;return{picked:r,data:g,isLoading:h,isError:m.isError,error:m.error,refetch:m.refetch}},pb=({outboxMessageId:e,onDraftCreated:t})=>{const[s,r]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=ye(),u=ve(il()),f=ve(pf()),d=c.useCallback(async v=>{if(r("saving"),o(null),e){const x=await f.mutateAsync({path:{outboxMessageId:e},body:{toAddresses:v.toAddresses,ccAddresses:v.ccAddresses,bccAddresses:v.bccAddresses,subject:v.subject,textBody:v.textBody,htmlBody:v.htmlBody,inReplyTo:v.inReplyTo,references:v.references}});return r("saved"),x}const p=await u.mutateAsync({body:{...v,sendImmediately:!1}});return t(p.outboxMessageId),r("saved"),l.invalidateQueries({queryKey:Wn().queryKey}),p},[e,u,f,t,l]),m=c.useCallback(v=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{d(v).catch(p=>{o(p),r("error")})},2e3)},[d]),h=c.useCallback(v=>(i.current&&clearTimeout(i.current),d(v)),[d]),g=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:m,saveImmediately:h,cancelAutoSave:g}},Hc=e=>"text"in e&&!("children"in e),Wc=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),gb=e=>{let t=Wc(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},Vc=e=>{const t=e.children.map(s=>Hc(s)?gb(s):Vc(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${Wc(s)}">${t}</a>`}default:return`<p>${t}</p>`}},ji=e=>e.map(Vc).join(""),Qc=e=>Hc(e)?e.text:e.children.map(Qc).join(""),ra=e=>e.map(Qc).join(`
116
- `),xb=e=>e.displayName?`${e.displayName} <${e.normalizedEmail}>`:e.normalizedEmail,Si=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),bb=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(Si(a))return{email:a,displayName:r}}if(Si(t))return{email:t}},Fr=({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=vl(a,200),{data:g}=fe({...ll({query:{q:h,limit:8}}),enabled:h.length>=2}),v=g?.items??[],p=new Set(t.map(k=>k.email.toLowerCase())),x=v.filter(k=>!p.has(k.normalizedEmail.toLowerCase()));c.useEffect(()=>{l(-1),f(x.length>0&&a.length>=2)},[x.length,a.length]);const b=c.useCallback(k=>{p.has(k.email.toLowerCase())||(s([...t,k]),o(""),f(!1))},[t,p,s]),y=c.useCallback(k=>{s(t.filter((C,M)=>M!==k))},[t,s]),j=c.useCallback(k=>{b({email:k.normalizedEmail,displayName:k.displayName}),d.current?.focus()},[b]),w=c.useCallback(()=>{const k=bb(a);k&&b(k)},[a,b]),E=c.useCallback(k=>{if(k.key==="Backspace"&&a===""&&t.length>0){y(t.length-1);return}if(k.key==="Enter"||k.key==="Tab"||k.key===","){if(i>=0&&x[i]){k.preventDefault(),j(x[i]);return}a.trim()&&(k.preventDefault(),w());return}if(k.key==="ArrowDown"&&u){k.preventDefault(),l(C=>C<x.length-1?C+1:0);return}if(k.key==="ArrowUp"&&u){k.preventDefault(),l(C=>C>0?C-1:x.length-1);return}k.key==="Escape"&&(f(!1),l(-1))},[a,t.length,i,x,u,y,j,w]),N=c.useCallback(()=>{setTimeout(()=>{w(),f(!1)},150)},[w]);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:k=>{(k.key==="Enter"||k.key===" ")&&d.current?.focus()},children:[t.map((k,C)=>n.jsx(nh,{email:k.email,displayName:k.displayName,onRemove:()=>y(C)},k.email)),n.jsx("input",{ref:d,id:`address-field-${e}`,type:"text",value:a,onChange:k=>o(k.target.value),onKeyDown:E,onBlur:N,placeholder:t.length===0?r:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5"})]})]}),u&&x.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:x.map((k,C)=>n.jsx("li",{className:be("px-3 py-2 text-sm cursor-pointer transition-colors",C===i&&"bg-accent-2-soft"),onMouseDown:M=>{M.preventDefault(),j(k)},onMouseEnter:()=>l(C),children:xb(k)},k.addressId))})]})},vb=({accountId:e})=>{const t=Me();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(xa,{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(Bm,{className:"size-3","aria-hidden":"true"})]})]})]})},ki=150,yb=()=>{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>ki}});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>ki})};return r(),s.addEventListener("resize",r),()=>s.removeEventListener("resize",r)},[]),e},wb=({selectedAccountId:e,onSelect:t})=>{const{data:s}=fe({...vt(),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))})]})},jb=({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})]}),Sb=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],kb=["href"],Cb=e=>tl.sanitize(e,{ALLOWED_TAGS:Sb,ALLOWED_ATTR:kb}),Nb=c.lazy(()=>xf(()=>import("./ComposeBody-BYDXbvpM.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.ComposeBody}))),Eb=()=>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"})]}),Yc=[{type:"p",children:[{text:""}]}],Ib=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],Tb=e=>e?[...Ib,{type:"p",children:[{text:e}]}]:Yc,Rb=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",Mb=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",Ab=(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}},Ob=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}},Db=(e,t,s,r,a)=>e.length===0&&t.length===0&&s.length===0&&r.trim()===""&&ra(a).trim()==="",Pb=({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:g})=>{const v=$t(),{isKeyboardOpen:p}=yb();if(!v&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(y=>y.displayName??y.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.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:b.length>0?b.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(wb,{selectedAccountId:e,onSelect:t}),n.jsx(Fr,{label:"To",addresses:s,onChange:r,placeholder:"Recipients"}),u?n.jsx(Fr,{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(Fr,{label:"Bcc",addresses:i,onChange:l}),n.jsx(jb,{value:h,onChange:g})]})},Ya=({mode:e,account:t,sourceMessage:s,onClose:r,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Lt(),{pushError:u}=Ve(),{outboxMessageId:f}=o,[d,m]=c.useState([]),[h,g]=c.useState([]),[v,p]=c.useState([]),[x,b]=c.useState(""),[y,j]=c.useState(!1),[w,E]=c.useState(!1),[N,k]=c.useState(t?.accountId),[C,M]=c.useState(!1),A=c.useRef(f);c.useEffect(()=>{A.current!==f&&(A.current=f,f&&(m([]),g([]),p([]),b(""),j(!1),E(!1),I(Yc),M(!1)))},[f]);const{signature:D}=Qf(N),[P,I]=c.useState(()=>Tb(D.plainText)),{data:S}=fe({...gf({path:{outboxMessageId:f??""}}),enabled:!!f&&!C});c.useEffect(()=>{!S||C||(m(S.toAddresses.map(X=>({email:X,displayName:void 0}))),S.ccAddresses&&S.ccAddresses.length>0&&(g(S.ccAddresses.map(X=>({email:X,displayName:void 0}))),j(!0)),S.bccAddresses&&S.bccAddresses.length>0&&(p(S.bccAddresses.map(X=>({email:X,displayName:void 0}))),E(!0)),S.subject&&b(S.subject),S.textBody&&I([{type:"p",children:[{text:S.textBody}]}]),k(S.accountId),M(!0))},[S,C]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:X,cc:re}=Ab(s,e,t?.email);m(X),g(re),re.length>0&&j(!0),b(Rb(s.envelope.subject))}e==="forward"&&b(Mb(s.envelope.subject))}},[e,s,t?.email]);const O=e==="reply"||e==="reply_all"||e==="forward",{data:L}=qc({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:O&&!!s}),T=L?.kind==="text"?L.body:"",$=L?.kind==="html"?Cb(L.body):void 0,R=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:F,saveError:Q,saveDraft:Z,cancelAutoSave:K}=pb({outboxMessageId:f,onDraftCreated:i});c.useEffect(()=>{Q&&u({title:"Couldn't save draft",detail:rt(Q)??"Saving the draft failed.",error:Q})},[Q,u]);const z=ve(il()),Y=ve(cl()),ue=ve({...Vn(),onError:X=>{u(Yt("Couldn't discard draft","The draft wasn't discarded.",X))}}),{data:oe}=fe({...vt(),staleTime:1/0}),se=oe?.accounts.find(X=>X.accountId===N),H=se?Wf(se):!1,G=z.isPending||Y.isPending,ae=d.length>0&&!!N&&!H;c.useEffect(()=>{if(!N||f&&!C||Db(d,h,v,x,P))return;const X=ra(P),re=ji(P);Z({accountId:N,toAddresses:d.map(te=>te.email),ccAddresses:h.length>0?h.map(te=>te.email):void 0,bccAddresses:v.length>0?v.map(te=>te.email):void 0,subject:x||void 0,textBody:X||void 0,htmlBody:re||void 0})},[N,f,C,d,h,v,x,P,Z]);const je=c.useCallback(async()=>{if(!N||d.length===0)return;K();const X=s&&(e==="reply"||e==="reply_all")?Ob(s):{};let re=f,te=!1;if(!re){const Qe=ra(P),B=ji(P),ze=await z.mutateAsync({body:{accountId:N,toAddresses:d.map(Le=>Le.email),ccAddresses:h.length>0?h.map(Le=>Le.email):void 0,bccAddresses:v.length>0?v.map(Le=>Le.email):void 0,subject:x||void 0,textBody:Qe||void 0,htmlBody:B||void 0,sendImmediately:!0,...X}}).catch(Le=>(u({title:"Couldn't send message",detail:rt(Le)??"Saving the draft failed.",error:Le}),null));if(ze===null)return;re=ze.outboxMessageId,te=!0,i(re)}await Y.mutateAsync({path:{outboxMessageId:re}}).catch(Qe=>(u({title:"Couldn't send message",detail:rt(Qe)??(te?"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(re),r())},[N,d,h,v,x,P,e,s,f,z,Y,K,l,i,u,r]),Ne=c.useCallback(()=>{K(),f&&ue.mutate({path:{outboxMessageId:f}}),r()},[K,f,ue,r]),J=c.useCallback(X=>{k(X.accountId),a?.(X)},[a]);return n.jsx(hp,{banner:se&&H?n.jsx(vb,{accountId:se.accountId}):void 0,header:n.jsx(Pb,{selectedAccountId:N,onAccountChange:J,toAddresses:d,setToAddresses:m,ccAddresses:h,setCcAddresses:g,bccAddresses:v,setBccAddresses:p,showCc:y,setShowCc:j,showBcc:w,setShowBcc:E,subject:x,setSubject:b}),quoted:T||$?n.jsx(Lp,{text:T,html:$,senderName:R}):void 0,actionBar:n.jsx(mp,{onSend:je,onDiscard:Ne,sending:G,canSend:ae,saveStatus:F,unavailableReason:H?"SMTP not configured":void 0,onUnavailable:X=>u({title:"Can't send yet",detail:X})}),children:n.jsx(c.Suspense,{fallback:n.jsx(Eb,{}),children:n.jsx(Nb,{value:P,onChange:I,onSubmit:je,autoFocus:e==="new"})})})},Ci=({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(Ya,{mode:e,account:t,sourceMessage:s,onClose:r})}),Gc=({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})]}),Ga=({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])},Xc=e=>{const{data:t,isLoading:s}=fe({...vt(),staleTime:1/0}),r=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=Bt({queries:r.map(l=>({...Ue({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}},Lb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),$b=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Jc=(e,t)=>e===void 0?e:Lb(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:$b(e)?{...e,items:t(e.items)}:e,wt=e=>{const t=[];for(const s of new Set(e))t.push(Na({path:{mailboxId:s}})),t.push(ul({path:{mailboxId:s}}));return t.push(dl()),t},un=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),dn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,r])=>({queryKey:s,data:r})),fn=(e,t,s)=>{const r=a=>Jc(a,s);for(const a of t)e.setQueriesData({queryKey:a},r)},mn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},jt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Fb=3e3,_b=(e,t,s)=>{if(e.length===0)return()=>{};const r=setTimeout(()=>s(e),t);return()=>clearTimeout(r)},ar=(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]},_n=(e,t,s)=>e.map(r=>t.has(r.messageId)?{...r,isRead:s}:r),zb=(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),Bb=({messages:e,expandedIds:t,threadId:s,mailboxId:r,accountId:a})=>{const o=ye(),{pushError:i}=Ve(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:f}=ve({...Qn(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),v=h.body.isRead??!0,p=ss({path:{threadId:s}}),x=wt(ar(g,e,r));await Promise.all([o.cancelQueries({queryKey:p}),un(o,x)]);const b=o.getQueriesData({queryKey:p}).filter(j=>j[1]!==void 0).map(([j,w])=>({queryKey:j,data:w})),y=dn(o,x);return o.setQueriesData({queryKey:p},j=>j&&{...j,items:_n(j.items,g,v)}),fn(o,x,j=>_n(j,g,v)),{threadMessagesPrefix:p,listPrefixes:x,previousThreadMessages:b,previousThreadsList:y}},onSuccess:(h,g)=>{const v=g.body.messageIds??[];for(const p of v)l.current.add(p),u.current.delete(p)},onError:(h,g,v)=>{const p=g.body.messageIds??[];for(const b of p)u.current.delete(b);if(v){for(const b of v.previousThreadMessages)o.setQueryData(b.queryKey,b.data);mn(o,v.previousThreadsList)}const x=g.body.isRead??!0;i({title:x?"Couldn't mark as read":"Couldn't mark as unread",detail:rt(h),error:h})},onSettled:(h,g,v,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),jt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:ts({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(v=>!l.current.has(v)&&!u.current.has(v));if(g.length!==0){for(const v of g)u.current.add(v);f({body:{messageIds:g,isRead:!0}})}},[f]),m=c.useMemo(()=>zb(e,t,l.current,u.current),[e,t]);c.useEffect(()=>_b(m,Fb,d),[m,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},or=e=>{const{mailboxId:t,accountId:s,messages:r}=e,a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...Qn(),onError:(f,d)=>{const m=d.body.isRead??!0;o({title:m?"Couldn't mark as read":"Couldn't mark as unread",detail:rt(f),error:f})},onSettled:(f,d,m)=>{jt(a,wt(ar(m.body.messageIds??[],r??[],t))),s&&a.invalidateQueries({queryKey:ts({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,isRead:d}})},[i]),isPending:l}},Kb=60,Ub=1.5,qb=(e,t,s)=>{const r=Math.abs(e),a=Math.abs(t);return r<s?{direction:null}:r<a*Ub?{direction:null}:{direction:e<0?"left":"right"}},Hb=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Kb})=>{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}=qb(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}}},Wb=(e,t,s)=>t?.find(r=>r.messageId===e)?.mailboxId??s,Ni=(e,t,s)=>e.map(r=>r.messageId===t?{...r,hasStars:s}:r),Xa=({threadId:e,mailboxId:t,messages:s})=>{const r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i,variables:l}=ve({...bf(),onMutate:async f=>{const d=f.path.messageId,m=f.body.isStarred??!1,h=ss({path:{threadId:e}}),g=wt([Wb(d,s,t)]);await Promise.all([r.cancelQueries({queryKey:h}),un(r,g)]);const v=r.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})),p=dn(r,g);return r.setQueriesData({queryKey:h},x=>Jc(x,b=>Ni(b,d,m))),fn(r,g,x=>Ni(x,d,m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)r.setQueryData(g.queryKey,g.data);mn(r,m.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:rt(f),error:f})},onSettled:(f,d,m,h)=>{h&&(r.invalidateQueries({queryKey:h.threadMessagesPrefix}),jt(r,h.listPrefixes))}});return{toggleStar:(f,d)=>{o({path:{messageId:f},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function ir(e){return e===void 0?"uncategorized":e}const Vb={inbox:"Inbox",junk:"Junk"},Ja=e=>e.destinationMailboxId!==void 0,Qb=(e,t)=>{if(Ja(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${Vb[s]??"another folder"} by Remit`},Yb=(e,t)=>{if(e===No.MoveToInbox)return t.inboxMailboxId;if(e===No.MoveToJunk)return t.junkMailboxId},Gb=(e,t,s)=>{if(!e||!t)return!1;const r=Ja(e)?e.destinationMailboxId:Yb(e.action,s);return r!==void 0&&r===t},Xb=(e,t)=>{if(e){if(Ja(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},lr=(e,t)=>{const{data:s,isLoading:r}=fe({...vt(),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}},Jb=e=>{const{mailboxId:t,isLoading:s}=lr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Zb=e=>{const{mailboxId:t,isLoading:s}=lr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},Za=e=>{const{mailboxId:t,isLoading:s}=lr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},cr=e=>{const{mailboxId:t,isLoading:s}=lr(e,"Junk");return{junkMailboxId:t,isLoading:s}},Zc=e=>{const{data:t}=fe({...vt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Ei=(e,t)=>e.filter(s=>!t.has(s.messageId)),Xt=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...vf(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),m=t?ss({path:{threadId:t}}):[],h=wt([e,f.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:m})]:[],un(a,h)]);const g=t?a.getQueriesData({queryKey:m}).filter(p=>p[1]!==void 0).map(([p,x])=>({queryKey:p,data:x})):[],v=dn(a,h);return t&&a.setQueriesData({queryKey:m},p=>p&&{...p,items:Ei(p.items,d)}),fn(a,h,p=>Ei(p,d)),r?.(Array.from(d)),{threadMessagesPrefix:m,listPrefixes:h,previousThreadMessages:g,previousThreadsList:v}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)a.setQueryData(g.queryKey,g.data);mn(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:rt(f),error:f})},onSettled:(f,d,m,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),jt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:ts({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,destinationMailboxId:d}})},[i]),isPending:l}},ev=({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a})=>{const{inboxMailboxId:o}=Za(e),{junkMailboxId:i}=cr(e),{moveMessages:l,isPending:u}=Xt({mailboxId:r,threadId:s,accountId:e}),{data:f}=fe({...Ue({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},m=Gb(a,r,d),h=Xb(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!m||!a)return{show:!1,label:"",isUndoing:!1};const v=a.fromMailboxId?f?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>Yn(p.fullPath))[0]:void 0;return{show:!0,label:Qb(a,v),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function eu({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a,size:o="sm"}){const i=ev({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a});return i.show?n.jsx(dp,{label:i.label,size:o,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:o==="md"?i.filtersHref:void 0}):null}const Ii=(e,t)=>e.filter(s=>!t.has(s.messageId)),tv=e=>e.filter(t=>t.isDeleted!==!0),Jt=({mailboxId:e,threadId:t,accountId:s,messages:r,onAfterOptimisticRemove:a})=>{const o=ye(),{pushError:i}=Ve(),{mutate:l,isPending:u}=ve({...yf(),onMutate:async d=>{const m=new Set(d.body.messageIds??[]),h=t?ss({path:{threadId:t}}):[],g=wt(ar(m,r??[],e));await Promise.all([o.cancelQueries({queryKey:h}),un(o,g)]);const v=t?o.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})):[],p=dn(o,g);return t&&o.setQueriesData({queryKey:h},x=>x&&{...x,items:Ii(x.items,m)}),fn(o,g,x=>Ii(x,m)),a?.(Array.from(m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(d,m,h)=>{if(h){for(const v of h.previousThreadMessages)o.setQueryData(v.queryKey,v.data);mn(o,h.previousThreadsList)}const g=m.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:rt(d),error:d})},onSettled:(d,m,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),jt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:ts({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&l({body:{messageIds:d}})},[l]),isPending:u}},tu=(e,t=Date.now())=>({value:e,setAt:t}),sv=(e,t,s,r)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=tu(!0,r):delete a.trusted,{...e,flags:a}},nv=(e,t,s,r)=>{const a=o=>o.map(i=>sv(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)}}},eo=({messageId:e})=>{const t=ye(),{pushError:s}=Ve(),{mutate:r,isPending:a,error:o,reset:i}=ve({...fl(),onMutate:async u=>{const f=u.path.addressId,m=u.body.flags?.trusted?.value===!0,h=ol({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,p])=>({queryKey:v,data:p}));return t.setQueriesData({queryKey:h},v=>v&&nv(v,f,m)),{describePrefix:h,previous:g}},onError:(u,f,d)=>{if(d)for(const m of d.previous)t.setQueryData(m.queryKey,m.data);s(Yt("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:tu(!f)}}})},isPending:a,error:o,reset:i}};var ur="Dialog",[su]=mg(ur),[rv,ot]=su(ur),nu=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]=gg({prop:r,defaultProp:a??!1,onChange:o,caller:ur});return n.jsx(rv,{scope:t,triggerRef:l,contentRef:u,contentId:Or(),titleId:Or(),descriptionId:Or(),open:f,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),modal:i,children:s})};nu.displayName=ur;var ru="DialogTrigger",av=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(ru,s),o=ns(t,a.triggerRef);return n.jsx(yt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":so(a.open),...r,ref:o,onClick:At(e.onClick,a.onOpenToggle)})});av.displayName=ru;var to="DialogPortal",[ov,au]=su(to,{forceMount:void 0}),ou=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,o=ot(to,t);return n.jsx(ov,{scope:t,forceMount:s,children:c.Children.map(r,i=>n.jsx(tr,{present:s||o.open,children:n.jsx(wc,{asChild:!0,container:a,children:i})}))})};ou.displayName=to;var zn="DialogOverlay",iu=c.forwardRef((e,t)=>{const s=au(zn,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=ot(zn,e.__scopeDialog);return o.modal?n.jsx(tr,{present:r||o.open,children:n.jsx(lv,{...a,ref:t})}):null});iu.displayName=zn;var iv=qa("DialogOverlay.RemoveScroll"),lv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(zn,s),o=Pg(),i=ns(t,o);return n.jsx(Tc,{as:iv,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(yt.div,{"data-state":so(a.open),...r,ref:i,style:{pointerEvents:"auto",...r.style}})})}),Ss="DialogContent",lu=c.forwardRef((e,t)=>{const s=au(Ss,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=ot(Ss,e.__scopeDialog);return n.jsx(tr,{present:r||o.open,children:o.modal?n.jsx(cv,{...a,ref:t}):n.jsx(uv,{...a,ref:t})})});lu.displayName=Ss;var cv=c.forwardRef((e,t)=>{const s=ot(Ss,e.__scopeDialog),r=c.useRef(null),a=ns(t,s.contentRef,r);return c.useEffect(()=>{const o=r.current;if(o)return nx(o)},[]),n.jsx(cu,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:At(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:At(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:At(e.onFocusOutside,o=>o.preventDefault())})}),uv=c.forwardRef((e,t)=>{const s=ot(Ss,e.__scopeDialog),r=c.useRef(!1),a=c.useRef(!1);return n.jsx(cu,{...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()}})}),cu=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=ot(Ss,s);return _g(),n.jsx(n.Fragment,{children:n.jsx(vc,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:o,children:n.jsx(xc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":so(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),uu="DialogTitle",du=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(uu,s);return n.jsx(yt.h2,{id:a.titleId,...r,ref:t})});du.displayName=uu;var fu="DialogDescription",dv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(fu,s);return n.jsx(yt.p,{id:a.descriptionId,...r,ref:t})});dv.displayName=fu;var mu="DialogClose",fv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(mu,s);return n.jsx(yt.button,{type:"button",...r,ref:t,onClick:At(e.onClick,()=>a.onOpenChange(!1))})});fv.displayName=mu;function so(e){return e?"open":"closed"}function mv(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 hu=U.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}),hn=()=>{const e=U.useContext(hu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};mv(`[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
+ `),xb=e=>e.displayName?`${e.displayName} <${e.normalizedEmail}>`:e.normalizedEmail,Si=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),bb=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(Si(a))return{email:a,displayName:r}}if(Si(t))return{email:t}},Fr=({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=vl(a,200),{data:g}=fe({...ll({query:{q:h,limit:8}}),enabled:h.length>=2}),v=g?.items??[],p=new Set(t.map(k=>k.email.toLowerCase())),x=v.filter(k=>!p.has(k.normalizedEmail.toLowerCase()));c.useEffect(()=>{l(-1),f(x.length>0&&a.length>=2)},[x.length,a.length]);const b=c.useCallback(k=>{p.has(k.email.toLowerCase())||(s([...t,k]),o(""),f(!1))},[t,p,s]),y=c.useCallback(k=>{s(t.filter((C,M)=>M!==k))},[t,s]),j=c.useCallback(k=>{b({email:k.normalizedEmail,displayName:k.displayName}),d.current?.focus()},[b]),w=c.useCallback(()=>{const k=bb(a);k&&b(k)},[a,b]),E=c.useCallback(k=>{if(k.key==="Backspace"&&a===""&&t.length>0){y(t.length-1);return}if(k.key==="Enter"||k.key==="Tab"||k.key===","){if(i>=0&&x[i]){k.preventDefault(),j(x[i]);return}a.trim()&&(k.preventDefault(),w());return}if(k.key==="ArrowDown"&&u){k.preventDefault(),l(C=>C<x.length-1?C+1:0);return}if(k.key==="ArrowUp"&&u){k.preventDefault(),l(C=>C>0?C-1:x.length-1);return}k.key==="Escape"&&(f(!1),l(-1))},[a,t.length,i,x,u,y,j,w]),N=c.useCallback(()=>{setTimeout(()=>{w(),f(!1)},150)},[w]);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:k=>{(k.key==="Enter"||k.key===" ")&&d.current?.focus()},children:[t.map((k,C)=>n.jsx(nh,{email:k.email,displayName:k.displayName,onRemove:()=>y(C)},k.email)),n.jsx("input",{ref:d,id:`address-field-${e}`,type:"text",value:a,onChange:k=>o(k.target.value),onKeyDown:E,onBlur:N,placeholder:t.length===0?r:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5"})]})]}),u&&x.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:x.map((k,C)=>n.jsx("li",{className:be("px-3 py-2 text-sm cursor-pointer transition-colors",C===i&&"bg-accent-2-soft"),onMouseDown:M=>{M.preventDefault(),j(k)},onMouseEnter:()=>l(C),children:xb(k)},k.addressId))})]})},vb=({accountId:e})=>{const t=Me();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(xa,{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(Bm,{className:"size-3","aria-hidden":"true"})]})]})]})},ki=150,yb=()=>{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>ki}});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>ki})};return r(),s.addEventListener("resize",r),()=>s.removeEventListener("resize",r)},[]),e},wb=({selectedAccountId:e,onSelect:t})=>{const{data:s}=fe({...vt(),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))})]})},jb=({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})]}),Sb=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],kb=["href"],Cb=e=>tl.sanitize(e,{ALLOWED_TAGS:Sb,ALLOWED_ATTR:kb}),Nb=c.lazy(()=>xf(()=>import("./ComposeBody-PaioGRCf.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.ComposeBody}))),Eb=()=>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"})]}),Yc=[{type:"p",children:[{text:""}]}],Ib=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],Tb=e=>e?[...Ib,{type:"p",children:[{text:e}]}]:Yc,Rb=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",Mb=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",Ab=(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}},Ob=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}},Db=(e,t,s,r,a)=>e.length===0&&t.length===0&&s.length===0&&r.trim()===""&&ra(a).trim()==="",Pb=({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:g})=>{const v=$t(),{isKeyboardOpen:p}=yb();if(!v&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(y=>y.displayName??y.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.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:b.length>0?b.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(wb,{selectedAccountId:e,onSelect:t}),n.jsx(Fr,{label:"To",addresses:s,onChange:r,placeholder:"Recipients"}),u?n.jsx(Fr,{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(Fr,{label:"Bcc",addresses:i,onChange:l}),n.jsx(jb,{value:h,onChange:g})]})},Ya=({mode:e,account:t,sourceMessage:s,onClose:r,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Lt(),{pushError:u}=Ve(),{outboxMessageId:f}=o,[d,m]=c.useState([]),[h,g]=c.useState([]),[v,p]=c.useState([]),[x,b]=c.useState(""),[y,j]=c.useState(!1),[w,E]=c.useState(!1),[N,k]=c.useState(t?.accountId),[C,M]=c.useState(!1),A=c.useRef(f);c.useEffect(()=>{A.current!==f&&(A.current=f,f&&(m([]),g([]),p([]),b(""),j(!1),E(!1),I(Yc),M(!1)))},[f]);const{signature:D}=Qf(N),[P,I]=c.useState(()=>Tb(D.plainText)),{data:S}=fe({...gf({path:{outboxMessageId:f??""}}),enabled:!!f&&!C});c.useEffect(()=>{!S||C||(m(S.toAddresses.map(X=>({email:X,displayName:void 0}))),S.ccAddresses&&S.ccAddresses.length>0&&(g(S.ccAddresses.map(X=>({email:X,displayName:void 0}))),j(!0)),S.bccAddresses&&S.bccAddresses.length>0&&(p(S.bccAddresses.map(X=>({email:X,displayName:void 0}))),E(!0)),S.subject&&b(S.subject),S.textBody&&I([{type:"p",children:[{text:S.textBody}]}]),k(S.accountId),M(!0))},[S,C]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:X,cc:re}=Ab(s,e,t?.email);m(X),g(re),re.length>0&&j(!0),b(Rb(s.envelope.subject))}e==="forward"&&b(Mb(s.envelope.subject))}},[e,s,t?.email]);const O=e==="reply"||e==="reply_all"||e==="forward",{data:L}=qc({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:O&&!!s}),T=L?.kind==="text"?L.body:"",$=L?.kind==="html"?Cb(L.body):void 0,R=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:F,saveError:Q,saveDraft:Z,cancelAutoSave:K}=pb({outboxMessageId:f,onDraftCreated:i});c.useEffect(()=>{Q&&u({title:"Couldn't save draft",detail:rt(Q)??"Saving the draft failed.",error:Q})},[Q,u]);const z=ve(il()),Y=ve(cl()),ue=ve({...Vn(),onError:X=>{u(Yt("Couldn't discard draft","The draft wasn't discarded.",X))}}),{data:oe}=fe({...vt(),staleTime:1/0}),se=oe?.accounts.find(X=>X.accountId===N),H=se?Wf(se):!1,G=z.isPending||Y.isPending,ae=d.length>0&&!!N&&!H;c.useEffect(()=>{if(!N||f&&!C||Db(d,h,v,x,P))return;const X=ra(P),re=ji(P);Z({accountId:N,toAddresses:d.map(te=>te.email),ccAddresses:h.length>0?h.map(te=>te.email):void 0,bccAddresses:v.length>0?v.map(te=>te.email):void 0,subject:x||void 0,textBody:X||void 0,htmlBody:re||void 0})},[N,f,C,d,h,v,x,P,Z]);const je=c.useCallback(async()=>{if(!N||d.length===0)return;K();const X=s&&(e==="reply"||e==="reply_all")?Ob(s):{};let re=f,te=!1;if(!re){const Qe=ra(P),B=ji(P),ze=await z.mutateAsync({body:{accountId:N,toAddresses:d.map(Le=>Le.email),ccAddresses:h.length>0?h.map(Le=>Le.email):void 0,bccAddresses:v.length>0?v.map(Le=>Le.email):void 0,subject:x||void 0,textBody:Qe||void 0,htmlBody:B||void 0,sendImmediately:!0,...X}}).catch(Le=>(u({title:"Couldn't send message",detail:rt(Le)??"Saving the draft failed.",error:Le}),null));if(ze===null)return;re=ze.outboxMessageId,te=!0,i(re)}await Y.mutateAsync({path:{outboxMessageId:re}}).catch(Qe=>(u({title:"Couldn't send message",detail:rt(Qe)??(te?"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(re),r())},[N,d,h,v,x,P,e,s,f,z,Y,K,l,i,u,r]),Ne=c.useCallback(()=>{K(),f&&ue.mutate({path:{outboxMessageId:f}}),r()},[K,f,ue,r]),J=c.useCallback(X=>{k(X.accountId),a?.(X)},[a]);return n.jsx(hp,{banner:se&&H?n.jsx(vb,{accountId:se.accountId}):void 0,header:n.jsx(Pb,{selectedAccountId:N,onAccountChange:J,toAddresses:d,setToAddresses:m,ccAddresses:h,setCcAddresses:g,bccAddresses:v,setBccAddresses:p,showCc:y,setShowCc:j,showBcc:w,setShowBcc:E,subject:x,setSubject:b}),quoted:T||$?n.jsx(Lp,{text:T,html:$,senderName:R}):void 0,actionBar:n.jsx(mp,{onSend:je,onDiscard:Ne,sending:G,canSend:ae,saveStatus:F,unavailableReason:H?"SMTP not configured":void 0,onUnavailable:X=>u({title:"Can't send yet",detail:X})}),children:n.jsx(c.Suspense,{fallback:n.jsx(Eb,{}),children:n.jsx(Nb,{value:P,onChange:I,onSubmit:je,autoFocus:e==="new"})})})},Ci=({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(Ya,{mode:e,account:t,sourceMessage:s,onClose:r})}),Gc=({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})]}),Ga=({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])},Xc=e=>{const{data:t,isLoading:s}=fe({...vt(),staleTime:1/0}),r=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=Bt({queries:r.map(l=>({...Ue({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}},Lb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),$b=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Jc=(e,t)=>e===void 0?e:Lb(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:$b(e)?{...e,items:t(e.items)}:e,wt=e=>{const t=[];for(const s of new Set(e))t.push(Na({path:{mailboxId:s}})),t.push(ul({path:{mailboxId:s}}));return t.push(dl()),t},un=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),dn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,r])=>({queryKey:s,data:r})),fn=(e,t,s)=>{const r=a=>Jc(a,s);for(const a of t)e.setQueriesData({queryKey:a},r)},mn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},jt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Fb=3e3,_b=(e,t,s)=>{if(e.length===0)return()=>{};const r=setTimeout(()=>s(e),t);return()=>clearTimeout(r)},ar=(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]},_n=(e,t,s)=>e.map(r=>t.has(r.messageId)?{...r,isRead:s}:r),zb=(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),Bb=({messages:e,expandedIds:t,threadId:s,mailboxId:r,accountId:a})=>{const o=ye(),{pushError:i}=Ve(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:f}=ve({...Qn(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),v=h.body.isRead??!0,p=ss({path:{threadId:s}}),x=wt(ar(g,e,r));await Promise.all([o.cancelQueries({queryKey:p}),un(o,x)]);const b=o.getQueriesData({queryKey:p}).filter(j=>j[1]!==void 0).map(([j,w])=>({queryKey:j,data:w})),y=dn(o,x);return o.setQueriesData({queryKey:p},j=>j&&{...j,items:_n(j.items,g,v)}),fn(o,x,j=>_n(j,g,v)),{threadMessagesPrefix:p,listPrefixes:x,previousThreadMessages:b,previousThreadsList:y}},onSuccess:(h,g)=>{const v=g.body.messageIds??[];for(const p of v)l.current.add(p),u.current.delete(p)},onError:(h,g,v)=>{const p=g.body.messageIds??[];for(const b of p)u.current.delete(b);if(v){for(const b of v.previousThreadMessages)o.setQueryData(b.queryKey,b.data);mn(o,v.previousThreadsList)}const x=g.body.isRead??!0;i({title:x?"Couldn't mark as read":"Couldn't mark as unread",detail:rt(h),error:h})},onSettled:(h,g,v,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),jt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:ts({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(v=>!l.current.has(v)&&!u.current.has(v));if(g.length!==0){for(const v of g)u.current.add(v);f({body:{messageIds:g,isRead:!0}})}},[f]),m=c.useMemo(()=>zb(e,t,l.current,u.current),[e,t]);c.useEffect(()=>_b(m,Fb,d),[m,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},or=e=>{const{mailboxId:t,accountId:s,messages:r}=e,a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...Qn(),onError:(f,d)=>{const m=d.body.isRead??!0;o({title:m?"Couldn't mark as read":"Couldn't mark as unread",detail:rt(f),error:f})},onSettled:(f,d,m)=>{jt(a,wt(ar(m.body.messageIds??[],r??[],t))),s&&a.invalidateQueries({queryKey:ts({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,isRead:d}})},[i]),isPending:l}},Kb=60,Ub=1.5,qb=(e,t,s)=>{const r=Math.abs(e),a=Math.abs(t);return r<s?{direction:null}:r<a*Ub?{direction:null}:{direction:e<0?"left":"right"}},Hb=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Kb})=>{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}=qb(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}}},Wb=(e,t,s)=>t?.find(r=>r.messageId===e)?.mailboxId??s,Ni=(e,t,s)=>e.map(r=>r.messageId===t?{...r,hasStars:s}:r),Xa=({threadId:e,mailboxId:t,messages:s})=>{const r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i,variables:l}=ve({...bf(),onMutate:async f=>{const d=f.path.messageId,m=f.body.isStarred??!1,h=ss({path:{threadId:e}}),g=wt([Wb(d,s,t)]);await Promise.all([r.cancelQueries({queryKey:h}),un(r,g)]);const v=r.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})),p=dn(r,g);return r.setQueriesData({queryKey:h},x=>Jc(x,b=>Ni(b,d,m))),fn(r,g,x=>Ni(x,d,m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)r.setQueryData(g.queryKey,g.data);mn(r,m.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:rt(f),error:f})},onSettled:(f,d,m,h)=>{h&&(r.invalidateQueries({queryKey:h.threadMessagesPrefix}),jt(r,h.listPrefixes))}});return{toggleStar:(f,d)=>{o({path:{messageId:f},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function ir(e){return e===void 0?"uncategorized":e}const Vb={inbox:"Inbox",junk:"Junk"},Ja=e=>e.destinationMailboxId!==void 0,Qb=(e,t)=>{if(Ja(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${Vb[s]??"another folder"} by Remit`},Yb=(e,t)=>{if(e===No.MoveToInbox)return t.inboxMailboxId;if(e===No.MoveToJunk)return t.junkMailboxId},Gb=(e,t,s)=>{if(!e||!t)return!1;const r=Ja(e)?e.destinationMailboxId:Yb(e.action,s);return r!==void 0&&r===t},Xb=(e,t)=>{if(e){if(Ja(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},lr=(e,t)=>{const{data:s,isLoading:r}=fe({...vt(),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}},Jb=e=>{const{mailboxId:t,isLoading:s}=lr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Zb=e=>{const{mailboxId:t,isLoading:s}=lr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},Za=e=>{const{mailboxId:t,isLoading:s}=lr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},cr=e=>{const{mailboxId:t,isLoading:s}=lr(e,"Junk");return{junkMailboxId:t,isLoading:s}},Zc=e=>{const{data:t}=fe({...vt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Ei=(e,t)=>e.filter(s=>!t.has(s.messageId)),Xt=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...vf(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),m=t?ss({path:{threadId:t}}):[],h=wt([e,f.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:m})]:[],un(a,h)]);const g=t?a.getQueriesData({queryKey:m}).filter(p=>p[1]!==void 0).map(([p,x])=>({queryKey:p,data:x})):[],v=dn(a,h);return t&&a.setQueriesData({queryKey:m},p=>p&&{...p,items:Ei(p.items,d)}),fn(a,h,p=>Ei(p,d)),r?.(Array.from(d)),{threadMessagesPrefix:m,listPrefixes:h,previousThreadMessages:g,previousThreadsList:v}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)a.setQueryData(g.queryKey,g.data);mn(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:rt(f),error:f})},onSettled:(f,d,m,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),jt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:ts({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,destinationMailboxId:d}})},[i]),isPending:l}},ev=({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a})=>{const{inboxMailboxId:o}=Za(e),{junkMailboxId:i}=cr(e),{moveMessages:l,isPending:u}=Xt({mailboxId:r,threadId:s,accountId:e}),{data:f}=fe({...Ue({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},m=Gb(a,r,d),h=Xb(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!m||!a)return{show:!1,label:"",isUndoing:!1};const v=a.fromMailboxId?f?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>Yn(p.fullPath))[0]:void 0;return{show:!0,label:Qb(a,v),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function eu({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a,size:o="sm"}){const i=ev({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a});return i.show?n.jsx(dp,{label:i.label,size:o,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:o==="md"?i.filtersHref:void 0}):null}const Ii=(e,t)=>e.filter(s=>!t.has(s.messageId)),tv=e=>e.filter(t=>t.isDeleted!==!0),Jt=({mailboxId:e,threadId:t,accountId:s,messages:r,onAfterOptimisticRemove:a})=>{const o=ye(),{pushError:i}=Ve(),{mutate:l,isPending:u}=ve({...yf(),onMutate:async d=>{const m=new Set(d.body.messageIds??[]),h=t?ss({path:{threadId:t}}):[],g=wt(ar(m,r??[],e));await Promise.all([o.cancelQueries({queryKey:h}),un(o,g)]);const v=t?o.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})):[],p=dn(o,g);return t&&o.setQueriesData({queryKey:h},x=>x&&{...x,items:Ii(x.items,m)}),fn(o,g,x=>Ii(x,m)),a?.(Array.from(m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(d,m,h)=>{if(h){for(const v of h.previousThreadMessages)o.setQueryData(v.queryKey,v.data);mn(o,h.previousThreadsList)}const g=m.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:rt(d),error:d})},onSettled:(d,m,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),jt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:ts({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&l({body:{messageIds:d}})},[l]),isPending:u}},tu=(e,t=Date.now())=>({value:e,setAt:t}),sv=(e,t,s,r)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=tu(!0,r):delete a.trusted,{...e,flags:a}},nv=(e,t,s,r)=>{const a=o=>o.map(i=>sv(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)}}},eo=({messageId:e})=>{const t=ye(),{pushError:s}=Ve(),{mutate:r,isPending:a,error:o,reset:i}=ve({...fl(),onMutate:async u=>{const f=u.path.addressId,m=u.body.flags?.trusted?.value===!0,h=ol({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,p])=>({queryKey:v,data:p}));return t.setQueriesData({queryKey:h},v=>v&&nv(v,f,m)),{describePrefix:h,previous:g}},onError:(u,f,d)=>{if(d)for(const m of d.previous)t.setQueryData(m.queryKey,m.data);s(Yt("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:tu(!f)}}})},isPending:a,error:o,reset:i}};var ur="Dialog",[su]=mg(ur),[rv,ot]=su(ur),nu=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]=gg({prop:r,defaultProp:a??!1,onChange:o,caller:ur});return n.jsx(rv,{scope:t,triggerRef:l,contentRef:u,contentId:Or(),titleId:Or(),descriptionId:Or(),open:f,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),modal:i,children:s})};nu.displayName=ur;var ru="DialogTrigger",av=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(ru,s),o=ns(t,a.triggerRef);return n.jsx(yt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":so(a.open),...r,ref:o,onClick:At(e.onClick,a.onOpenToggle)})});av.displayName=ru;var to="DialogPortal",[ov,au]=su(to,{forceMount:void 0}),ou=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,o=ot(to,t);return n.jsx(ov,{scope:t,forceMount:s,children:c.Children.map(r,i=>n.jsx(tr,{present:s||o.open,children:n.jsx(wc,{asChild:!0,container:a,children:i})}))})};ou.displayName=to;var zn="DialogOverlay",iu=c.forwardRef((e,t)=>{const s=au(zn,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=ot(zn,e.__scopeDialog);return o.modal?n.jsx(tr,{present:r||o.open,children:n.jsx(lv,{...a,ref:t})}):null});iu.displayName=zn;var iv=qa("DialogOverlay.RemoveScroll"),lv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(zn,s),o=Pg(),i=ns(t,o);return n.jsx(Tc,{as:iv,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(yt.div,{"data-state":so(a.open),...r,ref:i,style:{pointerEvents:"auto",...r.style}})})}),Ss="DialogContent",lu=c.forwardRef((e,t)=>{const s=au(Ss,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=ot(Ss,e.__scopeDialog);return n.jsx(tr,{present:r||o.open,children:o.modal?n.jsx(cv,{...a,ref:t}):n.jsx(uv,{...a,ref:t})})});lu.displayName=Ss;var cv=c.forwardRef((e,t)=>{const s=ot(Ss,e.__scopeDialog),r=c.useRef(null),a=ns(t,s.contentRef,r);return c.useEffect(()=>{const o=r.current;if(o)return nx(o)},[]),n.jsx(cu,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:At(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:At(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:At(e.onFocusOutside,o=>o.preventDefault())})}),uv=c.forwardRef((e,t)=>{const s=ot(Ss,e.__scopeDialog),r=c.useRef(!1),a=c.useRef(!1);return n.jsx(cu,{...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()}})}),cu=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=ot(Ss,s);return _g(),n.jsx(n.Fragment,{children:n.jsx(vc,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:o,children:n.jsx(xc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":so(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),uu="DialogTitle",du=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(uu,s);return n.jsx(yt.h2,{id:a.titleId,...r,ref:t})});du.displayName=uu;var fu="DialogDescription",dv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(fu,s);return n.jsx(yt.p,{id:a.descriptionId,...r,ref:t})});dv.displayName=fu;var mu="DialogClose",fv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ot(mu,s);return n.jsx(yt.button,{type:"button",...r,ref:t,onClick:At(e.onClick,()=>a.onOpenChange(!1))})});fv.displayName=mu;function so(e){return e?"open":"closed"}function mv(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 hu=U.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}),hn=()=>{const e=U.useContext(hu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};mv(`[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 hv(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function pv(){return no(/^Mac/)}function gv(){return no(/^iPhone/)}function Ti(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function xv(){return no(/^iPad/)||pv()&&navigator.maxTouchPoints>1}function pu(){return gv()||xv()}function no(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const bv=24,vv=typeof window<"u"?c.useLayoutEffect:c.useEffect;function Ri(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const _r=typeof document<"u"&&window.visualViewport;function Mi(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function gu(e){for(Mi(e)&&(e=e.parentElement);e&&!Mi(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const yv=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let In=0,zr;function wv(e={}){let{isDisabled:t}=e;vv(()=>{if(!t)return In++,In===1&&pu()&&(zr=jv()),()=>{In--,In===0&&zr?.()}},[t])}function jv(){let e,t=0,s=m=>{e=gu(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,g=e.scrollTop,v=e.scrollHeight-e.clientHeight;v!==0&&((g<=0&&h>t||g>=v&&h<t)&&m.preventDefault(),t=h)},a=m=>{let h=m.target;aa(h)&&h!==document.activeElement&&(m.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=m=>{let h=m.target;aa(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",_r&&(_r.height<window.innerHeight?requestAnimationFrame(()=>{Ai(h)}):_r.addEventListener("resize",()=>Ai(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,f=Ri(Sv(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=Ri(zs(document,"touchstart",s,{passive:!1,capture:!0}),zs(document,"touchmove",r,{passive:!1,capture:!0}),zs(document,"touchend",a,{passive:!1,capture:!0}),zs(document,"focus",o,!0),zs(window,"scroll",i));return()=>{f(),d(),window.scrollTo(l,u)}}function Sv(e,t,s){let r=e.style[t];return e.style[t]=s,()=>{e.style[t]=r}}function zs(e,t,s,r){return e.addEventListener(t,s,r),()=>{e.removeEventListener(t,s,r)}}function Ai(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=gu(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+bv;o>i&&(s.scrollTop+=a-r)}e=s.parentElement}}function aa(e){return e instanceof HTMLInputElement&&!yv.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function kv(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function Cv(...e){return t=>e.forEach(s=>kv(s,t))}function xu(...e){return c.useCallback(Cv(...e),e)}const bu=new WeakMap;function Ie(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&&bu.set(e,r)}function Nv(e,t){if(!e||!(e instanceof HTMLElement))return;let s=bu.get(e);s&&(e.style[t]=s[t])}const ke=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function Tn(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(", ")[ke(t)?13:12]):(a=r.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[ke(t)?5:4]):null)}function Ev(e){return 8*(Math.log(e+1)-2)}function Br(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function Iv(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const xe={DURATION:.5,EASE:[.32,.72,0,1]},vu=.4,Tv=.25,Rv=100,yu=8,Wt=16,oa=26,Kr="vaul-dragging";function wu(e){const t=U.useRef(e);return U.useEffect(()=>{t.current=e}),U.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function Mv({defaultProp:e,onChange:t}){const s=U.useState(e),[r]=s,a=U.useRef(r),o=wu(t);return U.useEffect(()=>{a.current!==r&&(o(r),a.current=r)},[r,a,o]),s}function ju({prop:e,defaultProp:t,onChange:s=()=>{}}){const[r,a]=Mv({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:r,l=wu(s),u=U.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 Av({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:r,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:f}){const[d,m]=ju({prop:e,defaultProp:s?.[0],onChange:t}),[h,g]=U.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);U.useEffect(()=>{function k(){g({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]);const v=U.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=U.useMemo(()=>{var k;return(k=s?.findIndex(C=>C===d))!=null?k:null},[s,d]),x=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,b=U.useMemo(()=>{const k=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var C;return(C=s?.map(M=>{const A=typeof M=="string";let D=0;if(A&&(D=parseInt(M,10)),ke(l)){const I=A?D:h?M*k.height:0;return h?l==="bottom"?k.height-I:-k.height+I:I}const P=A?D:h?M*k.width:0;return h?l==="right"?k.width-P:-k.width+P:P}))!=null?C:[]},[s,h,u]),y=U.useMemo(()=>p!==null?b?.[p]:null,[b,p]),j=U.useCallback(k=>{var C;const M=(C=b?.findIndex(A=>A===k))!=null?C:null;i(M),Ie(r.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(l)?`translate3d(0, ${k}px, 0)`:`translate3d(${k}px, 0, 0)`}),b&&M!==b.length-1&&o!==void 0&&M!==o&&M<o?Ie(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"0"}):Ie(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"1"}),m(s?.[Math.max(M,0)])},[r.current,s,b,o,a,m]);U.useEffect(()=>{if(d||e){var k;const C=(k=s?.findIndex(M=>M===e||M===d))!=null?k:-1;b&&C!==-1&&typeof b[C]=="number"&&j(b[C])}},[d,e,s,b,j]);function w({draggedDistance:k,closeDrawer:C,velocity:M,dismissible:A}){if(o===void 0)return;const D=l==="bottom"||l==="right"?(y??0)-k:(y??0)+k,P=p===o-1,I=p===0,S=k>0;if(P&&Ie(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`}),!f&&M>2&&!S){A?C():j(b[0]);return}if(!f&&M>2&&S&&b&&s){j(b[s.length-1]);return}const O=b?.reduce((T,$)=>typeof T!="number"||typeof $!="number"?T:Math.abs($-D)<Math.abs(T-D)?$:T),L=ke(l)?window.innerHeight:window.innerWidth;if(M>vu&&Math.abs(k)<L*.4){const T=S?1:-1;if(T>0&&v&&s){j(b[s.length-1]);return}if(I&&T<0&&A&&C(),p===null)return;j(b[p+T]);return}j(O)}function E({draggedDistance:k}){if(y===null)return;const C=l==="bottom"||l==="right"?y-k:y+k;(l==="bottom"||l==="right")&&C<b[b.length-1]||(l==="top"||l==="left")&&C>b[b.length-1]||Ie(r.current,{transform:ke(l)?`translate3d(0, ${C}px, 0)`:`translate3d(${C}px, 0, 0)`})}function N(k,C){if(!s||typeof p!="number"||!b||o===void 0)return null;const M=p===o-1;if(p>=o&&C)return 0;if(M&&!C)return 1;if(!x&&!M)return null;const D=M?p+1:p-1,P=M?b[D]-b[D-1]:b[D+1]-b[D],I=k/Math.abs(P);return M?1-I:I}return{isLastSnapPoint:v,activeSnapPoint:d,shouldFade:x,getPercentageDragged:N,setActiveSnapPoint:m,activeSnapPointIndex:p,onRelease:w,onDrag:E,snapPointsOffset:b}}const Ov=()=>()=>{};function Dv(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:r,noBodyStyles:a}=hn(),o=U.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-oa)/window.innerWidth}U.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;Iv(r&&!a?Br(document.body,{background:"black"}):Ov,Br(u,{transformOrigin:ke(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${xe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${xe.EASE.join(",")})`}));const f=Br(u,{borderRadius:`${yu}px`,overflow:"hidden",...ke(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")},xe.DURATION*1e3)}}},[t,s,i])}let Bs=null;function Pv({isOpen:e,modal:t,nested:s,hasBeenOpened:r,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=U.useState(()=>typeof window<"u"?window.location.href:""),u=U.useRef(0),f=U.useCallback(()=>{if(Ti()&&Bs===null&&e&&!o){Bs={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 g=h-window.innerHeight;g&&u.current>=h&&(document.body.style.top=`${-(u.current+g)}px`)}),300)}},[e]),d=U.useCallback(()=>{if(Ti()&&Bs!==null&&!o){const m=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Bs),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,m)}),Bs=null}},[i]);return U.useEffect(()=>{function m(){u.current=window.scrollY}return m(),window.addEventListener("scroll",m),()=>{window.removeEventListener("scroll",m)}},[]),U.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),U.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 Lv({open:e,onOpenChange:t,children:s,onDrag:r,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=Tv,scrollLockTimeout:f=Rv,dismissible:d=!0,handleOnly:m=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:g,setActiveSnapPoint:v,fixed:p,modal:x=!0,onClose:b,nested:y,noBodyStyles:j=!1,direction:w="bottom",defaultOpen:E=!1,disablePreventScroll:N=!0,snapToSequentialPoint:k=!1,preventScrollRestoration:C=!1,repositionInputs:M=!0,onAnimationEnd:A,container:D,autoFocus:P=!1}){var I,S;const[O=!1,L]=ju({defaultProp:E,prop:e,onChange:ee=>{t?.(ee),!ee&&!y&&St(),setTimeout(()=>{A?.(ee)},xe.DURATION*1e3),ee&&!x&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),ee||(document.body.style.pointerEvents="auto")}}),[T,$]=U.useState(!1),[R,F]=U.useState(!1),[Q,Z]=U.useState(!1),K=U.useRef(null),z=U.useRef(null),Y=U.useRef(null),ue=U.useRef(null),oe=U.useRef(null),se=U.useRef(!1),H=U.useRef(null),G=U.useRef(0),ae=U.useRef(!1),je=U.useRef(!E),Ne=U.useRef(0),J=U.useRef(null),X=U.useRef(((I=J.current)==null?void 0:I.getBoundingClientRect().height)||0),re=U.useRef(((S=J.current)==null?void 0:S.getBoundingClientRect().width)||0),te=U.useRef(0),Pe=U.useCallback(ee=>{o&&ee===he.length-1&&(z.current=new Date)},[]),{activeSnapPoint:Qe,activeSnapPointIndex:B,setActiveSnapPoint:ze,onRelease:Le,snapPointsOffset:he,onDrag:Ae,shouldFade:pe,getPercentageDragged:Kt}=Av({snapPoints:o,activeSnapPointProp:g,setActiveSnapPointProp:v,drawerRef:J,fadeFromIndex:h,overlayRef:K,onSnapPointChange:Pe,direction:w,container:D,snapToSequentialPoint:k});wv({isDisabled:!O||R||!x||Q||!T||!M||!N});const{restorePositionSetting:St}=Pv({isOpen:O,modal:x,nested:y??!1,hasBeenOpened:T,preventScrollRestoration:C,noBodyStyles:j});function qe(){return(window.innerWidth-oa)/window.innerWidth}function Ye(ee){var ie,de;!d&&!o||J.current&&!J.current.contains(ee.target)||(X.current=((ie=J.current)==null?void 0:ie.getBoundingClientRect().height)||0,re.current=((de=J.current)==null?void 0:de.getBoundingClientRect().width)||0,F(!0),Y.current=new Date,pu()&&window.addEventListener("touchend",()=>se.current=!1,{once:!0}),ee.target.setPointerCapture(ee.pointerId),G.current=ke(w)?ee.pageY:ee.pageX)}function tt(ee,ie){var de;let le=ee;const ce=(de=window.getSelection())==null?void 0:de.toString(),Se=J.current?Tn(J.current,w):null,Ee=new Date;if(le.tagName==="SELECT"||le.hasAttribute("data-vaul-no-drag")||le.closest("[data-vaul-no-drag]"))return!1;if(w==="right"||w==="left")return!0;if(z.current&&Ee.getTime()-z.current.getTime()<500)return!1;if(Se!==null&&(w==="bottom"?Se>0:Se<0))return!0;if(ce&&ce.length>0)return!1;if(oe.current&&Ee.getTime()-oe.current.getTime()<f&&Se===0||ie)return oe.current=Ee,!1;for(;le;){if(le.scrollHeight>le.clientHeight){if(le.scrollTop!==0)return oe.current=new Date,!1;if(le.getAttribute("role")==="dialog")return!0}le=le.parentNode}return!0}function He(ee){if(J.current&&R){const ie=w==="bottom"||w==="right"?1:-1,de=(G.current-(ke(w)?ee.pageY:ee.pageX))*ie,le=de>0,ce=o&&!d&&!le;if(ce&&B===0)return;const Se=Math.abs(de),Ee=document.querySelector("[data-vaul-drawer-wrapper]"),Oe=w==="bottom"||w==="top"?X.current:re.current;let Re=Se/Oe;const De=Kt(Se,le);if(De!==null&&(Re=De),ce&&Re>=1||!se.current&&!tt(ee.target,le))return;if(J.current.classList.add(Kr),se.current=!0,Ie(J.current,{transition:"none"}),Ie(K.current,{transition:"none"}),o&&Ae({draggedDistance:de}),le&&!o){const we=Ev(de),it=Math.min(we*-1,0)*ie;Ie(J.current,{transform:ke(w)?`translate3d(0, ${it}px, 0)`:`translate3d(${it}px, 0, 0)`});return}const Be=1-Re;if((pe||h&&B===h-1)&&(r?.(ee,Re),Ie(K.current,{opacity:`${Be}`,transition:"none"},!0)),Ee&&K.current&&i){const we=Math.min(qe()+Re*(1-qe()),1),it=8-Re*8,qt=Math.max(0,14-Re*14);Ie(Ee,{borderRadius:`${it}px`,transform:ke(w)?`scale(${we}) translate3d(0, ${qt}px, 0)`:`scale(${we}) translate3d(${qt}px, 0, 0)`,transition:"none"},!0)}if(!o){const we=Se*ie;Ie(J.current,{transform:ke(w)?`translate3d(0, ${we}px, 0)`:`translate3d(${we}px, 0, 0)`})}}}U.useEffect(()=>{window.requestAnimationFrame(()=>{je.current=!0})},[]),U.useEffect(()=>{var ee;function ie(){if(!J.current||!M)return;const de=document.activeElement;if(aa(de)||ae.current){var le;const ce=((le=window.visualViewport)==null?void 0:le.height)||0,Se=window.innerHeight;let Ee=Se-ce;const Oe=J.current.getBoundingClientRect().height||0,Re=Oe>Se*.8;te.current||(te.current=Oe);const De=J.current.getBoundingClientRect().top;if(Math.abs(Ne.current-Ee)>60&&(ae.current=!ae.current),o&&o.length>0&&he&&B){const Be=he[B]||0;Ee+=Be}if(Ne.current=Ee,Oe>ce||ae.current){const Be=J.current.getBoundingClientRect().height;let we=Be;Be>ce&&(we=ce-(Re?De:oa)),p?J.current.style.height=`${Be-Math.max(Ee,0)}px`:J.current.style.height=`${Math.max(we,ce-De)}px`}else hv()||(J.current.style.height=`${te.current}px`);o&&o.length>0&&!ae.current?J.current.style.bottom="0px":J.current.style.bottom=`${Math.max(Ee,0)}px`}}return(ee=window.visualViewport)==null||ee.addEventListener("resize",ie),()=>{var de;return(de=window.visualViewport)==null?void 0:de.removeEventListener("resize",ie)}},[B,o,he]);function st(ee){pt(),b?.(),ee||L(!1),setTimeout(()=>{o&&ze(o[0])},xe.DURATION*1e3)}function ht(){if(!J.current)return;const ee=document.querySelector("[data-vaul-drawer-wrapper]"),ie=Tn(J.current,w);Ie(J.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`}),Ie(K.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"1"}),i&&ie&&ie>0&&O&&Ie(ee,{borderRadius:`${yu}px`,overflow:"hidden",...ke(w)?{transform:`scale(${qe()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${qe()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${xe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${xe.EASE.join(",")})`},!0)}function pt(){!R||!J.current||(J.current.classList.remove(Kr),se.current=!1,F(!1),ue.current=new Date)}function Ut(ee){if(!R||!J.current)return;J.current.classList.remove(Kr),se.current=!1,F(!1),ue.current=new Date;const ie=Tn(J.current,w);if(!ee||!tt(ee.target,!1)||!ie||Number.isNaN(ie)||Y.current===null)return;const de=ue.current.getTime()-Y.current.getTime(),le=G.current-(ke(w)?ee.pageY:ee.pageX),ce=Math.abs(le)/de;if(ce>.05&&(Z(!0),setTimeout(()=>{Z(!1)},200)),o){Le({draggedDistance:le*(w==="bottom"||w==="right"?1:-1),closeDrawer:st,velocity:ce,dismissible:d}),a?.(ee,!0);return}if(w==="bottom"||w==="right"?le>0:le<0){ht(),a?.(ee,!0);return}if(ce>vu){st(),a?.(ee,!1);return}var Se;const Ee=Math.min((Se=J.current.getBoundingClientRect().height)!=null?Se:0,window.innerHeight);var Oe;const Re=Math.min((Oe=J.current.getBoundingClientRect().width)!=null?Oe:0,window.innerWidth),De=w==="left"||w==="right";if(Math.abs(ie)>=(De?Re:Ee)*u){st(),a?.(ee,!1);return}a?.(ee,!0),ht()}U.useEffect(()=>(O&&(Ie(document.documentElement,{scrollBehavior:"auto"}),z.current=new Date),()=>{Nv(document.documentElement,"scrollBehavior")}),[O]);function ge(ee){const ie=ee?(window.innerWidth-Wt)/window.innerWidth:1,de=ee?-Wt:0;H.current&&window.clearTimeout(H.current),Ie(J.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(w)?`scale(${ie}) translate3d(0, ${de}px, 0)`:`scale(${ie}) translate3d(${de}px, 0, 0)`}),!ee&&J.current&&(H.current=setTimeout(()=>{const le=Tn(J.current,w);Ie(J.current,{transition:"none",transform:ke(w)?`translate3d(0, ${le}px, 0)`:`translate3d(${le}px, 0, 0)`})},500))}function Ge(ee,ie){if(ie<0)return;const de=(window.innerWidth-Wt)/window.innerWidth,le=de+ie*(1-de),ce=-Wt+ie*Wt;Ie(J.current,{transform:ke(w)?`scale(${le}) translate3d(0, ${ce}px, 0)`:`scale(${le}) translate3d(${ce}px, 0, 0)`,transition:"none"})}function rs(ee,ie){const de=ke(w)?window.innerHeight:window.innerWidth,le=ie?(de-Wt)/de:1,ce=ie?-Wt:0;ie&&Ie(J.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(w)?`scale(${le}) translate3d(0, ${ce}px, 0)`:`scale(${le}) translate3d(${ce}px, 0, 0)`})}return U.useEffect(()=>{x||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[x]),U.createElement(nu,{defaultOpen:E,onOpenChange:ee=>{!d&&!ee||(ee?$(!0):st(!0),L(ee))},open:O},U.createElement(hu.Provider,{value:{activeSnapPoint:Qe,snapPoints:o,setActiveSnapPoint:ze,drawerRef:J,overlayRef:K,onOpenChange:t,onPress:Ye,onRelease:Ut,onDrag:He,dismissible:d,shouldAnimate:je,handleOnly:m,isOpen:O,isDragging:R,shouldFade:pe,closeDrawer:st,onNestedDrag:Ge,onNestedOpenChange:ge,onNestedRelease:rs,keyboardIsOpen:ae,modal:x,snapPointsOffset:he,activeSnapPointIndex:B,direction:w,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:j,container:D,autoFocus:P}},s))}const Su=U.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:r,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=hn(),f=xu(t,s),d=r&&r.length>0;if(!l)return null;const m=U.useCallback(h=>a(h),[a]);return U.createElement(iu,{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})});Su.displayName="Drawer.Overlay";const ku=U.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:g,direction:v,snapPoints:p,container:x,handleOnly:b,shouldAnimate:y,autoFocus:j}=hn(),[w,E]=U.useState(!1),N=xu(a,o),k=U.useRef(null),C=U.useRef(null),M=U.useRef(!1),A=p&&p.length>0;Dv();const D=(I,S,O=0)=>{if(M.current)return!0;const L=Math.abs(I.y),T=Math.abs(I.x),$=T>L,R=["bottom","right"].includes(S)?1:-1;if(S==="left"||S==="right"){if(!(I.x*R<0)&&T>=0&&T<=O)return $}else if(!(I.y*R<0)&&L>=0&&L<=O)return!$;return M.current=!0,!0};U.useEffect(()=>{A&&window.requestAnimationFrame(()=>{E(!0)})},[]);function P(I){k.current=null,M.current=!1,l(I)}return U.createElement(lu,{"data-vaul-drawer-direction":v,"data-vaul-drawer":"","data-vaul-delayed-snap-points":w?"true":"false","data-vaul-snap-points":g&&A?"true":"false","data-vaul-custom-container":x?"true":"false","data-vaul-animate":y?.current?"true":"false",...r,ref:N,style:d&&d.length>0?{"--snap-point-height":`${d[m??0]}px`,...t}:t,onPointerDown:I=>{b||(r.onPointerDown==null||r.onPointerDown.call(r,I),k.current={x:I.pageX,y:I.pageY},i(I))},onOpenAutoFocus:I=>{s?.(I),j||I.preventDefault()},onPointerDownOutside:I=>{if(e?.(I),!h||I.defaultPrevented){I.preventDefault();return}f.current&&(f.current=!1)},onFocusOutside:I=>{if(!h){I.preventDefault();return}},onPointerMove:I=>{if(C.current=I,b||(r.onPointerMove==null||r.onPointerMove.call(r,I),!k.current))return;const S=I.pageY-k.current.y,O=I.pageX-k.current.x,L=I.pointerType==="touch"?10:2;D({x:O,y:S},v,L)?u(I):(Math.abs(O)>L||Math.abs(S)>L)&&(k.current=null)},onPointerUp:I=>{r.onPointerUp==null||r.onPointerUp.call(r,I),k.current=null,M.current=!1,l(I)},onPointerOut:I=>{r.onPointerOut==null||r.onPointerOut.call(r,I),P(C.current)},onContextMenu:I=>{r.onContextMenu==null||r.onContextMenu.call(r,I),C.current&&P(C.current)}})});ku.displayName="Drawer.Content";const $v=250,Fv=120,Cu=U.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:g}=hn(),v=U.useRef(null),p=U.useRef(!1);function x(){if(p.current){j();return}window.setTimeout(()=>{b()},Fv)}function b(){if(o||e||p.current){j();return}if(j(),!i||i.length===0){f||a();return}if(l===i[i.length-1]&&f){a();return}const E=i.findIndex(k=>k===l);if(E===-1)return;const N=i[E+1];u(N)}function y(){v.current=window.setTimeout(()=>{p.current=!0},$v)}function j(){v.current&&window.clearTimeout(v.current),p.current=!1}return U.createElement("div",{onClick:x,onPointerCancel:j,onPointerDown:w=>{d&&h(w),y()},onPointerMove:w=>{d&&g(w)},ref:r,"data-vaul-drawer-visible":m?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},U.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});Cu.displayName="Drawer.Handle";function _v(e){const t=hn(),{container:s=t.container,...r}=e;return U.createElement(ou,{container:s,...r})}const Ze={Root:Lv,Content:ku,Overlay:Su,Portal:_v,Handle:Cu,Title:du},Nu="inline-flex items-center justify-center transition-colors",zv=be(Nu,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Bv=be(Nu,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),pn=({accountId:e,currentMailboxId:t,onMove:s,disabled:r=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),f=$t(),d=c.useRef(null),m=i??"Move to folder",h=c.useId(),{t:g}=Hn("mail",{useSuspense:!1}),v=c.useCallback((P,I)=>g(P,{defaultValue:I}),[g]),{data:p,isLoading:x,isError:b,error:y,refetch:j}=fe({...Ue({path:{accountId:e}}),staleTime:1/0,enabled:l}),w=Zc(e),{createFolder:E}=Il(e),N=c.useMemo(()=>{const P=an(p?.items??[],w),I=sn(w);return P.map(S=>({id:S.mailboxId,label:ys(S,I.get(S.mailboxId),v),searchValue:S.fullPath,isCurrent:S.mailboxId===t}))},[p?.items,w,t,v]),k=c.useCallback(P=>{u(!1),s(P)},[s]),C=c.useCallback(async(P,I)=>{const S=await E(P,I);return{id:S.id,label:S.label}},[E]);c.useEffect(()=>{if(!l||!f)return;const P=S=>{d.current&&!d.current.contains(S.target)&&u(!1)},I=S=>{S.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",P),document.addEventListener("keydown",I),()=>{document.removeEventListener("mousedown",P),document.removeEventListener("keydown",I)}},[l,f]);const M=r||!!a,A=n.jsxs("button",{type:"button",onClick:P=>{P.stopPropagation(),!M&&u(I=>!I)},"aria-label":m,"aria-haspopup":f?"listbox":"dialog","aria-expanded":l,"aria-controls":l?h:void 0,title:a,className:o==="icon-only"?zv:Bv,children:[n.jsx(Da,{className:"size-4"}),o==="compact"&&n.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),D=x?n.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):b?n.jsx("div",{className:"p-3",children:n.jsx(Ft,{variant:"inline",title:"Couldn't load folders",error:y,onRetry:()=>j()})}):n.jsx(Tl,{mailboxes:N,onSelect:k,onCreateFolder:C,onCancel:()=>u(!1),autoFocus:!f,labels:{createLabel:P=>`Create "${P}"`,searchPlaceholder:g("move_picker_placeholder",{defaultValue:"Move to…"}),searchAriaLabel:g("move_picker_filter_label",{defaultValue:"Filter folders"}),optionLabel:P=>`Move to ${P}`,currentSuffix:"(current folder)",currentTag:"current",emptyMessage:P=>`No folders match "${P}"`}});return f?n.jsxs("div",{ref:d,className:"relative inline-block",children:[A,l&&n.jsx("div",{id:h,className:be("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:[A,n.jsx(Ze.Root,{open:l,onOpenChange:u,children:n.jsxs(Ze.Portal,{children:[n.jsx(Ze.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Ze.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(Ze.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),n.jsx(Ze.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})]})]})})]})},Kv=({messageId:e,threadId:t,mailboxId:s,isRead:r,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const f=ye(),d=Me(),{pushError:m}=Ve(),{selectedMessageId:h}=ws({strict:!1}),{mutate:g,isPending:v}=ve({...Qn(),onMutate:async O=>{const L=O.body.isRead??!0,T=new Set(O.body.messageIds??[]),$=ss({path:{threadId:t}}),R=wt([s]);await Promise.all([f.cancelQueries({queryKey:$}),un(f,R)]);const F=f.getQueriesData({queryKey:$}).filter(Z=>Z[1]!==void 0).map(([Z,K])=>({queryKey:Z,data:K})),Q=dn(f,R);return f.setQueriesData({queryKey:$},Z=>Z&&{...Z,items:_n(Z.items,T,L)}),fn(f,R,Z=>_n(Z,T,L)),{threadMessagesPrefix:$,listPrefixes:R,previousThreadMessages:F,previousThreadsList:Q}},onError:(O,L,T)=>{if(T){for(const R of T.previousThreadMessages)f.setQueryData(R.queryKey,R.data);mn(f,T.previousThreadsList)}const $=L.body.isRead??!0;m({title:$?"Couldn't mark as read":"Couldn't mark as unread",detail:rt(O),error:O})},onSettled:(O,L,T,$)=>{$&&(f.invalidateQueries({queryKey:$.threadMessagesPrefix}),jt(f,$.listPrefixes))}}),p=c.useCallback(O=>{h&&O.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:L=>({...L,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:x,isPending:b}=Jt({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:y,isPending:j}=Xt({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:w,isPending:E,error:N,reset:k}=eo({messageId:e}),C=()=>{g({body:{messageIds:[e],isRead:!1}})},M=()=>{x([e])},A=()=>{o&&w(o,i)},D=v||b||j||E,P=D||!o,I=c.useCallback(O=>{y([e],O)},[y,e]),S=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(pn,{accountId:a,currentMailboxId:s,onMove:I,disabled:D,label:"Move this message"}),n.jsxs(Ac,{trigger:n.jsx(Hl,{className:"size-4"}),children:[n.jsxs(gs,{onClick:A,disabled:P,children:[i?n.jsx(Zn,{className:"size-4 text-positive"}):n.jsx(en,{className:"size-4 opacity-0"}),n.jsx("span",{title:S,children:"Trusted sender"})]}),r&&n.jsxs(gs,{onClick:C,disabled:D,children:[n.jsx(Ns,{className:"size-4"}),"Mark as unread"]}),u&&n.jsxs(gs,{onClick:u,children:[n.jsx(ql,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),n.jsx(sa,{}),n.jsxs(gs,{onClick:M,disabled:D,destructive:!0,children:[n.jsx(at,{className:"size-4"}),"Delete"]})]})]}),N&&n.jsx("div",{className:"w-64",children:n.jsx(Ft,{variant:"inline",title:"Couldn't update trust",error:N,onRetry:()=>{k(),A()}})})]})},Uv=()=>{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},qv=({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"})]})]}),Hv=(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}}},Wv=e=>e instanceof Vt?e.reason:"generic",Vv=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",Qv=({error:e,onRetry:t})=>{const s=Wv(e),r=Vv(e),{title:a,detail:o}=Hv(s,r),[i,l]=c.useState(!1),{Account:u}=ja();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(Zt,{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"})})]})]})},Yv=()=>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"})]}),Oi=()=>n.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Eu=({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=Uv(),{toggleTrusted:h,isPending:g}=eo({messageId:a??""}),v=!!e&&e.length>0,{picked:p,data:x,isLoading:b,isError:y,error:j,refetch:w}=qc({messageId:a,bodyParts:e,enabled:v}),E=c.useMemo(()=>Rh(e??[]),[e]),N=v&&x?.kind==="html"?x.body:t,k=v&&x?.kind==="text"?x.body:s;if(v){if(b)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Yv,{})});if(y)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Qv,{error:j,onRetry:()=>w()})});if(!p)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Oi,{})})}else if(!t&&!s)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Oi,{})});const C=!!(o&&a),M=()=>{!o||g||(f(!0),h(o,!1))};return n.jsx(lc,{className:l,html:N,text:k,isDark:m,category:i,allowImages:d,resolveCid:E,renderBlockedNotice:A=>n.jsx(qv,{blockedImageCount:A,canAlwaysTrust:C,isTrustPending:g,onLoadOnce:()=>f(!0),onAlwaysTrust:M})})},Gv=({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:g})=>{const v=ye(),{deleteMessages:p}=Jt({mailboxId:s,threadId:t}),{moveMessages:x}=Xt({mailboxId:s,threadId:t,accountId:r}),{toggleTrusted:b}=eo({messageId:e}),{mutate:y}=ve({...Qn(),onSettled:()=>{v.invalidateQueries({queryKey:ss({path:{threadId:t}})}),jt(v,wt([s]))}}),j=c.useCallback(k=>{x([e],k)},[x,e]),w=c.useCallback(()=>{p([e])},[p,e]),E=c.useCallback(()=>{y({body:{messageIds:[e],isRead:!a}})},[y,e,a]),N=[];return l&&N.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?n.jsx(Zn,{className:"size-4 text-positive"}):n.jsx(en,{className:"size-4"}),onSelect:()=>b(l,u)}),d&&N.push({key:"raw",label:f?"Show formatted":"Show raw email",icon:n.jsx(ql,{className:"size-4"}),onSelect:d}),n.jsx(ic,{hasThread:!0,onReply:m,onReplyAll:h,onForward:g,isStarred:o,onToggleStar:i,onDelete:w,isRead:a,onToggleRead:E,overflowItems:N,moveSlot:r?n.jsx(pn,{accountId:r,currentMailboxId:s,onMove:j,label:"Move this message"}):void 0})},Xv=()=>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"})]}),Jv=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:r,isError:a,error:o,refetch:i}=fe({...wf({path:{messageId:e}}),enabled:t});if(r)return n.jsx("div",{className:"message-body",children:n.jsx(Xv,{})});if(a)return n.jsx("div",{className:"message-body",children:n.jsx(Ft,{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})})},Zv=()=>n.jsx(Zn,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),Iu=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),Tu=({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:be("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":be("text-fg-subtle hover:text-warning",r&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:n.jsx(Pt,{className:be("size-3.5",e&&"fill-current")})}),ey=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:r,isStarPending:a})=>{const o=Nl(e.sentDate,"datetime"),i=Iu(e,o);return n.jsx(cc,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:n.jsxs(n.Fragment,{children:[e.hasAttachment&&n.jsx(er,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx(Tu,{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})]})})},ty=({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:g,onReply:v,onReplyAll:p,onForward:x})=>{const b=Nl(e.sentDate,"long"),y=!e.isRead,j=t?.envelope.from[0]?.flags?.trusted?.value===!0,w=t?.envelope.from[0]?.addressId,E=Iu(e,b),N=e.autoMoved?n.jsx(eu,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"md"}):null;return n.jsx(uc,{message:E,isFocused:g?!1:i,onHeaderClick:l,senderBadge:j?n.jsx(Zv,{}):void 0,trailing:n.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:b}),to:t?n.jsx(sh,{label:"To",addresses:t.envelope.to}):null,indicators:N||!g?n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[N,!g&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n.jsx(Tu,{isStarred:e.hasStars,onToggleStar:u,isStarPending:f}),e.hasAttachment&&n.jsx("span",{className:"text-fg-subtle p-0.5",children:n.jsx(er,{className:"size-3.5"})})]}),y&&n.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:g?void 0:n.jsx(Kv,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:w,isTrusted:j,showRaw:m,onToggleRaw:h}),actionBar:g?n.jsx(Gv,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:w,isTrusted:j,showRaw:m,onToggleRaw:h,onReply:v,onReplyAll:p,onForward:x}):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&&jf(a)?n.jsx("div",{className:"mt-3",children:n.jsx(Gc,{message:"This message has been deleted"})}):r?n.jsx("div",{className:"mt-3",children:n.jsx(Ft,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):m?n.jsx("div",{className:"mt-3",children:n.jsx(Jv,{messageId:e.messageId})}):n.jsx("div",{className:"mt-3",children:n.jsx(Eu,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:j,category:ir(e.category)})})})},sy=({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:g,isLoading:v,isError:p,error:x,refetch:b}=fe({...Ea({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?n.jsx(ty,{threadMessage:e,messageData:g,isLoading:v,isError:p,error:x,onRetry:()=>b(),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(ey,{threadMessage:e,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o})},ny=()=>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 Di({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(Es,{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 Ts=({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=$t(),{handlers:g}=Hb({onSwipeLeft:f,onSwipeRight:d}),{accountId:v}=Xc(t),{data:p,isLoading:x,isError:b,error:y,refetch:j}=fe({...Sf({path:{threadId:e}})}),w=c.useMemo(()=>p?.items??[],[p?.items]),E=w[w.length-1],N=c.useRef(new Map),[k,C]=c.useState(new Set),[M,A]=c.useState(null),[D,P]=c.useState(0);c.useEffect(()=>{if(w.length>0&&e!==M){A(e);const X=new Set([w[w.length-1].threadMessageId]);if(r){const re=w.find(te=>te.messageId===r);re&&X.add(re.threadMessageId)}C(X),P(w.length-1)}},[e,w,M,r]);const I=c.useCallback(X=>{C(re=>{const te=new Set(re);return te.has(X)?te.delete(X):te.add(X),te})},[]),S=c.useCallback(X=>{const re=w[X];if(!re)return;N.current.get(re.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[w]),O=c.useCallback(()=>{if(w.length===0)return;const X=Math.min(D+1,w.length-1);P(X),S(X)},[w.length,D,S]),L=c.useCallback(()=>{if(w.length===0)return;const X=Math.max(D-1,0);P(X),S(X)},[w.length,D,S]),T=c.useCallback(()=>{const X=w[D];X&&I(X.threadMessageId)},[w,D,I]),{data:$}=fe({...vt(),staleTime:1/0}),R=$?.accounts?.[0],F=!!R?.smtpHost;Bb({messages:w,expandedIds:k,threadId:e,mailboxId:t,accountId:R?.accountId});const{toggleStar:Q,isPending:Z,pendingMessageId:K}=Xa({threadId:e,mailboxId:t,messages:w}),[z,Y]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(Y(l),u?.())},[l,u]);const{data:ue}=fe({...Ea({path:{messageId:E?.messageId??""}}),enabled:!!E&&z!==null}),oe=c.useCallback(()=>{Y("reply")},[]),se=c.useCallback(()=>{Y("reply_all")},[]),H=c.useCallback(()=>{Y("forward")},[]),G=c.useCallback(()=>{Y(null),u?.()},[u]);if(Ga({enabled:!x&&w.length>0&&z===null,bindings:[{key:"j",handler:O,preventDefault:!0},{key:"ArrowDown",handler:O,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},...F?[{key:"r",handler:oe,preventDefault:!0},{key:"R",handler:se,noModifiers:!1,preventDefault:!0},{key:"f",handler:H,preventDefault:!0}]:[]]}),x)return n.jsx(ny,{});if(b)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(Ft,{title:"Couldn't load this conversation",error:y,onRetry:()=>j()})});if(w.length===0)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(Gc,{message:"No messages in this thread"})});const ae=s||w[0]?.subject||"(No subject)",je=w.length,Ne=X=>n.jsx("div",{children:w.map((re,te)=>n.jsx("div",{ref:Pe=>{Pe&&N.current.set(re.threadMessageId,Pe)},children:n.jsx(sy,{threadMessage:re,isExpanded:k.has(re.threadMessageId),isFocused:te===D,onToggle:()=>I(re.threadMessageId),onToggleStar:()=>Q(re.messageId,re.hasStars),isStarPending:Z&&K===re.messageId,accountId:v,mobile:X,onReply:X&&F?oe:void 0,onReplyAll:X&&F?se:void 0,onForward:X&&F?H:void 0})},re.threadMessageId))}),J=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:ae}),n.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[je," ",je===1?"message":"messages"]})]});return h?n.jsxs("article",{className:"h-full flex flex-col",children:[J,a?.dkimMismatch&&n.jsx(Di,{authenticity:a,onOpenIntelligence:o}),n.jsx("div",{className:"flex-1 overflow-auto",children:Ne(!1)}),z!==null&&n.jsx(Ci,{mode:z,account:R,sourceMessage:ue,onClose:G})]}):n.jsxs(tp,{thread:{subject:ae,messages:[]},onBack:i??(()=>{}),intelligenceOpen:m,onToggleIntelligence:o,touchHandlers:g,children:[a?.dkimMismatch&&n.jsx(Di,{authenticity:a,onOpenIntelligence:o}),Ne(!0),z!==null&&n.jsx(Ci,{mode:z,account:R,sourceMessage:ue,onClose:G})]})};function Rs(){const{mailboxNameIndex:e,accountNameIndex:t}=Ce();return{...bt({select:r=>_c(r.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const ro=e=>e.trim().toLocaleLowerCase(),ry=/^\d{4}-\d{2}-\d{2}$/;function Pi(e,t,s){if(!ry.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 ay(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 Pi("before",e,e.slice(7));if(s.startsWith("after:")&&e.length>6)return Pi("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 Ms(e,t={}){const s=e.split(/\s+/).filter(o=>o.length>0),r=[],a=[];for(const o of s){const i=ay(o,t);i?r.push(i):a.push(o)}return{freeText:a.join(" "),tokens:r}}function oy(e,t){return e.split(/\s+/).filter(s=>s.length>0&&s!==t.raw).join(" ")}function Ru(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 iy=20,ly=new Set(Object.values(nt)),cy=e=>e!==void 0&&ly.has(e)?e:void 0;function Mu({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Ce(),r=Rs(),a=bt({select:y=>y.matches}),o=ro(s),{freeText:i,tokens:l}=Ms(o,r),u=i.length>0,f=cy(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"),g=l.find(y=>y.type==="before"),v=l.find(y=>y.type==="in"),p=Zx({matches:a,callerMailboxId:e,inTokenMailboxId:v?.mailboxId}),{data:x,isLoading:b}=fe({...ml({query:{query:i,mailboxId:p,limit:iy,...f!==void 0?{category:f}:{},...d!==void 0?{hasAttachment:d}:{},...m!==void 0?{isRead:m}:{},...h?{sentDateFrom:h.epochSeconds}:{},...g?{sentDateTo:g.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:x?.items??[],isLoading:u&&b}}const uy=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),dy=e=>[...e].sort(uy);function ia(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:_t(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:ir(e.category),suspicious:t}}function Li(e){return e.filter(t=>t.muted!==!0)}function fy(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 $i=[{id:"personal",label:"Personal",category:nt.personal},{id:"transactional",label:"Transactional",category:nt.transactional},{id:"newsletter",label:"Newsletter",category:nt.newsletter},{id:"marketing",label:"Marketing",category:nt.marketing},{id:"social",label:"Social",category:nt.social},{id:"automated",label:"Automated",category:nt.automated},{id:"uncategorized",label:"Unclassified",category:nt.uncategorized}];function my(e){const t=new Map($i.map(r=>[r.category,[]]));for(const r of e){const a=r.category??nt.uncategorized;(t.get(a)??t.get(nt.uncategorized))?.push(r)}const s=[];for(const r of $i){const a=t.get(r.category);a&&a.length>0&&s.push({id:r.id,label:r.label,threads:a})}return s}function Au(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Ou(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 hy={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function py(e){return hy[e]??e}function gy(e,t){const{folder:s}=Ia(t,[e.mailboxId]);return{id:e.messageId,sender:e.fromName??e.fromEmail??"Unknown",subject:e.subject??"(No subject)",snippet:e.snippet??"",date:_t(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Du(e,t){const{folder:s}=Ia(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 xy(e,t){const{mailboxId:s,folder:r}=Ia(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?_t(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:py(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...r?{folder:r}:{}}}function Pu(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(xy(o,s)));return a}const by=768,vy=1024,Lu=e=>e!=="desktop",dr=()=>{const e=Co(`(min-width: ${by}px)`);return Co(`(min-width: ${vy}px)`)?"desktop":e?"tablet":"phone"},yy=new Set(["hasAttachment","isUnread","before","after"]),$u=(e,{searchHadSemanticReach:t})=>{const s=[],r=[];let a,o;for(const u of e.tokens){if(u.type==="from"){s.push({field:"From",value:u.value});continue}if(u.type==="in"){a={mailboxId:u.mailboxId,label:u.value};continue}if(u.type==="account"){o=u.accountId;continue}yy.has(u.type)&&r.push({type:u.type,label:Ru(u)})}const i=e.freeText.trim(),l=i.length>0;return l&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:r,targetAccountId:o,keptTerms:l,droppedSemantic:l&&t}},wy=e=>e.clauses.length>0,Fu=(e,{scope:t="standing",moveMailboxId:s}={})=>({clauses:e.clauses.map((r,a)=>({id:`search-${a}`,field:r.field,value:r.value})),matchOperator:e.matchOperator,moveMailboxId:s,scope:t,name:""}),_u="remit.recentSearches",jy=5;function la(){try{const e=localStorage.getItem(_u);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Fi(e){const t=e.trim();if(!t)return la();const s=[t,...la().filter(r=>r!==t)].slice(0,jy);try{localStorage.setItem(_u,JSON.stringify(s))}catch{return s}return s}const Sy=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function ky(e){const{spam:t}=fc([...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}const Cy=(e,t)=>{const s=ve(hl()),{mutate:r,reset:a}=s,o=c.useCallback(()=>{e&&(a(),r({path:{accountId:e},body:Yr({matchOperator:t.matchOperator,literalClauses:t.literalClauses})}))},[e,t.matchOperator,t.literalClauses,r,a]);return c.useEffect(()=>{o()},[o]),{seedCount:s.data?.matchedCount,isPending:s.isPending||s.data===void 0,isError:s.isError,error:s.error,retry:o}},zu=({initialRule:e,widenAnchorCount:t=1})=>{const[s,r]=c.useState(e),[a,o]=c.useState(),i=c.useRef(0);return{rule:s,setRule:N=>r(N),handlers:{clauseEdit:a,onStartAddClause:()=>o({mode:"add",draft:{field:Aa[0],value:""}}),onStartEditClause:N=>{const k=s.clauses.find(C=>C.id===N);k&&o({mode:"edit",clauseId:N,draft:{field:k.field,value:k.value}})},onRemoveClause:N=>r(k=>({...k,clauses:k.clauses.filter(C=>C.id!==N)})),onChangeDraftField:N=>o(k=>k&&{...k,draft:{...k.draft,field:N}}),onChangeDraftValue:N=>o(k=>k&&{...k,draft:{...k.draft,value:N}}),onSubmitClause:()=>{if(!a)return;const N=a.draft.field,k=Yf(N,a.draft.value);k!==""&&(r(C=>a.mode==="edit"&&a.clauseId?{...C,clauses:C.clauses.map(M=>M.id===a.clauseId?{id:M.id,field:N,value:k}:M)}:(i.current+=1,{...C,clauses:[...C.clauses,{id:`clause-${i.current}`,field:N,value:k}]})),o(void 0))},onCancelClause:()=>o(void 0),onAddWiden:()=>r(N=>({...N,widen:{anchorCount:Math.max(t,1)}})),onRemoveWiden:()=>r(N=>({...N,widen:void 0})),onChangeMatchOperator:N=>r(k=>({...k,matchOperator:N})),onChangeMove:N=>r(k=>({...k,moveMailboxId:N||void 0})),onChangeLabel:N=>r(k=>({...k,labelId:N||void 0})),onChangeScope:N=>r(k=>({...k,scope:N})),onChangeName:N=>r(k=>({...k,name:N})),onChangeUntil:N=>r(k=>({...k,until:N}))}}};function Bu({progress:e,isDone:t,runningLabel:s,onClose:r}){const a=e.state==="Failed";return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[t?a?n.jsx("span",{className:"text-sm font-semibold text-danger",children:"Organize failed"}):n.jsx(Xn,{className:"size-8 text-positive"}):n.jsx(et,{className:"size-8 animate-spin text-accent-2"}),!t&&n.jsx("p",{className:"text-sm font-medium text-fg",children:s}),t&&!a&&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&&a&&n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:e.errorMessage||"Something went wrong. Please try again."}),t&&n.jsx(V,{variant:"primary",onClick:r,className:"mt-2",children:"Done"})]})}function ca(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(et,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Saving rule…"})]})}function Ku({onClose:e}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(Xn,{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(V,{variant:"primary",onClick:e,className:"mt-2",children:"Done"})]})}function Ny({onRetry:e,onClose:t}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(Xn,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Rule saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"New mail follows it automatically. Moving the mail already in your mailbox didn't run — try again?"}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(V,{variant:"primary",onClick:e,children:"Move existing mail"}),n.jsx(V,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function Uu({onRetry:e,onClose:t}){return 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 save the rule"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(V,{variant:"primary",onClick:e,children:"Try again"}),n.jsx(V,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function Ey({accountId:e,conversion:t,seedCount:s,onClose:r}){const[a]=c.useState(()=>Fu(t)),{rule:o,handlers:i}=zu({initialRule:a}),{data:l}=fe({...Ue({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),u=c.useMemo(()=>an(l?.items??[]).map(g=>({id:g.mailboxId,label:Yn(g.fullPath)})),[l?.items]),f=wl(e,Oa(o),s),d=jl(e),m=Sl(e),h=()=>{const g=kl(o);if(o.scope==="once"){d.start(g);return}m.createFilter(g,o.scope==="standing"?"standing":"temporary",(o.name??"").trim())};return d.isStarting||d.isRunning||d.isDone?n.jsx(Bu,{progress:d.progress,isDone:d.isDone,runningLabel:"Organizing your mail…",onClose:r}):m.isPending?n.jsx(ca,{}):m.isSuccess?n.jsx(Ku,{onClose:r}):m.isError?n.jsx(Uu,{onRetry:m.reset,onClose:r}):n.jsx(pl,{rule:o,folders:u,preview:f,notice:n.jsx(eg,{notice:{scopedOutFolder:t.scopedOut?.label,droppedFacets:t.droppedFacets.map(g=>g.label),droppedSemantic:t.droppedSemantic}}),semanticAvailable:!1,clauseFields:Aa,...i,onCommit:h,onCancel:r})}function Iy({open:e,accountId:t,parsed:s,searchHadSemanticReach:r,onClose:a}){const o=c.useMemo(()=>$u(s,{searchHadSemanticReach:r}),[s,r]),i=c.useMemo(()=>Oa(Fu(o)),[o]),{seedCount:l,isPending:u,isError:f,retry:d}=Cy(e?t:void 0,i);return e?n.jsx(pa,{open:e,onClose:a,title:"Filter rule",children:f?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 build the filter"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(V,{variant:"primary",onClick:d,children:"Try again"}),n.jsx(V,{variant:"ghost",onClick:a,children:"Not now"})]})]}):u||l===void 0?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(et,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Turning your search into a filter…"})]}):n.jsx(Ey,{accountId:t,conversion:o,seedCount:l,onClose:a})}):null}function qu({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:g,resultFolderIndex:v,searchQuery:p,searchInput:x,onSearchChange:b,onSearchClear:y,searchViewKey:j}=Ce(),w=Rs(),E=Me(),N=ks(),k=dr(),[C,M]=c.useState(!1),[A,D]=c.useState(la),[P,I]=c.useState(!1),S=c.useRef(j);c.useEffect(()=>{S.current!==j&&(S.current=j,M(!1))},[j]);const O=x.trim().length>0,{mailboxesByName:L,accountsByName:T}=w,$=c.useMemo(()=>Ms(x,{mailboxesByName:L,accountsByName:T}),[x,L,T]),R=$.tokens.map(B=>({label:Ru(B),onRemove:()=>b(oy(x,B))})),F=o??[],Q=l??[],Z=O?[{id:"top",label:d,results:F},{id:"related",label:m,results:Q}]:[],z=!(F.length+Q.length>0)&&(i===!0||u===!0),{scope:Y}=Kc(g),ue=bt({select:B=>B.matches}),oe=zc(ue),se=tb(ue,Y,oe?v.get(oe)?.role:void 0),H=se.kind==="global"?ky([...F,...Q]):void 0,G=H?{kind:"global",onScopeToSpam:()=>E({to:"/mail/$mailboxId",params:{mailboxId:H.mailboxId},search:{q:p||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:se,je=$.tokens.find(B=>B.type==="account")?.accountId??g[0]?.accountId,Ne=Q.length>0,J=O&&je?{onClick:()=>I(!0),disabledReason:wy($u($,{searchHadSemanticReach:Ne}))?void 0:"Add a sender or words to filter on"}:void 0,X=P&&je?n.jsx(Iy,{open:P,accountId:je,parsed:$,searchHadSemanticReach:Ne,onClose:()=>I(!1)}):null;if(k==="phone"&&C){const B=ze=>{D(Fi(x)),M(!1),f?.(ze)};return n.jsxs(n.Fragment,{children:[n.jsx(Rp,{value:x,onChange:b,onClear:y,onCancel:()=>{M(!1),y()},filter:a,recentSearches:A,onPickRecent:b,makeFilter:J,sections:Z,loading:z,onSelectResult:B,tokens:R,scope:G}),X]})}const re=Sy({tier:k,hasLiveInput:O,hasCommittedQuery:p.trim().length>0,bodyRendersCommittedResults:h}),te=B=>{D(Fi(x)),f?.(B)},Pe=n.jsx(mc,{value:x,sections:Z,loading:z,onSelectResult:te,tokens:R,scope:G,makeFilter:J}),Qe=re?a?n.jsx(ga,{...a,children:Pe}):n.jsx("div",{className:"h-full overflow-y-auto",children:Pe}):s;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsx(yp,{title:e,unreadCount:t,isDesktop:!1,showSearch:Lu(k),onMenuClick:()=>N?.openNav(),searchValue:x,onSearchChange:b,onSearchClear:y,searchOpen:C,onSearchOpenChange:M}),n.jsx("div",{className:"min-h-0 flex-1",children:Qe}),r,X]})}const Ty=(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)},Ry=(e,t,s,r)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:r,My=(e,t)=>{const s=new Set(t),r=new Set;for(const a of e)s.has(a)&&r.add(a);return r},Hu=(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]},Wu=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(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},[]),l=c.useCallback(p=>{a(p),s(x=>{if(x.has(p))return x;const b=new Set(x);return b.add(p),b})},[]),u=c.useCallback(p=>{s(x=>{if(!x.has(p))return x;const b=new Set(x);return b.delete(p),b})},[]),f=c.useCallback(p=>{s(new Set(p))},[]),d=c.useCallback(()=>{a(void 0),s(new Set)},[]),m=c.useCallback(p=>{s(x=>p.every(y=>x.has(y))?new Set:new Set(p))},[]),h=c.useCallback(p=>{a(p)},[]),g=c.useCallback(p=>{s(x=>{if(x.size===0)return x;const b=My(x,p);return b.size===x.size?x:b})},[]),v=c.useCallback((p,x,b)=>{const y=Ry(p,r,b,x);s(j=>{const w=Ty(p,y,x);if(w.length===0)return j;const E=new Set(j);for(const N of w)E.add(N);return E}),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:v,setAnchor:h,anchorId:r,intersectWith:g}},Vu=(e,t)=>!t&&e>0,Ay=(e,t)=>e==="BACK"&&t,Oy=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:r})=>{const[a,o]=c.useState(s),i=Wu(),{selectedCount:l,toggle:u,clearSelection:f,selectRange:d,setAnchor:m,selectAll:h}=i,g=Vu(l,t),v=c.useRef(null),p=c.useRef(!1),x=c.useCallback(()=>{r?.(),f()},[f,r]),b=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),y=c.useCallback(I=>{if(I<0||I>=e.length)return;const S=e[I];if(g){u(S);return}v.current=S,p.current=!1,o(S)},[e,g,u]),j=c.useCallback(()=>{e.length!==0&&y(b<0?0:Math.min(b+1,e.length-1))},[e.length,b,y]),w=c.useCallback(()=>{e.length!==0&&y(b<=0?0:b-1)},[e.length,b,y]),E=c.useCallback(()=>y(0),[y]),N=c.useCallback(()=>y(e.length-1),[y,e.length]),k=c.useCallback(()=>{a&&u(a)},[a,u]),C=c.useCallback((I,S)=>S.shiftKey?(d(e,I,a),!0):S.metaKey||S.ctrlKey?(u(I),!0):(x(),m(I),!1),[e,a,d,u,x,m]),M=c.useCallback(I=>{const S=Hu(e,a,I);S!==void 0&&(d(e,S),v.current=S,p.current=!1,o(S))},[e,a,d]),A=c.useCallback(()=>M(-1),[M]),D=c.useCallback(()=>M(1),[M]),P=c.useCallback(()=>{e.length>0&&h(e)},[e,h]);return{focusedMessageId:a,setFocusedMessageId:o,focusIndex:b,pendingDomFocusRef:v,cursorMovedByPointerRef:p,selection:i,isMultiSelectMode:g,exitSelection:x,moveFocusToIndex:y,focusNext:j,focusPrevious:w,focusFirst:E,focusLast:N,toggleFocusedSelection:k,extendRangeUp:A,extendRangeDown:D,selectAllLoaded:P,handleRowSelect:C}};function Qu(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Dy=e=>{const{mailboxId:t,messages:s}=e,r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i}=ve({...kf(),onError:(u,f)=>{a({title:f.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:rt(u),error:u})},onSettled:(u,f,d)=>{jt(r,wt(ar(d.body.messageIds??[],s??[],t)))}});return{applyLabel:c.useCallback((u,f,d)=>{u.length!==0&&o({body:{messageIds:u,labelId:f,action:d}})},[o]),isPending:i}};function Py({accountId:e,mailboxId:t,messageIds:s}){const{labels:r}=Rl(e),{applyLabel:a}=Dy({mailboxId:t}),o=c.useMemo(()=>r.map(i=>({key:i.labelId,label:i.name,icon:n.jsx("span",{className:`size-2.5 rounded-full ${Cf(i.color)?ko[i.color]:ko.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[r,s,a]);return o.length===0?null:n.jsx(oc,{triggerLabel:"Apply label to selected messages",triggerIcon:n.jsx(Nf,{className:"size-4"}),items:o})}const Yu=({selectedCount:e,onDelete:t,onClearSelection:s,onMarkAsRead:r,onMove:a,onOrganize:o,isDeleting:i=!1,isMoving:l=!1,accountId:u,currentMailboxId:f,selectedMessageIds:d,moveDisabledHint:m,selectAll:h,statusLabel:g,isCounting:v=!1,progress:p,notice:x})=>{if(e===0)return null;const b=p!==void 0,y=i||l||b,j=!b&&!v,w=!!a&&!!u&&!!f,E=!!u&&!!f&&!!d?.length,N=!!o&&!!u&&!!f&&!m&&!g,k=h?.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"})}),h&&n.jsx("label",{className:"flex size-11 shrink-0 cursor-pointer items-center justify-center",children:n.jsx(ln,{"aria-label":"Select all",checked:h.checked,indeterminate:h.indeterminate,onChange:h.onChange})}),n.jsx("span",{className:"text-sm font-medium",children:g??k}),m&&!x&&n.jsx("span",{className:"text-xs text-fg-muted",role:"status","aria-live":"polite",children:m})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[N&&o&&n.jsxs("button",{type:"button",onClick:y?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(ft,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:"Organize"})]}),j&&r&&n.jsx("button",{type:"button",onClick:y?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":y,children:n.jsx(Ns,{className:"size-4"})}),j&&w&&a&&u&&f&&n.jsx(pn,{accountId:u,currentMailboxId:f,onMove:y?()=>{}:a,disabledHint:m,variant:"icon-only",label:"Move selected messages"}),j&&E&&u&&f&&d&&n.jsx(Py,{accountId:u,mailboxId:f,messageIds:d}),j&&n.jsxs("button",{type:"button",onClick:y?void 0:t,className:be("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(et,{className:"size-4 animate-spin"}):n.jsx(at,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:i?"Deleting...":"Delete"})]})]})]}),p&&n.jsx("div",{className:"px-3 pb-2",children:n.jsx(za,{value:p.value,max:p.max,tone:p.tone})}),x&&n.jsx(es,{tone:x.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:[x.text&&n.jsx("span",{children:x.text}),x.action&&n.jsx("button",{type:"button",onClick:x.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:x.action.label})]})})]})},ao=c.createContext(null),Ly=e=>{const t=c.useContext(ao);return t?t.rowInteraction(e):null},$y=()=>{const e=c.useContext(ao);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},Fy="[data-message-id]",_y=e=>Array.from(e.querySelectorAll(Fy)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),zy=(e,t)=>e.length===t.length&&e.every((s,r)=>s===t[r]),By=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const r=e.current;if(!r)return;const a=()=>{const i=_y(r);s(l=>zy(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(r,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function Gu({selectedMessageId:e,onOpen:t,onDeleteMessages:s,isDeleting:r=!1,commandsRef:a,onTriageContextChange:o,children:i}){const l=$t(),u=c.useRef(null),f=By(u),d=Oy({orderedIds:f,isDesktop:l,initialFocusedId:e}),{focusedMessageId:m,setFocusedMessageId:h,pendingDomFocusRef:g,cursorMovedByPointerRef:v,selection:p,isMultiSelectMode:x,exitSelection:b,handleRowSelect:y}=d,{selectedIds:j,selectedCount:w,isSelected:E,toggle:N,select:k}=p,{intersectWith:C}=p;c.useEffect(()=>{C(f)},[C,f]),c.useEffect(()=>{const Y=g.current;Y!==null&&(g.current=null,u.current?.querySelector(`[data-message-id="${Y}"]`)?.focus())});const M=c.useCallback(Y=>{v.current=!0,h(Y)},[v,h]),A=c.useCallback(Y=>{l||k(Y)},[l,k]),D=c.useCallback(()=>{m&&t(m)},[m,t]),[P,I]=c.useState(null),S=c.useCallback(Y=>!s||Y.length===0?!1:(I(Y),!0),[s]),O=c.useCallback(()=>{S(Array.from(j))},[S,j]),L=c.useCallback(()=>P!==null?!0:w>0?S(Array.from(j)):m?S([m]):!1,[P,w,j,m,S]),T=c.useCallback(()=>{P!==null&&(s?.(P),I(null),b())},[P,s,b]),$=c.useCallback(()=>I(null),[]),R=c.useCallback(()=>w===0?!1:(b(),!0),[w,b]),F=f.length>0;c.useEffect(()=>{if(a){if(!F){a.current=null;return}return a.current={focusNext:d.focusNext,focusPrevious:d.focusPrevious,focusFirst:d.focusFirst,focusLast:d.focusLast,openFocused:D,toggleSelect:d.toggleFocusedSelection,extendSelectDown:d.extendRangeDown,extendSelectUp:d.extendRangeUp,selectAll:d.selectAllLoaded,clearSelection:R,requestDelete:L,toggleDensity:()=>{}},()=>{a.current=null}}},[a,F,d.focusNext,d.focusPrevious,d.focusFirst,d.focusLast,d.toggleFocusedSelection,d.extendRangeDown,d.extendRangeUp,d.selectAllLoaded,D,R,L]);const Q=c.useMemo(()=>Array.from(j),[j]),Z=P!==null;c.useEffect(()=>{o?.({focusedMessageId:m,selectedIds:Q,orderedIds:f,hasList:F,blocksKeyboard:Z})},[o,m,Q,f,F,Z]);const K=Qu(f,m),z=c.useMemo(()=>({selectedIds:j,selectedCount:w,exitSelection:b,requestDeleteSelection:O,rowInteraction:Y=>({focused:Y===m,isTabStop:Y===K,isDesktop:l,onFocusRow:M,selection:{isChecked:E(Y),onToggleCheck:N,onRowSelect:y,isMultiSelectMode:x,onLongPress:A}})}),[j,w,b,O,m,K,l,M,E,N,y,x,A]);return n.jsxs(ao.Provider,{value:z,children:[n.jsx("div",{ref:u,className:"contents",children:i}),n.jsx(Pa,{isOpen:Z,title:El(P?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:r,onConfirm:T,onCancel:$})]})}function Xu({onMarkAsRead:e,isDeleting:t}){const{selectedIds:s,selectedCount:r,exitSelection:a,requestDeleteSelection:o}=$y(),i=c.useCallback(()=>{e?.(Array.from(s)),a()},[e,s,a]);return n.jsx(Yu,{selectedCount:r,onDelete:o,onClearSelection:a,onMarkAsRead:e?i:void 0,isDeleting:t})}const Ky=({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(),g=e.id,v=Ly(g),p=s??v?.focused??!1,x=r??v?.isTabStop??!1,b=l??v?.selection,y=m??v?.onFocusRow,j=o??v?.isDesktop??!0,w=b?.isChecked??!1,E=b?.isMultiSelectMode??!1,N=b?.onToggleCheck,k=b?.onRowSelect,C=b?.onLongPress,M=c.useCallback(R=>{R.preventDefault(),R.stopPropagation(),N?.(g)},[N,g]),A=c.useCallback(R=>{if(!j){if(E){R.preventDefault(),R.stopPropagation(),N?.(g);return}d?.();return}const F={shiftKey:R.shiftKey,metaKey:R.metaKey,ctrlKey:R.ctrlKey};if(k?.(g,F)){R.preventDefault(),R.stopPropagation(),F.shiftKey&&window.getSelection()?.removeAllRanges();return}d?.()},[j,E,N,k,d,g]),D=c.useCallback(R=>{j&&R.shiftKey&&R.preventDefault()},[j]),P=c.useCallback(()=>{C?.(g)},[C,g]),{longPressProps:I}=nc({onLongPress:P,accessibilityDescription:w?"Deselect message":"Select message"}),S=c.useCallback(()=>{h.prefetchQuery(Ea({path:{messageId:g}}))},[h,g]),O=c.useCallback(()=>{S(),y?.(g)},[S,y,g]),L=Cs({"data-list-row":"","data-message-row":!0,"data-message-id":g,...u?{role:"option","aria-selected":w}:{},tabIndex:x?0:-1,onClick:A,onMouseDown:D,onMouseEnter:S,onFocus:O},j||!b?{}:I),T=be(a==="compact"?ec({active:t,focused:p}):be("group",on({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",w&&"bg-accent-soft",!j&&"min-h-11 select-none [-webkit-touch-callout:none]"),$=a==="compact"?n.jsx(tc,{thread:e}):n.jsx(sc,{thread:e,badge:i,selection:b?{checked:w,alwaysVisible:E,onToggle:M}:void 0});return f===void 0?n.jsx("button",{type:"button",...L,className:T,children:$}):n.jsx(xt,{to:"/mail/$mailboxId",params:{mailboxId:f},search:R=>({...R,selectedMessageId:g}),...L,className:T,children:$})},oo=c.memo(Ky),Uy=200,qy={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()},_i=()=>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))}),Hy=({accountEmail:e})=>{const t=Me();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(Zt,{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 Wy({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:r,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i,onMarkMessagesRead:l}){const{searchQuery:u,resultFolderIndex:f}=Ce(),d=Rs(),m=$t(),h=c.useMemo(()=>dy(e.filter(H=>!H.muted?.value)),[e]),[g,v]=c.useState("all"),[p,x]=c.useState("all"),[b,y]=c.useState(new Set),[j,w]=c.useState(!1),E=c.useCallback(H=>{y(G=>{const ae=new Set(G);return ae.has(H)?ae.delete(H):ae.add(H),ae})},[]),{data:N,isLoading:k,isError:C,refetch:M}=fe({...Vr(),staleTime:6e4}),A=Bt({queries:h.map(H=>({...Ue({path:{accountId:H.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),D=c.useMemo(()=>{const H=new Map;for(let G=0;G<h.length;G++){const ae=h[G].accountId,Ne=(A[G]?.data?.items??[]).reduce((J,X)=>J+(X.unseenCount??0),0);H.set(ae,Ne)}return H},[h,A]),P=c.useMemo(()=>h.filter((H,G)=>{const ae=A[G];return ae?.isError?!Qr(ae.error):!1}),[h,A]),{freeText:I,tokens:S}=Ms(u.trim().toLowerCase(),d),{data:O,isFetching:L}=fe({...Vr({query:{query:I,limit:Uy}}),enabled:I.length>0,staleTime:3e4}),T=c.useMemo(()=>{const H=Li(N?.items??[]).map(ia);return(I?fy(H.filter(ae=>Au(ae,I)),Li(O?.items??[]).map(ia)):H).filter(ae=>(g==="all"||ae.accountId===g)&&Ou(ae,S))},[N,O,g,I,S]),$=c.useMemo(()=>my(T),[T]),R=c.useMemo(()=>h.length<=1?[]:[{id:"all",label:"All",active:g==="all"},...h.map(H=>({id:H.accountId,label:H.email.split("@")[0]??H.email,count:D.get(H.accountId),active:g===H.accountId}))],[h,D,g]),F=c.useMemo(()=>e.filter(H=>H.muted?.value).length,[e]),Q=c.useMemo(()=>Array.from(D.values()).reduce((H,G)=>H+G,0),[D]),Z=c.useMemo(()=>{const H=Array.from(b).map(G=>qy[G]).filter(G=>G!=null);return T.filter(G=>(p==="all"||G.category===p)&&H.every(ae=>ae(G))).map(G=>Du(G,f))},[T,p,b,f]),{hits:K,isLoading:z}=Mu(),Y=c.useMemo(()=>{const H=new Map;for(const ae of N?.items??[])H.set(ae.messageId,ae.threadId);const G=Z.map(ae=>H.get(ae.id)).filter(ae=>ae!=null);return Pu(K,G,f)},[K,Z,N,f]),ue=c.useMemo(()=>{const H=ug(R.map(G=>({id:G.id,label:G.label,count:G.count,active:G.active})));return{categories:H.categories,filters:H.filters,sources:H.sources,sourcesNote:F>0?`+${F} muted`:void 0,selectedCategory:p,activeFilters:b,expanded:j,onExpandedChange:w,onSelectCategory:G=>x(G),onSelectSource:v,onToggleFilter:E,onClear:()=>{x("all"),v("all"),y(new Set)}}},[R,F,p,b,j,E]),oe=$.length===0&&g==="all"&&I.length===0,se=k?n.jsxs("div",{className:"h-full overflow-y-auto",children:[n.jsx(_i,{}),n.jsx(_i,{})]}):C?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(Zt,{className:"size-8 text-danger"}),n.jsx("p",{children:"Couldn't load your messages"}),n.jsxs("button",{type:"button",onClick:()=>M(),className:"flex items-center gap-1 text-accent underline text-xs",children:[n.jsx(Ql,{className:"size-3.5"}),"Try again"]})]}):oe?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[n.jsx(ft,{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(Gu,{selectedMessageId:t,onOpen:H=>s?.(H),onDeleteMessages:i,commandsRef:a,onTriageContextChange:o,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[i?n.jsx(Xu,{onMarkAsRead:l}):null,n.jsx("div",{className:"min-h-0 flex-1",children:n.jsx(el,{sections:$,Row:oo,manageFocus:!1,briefCategory:p,onSelectBriefCategory:x,sources:R,sourcesNote:F>0?`+${F} muted`:void 0,onSelectSource:v,selectedThreadId:t,onSelectThread:s})})]})});return n.jsx(qu,{title:"Daily brief",unreadCount:Q,footer:m?n.jsx(Jl,{}):void 0,searchFilter:ue,searchResults:Z,searchLoading:k||L,relatedResults:Y,relatedLoading:z,onSelectSearchResult:r,children:n.jsxs("div",{className:"flex h-full flex-col",children:[P.map(H=>n.jsx(Hy,{accountEmail:H.email,accountId:H.accountId},H.accountId)),n.jsx("div",{className:"min-h-0 flex-1",children:se})]})})}const Vy=10,Ju=e=>({q:e?.toLowerCase()??"",limit:Vy}),Qy=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(r=>r.normalizedEmail===s)};function Yy(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":$n(t,{month:"short",year:"numeric"})}function Zu(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 Jy(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?Yy(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Zu(e.fromEmail)}}function Zy(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 e0(e,t){const s=t>0?t:void 0;if(Zu(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 ed(e,t){const s=e?.fromEmail??null,r=e?.subject??"",{data:a,error:o}=fe({...ll({query:Ju(s??void 0)}),enabled:!!s,staleTime:3e4}),i=Qy(a?.items,s??void 0),l=[r,s].filter(Boolean).join(" "),{data:u,isLoading:f,error:d}=fe({...ml({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(b=>b.messageId!==e.messageId).map(b=>({id:b.messageId,mailboxId:t!=null&&b.mailboxIds.includes(t)?t:b.mailboxIds[0]??"",fromName:b.fromName??"",subject:b.subject??"(No subject)",timeLabel:b.sentDate!=null?_t(b.sentDate*1e3):"",matched:b.matchedChunkType})),g=Jy(e,i),v=e0(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},x=Zy(i);return{sender:g,authenticity:v,category:p,flags:x,similar:h}},[e,i,u,t]),isSimilarLoading:f,similarError:d,similarErrorIsFatal:Qr(d),addressErrorIsFatal:Qr(o),addressId:i?.addressId,address:i}}function t0(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 td({addressId:e,senderEmail:t}){const s=ye(),{pushError:r}=Ve(),a=Ef({query:Ju(t)}),{mutate:o,isPending:i}=ve({...fl(),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:t0(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:rt(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){gl(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 s0=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",sd=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function n0(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function r0(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function a0(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function nd(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const o0=["personal","newsletter","marketing","automated","transactional","social"],i0=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:r}=e;return t?s&&t===s?r?"notSpam":null:s?"markSpam":null:null},l0=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:r}=e;return t&&!s?"error":r?"loading":"ready"};function c0(){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(ft,{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 u0({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:o0.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 d0({thread:e,onClose:t,mailboxId:s,accountId:r,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:f}=ed(e,s),[d,m]=c.useState(!1),[h,g]=c.useState(!1),v=e.fromEmail??void 0,{updateFlags:p,isPending:x}=td({addressId:i,senderEmail:v}),{junkMailboxId:b}=cr(r),{inboxMailboxId:y}=Za(r),{moveMessages:j}=Xt({mailboxId:s??"",threadId:e.threadId,accountId:r}),w=nn(),E=i0({mailboxId:s,junkMailboxId:b,inboxMailboxId:y}),N=c.useCallback(()=>{y&&j([e.messageId],y)},[y,j,e.messageId]),k=c.useCallback(()=>{b&&(nd(w,{count:1,senderTrust:e.senderTrust,wasRescuable:sd(e)}),j([e.messageId],b))},[b,j,e,w]),C=c.useCallback(()=>{},[]),M=c.useCallback(()=>{const R=o?.flags?.vip!==!0;p({vip:{value:R}})},[o?.flags?.vip,p]),A=c.useCallback(()=>{const R=o?.flags?.muted!==!0;p({muted:{value:R}})},[o?.flags?.muted,p]),D=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]),I=c.useCallback(()=>{const R=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:R}})},[o?.flags?.unsubscribed,p]),S=c.useCallback(R=>{g(!1),p({category:{value:R}})},[p]),O=i!==void 0,L={onToggleVip:O?M:void 0,onToggleMute:O?A:void 0,onToggleBlock:O?D:void 0,onToggleUnsubscribe:O?I:void 0,onReclassify:O?()=>g(!0):void 0,onNotSpam:E==="notSpam"?N:void 0,onMarkSpam:E==="markSpam"?k:void 0},T=({mailboxId:R,messageId:F,className:Q,ariaLabel:Z,children:K})=>n.jsx(xt,{to:"/mail/$mailboxId",params:{mailboxId:R},search:z=>({...z,selectedMessageId:F}),className:Q,"aria-label":Z,children:K});if(!o)return n.jsx(c0,{});const $=l0({similarError:u,similarErrorIsFatal:f,isSimilarLoading:l});return n.jsxs(n.Fragment,{children:[n.jsx(Xl,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:C,actions:L,similarState:$,similarLinkComponent:T,className:"border-l-0 h-full w-full"}),n.jsx(Pa,{isOpen:d,title:"Block this sender?",description:`Messages from ${v??"this sender"} will never load images and will be flagged. You can undo this in Settings → Senders.`,confirmLabel:"Block sender",destructive:!0,isBusy:x,onConfirm:P,onCancel:()=>m(!1)}),n.jsx(u0,{isOpen:h,current:o.category.value,onSelect:S,onCancel:()=>g(!1)})]})}const As=({onClose:e,thread:t,mailboxId:s,accountId:r,hideCloseButton:a})=>t?n.jsx(d0,{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(ft,{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(ft,{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."})]})]}),Ur="Open a message first",io=({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,g]=c.useState(null),v=u??e,p=x=>()=>g(x);return n.jsx(Eh,{hasThread:e,isStarred:d,onUnavailable:x=>g(Ur),unavailableHint:h,replyTitle:`Reply ${hs("reply")}`,replyAllTitle:`Reply all ${hs("replyAll")}`,forwardTitle:`Forward ${hs("forward")}`,deleteTitle:`Move to Trash ${hs("delete")}`,flagTitle:`Star ${hs("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:v?l:p(Ur),onToggleStar:f,onMove:p(Ur),moveSlot:m?n.jsx(pn,{accountId:m.accountId,currentMailboxId:m.currentMailboxId,onMove:m.onMove,label:"Move to mailbox"}):void 0,children:n.jsx(Nh,{open:t,enabled:s,onToggle:r})})},rd=()=>{const e=ye();return c.useCallback(t=>{const s=ss({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])},Zs=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=t??e?.mailboxId,o=s??e?.accountConfigId,i=rd(),{deleteMessages:l}=Jt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{moveMessages:u}=Xt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{toggleStar:f}=Xa({threadId:e?.threadId??"",mailboxId:a??""}),d=c.useCallback(()=>{e&&l(i(e))},[e,i,l]),m=c.useCallback(x=>{e&&u(i(e),x)},[e,i,u]),h=c.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[g,v]=c.useState(null),p=c.useCallback(()=>v(null),[]);return{mailboxId:a,accountId:o,isStarred:e?.hasStars,deleteThread:d,moveThread:m,toggleStar:h,composeRequest:g,requestCompose:v,clearComposeRequest:p}},Ks={action:null,nextPrefix:null,preventDefault:!1},f0={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},m0={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 h0(e,t){const s=e.key.toLowerCase(),r=e.metaKey||e.ctrlKey;if(e.inEditable)return{...Ks,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...Ks,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{...Ks,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=f0[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=m0[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?Ks:{action:a.action,nextPrefix:null,preventDefault:!0}}return Ks}function p0(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const g0="data-message-row",x0='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function b0(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(x0);return t?!t.hasAttribute(g0):!1}function v0({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=h0({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:p0(u.target),onControl:b0(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 zi=(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]},lo=()=>{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}},co=({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 v0({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:zi(t,s,"next")??void 0,previousMessageId:zi(t,s,"previous")??void 0}};function y0(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function ad(e,t){if(e)return y0(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const od=c.createContext(null);function fr(){const e=c.useContext(od);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function w0({selectedMessageId:e,children:t}){const s=Me(),{searchInput:r}=Ce(),{selectedThreadId:a,selectedMailboxId:o}=ws({strict:!1}),{data:i}=fe({...Vr(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(A=>A.messageId===e)},[i,e]),u=c.useMemo(()=>ad(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),f=c.useCallback(A=>{s({to:"/mail",search:D=>({...D,selectedMessageId:A,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),d=c.useCallback(A=>{s({to:"/mail",search:D=>({...D,q:r||void 0,selectedMessageId:A.id,selectedThreadId:A.threadId,selectedMailboxId:A.mailboxId})})},[s,r]),m=c.useCallback(A=>{e&&A.includes(e)&&s({to:"/mail",search:D=>({...D,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=Zs({thread:l,onAfterOptimisticRemove:m}),g=c.useCallback(()=>{s({to:"/mail",search:A=>({...A,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),v=lo(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:x}=Jt({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:m}),{toggleReadFor:b}=or({mailboxId:l?.mailboxId??"",messages:p}),y=c.useCallback(A=>b(A,!0),[b]),j=v.focusedMessageId,E=c.useMemo(()=>i?.items.find(A=>A.messageId===j),[i,j])??l,N=Zs({thread:E}),{nextMessageId:k,previousMessageId:C}=co({context:v,orderedIds:v.orderedIds,selectedMessageId:e,onClose:g,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{v.listCommandsRef.current?.requestDelete()||N.deleteThread()},toggleStar:N.toggleStar,toggleRead:()=>{const A=v.selectedIds.length>0?v.selectedIds:E?[E.messageId]:[];A.length!==0&&b(A,!(E?.isRead??!1))},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),M={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:f,onSelectSearchResult:d,onCloseThread:g,actions:h,triage:v,onDeleteMessages:x,onMarkMessagesRead:y,nextMessageId:k,previousMessageId:C};return n.jsx(od.Provider,{value:M,children:t})}function id(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:r,onDeleteMessages:a,onMarkMessagesRead:o}=fr(),{accounts:i}=Ce();return n.jsx(Wy,{accounts:i,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:r.listCommandsRef,onTriageContextChange:r.onTriageContextChange,onDeleteMessages:a,onMarkMessagesRead:o})}function j0(){const{conversation:e,actions:t}=fr(),{intelligenceOpen:s,onToggleIntelligence:r}=Ce(),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(io,{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(Ts,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Is,{})})]})}function S0(){const{selectedThread:e}=fr(),{onToggleIntelligence:t}=Ce();return n.jsx(As,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function k0(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:r,nextMessageId:a,previousMessageId:o}=fr(),{intelligenceOpen:i,onToggleIntelligence:l}=Ce();return t?n.jsxs(n.Fragment,{children:[n.jsx(Ts,{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(Qa,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:n.jsx(As,{onClose:l,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(id,{})})}const Us=Object.assign(w0,{List:id,Reading:j0,Intelligence:S0,Phone:k0}),C0=()=>dl({query:{starred:!0,order:"desc"}});function ld(){const{data:e,isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=Rc({queryKey:C0(),queryFn:async({pageParam:f})=>{const{data:d}=await If({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 N0=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function cd({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:g,relatedLoading:v,onSelectSearchResult:p,searchResultsLabel:x,relatedResultsLabel:b,searchResultsInBody:y}){const[j,w]=c.useState(!1),E={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:r,activeFilters:a,expanded:j,onExpandedChange:w,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return n.jsx(qu,{title:e,unreadCount:t,footer:d,searchFilter:E,searchResults:m,searchLoading:h,relatedResults:g,relatedLoading:v,onSelectSearchResult:p,searchResultsLabel:x,relatedResultsLabel:b,searchResultsInBody:y,children:n.jsx(ga,{...E,children:f})})}const E0={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function I0({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:r,onDeleteMessages:a,onMarkMessagesRead:o}){const{searchQuery:i,resultFolderIndex:l}=Ce(),u=Rs(),f=$t(),[d,m]=c.useState("all"),[h,g]=c.useState(new Set),v=c.useCallback(T=>{g($=>{const R=new Set($);return R.has(T)?R.delete(T):R.add(T),R})},[]),p=c.useCallback(()=>{m("all"),g(new Set)},[]),{threads:x,isLoading:b,isError:y,error:j,refetch:w,fetchNextPage:E,hasNextPage:N,isFetchingNextPage:k}=ld(),{freeText:C,tokens:M}=Ms(i.trim().toLowerCase(),u),A=c.useMemo(()=>{const T=Array.from(h).map($=>E0[$]).filter($=>$!=null);return N0(x).map(ia).filter($=>(d==="all"||$.category===d)&&T.every(R=>R($))&&(!C||Au($,C))&&Ou($,M))},[x,d,h,C,M]),D=c.useMemo(()=>dg(),[]),P=c.useMemo(()=>A.map(T=>Du(T,l)),[A,l]),I=c.useMemo(()=>A.filter(T=>!T.isRead).length,[A]),S=b?"loading":y?"error":A.length===0?"empty":"ready",O=c.useCallback(()=>{const T=ka(Sa());window.open(T,"_blank","noopener,noreferrer")},[]),L=n.jsx(Gu,{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(Xu,{onMarkAsRead:o}):null,n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.jsx("div",{className:"divide-y divide-line",children:A.map(T=>n.jsx(oo,{thread:T,active:T.id===e,onClick:()=>t?.(T.id)},T.id))}),N?n.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>E(),disabled:k,children:k?"Loading…":"Load more"}):null]})]})});return n.jsx(cd,{title:"Starred",unreadCount:I,preset:D,selectedCategory:d,activeFilters:h,onSelectCategory:m,onToggleFilter:v,onClearFilters:p,searchResults:P,searchLoading:b,onSelectSearchResult:T=>t?.(T.id),children:n.jsx(ac,{listTitle:"Starred",sections:[{id:"flagged",threads:A}],flatList:!0,hideHeader:!0,listState:S,searchQuery:C?i:void 0,errorMessage:y?Cl(j):void 0,onRetry:()=>w(),onReportError:O,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:f,listBody:S==="ready"?L:void 0})})}const ud=c.createContext(null);function mr(){const e=c.useContext(ud);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function T0({selectedMessageId:e,children:t}){const s=Me(),{threads:r}=ld(),a=c.useMemo(()=>{if(e)return r.find(w=>w.messageId===e)},[r,e]),o=c.useCallback(w=>{s({to:"/mail/flagged",search:E=>({...E,selectedMessageId:w})})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:w=>({...w,selectedMessageId:void 0})})},[s]),l=c.useCallback(w=>{e&&w.includes(e)&&i()},[e,i]),u=Zs({thread:a,onAfterOptimisticRemove:l}),f=lo(),{deleteMessages:d}=Jt({mailboxId:a?.mailboxId??"",messages:r,onAfterOptimisticRemove:l}),{toggleReadFor:m}=or({mailboxId:a?.mailboxId??"",messages:r}),h=c.useCallback(w=>m(w,!0),[m]),g=f.focusedMessageId,p=c.useMemo(()=>r.find(w=>w.messageId===g),[r,g])??a,x=Zs({thread:p}),{nextMessageId:b,previousMessageId:y}=co({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()||x.deleteThread()},toggleStar:x.toggleStar,toggleRead:()=>{const w=f.selectedIds.length>0?f.selectedIds:p?[p.messageId]:[];w.length!==0&&m(w,!(p?.isRead??!1))},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),j={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:f,onDeleteMessages:d,onMarkMessagesRead:h,nextMessageId:b,previousMessageId:y};return n.jsx(ud.Provider,{value:j,children:t})}function dd(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:r,onMarkMessagesRead:a}=mr();return n.jsx(I0,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:r,onMarkMessagesRead:a})}function R0(){const{selectedThread:e,actions:t}=mr(),{intelligenceOpen:s,onToggleIntelligence:r}=Ce(),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(io,{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(Ts,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Is,{})})]})}function M0(){const{selectedThread:e}=mr(),{onToggleIntelligence:t}=Ce();return n.jsx(As,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function A0(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:r,previousMessageId:a}=mr(),{intelligenceOpen:o,onToggleIntelligence:i}=Ce();return e?n.jsxs(n.Fragment,{children:[n.jsx(Ts,{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(Qa,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:n.jsx(As,{onClose:i,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(dd,{})})}const qs=Object.assign(T0,{List:dd,Reading:R0,Intelligence:M0,Phone:A0}),O0={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},D0=()=>{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},[])},P0=()=>{const{state:e,closeCompose:t}=Lt(),s=D0(),[r,a]=c.useState(!1),{isError:o,error:i,refetch:l}=fe({...vt(),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=O0[e.mode]??"New Message";return n.jsxs(Ze.Root,{open:e.isOpen,onOpenChange:u,children:[n.jsxs(Ze.Portal,{children:[n.jsx(Ze.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Ze.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[n.jsx(Ze.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),n.jsx(Ze.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(Ft,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):n.jsx("div",{className:"flex-1 overflow-hidden",children:n.jsx(Ya,{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"})]})]})})]})},L0={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},fd=()=>{const{state:e,closeCompose:t}=Lt(),s=$t(),{isError:r,error:a,refetch:o}=fe({...vt(),staleTime:1/0});if(!s)return n.jsx(P0,{});if(!e.isOpen)return null;const i=L0[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(Ft,{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(Ya,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function $0(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:_t(e.updatedAt),isRead:!0}}function F0(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:_t(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function _0({outboxMessages:e,accountId:t,imapThreads:s}){const r=e.filter(i=>i.status==="draft"&&i.accountId===t).map($0),a=s.map(F0),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 uo(){const e=ks();return!e||e.showNavPane?null:n.jsx(V,{variant:"ghost",size:"sm",icon:n.jsx(Ra,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const z0=({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})]}),B0=({row:e,isSelected:t,onOpen:s,onDelete:r,isDeleting:a})=>n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:q("group",on({active:t})),children:[n.jsx(sl,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),n.jsx(Gs,{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(at,{className:"size-3.5"})})})]}),K0=({row:e,isSelected:t,onOpen:s})=>{const r=!e.isRead;return n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:q("group",on({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(mt,{name:e.fromName,email:e.fromEmail,size:"sm"}),n.jsx(Gs,{thread:e})]})};function U0({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:r,title:a,unreadCount:o}){const{openCompose:i,state:l}=Lt(),u=Me(),f=ye(),{data:d}=fe(Wn()),m=c.useMemo(()=>_0({outboxMessages:d?.items??[],accountId:t,imapThreads:r}),[d?.items,t,r]),h=ve({...Vn(),onSuccess:()=>{f.invalidateQueries({queryKey:Ta()})}}),g=b=>{h.mutate({path:{outboxMessageId:b}})},v=b=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:b})},p=b=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:b}})},x=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(uo,{}),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:x?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[n.jsx(ha,{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(b=>n.jsxs("div",{children:[b.label&&n.jsx(z0,{label:b.label,count:b.threads.length}),n.jsx("div",{className:"divide-y divide-line",children:b.threads.map(y=>b.id==="remit-drafts"?n.jsx(B0,{row:y,isSelected:l.isOpen&&y.id===l.outboxMessageId,onOpen:v,onDelete:g,isDeleting:h.isPending},y.id):n.jsx(K0,{row:y,isSelected:y.id===s,onOpen:p},y.id))})]},b.id))})]})}function q0(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 ms(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 Bi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const H0=(e,t)=>Math.abs(e-t)<1.01,W0=(e,t,s)=>{let r;return function(...a){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,a),s)}};let Hs;const qr=()=>{if(Hs!==void 0)return Hs;if(typeof navigator>"u")return Hs=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Hs=!0;const e=navigator.maxTouchPoints;return Hs=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Ki=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},V0=e=>e,Q0=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},Y0=(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(Ki(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(Ki(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},Bn={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:W0(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,Bn),o&&r.addEventListener("scrollend",d,Bn),()=>{r.removeEventListener("scroll",f),o&&r.removeEventListener("scrollend",d)}},J0=(e,t)=>X0(e,t,s=>{const{horizontal:r,isRtl:a}=e.options;return r?s.scrollLeft*(a&&-1||1):s.scrollTop}),Z0=(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"]},ew=(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})},tw=ew;class sw{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:V0,rangeExtractor:Q0,onChange:()=>{},measureElement:Z0,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 g=s[h];g!==void 0&&(o[h]=g)}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,g=o.count,v=this.getMeasurements(),p=h>0?((r=v[0])==null?void 0:r.key)??i.getItemKey(0):null,x=h>0?((a=v[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(g!==h||h>0&&g>0&&(o.getItemKey(0)!==p||o.getItemKey(g-1)!==x)){f=!0;const j=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??v[0]:null;j&&(l=[j.key,this.getScrollOffset()-j.start]);const w=o.followOnAppend===!0?"auto":o.followOnAppend||null;w&&g>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(g-1)!==x)&&(u=w)}}this.options=o,f&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,m=0;if(l&&this.scrollOffset!==null){const[h,g]=l,v=this.getMeasurements(),{count:p,getItemKey:x}=this.options;let b=0;for(;b<p&&x(b)!==h;)b++;if(b<p){const y=v[b];if(y){const j=y.start+g;j!==this.scrollOffset&&(m=j-this.scrollOffset,this.scrollOffset=j,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=ms(()=>(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,!(!qr()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,Bn),o.addEventListener("touchend",l,Bn),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&&(qr()&&(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=ms(()=>[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=ms(()=>[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 b of this.laneAssignments.keys())b>=s&&this.laneAssignments.delete(b);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(b=>{this.itemSizeCache.set(b.key,b.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 b=s*2;let y=this._flatMeasurements;if(!y||y.length<b){const E=new Float64Array(b);y&&h>0&&E.set(y.subarray(0,h*2)),y=E,this._flatMeasurements=y}let j;if(h===0)j=r+a;else{const E=h-1;j=y[E*2]+y[E*2+1]+f}for(let E=h;E<s;E++){const N=o(E),k=m.get(N),C=typeof k=="number"?k:this.options.estimateSize(E);y[E*2]=j,y[E*2+1]=C,j+=C+f}const w=q0(s,y,o);return this.measurementsCache=w,w}const g=this.measurementsCache.slice(0,h),v=new Array(l).fill(void 0),p=new Float64Array(l);let x=0;for(let b=0;b<h;b++){const y=g[b];y&&(v[y.lane]===void 0&&x++,v[y.lane]=b,p[y.lane]=y.end)}for(let b=h;b<s;b++){const y=o(b),j=this.laneAssignments.get(b);let w,E;const N=u==="estimate"||m.has(y);if(j!==void 0&&this.options.lanes>1){w=j;const A=v[w],D=A!==void 0?g[A]:void 0;E=D?D.end+f:r+a}else if(x===l){let A=0,D=p[0],P=v[0];for(let I=1;I<l;I++){const S=p[I];(S<D||S===D&&v[I]<P)&&(A=I,D=S,P=v[I])}w=A,E=D+f,N&&this.laneAssignments.set(b,w)}else w=b%this.options.lanes,E=r+a,N&&this.laneAssignments.set(b,w);const k=m.get(y),C=typeof k=="number"?k:this.options.estimateSize(b),M=E+C;g[b]={index:b,start:E,size:C,end:M,key:y,lane:w},v[w]===void 0&&x++,v[w]=b,p[w]=M}return this.measurementsCache=g,g},{key:!1,debug:()=>this.options.debug}),this.calculateRange=ms(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,r,a,o)=>s.length===0||r===0?(this.range=null,null):(this.range=rw(s,r,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ms(()=>{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,g=h?this.getTotalSize():0,v=((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()-g):v&&this.applyScrollAdjustment(m),this.notify(!1)}},this.getVirtualItems=ms(()=>[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=md(0,r.length-1,o?l=>a[l*2]:l=>Bi(r[l]).start,s);return Bi(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&&(qr()&&(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&&H0(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 md=(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 nw(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 rw(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=nw(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=md(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 Hr=typeof document<"u"?c.useLayoutEffect:c.useEffect;function aw({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 b=f.options.horizontal?"width":"height";d.container.style[b]=`${m}px`}const h=!!f.options.horizontal,g=d.mode==="transform",v=h?"left":"top",p=f.options.scrollMargin,x=f.getVirtualItems();for(const b of x){const y=b.start-p,j=f.elementsCache.get(b.key);j&&d.lastPositions.get(j)!==y&&(d.lastPositions.set(j,y),g?j.style.transform=h?`translate3d(${y}px, 0, 0)`:`translate3d(0, ${y}px, 0)`:j.style[v]=`${y}px`)}},l={...r,onChange:(f,d)=>{var m;const h=o.current;let g=!0;if(h.enabled){i(f);const v=f.range,p=h.prevRange;g=!p||p.isScrolling!==f.isScrolling||p.startIndex!==v?.startIndex||p.endIndex!==v?.endIndex,g&&(h.prevRange=v?{startIndex:v.startIndex,endIndex:v.endIndex,isScrolling:f.isScrolling}:null)}g&&(e&&d?va.flushSync(a):a()),(m=r.onChange)==null||m.call(r,f,d)}},[u]=c.useState(()=>{const f=new sw(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 g=f.options.horizontal?"width":"height";d.style[g]=`${h}px`}}})});return u.setOptions(l),Hr(()=>u._didMount(),[]),Hr(()=>u._willUpdate()),Hr(()=>{i(u)}),u}function ow(e){return aw({observeElementRect:Y0,observeElementOffset:J0,scrollToFn:tw,...e})}const iw={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},hd={delete:"moved to Trash",move:"moved",markRead:"marked as read"},pd={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},lw={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},cw={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},uw=(e,t,s)=>iw[e](dt(t),dt(s)),Ui=(e,t)=>`${dt(t)} ${hd[e]}. Your mail server is still catching up.`,dw=(e,t,s)=>`${dt(t)} ${hd[e]}. ${dt(s)} ${pd[e]}.`,fw=(e,t)=>t>0?`Stopped after ${dt(t)} — some messages ${pd[e]}`:lw[e],mw=e=>cw[e],hw=e=>e==="delete"?"danger":"info",gd=100,Kn=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),pw=(e,t=gd)=>{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},gw=async(e,t,s,r)=>{const a=pw(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 Kn(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}},xw=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 Kn(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 Kn(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}},bw=e=>({done:e.done,total:Math.max(e.total,e.done)}),vw=async(e,t,s)=>{let r=0,a;do{if(s())return{total:r,cancelled:!0};const o=await Kn(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}},yw=e=>e.failedIds.length>0?{exit:!1,retryIds:e.failedIds}:e.cancelled||e.error?{exit:!1,retryIds:[]}:{exit:!0,retryIds:[]},ww=100,jw=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],Sw=({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:g}=Ve();c.useEffect(()=>{m.current=!0,i({kind:"idle"})},[s,r]);const v=c.useRef(a);v.current=a;const p=c.useCallback(async N=>{const{data:k}=await xl({path:{mailboxId:e},query:{...v.current,continuationToken:N,limit:ww},throwOnError:!0});return{ids:(k.items??[]).map(C=>C.messageId),continuationToken:k.continuationToken}},[e]),x=c.useCallback(N=>async k=>{if(N.kind==="move"){const{data:M}=await Tf({body:{messageIds:k,destinationMailboxId:N.destinationMailboxId},throwOnError:!0});return M}if(N.kind==="markRead"){const{data:M}=await Rf({body:{messageIds:k,isRead:!0},throwOnError:!0});return M}const{data:C}=await Mf({body:{messageIds:k},throwOnError:!0});return C},[]),b=c.useCallback(N=>{jt(h,wt(jw(N,e))),t&&h.invalidateQueries({queryKey:ts({path:{accountId:t}})})},[h,e,t]),y=c.useCallback(()=>{m.current=!1,i({kind:"counting",countSoFar:0}),vw(p,N=>i({kind:"counting",countSoFar:N}),()=>m.current).then(N=>{if(N.error){g(Yt("Couldn't count matching messages","The count didn't finish.",N.error)),i({kind:"idle"});return}if(N.cancelled){i({kind:"idle"});return}i({kind:"escalated",total:N.total})})},[p,g]),j=c.useCallback(()=>{m.current=!0},[]),w=c.useCallback(()=>{m.current=!0,i({kind:"idle"})},[]),E=c.useCallback(async(N,k)=>{m.current=!1,u(N);const C=D=>d(bw(D)),M=x(N),A=k!==void 0?await gw(k,M,C,()=>m.current):await xw(p,o.kind==="escalated"?o.total:0,M,C,()=>m.current);return u(void 0),d(void 0),i({kind:"idle"}),A.error&&g(Yt(fw(N.kind,A.done),mw(N.kind),A.error)),A.done>0&&b(N),A},[x,p,o,g,b]);return{phase:o,escalate:y,stop:j,clear:w,isRunning:l!==void 0,runningAction:l,progress:f,runAction:E}},xd=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",kw=e=>`Select all ${xd(e)}`,Cw=(e,t)=>`All ${dt(t)} ${xd(e)} selected`,Nw=e=>e.isRunning?"running":e.isCounting?"counting":e.isEscalated?"escalated":"idle",Ew=2,Iw=(e,t,s=!1)=>e>=Ew||t!=="idle"||s,bd=(e,t,s)=>{const r=ve(hl()),{mutate:a,reset:o}=r,[i,l]=c.useState(!1),u=c.useMemo(()=>Gf(s),[s]),f=c.useCallback(()=>{!e||!t||(l(!1),a({path:{accountId:e},body:Yr({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=c.useCallback(()=>{l(!1),o()},[o]),m=r.data,h=m?.semanticUnavailable===!0&&!i&&u.length>0;c.useEffect(()=>{!h||!e||(l(!0),a({path:{accountId:e},body:Yr(Xf(u))}))},[h,e,u,a]);const g=i||(m?.semanticUnavailable??!1),v=r.isPending||h,p=i?{matchOperator:"Or",literalClauses:Jf(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:f,reset:d,matchedCount:v?void 0:m?.matchedCount,messageIds:v?void 0:m?.messageIds,semanticUnavailable:g,senderFallback:i,senders:u,matchPredicate:p,isPending:v,isError:r.isError,error:r.error}},Tw=({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}};function vd({accountId:e,selectedMessageIds:t,seedCount:s,semanticUnavailable:r=!1,senders:a=[],seedMailboxId:o,seedScope:i,onClose:l}){const u=t[0],f=r&&a.length>0,[d]=c.useState(()=>Zf({anchorMessageId:u,semanticUnavailable:r,senders:a,selectionCount:t.length,seedMailboxId:o,seedScope:i})),{rule:m,handlers:h}=zu({initialRule:d,widenAnchorCount:t.length}),{data:g}=fe({...Ue({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),v=c.useMemo(()=>an(g?.items??[]).map(P=>({id:P.mailboxId,label:Yn(P.fullPath)})),[g?.items]),{labels:p}=Rl(e),x=c.useMemo(()=>p.map(P=>({id:P.labelId,name:P.name,color:P.color})),[p]),{createLabel:b}=nm(e),y=async P=>{const I=await b(P);return{id:I.labelId,name:I.name,color:I.color}},j=wl(e,Oa(m,u),s),w=jl(e),E=Sl(e),{createFolder:N}=Il(e),[k,C]=c.useState(),M=c.useRef(!1),A=()=>{const P=kl(m,u);if(m.scope==="once"){w.start(P);return}M.current=!1,C(em(P)?P:void 0),E.createFilter(P,m.scope==="standing"?"standing":"temporary",(m.name??"").trim())};c.useEffect(()=>{!k||M.current||!E.isSuccess||(M.current=!0,w.start(k))},[k,E.isSuccess,w.start]);const D=()=>{k&&w.start(k)};return w.isStarting||w.isRunning||w.isDone?n.jsx(Bu,{progress:w.progress,isDone:w.isDone,runningLabel:f?"Organizing mail from these senders…":"Organizing similar mail…",onClose:l}):E.isSuccess&&w.isError?n.jsx(Ny,{onRetry:D,onClose:l}):E.isPending?n.jsx(ca,{}):E.isSuccess?k?n.jsx(ca,{}):n.jsx(Ku,{onClose:l}):E.isError?n.jsx(Uu,{onRetry:E.reset,onClose:l}):n.jsx(pl,{rule:m,folders:v,labels:x,preview:j,semanticAvailable:!r,clauseFields:Aa,...h,onCreateFolder:N,onCreateLabel:y,onCommit:A,onCancel:l})}const qi=(e,t)=>e.find(s=>s.label.toLowerCase()===t),Rw=(e,t)=>{const s=[],r=qi(e,"inbox");r&&s.push({id:"keep-inbox",label:"Always keep in Inbox",seed:{moveMailboxId:r.id,scope:"standing"}});const a=qi(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},Mw=(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 Aw({folderOptions:e,junkMailboxId:t,onSeed:s}){const[r,a]=c.useState(""),o=c.useMemo(()=>Rw(e,t),[e,t]),i=()=>{const l=r.trim();l&&s(Mw(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(V,{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(Af,{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(V,{variant:"primary","aria-label":"Send",onClick:i,disabled:!r.trim(),icon:n.jsx(Km,{className:"size-4"}),className:"size-9 shrink-0 px-0"})]})]})}const Ow=e=>e?.scope==="standing"?"standing":void 0,Dw=(e,t,s)=>e?"error":t?"pending":s!==void 0?"success":"idle";function Pw({entry:e,accountId:t,selectedMessageIds:s,selectedSenders:r,junkMailboxId:a,onClose:o}){const i=s[0],[l,u]=c.useState(),{preview:f,matchedCount:d,semanticUnavailable:m,senders:h,isPending:g,isError:v,error:p}=bd(t,i,r);c.useEffect(()=>{f()},[f]);const{data:x}=fe({...Ue({path:{accountId:t}}),staleTime:Number.POSITIVE_INFINITY}),b=c.useMemo(()=>an(x?.items??[]).map(j=>({id:j.mailboxId,label:Yn(j.fullPath)})),[x?.items]),y=Tw({entry:e,hasSeed:l!==void 0,previewStatus:Dw(v,g,d),matchedCount:d});return n.jsxs(yl,{open:!0,onClose:o,dismissLabel:"Dismiss organize",children:[y.kind==="something-else"&&n.jsx(Aw,{folderOptions:b,junkMailboxId:a,onSeed:u}),y.kind==="widening"&&n.jsx(Lw,{}),y.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:p instanceof Error?p.message:"Please try again."}),n.jsx(V,{variant:"ghost",onClick:o,className:"mt-2",children:"Close"})]}),y.kind==="organize"&&n.jsx(vd,{accountId:t,selectedMessageIds:s,seedCount:y.matchedCount,seedScope:Ow(l),seedMailboxId:l?.moveMailboxId,semanticUnavailable:m,senders:h,onClose:o})]})}function Lw(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(et,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]})}function $w({open:e,accountId:t,selectedMessageIds:s,selectedSenders:r,onClose:a}){const o=s[0],{preview:i,reset:l,matchedCount:u,semanticUnavailable:f,senders:d,isPending:m,isError:h,error:g}=bd(t,o,r);c.useEffect(()=>{e&&i()},[e,i]);const v=()=>{l(),a()};return e?n.jsx(pa,{open:e,onClose:v,title:"Filter rule",children:m||u===void 0?h?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:g instanceof Error?g.message:"Please try again."}),n.jsx(V,{variant:"ghost",onClick:v,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(et,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]}):n.jsx(vd,{accountId:t,selectedMessageIds:s,seedCount:u,semanticUnavailable:f,senders:d,onClose:v})}):null}const Fw=(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:_t(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:ir(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),_w=({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:g,density:v})=>n.jsx(oo,{thread:Fw(e,d),linkMailboxId:t,inListbox:!0,active:r,focused:a,isTabStop:o,density:v,isDesktop:g,onFocusRow:i,selection:{isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:m,onLongPress:h},badge:e.autoMoved?n.jsx(eu,{accountId:s,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"sm"}):void 0}),zw=c.memo(_w),Bw=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:_t(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:ir(e.category),suspicious:t}},Kw=({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:g,onToggleRead:v,density:p})=>{const[x,b]=c.useState("none"),y=c.useCallback(E=>{navigator.vibrate?.(10),E==="trailing"?g(e.messageId):v(e.messageId,e.isRead),b("none")},[g,v,e.messageId,e.isRead]),j=c.useCallback(()=>{m(e.messageId)},[m,e.messageId]),w=c.useCallback(()=>{u(e.messageId)},[u,e.messageId]);return h||d?n.jsx(zw,{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(rc,{thread:Bw(e),selectionMode:!1,checked:!1,active:r,peek:x,onPeek:b,onToggleCheck:w,onLongPress:j,onOpen:()=>{},onAct:y,linkComponent:({onOpenClick:E,children:N,...k})=>n.jsx(xt,{...k,to:"/mail/$mailboxId",params:{mailboxId:t},search:C=>({...C,selectedMessageId:e.messageId}),"data-message-row":!0,onClick:E,children:N})})},Uw=72,qw=32,Hw=5,yd="remit:list-density",Ww={kind:"delete"},Hi={kind:"markRead"},Vw=()=>{try{const e=localStorage.getItem(yd);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},Qw=({query:e})=>n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[n.jsx(Gn,{className:"size-4 text-fg-muted"}),n.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),Yw=({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:g,hasMore:v=!1,isLoadingMore:p=!1,accountId:x,listTitle:b,listMeta:y,listFilter:j,listScopeLabel:w,onTriageContextChange:E,commandsRef:N,hideHeader:k=!1})=>{const C=c.useRef(null),M=Me(),A=$t(),[D,P]=c.useState(!1),[I,S]=c.useState(null),O=!!l?.trim(),[L,T]=c.useState(s),[$,R]=c.useState(Vw),F=c.useCallback(()=>{R(_=>{const ne=_==="comfortable"?"compact":"comfortable";try{localStorage.setItem(yd,ne)}catch{}return ne})},[]),{toggleReadFor:Q}=or({mailboxId:e}),{junkMailboxId:Z}=cr(x),{selectedIds:K,selectedCount:z,hasSelection:Y,isSelected:ue,toggle:oe,select:se,clearSelection:H,selectRange:G,setAnchor:ae,selectAll:je,toggleAll:Ne,intersectWith:J}=Wu(),X=Vu(z,A);c.useEffect(()=>{z===0&&S(null)},[z]);const[re,te]=c.useState(null),Pe=O&&!!u,Qe=`${e}|${JSON.stringify(u??{})}`,B=Sw({mailboxId:e,accountId:x,enabled:Pe,predicateKey:Qe,searchQuery:u??{}}),ze=B.phase.kind,Le=B.clear,he=c.useCallback(()=>{ze==="escalated"&&Le(),H()},[H,Le,ze]),[Ae,pe]=c.useState(null),[Kt,St]=c.useState(null),qe=c.useRef(null),Ye=c.useRef(!1),tt=c.useRef(null),He=!r&&t.length>0,st=re!==null,ht=c.useCallback((_,ne)=>{const{exit:Nt,retryIds:Je}=yw(ne);if(Nt){St(Ui(_.kind,ne.done)),pe(null),he();return}if(Je.length>0){pe({action:_,succeeded:ne.done}),je(Je);return}pe(null)},[he,je]),pt=ow({count:t.length,getScrollElement:()=>C.current,estimateSize:()=>$==="compact"?qw:Uw,overscan:Hw}),Ut=s?t.findIndex(_=>_.messageId===s):-1,ge=L?t.findIndex(_=>_.messageId===L):-1,Ge=c.useCallback(_=>{if(_<0||_>=t.length)return;const ne=t[_];if(X){oe(ne.messageId);return}qe.current=ne.messageId,Ye.current=!1,T(ne.messageId)},[t,X,oe]),rs=c.useCallback(()=>{if(t.length===0)return;const _=ge<0?0:Math.min(ge+1,t.length-1);Ge(_)},[t.length,ge,Ge]),ee=c.useCallback(()=>{if(t.length===0)return;const _=ge<=0?0:ge-1;Ge(_)},[t.length,ge,Ge]),ie=c.useCallback(()=>Ge(0),[Ge]),de=c.useCallback(()=>Ge(t.length-1),[Ge,t.length]),le=c.useCallback(()=>{L&&oe(L)},[L,oe]),ce=c.useMemo(()=>t.map(_=>_.messageId),[t]),Se=c.useMemo(()=>{const _=[];for(const ne of t)K.has(ne.messageId)&&ne.fromEmail&&_.push(ne.fromEmail);return _},[t,K]),Ee=c.useCallback((_,ne)=>ne.shiftKey?(G(ce,_,L),!0):ne.metaKey||ne.ctrlKey?(oe(_),!0):(he(),ae(_),!1),[ce,L,G,oe,he,ae]),Oe=c.useCallback(_=>{!f||_.length===0||(tt.current=L??null,te({source:"ids",ids:_}))},[f,L]),Re=c.useCallback(()=>{B.phase.kind==="escalated"&&(tt.current=L??null,te({source:"predicate",total:B.phase.total}))},[B.phase,L]),De=c.useCallback(_=>{const ne=Hu(ce,L,_);ne!==void 0&&(G(ce,ne),qe.current=ne,Ye.current=!1,T(ne))},[ce,L,G]),Be=c.useCallback(()=>De(-1),[De]),we=c.useCallback(()=>De(1),[De]),it=c.useCallback(()=>{ce.length>0&&je(ce)},[ce,je]),qt=c.useCallback(()=>re!==null?!0:f?z>0?(Oe(Array.from(K)),!0):L?(Oe([L]),!0):!1:!1,[re,f,z,K,L,Oe]),Os=c.useCallback(()=>{L&&M({to:"/mail/$mailboxId",params:{mailboxId:e},search:_=>({..._,selectedMessageId:L})})},[L,M,e]),Ds=c.useCallback(()=>{z>0&&Oe(Array.from(K))},[Oe,z,K]),$e=c.useCallback(async(_,ne)=>{const Nt=await B.runAction(_,ne);ht(_,Nt)},[B,ht]),lt=c.useCallback(async _=>{te(null),tt.current=null,await $e(Ww,_)},[$e]),as=c.useCallback(()=>{if(!re)return;if(re.source==="predicate"){lt(void 0);return}const{ids:_}=re;if(_.length===0){te(null);return}if(_.length>gd){lt(_);return}const ne=new Set(_),Nt=t.findIndex(_e=>ne.has(_e.messageId));let Je;for(let _e=Nt+1;_e<t.length;_e++)if(!ne.has(t[_e].messageId)){Je=t[_e].messageId;break}if(Je===void 0){for(let _e=Nt-1;_e>=0;_e--)if(!ne.has(t[_e].messageId)){Je=t[_e].messageId;break}}f?.(_),he(),tt.current=null,te(null),Je!==void 0&&(qe.current=Je,Ye.current=!1,T(Je),A&&M({to:"/mail/$mailboxId",params:{mailboxId:e},search:_e=>({..._e,selectedMessageId:Je}),replace:!0})),A||St(Ui("delete",_.length))},[re,t,f,he,M,e,A,lt]),kt=c.useCallback(()=>{const _=tt.current;tt.current=null,te(null),_!==null&&(qe.current=_,Ye.current=!1,T(_))},[]),gn=c.useCallback(()=>{if(B.phase.kind==="escalated"){$e(Hi);return}z!==0&&$e(Hi,Array.from(K))},[B.phase,$e,z,K]),os=c.useCallback(_=>{if(B.phase.kind==="escalated"){$e({kind:"move",destinationMailboxId:_});return}!d||z===0||(d(Array.from(K),_),he())},[B.phase,$e,d,z,K,he]),pr=c.useCallback(()=>{Z&&os(Z)},[Z,os]),Xe=c.useMemo(()=>{if(z===0)return;const _=new Set;for(const ne of t)K.has(ne.messageId)&&_.add(ne.accountConfigId);if(_.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[z,K,t]),gr=c.useCallback(_=>{f?.([_])},[f]),xr=c.useCallback((_,ne)=>{Q([_],!ne)},[Q]),br=c.useCallback(_=>{A||se(_)},[A,se]),xn=c.useCallback(()=>{if(B.phase.kind==="escalated"){Re();return}Ds()},[B.phase,Re,Ds]),bn=c.useCallback(()=>{if(B.isRunning||B.phase.kind==="counting"){B.stop();return}he()},[B,he]),vr=c.useCallback(()=>{B.clear()},[B]),yr=c.useCallback(()=>{if(!Ae)return;const _=Array.from(K);if(Ae.action.kind==="delete"){lt(_);return}$e(Ae.action,_)},[Ae,lt,$e,K]);c.useEffect(()=>{if(Ye.current||!A&&s)return;const _=ge>=0?ge:Ut;_>=0&&pt.scrollToIndex(_,{align:"auto"})},[ge,Ut,pt,A,s]),c.useEffect(()=>{s&&(Ye.current=!1,T(s))},[s]),c.useEffect(()=>{L&&(t.some(_=>_.messageId===L)||T(t[0]?.messageId))},[t,L]),c.useEffect(()=>{E?.({focusedMessageId:L,selectedIds:Array.from(K),hasList:He,blocksKeyboard:st})},[L,K,He,st,E]);const Ct=c.useRef(E);Ct.current=E,c.useEffect(()=>()=>Ct.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{B.phase.kind!=="idle"||B.isRunning||J(t.map(_=>_.messageId))},[t,J,B.phase,B.isRunning]);const Ps=c.useRef(e);c.useEffect(()=>{Ps.current!==e&&(Ps.current=e,he())},[e,he]),Ux({shouldBlockFn:({action:_})=>Ay(_,Y)?(he(),!0):!1,enableBeforeUnload:!1,disabled:!Y}),c.useEffect(()=>{const _=C.current;if(!_||!v||!g)return;const ne=()=>{if(p)return;const{scrollTop:Nt,scrollHeight:Je,clientHeight:_e}=_;Nt+_e>=Je-200&&g()};return _.addEventListener("scroll",ne,{passive:!0}),ne(),()=>_.removeEventListener("scroll",ne)},[v,p,g]),c.useEffect(()=>{const _=qe.current;if(!_)return;const ne=C.current?.querySelector(`[data-message-id="${_}"]`);ne&&(qe.current=null,ne.focus({preventScroll:!0}))}),c.useEffect(()=>{if(N){if(!He){N.current=null;return}return N.current={focusNext:rs,focusPrevious:ee,focusFirst:ie,focusLast:de,openFocused:Os,toggleSelect:le,extendSelectDown:we,extendSelectUp:Be,selectAll:it,clearSelection:()=>Y?(he(),!0):!1,requestDelete:qt,toggleDensity:F},()=>{N.current=null}}},[N,He,rs,ee,ie,de,Os,le,we,Be,it,Y,he,qt,F]);const Ls=r?"loading":a?"error":t.length===0?"empty":"ready",wr=a?Cl(o):void 0,jr=c.useCallback(()=>{const _=ka(Sa());window.open(_,"_blank","noopener,noreferrer")},[]),Sr=[{id:"inbox",threads:[]}],$s=ce.length>0&&ce.every(_=>K.has(_)),kr=Pe&&v&&$s&&!m&&!h&&B.phase.kind==="idle"&&!B.isRunning,W=m||h||B.isRunning,Fe=B.phase.kind==="escalated"?B.phase.total:z,Ke=B.runningAction?uw(B.runningAction.kind,B.progress?.done??0,B.progress?.total??0):B.phase.kind==="counting"?B.phase.countSoFar>=5e3?`Counting… ${dt(B.phase.countSoFar)} so far. This is a big result set.`:`Counting… ${dt(B.phase.countSoFar)} so far`:B.phase.kind==="escalated"?Cw(u??{},B.phase.total):void 0,ho=B.phase.kind!=="escalated"&&ce.length>0?{checked:$s,indeterminate:z>0&&!$s,onChange:()=>Ne(ce)}:void 0,po=B.runningAction&&B.progress?{value:B.progress.done,max:B.progress.total,tone:hw(B.runningAction.kind)}:void 0,go=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:vr}}:kr?{tone:"info",text:"",action:{label:kw(u??{}),onClick:B.escalate}}:Ae!==null&&z>0?{tone:"danger",text:dw(Ae.action.kind,Ae.succeeded,z),action:{label:`Retry ${dt(z)}`,onClick:yr}}:void 0,xo=go??(Xe?{tone:"warning",text:Xe}:void 0),bo=Nw({isRunning:B.isRunning,isCounting:B.phase.kind==="counting",isEscalated:B.phase.kind==="escalated"}),vo=!A&&X&&Iw(Fe,bo,xo!==void 0),Ad=(d||B.phase.kind==="escalated")&&x&&e?n.jsx(pn,{accountId:x,currentMailboxId:e,onMove:m||h?()=>{}:os,disabledHint:Xe,label:"Move selected messages"}):void 0,yo=I&&x&&!A&&z>0?n.jsx(Pw,{entry:I,accountId:x,selectedMessageIds:Array.from(K),selectedSenders:Se,junkMailboxId:Z,onClose:()=>{S(null),he()}}):void 0,wo=vo?n.jsx(ig,{count:Fe,mode:bo,onCancel:bn,onDelete:xn,onJunk:Z&&Z!==e&&!Xe?pr:void 0,onMarkRead:gn,onSelectSimilar:x?()=>S("select-similar"):void 0,onSomethingElse:x?()=>S("something-else"):void 0,moveSlot:Ad,isBusy:W,selectAll:ho,statusLabel:Ke,progress:po,notice:xo}):void 0,Od=wo||yo?n.jsxs(n.Fragment,{children:[wo,yo]}):void 0,Dd=Y&&A?n.jsx(Yu,{selectedCount:Fe,onDelete:xn,onClearSelection:bn,onMarkAsRead:gn,onMove:d?os:void 0,onOrganize:()=>P(!0),isDeleting:m,isMoving:h,accountId:x,currentMailboxId:e,selectedMessageIds:Array.from(K),moveDisabledHint:Xe,selectAll:Pe?ho:void 0,statusLabel:Ke,isCounting:B.phase.kind==="counting",progress:po,notice:go}):void 0,Pd=Qu(ce,L),Ld=c.useCallback(_=>{Ye.current=!0,T(_)},[]),$d=n.jsxs(n.Fragment,{children:[O&&l&&n.jsx(Qw,{query:l}),n.jsxs("div",{ref:C,role:"listbox","aria-multiselectable":!0,"aria-label":b,className:"flex-1 overflow-y-auto",style:vo?{paddingBottom:Vs}:void 0,children:[n.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${pt.getTotalSize()}px`},children:pt.getVirtualItems().map(_=>{const ne=t[_.index];return n.jsx("div",{role:"presentation","data-index":_.index,ref:pt.measureElement,className:be("absolute left-0 top-0 w-full border-b border-line",B.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${_.start}px)`},children:n.jsx(Kw,{thread:ne,mailboxId:e,accountId:x,isSelected:s===ne.messageId,isFocused:L===ne.messageId,isTabStop:Pd===ne.messageId,onFocusRow:Ld,isChecked:ue(ne.messageId),onToggleCheck:oe,onRowSelect:Ee,isMultiSelectMode:X,onLongPress:br,isDesktop:A,onDelete:gr,onToggleRead:xr,density:$})},_.key)})}),p&&n.jsx(ph,{})]})]}),Fd=re?re.source==="ids"?re.ids.length:re.total:0,jo=re?.source==="predicate";return n.jsxs(n.Fragment,{children:[Kt&&!A&&n.jsx(es,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>St(null),children:Kt}),n.jsx(ac,{listTitle:b,listMeta:y,sections:Sr,flatList:!0,listState:Ls,searchQuery:O?l:void 0,listFilter:j,listScopeLabel:w,errorMessage:wr,onRetry:i,onReportError:jr,density:$,selectedThreadId:s,onSelectThread:_=>M({to:"/mail/$mailboxId",params:{mailboxId:e},search:ne=>({...ne,selectedMessageId:_})}),onSelectBriefCategory:()=>{},isDesktop:A,hideHeader:k,selectionBar:Dd,selectionSheet:Od,listBody:Ls==="ready"?$d:void 0}),n.jsx(Pa,{isOpen:re!==null,title:El(Fd,jo),description:jo?"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:as,onCancel:kt}),D&&x&&n.jsx($w,{open:D,accountId:x,selectedMessageIds:Array.from(K),selectedSenders:Se,onClose:()=>P(!1)})]})},Gw=e=>ts({path:{accountId:e}}),Xw=e=>{const t=ye(),s=nn(),r=ve({...Of(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:Gw(e)})}});return{trigger:()=>{r.mutate({path:{accountId:e}})},triggerAsync:()=>r.mutateAsync({path:{accountId:e}}),isPending:r.isPending,error:r.error,reset:r.reset}},Jw=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:r}=Xw(e);return n.jsx(Pp,{onRefresh:s,isRefreshing:r,children:t})};function Zw({accountId:e,currentMailboxId:t,candidates:s,onMove:r,children:a}){const[o,i]=c.useState(!1),l=nn(),{t:u}=Hn("mail",{useSuspense:!1}),f=c.useCallback((y,j)=>u(y,{defaultValue:j}),[u]),{inboxMailboxId:d}=Za(e),m=Zc(e),{data:h}=fe({...Ue({path:{accountId:e}}),staleTime:1/0}),g=c.useMemo(()=>{const y=an(h?.items??[],m),j=sn(m);return y.map(w=>({id:w.mailboxId,label:ys(w,j.get(w.mailboxId),f),searchValue:w.fullPath,isCurrent:w.mailboxId===t}))},[h?.items,m,t,f]),v=c.useMemo(()=>d||(g.find(j=>j.label.toLowerCase()==="inbox")?.id??g.find(j=>!j.isCurrent)?.id??""),[d,g]),p=c.useRef(!1);c.useEffect(()=>{p.current||(p.current=!0,n0(l,s.length))},[l,s.length]);const x=c.useCallback(()=>{r0(l,s.length),i(!0)},[l,s.length]),b=c.useCallback((y,j)=>{a0(l,{selected:y.length,total:s.length,toInbox:j===d}),r(y,j)},[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(Fp,{count:s.length,onReview:x})}),n.jsx("div",{className:"min-h-0 flex-1",children:a}),n.jsx(Qp,{open:o,candidates:s,defaultDestinationId:v,availableFolders:g,onConfirmMove:b,onCancel:()=>i(!1)})]})}const ej="We can verify this sender";function tj(e){const{data:t}=fe({...Df({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:ej,trustSubReason:s0(r.senderTrust),senderTrust:r.senderTrust}))}}const sj=e=>{const t=new Set,s=[];for(const r of e)t.has(r.threadMessageId)||(t.add(r.threadMessageId),s.push(r));return s},nj={unread:"unread",flagged:"starred",attachment:"attachments"},rj=new Set(Object.values(nt)),wd=e=>rj.has(e),aj=e=>wd(e.category)||e.attributes.size>0,oj=e=>{const t={};wd(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const r=nj[s];r&&(t[r]=!0)}return t},ij=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",lj=["category","unread","starred","attachments"],Wi=e=>JSON.stringify(lj.map(t=>e?.[t]??null)),cj=e=>{if(!Array.isArray(e))return;const[t]=e;if(typeof t!="object"||t===null)return;const s=t.query;if(!(typeof s!="object"||s===null))return s},uj=(e,t)=>{const s=cj(e);return s?Wi(s)===Wi(t):!1},jd="remit:intelligence-open";function dj(){try{return localStorage.getItem(jd)!=="closed"}catch{return!0}}function Vi(e){try{localStorage.setItem(jd,e?"open":"closed")}catch{}}const fj=(e,t)=>e!==t,mj=(e,t,s)=>{if(!(s||!t))return e.find(r=>r.messageId===t)},hj=(e,t,s,r)=>{if(e)return e;if(!(r||!s))return t?.messageId===s?t:void 0},pj=50,gj=new Map(gc().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),Sd=c.createContext(null);function hr(){const e=c.useContext(Sd);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function xj({mailboxId:e,selectedMessageId:t,children:s}){const r=Me(),o=dr()==="desktop",i=nn(),{accounts:l,searchQuery:u,searchInput:f,intelligenceOpen:d,onToggleIntelligence:m,onSetIntelligenceOpen:h}=Ce(),g=Rs(),v=ro(u),p=v.length>0,{freeText:x,tokens:b}=Ms(v,g),y=b.find(W=>W.type==="from"),[j,w]=c.useState("all"),[E,N]=c.useState(new Set),k=c.useMemo(()=>({category:j,attributes:E}),[j,E]),C=c.useMemo(()=>oj(k),[k]),M=p||aj(k),A={order:"desc",limit:pj,...x?{query:x}:{},...y?{from:y.value}:{},...b.some(W=>W.type==="hasAttachment")?{attachments:!0}:{},...b.some(W=>W.type==="isUnread")?{unread:!0}:{},...C},D=M?ul({path:{mailboxId:e},query:A}):Na({path:{mailboxId:e},query:{order:"desc"}}),{data:P,isLoading:I,isError:S,error:O,refetch:L,fetchNextPage:T,hasNextPage:$,isFetchingNextPage:R}=Rc({queryKey:D,queryFn:async({pageParam:W})=>{if(M){const{data:Ke}=await xl({path:{mailboxId:e},query:{...A,continuationToken:W},throwOnError:!0});return Ke}const{data:Fe}=await Pf({path:{mailboxId:e},query:{order:"desc",continuationToken:W},throwOnError:!0});return Fe},initialPageParam:void 0,getNextPageParam:W=>W.continuationToken,placeholderData:(W,Fe)=>uj(Fe?.queryKey,C)?W:void 0}),F=c.useCallback(W=>{t&&W.includes(t)&&r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Fe=>({...Fe,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,r]),{deleteMessages:Q,isPending:Z}=Jt({mailboxId:e,onAfterOptimisticRemove:F}),{accountId:K}=Xc(e),z=Bc({accounts:l}),{moveMessages:Y,isPending:ue}=Xt({mailboxId:e,accountId:K,onAfterOptimisticRemove:F}),oe=tv(sj(P?.pages.flatMap(W=>W.items??[])??[])),se=c.useCallback(W=>{w(W)},[]),H=c.useCallback(W=>{N(Fe=>{const Ke=new Set(Fe);return Ke.has(W)?Ke.delete(W):Ke.add(W),Ke})},[]),G=c.useCallback(()=>{w("all"),N(new Set)},[]),ae=gj.get(j),je=ae?{label:ae,reach:ij(A),onClear:G}:void 0,Ne=fj(f,u),J=mj(oe,t,Ne),[X,re]=c.useState(void 0);c.useEffect(()=>{J&&re(J)},[J]);const te=hj(J,X,t,Ne),{selectedThreadId:Pe}=ws({strict:!1}),Qe=c.useMemo(()=>ad(te,{messageId:t,threadId:Ne?void 0:Pe,mailboxId:e}),[te,t,Pe,Ne,e]),B=lo(),{listCommandsRef:ze,onTriageContextChange:Le,focusedMessageId:he,selectedIds:Ae}=B,pe=oe.find(W=>W.messageId===he)??te,Kt=c.useRef(null);c.useEffect(()=>{const W=te?.messageId??null;W&&Kt.current!==W&&te?.authenticity?.dkimMismatch&&(Kt.current=W,d||m())},[te?.messageId,te?.authenticity?.dkimMismatch,d,m]);const St=c.useRef(!1);c.useEffect(()=>{St.current||o&&te?.messageId&&(St.current=!0,dj()&&!d&&h(!0))},[o,te?.messageId,d,h]);const qe=sb({accounts:l})??0,Ye=ye(),{pushError:tt}=Ve(),He=Zs({thread:te,mailboxId:e,accountId:K,onAfterOptimisticRemove:F}),{draftsMailboxId:st}=Zb(K),ht=st!==void 0&&st===e,{archiveMailboxId:pt}=Jb(K),Ut=rd(),{requestCompose:ge}=He,Ge=c.useCallback(()=>{ge("reply")},[ge]),rs=c.useCallback(()=>{ge("reply_all")},[ge]),ee=c.useCallback(()=>{ge("forward")},[ge]),{state:ie,openCompose:de,closeCompose:le}=Lt(),ce=c.useCallback(()=>{de({mode:"new"})},[de]),Se=ve({...Vn(),onError:W=>{tt(Yt("Couldn't discard draft","The draft wasn't deleted.",W))}}),Ee=c.useCallback(()=>{const W=ie.outboxMessageId;W&&(Se.mutate({path:{outboxMessageId:W}}),Ye.invalidateQueries({queryKey:Ta()}),le())},[ie.outboxMessageId,Se,Ye,le]),Oe=c.useCallback(()=>{r({to:"/mail/$mailboxId",params:{mailboxId:e},search:W=>({...W,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,r]),Re=c.useCallback(W=>W?Ut(W):[],[Ut]),{toggleStar:De}=Xa({threadId:pe?.threadId??"",mailboxId:e}),{toggleReadFor:Be}=or({mailboxId:e,accountId:K}),{junkMailboxId:we}=cr(K),it=we!=null&&we===e,{candidates:qt}=tj(it?we:void 0),{moveMessages:Os}=Xt({mailboxId:e,threadId:pe?.threadId,accountId:K,onAfterOptimisticRemove:F}),{deleteMessages:Ds}=Jt({mailboxId:e,threadId:pe?.threadId,onAfterOptimisticRemove:F}),{addressId:$e,address:lt}=ed(pe),{updateFlags:as}=td({addressId:$e,senderEmail:pe?.fromEmail??void 0}),kt=c.useCallback(()=>t||!he?!1:(r({to:"/mail/$mailboxId",params:{mailboxId:e},search:W=>({...W,selectedMessageId:he})}),!0),[t,he,e,r]),gn=c.useCallback(()=>{kt()||te&&ge("reply")},[kt,te,ge]),os=c.useCallback(()=>{kt()||te&&ge("reply_all")},[kt,te,ge]),pr=c.useCallback(()=>{kt()||te&&ge("forward")},[kt,te,ge]),Xe=c.useCallback(()=>Ae.length>0?Ae:Re(pe),[Ae,Re,pe]),gr=c.useCallback(()=>{if(ze.current?.requestDelete())return;const W=Xe();W.length>0&&Ds(W)},[ze,Xe,Ds]),xr=c.useCallback(()=>{if(!we)return;const W=Xe();W.length!==0&&(nd(i,{count:W.length,senderTrust:pe?.senderTrust??"unknown",wasRescuable:pe?sd(pe):!1}),Os(W,we))},[we,Xe,Os,i,pe]),br=c.useCallback(()=>{if(Ae.length>0){const W=!(pe?.hasStars??!1),Fe=new Set(Ae);for(const Ke of oe)Fe.has(Ke.messageId)&&Ke.hasStars!==W&&De(Ke.messageId,Ke.hasStars);return}pe&&De(pe.messageId,pe.hasStars)},[Ae,oe,pe,De]),xn=c.useCallback(()=>{const W=Xe();if(W.length===0)return;const Fe=!(pe?.isRead??!1);Be(W,Fe)},[Xe,pe,Be]),bn=c.useCallback(()=>{if(!$e)return;const W=lt?.flags?.muted?.value!==!0;as({muted:{value:W}})},[$e,lt,as]),vr=c.useCallback(()=>{if(!$e)return;const W=lt?.flags?.vip?.value!==!0;as({vip:{value:W}})},[$e,lt,as]),yr=c.useCallback(()=>{d||m()},[d,m]),Ct=c.useCallback(W=>{r({to:W})},[r]),Ps=ht?"drafts":pt===e?"archive":we===e?"junk":"inbox",Ls=c.useRef("");c.useEffect(()=>{const W=Ls.current;Ls.current=v,v.length>0&&W.length===0&&i.recordEvent("search.submitted",{mailboxType:Ps})},[v,Ps,i]);const wr=ht&&ie.isOpen&&!!ie.outboxMessageId&&!te,{goBack:jr,nextMessageId:Sr,previousMessageId:$s}=co({context:B,orderedIds:oe.map(W=>W.messageId),selectedMessageId:t,enabled:!ie.isOpen,onClose:Oe,handlers:{reply:gn,replyAll:os,forward:pr,delete:gr,toggleStar:br,toggleRead:xn,muteSender:bn,blockSender:yr,vipSender:vr,markJunk:xr,toggleIntelligence:te?m:void 0,compose:ce,goBrief:()=>Ct("/mail"),goInbox:()=>Ct("/mail"),goSent:()=>Ct("/mail"),goFlagged:()=>Ct("/mail/flagged"),goSettings:()=>Ct("/settings")}});Ga({enabled:ie.isOpen,bindings:[{key:"Escape",handler:le,preventDefault:!0}]});const kr={mailboxId:e,selectedMessageId:t,selectedThread:te,conversation:Qe,threads:oe,isLoading:I,isError:S,error:O,mailboxAccountId:K,mailboxName:z,unreadCount:qe,isDraftsMailbox:ht,isSpamFolder:it,rescueCandidates:qt,filterCategory:j,filterAttributes:E,onSelectFilterCategory:se,onToggleFilterAttribute:H,onClearFilters:G,listFilter:je,intelligenceOpen:d,onToggleIntelligence:m,searchPredicate:p?A:void 0,onDeleteMessages:Q,onMoveMessages:Y,isDeleting:Z,isMoving:ue,onLoadMore:T,hasMore:$,isLoadingMore:R,onTriageContextChange:Le,listCommandsRef:ze,onRetry:()=>L(),toolbarComposeRequest:He.composeRequest,onToolbarReply:Ge,onToolbarReplyAll:rs,onToolbarForward:ee,onClearComposeRequest:He.clearComposeRequest,onToolbarDelete:He.deleteThread,onToolbarStar:He.toggleStar,onToolbarDiscardDraft:Ee,onToolbarMove:He.moveThread,composeState:ie,closeCompose:le,hasRemitDraftOpen:wr,onBack:jr,nextMessageId:Sr,previousMessageId:$s};return n.jsx(Sd.Provider,{value:kr,children:s})}function kd(){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:g,mailboxName:v,unreadCount:p,isDraftsMailbox:x,isSpamFolder:b,rescueCandidates:y,onTriageContextChange:j,listCommandsRef:w,onRetry:E,filterCategory:N,filterAttributes:k,onSelectFilterCategory:C,onToggleFilterAttribute:M,onClearFilters:A,listFilter:D,searchPredicate:P}=hr(),{searchQuery:I,searchInput:S,accounts:O,resultFolderIndex:L}=Ce(),T=dr(),$=Me(),R=v??"Inbox",F=c.useMemo(()=>gc(),[]),Q=c.useMemo(()=>s.map(G=>gy(G,L)),[s,L]),{hits:Z,isLoading:K}=Mu({mailboxId:e,filterCategory:N}),z=c.useMemo(()=>Pu(Z,s.map(G=>G.threadId),L),[Z,s,L]),Y=c.useCallback(G=>$({to:"/mail/$mailboxId",params:{mailboxId:G.mailboxId??e},search:ae=>({...ae,q:S||void 0,selectedMessageId:G.id,selectedThreadId:G.threadId})}),[e,$,S]);if(x&&g)return n.jsx(U0,{mailboxId:e,accountId:g,selectedMessageId:t,imapThreads:s,title:v??"Drafts",unreadCount:p??void 0});const ue=n.jsx(Yw,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:r,isError:a,error:o,onRetry:E,searchQuery:I,searchPredicate:P,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,accountId:g,listTitle:R,listFilter:D,listScopeLabel:R,hideHeader:!0,onTriageContextChange:j,commandsRef:w}),oe=O[0]?.accountId,se=T==="phone"&&oe?n.jsx(Jw,{accountId:oe,children:ue}):ue,H=b&&y.length>0&&g?n.jsx(Zw,{accountId:g,currentMailboxId:e,candidates:y,onMove:l,children:se}):se;return n.jsx(cd,{title:R,unreadCount:p,preset:F,selectedCategory:N,activeFilters:k,onSelectCategory:C,onToggleFilter:M,onClearFilters:A,searchResults:Q,searchLoading:r,relatedResults:z,relatedLoading:K,onSelectSearchResult:Y,searchResultsInBody:!0,children:H})}function bj(){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:g,onToolbarDiscardDraft:v,onToolbarMove:p,composeState:x}=hr(),b=ks()?.showIntelligencePane??!1,y=!!r,j=b&&y,w=x.isOpen&&!r?n.jsx(fd,{}):r?n.jsx(Ts,{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(Is,{});return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(io,{hasThread:y,intelligenceOpen:j&&o,canToggleIntelligence:j,onToggleIntelligence:i,onReply:y?u:void 0,onReplyAll:y?f:void 0,onForward:y?d:void 0,canDelete:y||a,onDelete:y?h:a?v:void 0,onToggleStar:y?g: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:w})]})}function vj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:r}=hr();return n.jsx(As,{onClose:r,thread:s,mailboxId:e,accountId:t})}function yj(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:r,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=hr(),f=Me();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(Ts,{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(Qa,{isOpen:r,onClose:a,ariaLabel:"Message details",side:"right",children:n.jsx(As,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?n.jsx("div",{className:"h-full",children:n.jsx(fd,{})}):n.jsx(kd,{})}const Ws=Object.assign(xj,{List:kd,Reading:bj,Intelligence:vj,Phone:yj}),Cd=e=>e==="failed"||e==="blocked",Nd=e=>e!=="draft"&&e!=="sent",fo="remit.savedSearches",wj=25;function Un(){try{const e=localStorage.getItem(fo);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function jj(e){const t=e.trim();if(!t)return Un();const s=[t,...Un().filter(r=>r!==t)].slice(0,wj);try{localStorage.setItem(fo,JSON.stringify(s))}catch{return s}return s}function Sj(e){const t=Un().filter(s=>s!==e);try{localStorage.setItem(fo,JSON.stringify(t))}catch{return t}return t}const Qi=e=>/^\d/.test(e),kj=(e,t)=>{const s=Qi(e),r=Qi(t);return s&&!r?-1:!s&&r?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function Cj(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)=>kj(ys(o,void 0,s),ys(i,void 0,s))),{system:r,labels:a}}function Nj(e,t,s){const r=Lf(t)&&e.unseenCount>0;return{id:e.mailboxId,name:ys(e,t,s),unseen:r?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function Ej(){const e=nr(),t=Ca({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 Yi({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const r=ye(),a=Me(),o=Ej(),{searchInput:i,onSearchChange:l}=Ce(),[u,f]=c.useState(Un),{t:d}=Hn("mail",{useSuspense:!1}),m=c.useCallback((C,M)=>d(C,{defaultValue:M}),[d]),h=Bt({queries:e.map(C=>({...Ue({path:{accountId:C.accountId}}),staleTime:1/0}))}),{data:g}=fe(Wn()),v=c.useMemo(()=>(g?.items??[]).filter(C=>Nd(C.status)).length,[g?.items]),p=c.useMemo(()=>e.map((C,M)=>{const A=h[M],D=A?.data?.items??[],P=sn(C.folderAppointments),{system:I,labels:S}=Cj(D,P,m),O=A?.isError?"error":A?.isLoading?"loading":"ready";return{id:C.accountId,label:C.email,email:C.email,muted:!!C.muted,outboxPending:v,status:O,onRetry:()=>A?.refetch(),mailboxes:[...I,...S].map(L=>Nj(L,P.get(L.mailboxId),m))}}),[e,h,v,m]),x=C=>{r.invalidateQueries({queryKey:Na({path:{mailboxId:C},query:{order:"desc"}})})},b=({navId:C,className:M,ariaLabel:A,title:D,children:P,onClick:I})=>C==="brief"?n.jsx(xt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>I?.(),className:M,"aria-label":A,title:D,children:P}):C==="outbox"?n.jsx(xt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>I?.(),className:M,"aria-label":A,title:D,children:P}):C==="flagged"?n.jsx(xt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>I?.(),className:M,"aria-label":A,title:D,children:P}):C==="settings"?n.jsx(xt,{to:"/settings/accounts",onClick:()=>I?.(),className:M,"aria-label":A,title:D,children:P}):n.jsx(xt,{to:"/mail/$mailboxId",params:{mailboxId:C},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{x(C),I?.()},className:M,"aria-label":A,title:D,children:P}),y=()=>{l(""),t?.()},j=i.trim(),w=j.length>0&&!u.includes(j)?j:void 0,E=c.useCallback(()=>{w&&f(jj(w))},[w]),N=c.useCallback(C=>{f(Sj(C))},[]),k=c.useCallback(C=>{l(C),a({to:"/mail",search:{q:C,selectedMessageId:void 0}}),t?.()},[l,a,t]);return n.jsx(cp,{accounts:p,selectedNavId:o,onSelectNav:y,linkComponent:b,variant:s,savedSearches:u,saveableQuery:w,onSaveCurrentSearch:E,onSelectSavedSearch:k,onRemoveSavedSearch:N})}function Ij({accounts:e,onMailboxSelect:t}){return ks()?.showNavPane??!0?n.jsx(Yi,{accounts:e}):n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(Yi,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),n.jsxs("div",{className:"border-t border-line px-2 py-2",children:[n.jsxs(xt,{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(_a,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),n.jsx(Dc,{variant:"drawer"}),n.jsx(Oc,{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(Vl,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function Tj(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 Rj(e){return e.tokens.length>0&&e.freeText.trim().length===0}const Ed={queued:{icon:Ma,label:"Queued",className:"text-warning"},sending:{icon:et,label:"Sending…",className:"text-accent-2"},sent:{icon:Ul,label:"Sent",className:"text-positive"},failed:{icon:Zt,label:"Failed",className:"text-danger"},blocked:{icon:xa,label:"Blocked",className:"text-warning"}},Mj=e=>tm(e).toDateString()===new Date().toDateString()?$n(e,{hour:"numeric",minute:"2-digit"}):$n(e,{month:"short",day:"numeric"}),Gi=e=>$n(e,{dateStyle:"medium",timeStyle:"short"}),Aj=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},Id=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",Td=c.createContext(null);function mo(){const e=c.useContext(Td);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function Oj({children:e}){const t=Me(),{selectedOutboxMessageId:s}=ws({strict:!1}),{data:r,isLoading:a}=fe(Wn()),{searchQuery:o}=Ce(),i=Rs(),l=ro(o),u=Ms(l,i),f=l.length>0,d=Rj(u),m=c.useMemo(()=>d?[]:(r?.items??[]).filter(p=>Nd(p.status)).filter(p=>Tj(p,u.freeText)),[r,u.freeText,d]),h=c.useMemo(()=>m.find(p=>p.outboxMessageId===s),[m,s]),g=c.useCallback(p=>{t({to:"/mail/outbox",search:x=>({...x,selectedOutboxMessageId:p})})},[t]),v={messages:m,hasQuery:f,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:g};return n.jsx(Td.Provider,{value:v,children:e})}function Rd({message:e,isSelected:t,onSelect:s}){const r=ye(),{openCompose:a}=Lt(),{pushError:o}=Ve(),i=c.useCallback(()=>{r.invalidateQueries({queryKey:Ta()})},[r]),l=ve({...cl(),onSuccess:i,onError:m=>{o(Yt("Couldn't resend message","The message wasn't sent.",m))}}),u=ve({...Vn(),onSuccess:i,onError:m=>{o(Yt("Couldn't delete message","The message wasn't deleted.",m))}}),f=e.status;if(!Ed[f])return null;const d=Cd(e.status);return n.jsx(Op,{recipients:Aj(e),subject:e.subject||"",time:Mj(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 Md({message:e,onBack:t}){const s=e.status,r=Ed[s],a=r?.icon??tn,o=e.sentAt?Gi(e.sentAt):Gi(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(Bl,{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:be("size-4",r.className,s==="sending"&&"animate-spin")}),n.jsx("span",{className:be("text-xs font-medium",r.className),children:r.label}),Cd(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(Eu,{html:e.htmlBody,text:e.textBody})})]})}function Dj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,onSelectMessage:o}=mo(),i=c.useRef(null);return qn({containerRef:i,itemSelector:fa}),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(Is,{message:Id(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(uo,{}),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(Rd,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function Pj(){const{selectedMessage:e}=mo();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(Md,{message:e}):n.jsx(Is,{message:"Select a message to read",showHints:!1})})]})}function Lj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=mo(),l=c.useRef(null);return qn({containerRef:l,itemSelector:fa}),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(Md,{message:o,onBack:()=>i(void 0)}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Is,{message:Id(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(uo,{}),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(Rd,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const Rn=Object.assign(Oj,{List:Dj,Reading:Pj,Phone:Lj}),$j=({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:be("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:Uc.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(xs,{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(xs,{children:"Esc"})," to close"]})})]})]}):null};function Fj(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 _j(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 zj(e){const t=Bt({queries:e.map(s=>({...Ue({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>_j(t.map(s=>s.data?.items??[])),[t])}const Bj=e=>e.map(t=>t.data?.items??[]);function Kj(e){const t=Bt({queries:e.map(s=>({...Ue({path:{accountId:s.accountId}}),staleTime:1/0})),combine:Bj});return c.useMemo(()=>$f(e.map((s,r)=>({folderAppointments:s.folderAppointments,mailboxes:t[r]??[]}))),[e,t])}var Mn={exports:{}},Xi;function Uj(){if(Xi)return Mn.exports;Xi=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 g=()=>{if(f)return;const v=u.next(),p=h;if(h++,v.done){d=!0,m===0&&a(l);return}m++,Promise.resolve(v.value).then(x=>s(x,p)).then(x=>{l[p]=x,m--,g()},x=>{f=!0,o(x)})};for(let v=0;v<i&&(g(),!d);v++);});return Mn.exports=e,Mn.exports.default=e,Mn.exports}var qj=Uj();const Hj=Ff(qj),Wj=900*1e3,Vj=300,Qj=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},Yj=60*1e3,Gj=e=>Math.max(Qj(e,Vj)*1e3,Yj),Ln=Gj(Bf().mailboxPollIntervalSeconds),Xj=5,ua=new Set,Jj=(e,t,s=Wj)=>e.filter(r=>{const a=r.lastSyncAt;return a==null?!0:t-a>s}).map(r=>r.accountId),Zj=(e,t,s=Ln)=>e-t>=s,eS=(e,t)=>e.filter(s=>!t.has(s)),Ji=(e,t)=>{if(ua.delete(e),zf(t,{softError:!0})){gl(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},Zi=(e,t)=>_f({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:ts({path:{accountId:e}})})}),tS=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=Jj(s.current,a).filter(l=>!ua.has(l));if(i.length!==0)for(const l of i)ua.add(l),Zi(l,t).catch(u=>{Ji(l,u)})},[r,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const d=eS(s.current.map(m=>m.accountId),i);for(const m of d)i.add(m);Hj(d,m=>Zi(m,t).catch(h=>{Ji(m,h)}).finally(()=>{i.delete(m)}),{concurrency:Xj})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,Ln);return}},f=()=>{document.visibilityState==="visible"&&Zj(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,Ln))};return o=setTimeout(u,Ln),document.addEventListener("visibilitychange",f),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",f)}},[r,t])};function sS(e,t,s){if(e!==t)return s}function nS(e,t){return e===""?"":t}function rS(e,t,s){return t!==e?!1:t!==s}function aS(){const{q:e=""}=ws({from:"/mail"}),t=Me(),s=dr(),r=Lu(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,f]=c.useState(!1),d=c.useCallback(se=>{f(se),Vi(se)},[]),[m,h]=c.useState(e),g=vl(m,200),v=nS(m,g),p=c.useRef(e);p.current=e;const x=bt({select:se=>Xx(se.matches)}),[b,y]=c.useState(x);if(b!==x){const se=sS(b,x,e);y(x),se!==void 0&&h(se)}c.useEffect(()=>{rS(m,v,p.current)&&t({to:".",search:se=>{const H=se.q===v;return{...se,q:v||void 0,...v&&!H?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[m,v,t]);const{data:j,isLoading:w,isError:E,error:N,refetch:k}=fe({...vt(),staleTime:1/0}),C=!!(j&&(j.accounts?.length??0)===0);c.useEffect(()=>{C&&t({to:"/onboarding",replace:!0})},[C,t]),Ga({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const M=c.useCallback(se=>{h(se)},[]),A=c.useCallback(()=>{h("")},[]),D=c.useCallback(()=>{h("")},[]),P=c.useCallback(()=>{f(se=>{const H=!se;return Vi(H),H})},[]),I=j?.accounts??[],S=zj(I),O=Kj(I),L=c.useMemo(()=>Fj(I),[I]),T=bt({select:se=>se.matches.find(G=>"mailboxId"in G.params)?.params.mailboxId}),{selectedMessageId:$}=ws({strict:!1}),R=bt({select:se=>Va(se.matches)}),F=bt({select:se=>cn(se.matches)}),Q=bt({select:se=>rr(se.matches)});tS(I);const Z=c.useCallback(()=>{l(!1)},[]),K={accounts:I,mailboxNameIndex:S,accountNameIndex:L,resultFolderIndex:O,searchQuery:v,searchInput:m,searchViewKey:x,onSearchChange:M,onSearchClear:A,onSearchClearQuery:D,intelligenceOpen:u,onToggleIntelligence:P,onSetIntelligenceOpen:d},z=n.jsx(Ij,{accounts:I,onMailboxSelect:Z}),Y=r?n.jsx(Qx,{accounts:I}):void 0,ue=r?void 0:n.jsx(ab,{accounts:I}),oe={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return n.jsxs(Kf.Provider,{value:K,children:[E?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:n.jsx(Ft,{title:"Couldn't load your account",error:N,onRetry:()=>{k()}})}):R?n.jsx(Us,{selectedMessageId:$,children:r?n.jsx(Et,{nav:z,list:n.jsx(Us.Phone,{}),intelligenceOpen:u,overlay:Y,skeleton:n.jsx(gt,{}),isLoading:w||C,...oe}):n.jsx(Et,{nav:z,topBar:ue,list:n.jsx(Us.List,{}),reading:n.jsx(Us.Reading,{}),intelligence:n.jsx(Us.Intelligence,{}),intelligenceOpen:u,hasThread:!!$,overlay:Y,skeleton:n.jsx(gt,{}),isLoading:w||C,...oe})}):F?n.jsx(qs,{selectedMessageId:$,children:r?n.jsx(Et,{nav:z,list:n.jsx(qs.Phone,{}),intelligenceOpen:u,overlay:Y,skeleton:n.jsx(gt,{}),isLoading:w||C,...oe}):n.jsx(Et,{nav:z,topBar:ue,list:n.jsx(qs.List,{}),reading:n.jsx(qs.Reading,{}),intelligence:n.jsx(qs.Intelligence,{}),intelligenceOpen:u,hasThread:!!$,overlay:Y,skeleton:n.jsx(gt,{}),isLoading:w||C,...oe})}):T?n.jsx(Ws,{mailboxId:T,selectedMessageId:$,children:r?n.jsx(Et,{nav:z,list:n.jsx(Ws.Phone,{}),intelligenceOpen:u,overlay:Y,skeleton:n.jsx(gt,{}),isLoading:w||C,...oe}):n.jsx(Et,{nav:z,topBar:ue,list:n.jsx(Ws.List,{}),reading:n.jsx(Ws.Reading,{}),intelligence:n.jsx(Ws.Intelligence,{}),intelligenceOpen:u,hasThread:!!$,overlay:Y,skeleton:n.jsx(gt,{}),isLoading:w||C,...oe})}):Q?n.jsx(Rn,{children:r?n.jsx(Et,{nav:z,list:n.jsx(Rn.Phone,{}),intelligenceOpen:!1,overlay:Y,skeleton:n.jsx(gt,{}),isLoading:w||C,...oe}):n.jsx(Et,{nav:z,topBar:ue,list:n.jsx(Rn.List,{}),reading:n.jsx(Rn.Reading,{}),intelligenceOpen:!1,overlay:Y,skeleton:n.jsx(gt,{}),isLoading:w||C,...oe})}):n.jsx(gt,{}),n.jsx($j,{isOpen:a,onClose:()=>o(!1)}),n.jsx(Uf,{})]})}const CS=Object.freeze(Object.defineProperty({__proto__:null,component:aS,useMailContext:Ce},Symbol.toStringTag,{value:"Module"}));export{kS as S,eh as U,CS as m};