@remit/web-client-dist 0.0.301 → 0.0.303

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 (37) hide show
  1. package/assets/{ErrorState-K_DfCEXi.js → ErrorState-D2lY6diG.js} +1 -1
  2. package/assets/{OnboardingWizard-CFBfC_Cx.js → OnboardingWizard-C2v2MaXG.js} +1 -1
  3. package/assets/{account-form-helpers-BbRUMYkd.js → account-form-helpers-BCPF7T2c.js} +1 -1
  4. package/assets/{accounts-Do8sVKGo.js → accounts-CfEoqS0L.js} +1 -1
  5. package/assets/{advanced-D1fiZ_fQ.js → advanced-BLK43J_3.js} +1 -1
  6. package/assets/{appearance-gQ1gWf6o.js → appearance-DGW19EqU.js} +1 -1
  7. package/assets/{avatar-CzdzqSzA.js → avatar-DlxfC_TE.js} +1 -1
  8. package/assets/{browser-ponyfill-BG8I-k7n.js → browser-ponyfill-By-VhG1n.js} +1 -1
  9. package/assets/{circle-check-DT1Ux51L.js → circle-check-qpBrm1C8.js} +1 -1
  10. package/assets/{confirm-dialog-CIXlJwmO.js → confirm-dialog-ivDrzWwQ.js} +1 -1
  11. package/assets/{download-R6QdKZCO.js → download-DekBnaol.js} +1 -1
  12. package/assets/{filters-sVqTGjIM.js → filters-bXJmsKt1.js} +1 -1
  13. package/assets/{flagged-CoKvDI2R.js → flagged-C2YncaSs.js} +1 -1
  14. package/assets/{folders-CDTrujI2.js → folders-n-VPTunD.js} +1 -1
  15. package/assets/{index-BRWYLOII.js → index-Bh2inDwQ.js} +1 -1
  16. package/assets/{index-DxTf7mJG.js → index-Dqztfk9h.js} +4 -4
  17. package/assets/index-XmQyPKRM.js +1 -0
  18. package/assets/{kbd-BszviWxW.js → kbd-BKV6skNA.js} +1 -1
  19. package/assets/{labels-wYIFrXzO.js → labels-Qgv_Ouxu.js} +1 -1
  20. package/assets/{mail-B1GD7zkK.js → mail-Bhry7m-h.js} +3 -3
  21. package/assets/{move-options-bqfNnf-5.js → move-options-Bwi8g09M.js} +1 -1
  22. package/assets/{onboarding-BlmHjHRm.js → onboarding-BrW9dJRD.js} +1 -1
  23. package/assets/{pencil-BatcrqbL.js → pencil-B71AilUG.js} +1 -1
  24. package/assets/{rich-text-Cch_7nLF.js → rich-text-D1qTHV73.js} +1 -1
  25. package/assets/{senders-CXTCeTh1.js → senders-NnNHQyY5.js} +1 -1
  26. package/assets/settings-D2jPMWeU.js +1 -0
  27. package/assets/{settings-screen-DMiZMh86.js → settings-screen-BbR3IIRi.js} +1 -1
  28. package/assets/{shield-check-Bx44AaEs.js → shield-check-D2LdE9P6.js} +1 -1
  29. package/assets/{suggested-vips-oROGBDZu.js → suggested-vips-CudN8kK1.js} +1 -1
  30. package/assets/{useDebouncedValue-CyeiGvID.js → useDebouncedValue-zwE87nl2.js} +1 -1
  31. package/assets/{useFilters-Cw-yMezD.js → useFilters-Bpjv-7Lu.js} +1 -1
  32. package/assets/{useLabels-B7zuz_GA.js → useLabels-DBk8okj_.js} +1 -1
  33. package/assets/{useSignature-BH3ArXBe.js → useSignature-9qqSUS1h.js} +1 -1
  34. package/index.html +1 -1
  35. package/package.json +1 -1
  36. package/assets/index-D60kRk0L.js +0 -1
  37. package/assets/settings-C_MIWHGc.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/rich-text-Cch_7nLF.js","assets/index-DxTf7mJG.js","assets/index-DZJcX74M.css","assets/confirm-dialog-CIXlJwmO.js","assets/pencil-BatcrqbL.js","assets/avatar-CzdzqSzA.js","assets/kbd-BszviWxW.js","assets/shield-check-Bx44AaEs.js","assets/account-form-helpers-BbRUMYkd.js","assets/useSignature-BH3ArXBe.js","assets/useDebouncedValue-CyeiGvID.js","assets/useFilters-Cw-yMezD.js","assets/ErrorState-K_DfCEXi.js","assets/format-CKZmh-Ru.js","assets/move-options-bqfNnf-5.js","assets/download-R6QdKZCO.js","assets/useLabels-B7zuz_GA.js","assets/circle-check-DT1Ux51L.js"])))=>i.map(i=>d[i]);
2
- import{R as H,c as Uf,r as l,a as $e,j as r,C as Qt,b as Ms,X as Nt,d as W,B as ie,e as kt,S as Xt,f as Dt,g as Pt,L as hs,h as Kf,i as qf,k as tc,l as mn,T as Lt,m as Hf,u as nr,n as Hn,o as sc,I as nc,F as Pa,p as rc,q as La,s as Wf,A as Fa,D as Vf,t as hn,v as Qf,w as rr,O as Gf,M as Yf,x as Xf,y as ac,z as oc,E as ic,G as $a,H as Jf,J as Zf,K as em,N as pn,P as tm,Q as sm,U as nm,V as rm,W as lc,Y as ps,Z as am,_ as cc,$ as om,a0 as im,a1 as lm,a2 as _a,a3 as za,a4 as Kt,a5 as uc,a6 as cm,a7 as Ba,a8 as um,a9 as dm,aa as fm,ab as fa,ac as mm,ad as hm,ae as Te,af as pm,ag as gm,ah as xm,ai as bm,aj as vm,ak as ym,al as si,am as wm,an as Sm,ao as Cm,ap as Ua,aq as dc,ar as fc,as as Jt,at as Qe,au as it,av as Ka,aw as We,ax as ar,ay as Wn,az as Le,aA as Ls,aB as Ft,aC as mc,aD as hc,aE as qa,aF as Ha,aG as Wa,aH as Vn,aI as pc,aJ as ye,aK as Va,aL as gc,aM as ze,aN as km,aO as jm,aP as or,aQ as ir,aR as $t,aS as nt,aT as Nm,aU as Em,aV as ft,aW as xc,aX as ds,aY as lr,aZ as Im,a_ as Rm,a$ as Tm,b0 as cr,b1 as Qa,b2 as Ga,b3 as ur,b4 as Zt,b5 as Mm,b6 as Am,b7 as Om,b8 as Dm,b9 as Pm,ba as ma,bb as Lm,bc,bd as As,be as Ya,bf as Xa,bg as Fm,bh as dr,bi as $m,bj as _m,bk as vc,bl as Ja,bm as zm,bn as ni,bo as Bm,bp as Um,bq as Km,br as qm,bs as qt,bt as ha,bu as Hm,bv as Wm,bw as Vm,bx as yc,by as Qm,bz as Gm,bA as Ym,bB as Xm,bC as ri,bD as Jm,bE as Zm,bF as eh,bG as th,bH as Za,bI as pa,bJ as ga,bK as sh,bL as wc,bM as nh,bN as rh,bO as eo,bP as ah,bQ as oh,bR as ih,bS as lh,bT as ch,bU as uh,bV as dh,bW as fh,bX as Bt,bY as At,bZ as mh}from"./index-DxTf7mJG.js";import{P as hh}from"./pencil-BatcrqbL.js";import{A as jt,M as fr,C as ph}from"./avatar-CzdzqSzA.js";import{K as Is}from"./kbd-BszviWxW.js";import{S as gn,C as to,R as gh}from"./shield-check-Bx44AaEs.js";import{M as Sc,a as xh}from"./account-form-helpers-BbRUMYkd.js";import{R as bh,u as vh}from"./useSignature-BH3ArXBe.js";import{u as mr}from"./useDebouncedValue-CyeiGvID.js";import{D as Cc,B as yh,u as es,a as ai,b as oi,c as wh,d as Sh,e as Ch,n as kh,o as jh,f as Nh,g as Eh,S as Ih}from"./useFilters-Cw-yMezD.js";import{E as ts,f as kc}from"./ErrorState-K_DfCEXi.js";import{f as jc,a as gt,b as Nc,c as Gt,d as Qn,t as Rh}from"./format-CKZmh-Ru.js";import{P as ii,u as so,a as Ec,b as no,f as ro,C as Th,M as ot,D as li}from"./move-options-bqfNnf-5.js";import{D as Mh}from"./download-R6QdKZCO.js";import{u as ao}from"./useLabels-B7zuz_GA.js";import{C as oo}from"./confirm-dialog-CIXlJwmO.js";import{C as Ah}from"./circle-check-DT1Ux51L.js";function on(e){if(Oh())e.focus({preventScroll:!0});else{let t=Dh(e);e.focus(),Ph(t)}}let Nn=null;function Oh(){if(Nn==null){Nn=!1;try{document.createElement("div").focus({get preventScroll(){return Nn=!0,!0}})}catch{}}return Nn}function Dh(e){let t=e.parentNode,s=[],n=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==n;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return n instanceof HTMLElement&&s.push({element:n,scrollTop:n.scrollTop,scrollLeft:n.scrollLeft}),s}function Ph(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const Wt=e=>e?.ownerDocument??document,Yt=e=>e&&"window"in e&&e.window===e?e:Wt(e).defaultView||window;function Lh(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function Fh(e){return Lh(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let $h=!1;function Ic(){return $h}function Ct(e,t){if(!Ic())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:Fh(s)?s=s.host:s=s.parentNode}return!1}function Ze(e){if(Ic()&&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 _h=typeof Element<"u"&&"checkVisibility"in Element.prototype;function zh(e){const t=Yt(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:n}=e.style,a=s!=="none"&&n!=="hidden"&&n!=="collapse";if(a){const{getComputedStyle:o}=Yt(e);let{display:i,visibility:c}=o(e);a=i!=="none"&&c!=="hidden"&&c!=="collapse"}return a}function Bh(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 Rc(e,t){return _h?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&zh(e)&&Bh(e,t)&&(!e.parentElement||Rc(e.parentElement,e))}const Tc=["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"],Uh=Tc.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";Tc.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function Kh(e,t){return e.matches(Uh)&&!qh(e)&&(t?.skipVisibilityCheck||Rc(e))}function qh(e){let t=e;for(;t!=null;){if(t instanceof Yt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const io=typeof document<"u"?H.useLayoutEffect:()=>{};function Hh(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function Wh(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function Vh(e){for(;e&&!Kh(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Yt(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=d=>{(Ze(d)===s||n)&&d.stopImmediatePropagation()},o=d=>{(Ze(d)===s||n)&&(d.stopImmediatePropagation(),!e&&!n&&(n=!0,on(s),u()))},i=d=>{(Ze(d)===e||n)&&d.stopImmediatePropagation()},c=d=>{(Ze(d)===e||n)&&(d.stopImmediatePropagation(),n||(n=!0,on(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",c,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",c,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function hr(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 lo(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function ss(e){let t=null;return()=>(t==null&&(t=e()),t)}const Gn=ss(function(){return lo(/^Mac/i)}),Qh=ss(function(){return lo(/^iPhone/i)}),Mc=ss(function(){return lo(/^iPad/i)||Gn()&&navigator.maxTouchPoints>1}),Ac=ss(function(){return Qh()||Mc()}),Gh=ss(function(){return hr(/AppleWebKit/i)&&!Yh()}),Yh=ss(function(){return hr(/Chrome/i)}),Oc=ss(function(){return hr(/Android/i)}),Xh=ss(function(){return hr(/Firefox/i)});function Jh(e){return e.pointerType===""&&e.isTrusted?!0:Oc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function Zh(e){return!Oc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function ln(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;Xh()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Gn()?n=!0:a=!0);let c=Gh()&&Gn()&&!Mc()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});ln.isOpening=s,on(e),e.dispatchEvent(c),ln.isOpening=!1}ln.isOpening=!1;let Ht=new Map,xa=new Set;function ci(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=Ze(n);if(!e(n)||!a)return;let o=Ht.get(a);o||(o=new Set,Ht.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=Ze(n);if(!e(n)||!a)return;let o=Ht.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Ht.delete(a)),Ht.size===0)){for(let i of xa)i();xa.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?ci():document.addEventListener("DOMContentLoaded",ci));function ep(){for(const[e]of Ht)"isConnected"in e&&!e.isConnected&&Ht.delete(e)}function tp(e){requestAnimationFrame(()=>{ep(),Ht.size===0?e():xa.add(e)})}function Dc(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let ba=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{ba.delete(e)});function sp(e,t){if(e===t)return e;let s=ba.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=ba.get(t);return n?(n.forEach(a=>a.current=e),e):t}function np(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=ui(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():ui(e[o],null)})}}}function ui(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Fs(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let n=e[s];for(let a in n){let o=t[a],i=n[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=Dc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=Uf(o,i):a==="id"&&o&&i?t.id=sp(o,i):a==="ref"&&o&&i?t.ref=np(o,i):t[a]=i!==void 0?i:o}}return t}function rp(e,t){io(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const ap=H.useInsertionEffect??io;function zr(e){const t=l.useRef(null);return ap(()=>{t.current=e},[e]),l.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let Es="default",va="",_n=new WeakMap;function op(e){if(Ac()){if(Es==="default"){const t=Wt(e);va=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}Es="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";_n.set(e,e.style[t]),e.style[t]="none"}}function di(e){if(Ac()){if(Es!=="disabled")return;Es="restoring",setTimeout(()=>{tp(()=>{if(Es==="restoring"){const t=Wt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=va||""),va="",Es="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&_n.has(e)){let t=_n.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),_n.delete(e)}}function fi(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Br=new WeakMap;function ip(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return fi(t);if(Br.has(t))return Br.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof Yt(s).HTMLMetaElement&&(s.nonce||s.content)||fi(t)||void 0;return n!==void 0&&Br.set(t,n),n}const Pc=H.createContext({register:()=>{}});Pc.displayName="PressResponderContext";function Lc(){let e=l.useRef(new Map),t=l.useCallback((a,o,i,c)=>{let u=c?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:c}),a.addEventListener(o,u,c)},[]),s=l.useCallback((a,o,i,c)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,c),e.current.delete(i)},[]),n=l.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return l.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function lp(e){let t=l.useContext(Pc);if(t){let{register:s,ref:n,...a}=t;e=Fs(a,e),s()}return rp(t,e.ref),e}class En{#s;constructor(t,s,n,a){this.#s=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let c,u=0,m,d=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,d=n.clientY),i&&(m!=null&&d!=null?(c=m-i.left,u=d-i.top):(c=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=n.currentTarget,this.shiftKey=n.shiftKey,this.metaKey=n.metaKey,this.ctrlKey=n.ctrlKey,this.altKey=n.altKey,this.x=c,this.y=u,this.key=n.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const mi=Symbol("linkClicked"),hi="react-aria-pressable-style",pi="data-react-aria-pressable";function cp(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:c,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:f,ref:h,...v}=lp(e),[g,p]=l.useState(!1),b=l.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:y,removeAllGlobalListeners:S}=Lc(),x=l.useCallback((j,I)=>{let P=b.current;if(c||P.didFirePressStart)return!1;let R=!0;if(P.isTriggeringEvent=!0,n){let F=new En("pressstart",I,j);n(F),R=F.shouldStopPropagation}return s&&s(!0),P.isTriggeringEvent=!1,P.didFirePressStart=!0,p(!0),R},[c,n,s]),w=l.useCallback((j,I,P=!0)=>{let R=b.current;if(!R.didFirePressStart)return!1;R.didFirePressStart=!1,R.isTriggeringEvent=!0;let F=!0;if(a){let N=new En("pressend",I,j);a(N),F=N.shouldStopPropagation}if(s&&s(!1),p(!1),t&&P&&!c){let N=new En("press",I,j);t(N),F&&=N.shouldStopPropagation}return R.isTriggeringEvent=!1,F},[c,a,s,t]),C=zr(w),T=l.useCallback((j,I)=>{let P=b.current;if(c)return!1;if(o){P.isTriggeringEvent=!0;let R=new En("pressup",I,j);return o(R),P.isTriggeringEvent=!1,R.shouldStopPropagation}return!0},[c,o]),A=zr(T),k=l.useCallback(j=>{let I=b.current;if(I.isPressed&&I.target){I.didFirePressStart&&I.pointerType!=null&&w(os(I.target,j),I.pointerType,!1),I.isPressed=!1,I.isOverTarget=!1,I.activePointerId=null,I.pointerType=null,S(),f||di(I.target);for(let P of I.disposables)P();I.disposables=[]}},[f,S,w]),M=zr(k);l.useEffect(()=>{c&&b.current.isPressed&&M({currentTarget:b.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[c]);let D=l.useCallback(j=>{d&&k(j)},[d,k]),E=l.useCallback(j=>{c||i?.(j)},[c,i]),L=l.useCallback((j,I)=>{if(!c&&i){let P=new MouseEvent("click",j);Wh(P,I),i(Hh(P))}},[c,i]),O=l.useMemo(()=>{let j=b.current,I={onKeyDown(R){if(Ur(R.nativeEvent,R.currentTarget)&&Ct(R.currentTarget,Ze(R))){gi(Ze(R),R.key)&&R.preventDefault();let F=!0;!j.isPressed&&!R.repeat&&(j.target=R.currentTarget,j.isPressed=!0,j.pointerType="keyboard",F=x(R,"keyboard"));let N=R.currentTarget,V=Q=>{Ur(Q,N)&&!Q.repeat&&Ct(N,Ze(Q))&&j.target&&A(os(j.target,Q),"keyboard")};y(Wt(R.currentTarget),"keyup",Dc(V,P),!0),F&&R.stopPropagation(),R.metaKey&&Gn()&&j.metaKeyEvents?.set(R.key,R.nativeEvent)}else R.key==="Meta"&&(j.metaKeyEvents=new Map)},onClick(R){if(!(R&&!Ct(R.currentTarget,Ze(R)))&&R&&R.button===0&&!j.isTriggeringEvent&&!ln.isOpening){let F=!0;if(c&&R.preventDefault(),!j.ignoreEmulatedMouseEvents&&!j.isPressed&&(j.pointerType==="virtual"||Jh(R.nativeEvent))){let N=x(R,"virtual"),V=A(R,"virtual"),Q=C(R,"virtual");E(R),F=N&&V&&Q}else if(j.isPressed&&j.pointerType!=="keyboard"){let N=j.pointerType||R.nativeEvent.pointerType||"virtual",V=A(os(R.currentTarget,R),N),Q=C(os(R.currentTarget,R),N,!0);F=V&&Q,j.isOverTarget=!1,E(R),M(R)}j.ignoreEmulatedMouseEvents=!1,F&&R.stopPropagation()}}},P=R=>{if(j.isPressed&&j.target&&Ur(R,j.target)){gi(Ze(R),R.key)&&R.preventDefault();let F=Ze(R),N=Ct(j.target,F);C(os(j.target,R),"keyboard",N),N&&L(R,j.target),S(),R.key!=="Enter"&&co(j.target)&&Ct(j.target,F)&&!R[mi]&&(R[mi]=!0,ln(j.target,R,!1)),j.isPressed=!1,j.metaKeyEvents?.delete(R.key)}else if(R.key==="Meta"&&j.metaKeyEvents?.size){let F=j.metaKeyEvents;j.metaKeyEvents=void 0;for(let N of F.values())j.target?.dispatchEvent(new KeyboardEvent("keyup",N))}};if(typeof PointerEvent<"u"){I.onPointerDown=N=>{if(N.button!==0||!Ct(N.currentTarget,Ze(N)))return;if(Zh(N.nativeEvent)){j.pointerType="virtual";return}j.pointerType=N.pointerType;let V=!0;if(!j.isPressed){j.isPressed=!0,j.isOverTarget=!0,j.activePointerId=N.pointerId,j.target=N.currentTarget,f||op(j.target),V=x(N,j.pointerType);let Q=Ze(N);"releasePointerCapture"in Q&&("hasPointerCapture"in Q?Q.hasPointerCapture(N.pointerId)&&Q.releasePointerCapture(N.pointerId):Q.releasePointerCapture(N.pointerId)),y(Wt(N.currentTarget),"pointerup",R,!1),y(Wt(N.currentTarget),"pointercancel",F,!1)}V&&N.stopPropagation()},I.onMouseDown=N=>{if(Ct(N.currentTarget,Ze(N))&&N.button===0){if(m){let V=Vh(N.target);V&&j.disposables.push(V)}N.stopPropagation()}},I.onPointerUp=N=>{!Ct(N.currentTarget,Ze(N))||j.pointerType==="virtual"||N.button===0&&!j.isPressed&&A(N,j.pointerType||N.pointerType)},I.onPointerEnter=N=>{N.pointerId===j.activePointerId&&j.target&&!j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!0,x(os(j.target,N),j.pointerType))},I.onPointerLeave=N=>{N.pointerId===j.activePointerId&&j.target&&j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!1,C(os(j.target,N),j.pointerType,!1),D(N))};let R=N=>{if(N.pointerId===j.activePointerId&&j.isPressed&&N.button===0&&j.target){if(Ct(j.target,Ze(N))&&j.pointerType!=null){let V=!1,Q=setTimeout(()=>{j.isPressed&&j.target instanceof HTMLElement&&(V?M(N):(on(j.target),j.target.click()))},80);y(N.currentTarget,"click",()=>V=!0,!0),j.disposables.push(()=>clearTimeout(Q))}else M(N);j.isOverTarget=!1}},F=N=>{M(N)};I.onDragStart=N=>{Ct(N.currentTarget,Ze(N))&&M(N)}}return I},[y,c,m,S,f,D,x,E,L]);return l.useEffect(()=>{if(!h)return;const j=Wt(h.current);if(!j||!j.head||j.getElementById(hi))return;const I=j.createElement("style");I.id=hi;let P=ip(j);P&&(I.nonce=P),I.textContent=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/rich-text-D1qTHV73.js","assets/index-Dqztfk9h.js","assets/index-DZJcX74M.css","assets/confirm-dialog-ivDrzWwQ.js","assets/pencil-B71AilUG.js","assets/avatar-DlxfC_TE.js","assets/kbd-BKV6skNA.js","assets/shield-check-D2LdE9P6.js","assets/account-form-helpers-BCPF7T2c.js","assets/useSignature-9qqSUS1h.js","assets/useDebouncedValue-zwE87nl2.js","assets/useFilters-Bpjv-7Lu.js","assets/ErrorState-D2lY6diG.js","assets/format-CKZmh-Ru.js","assets/move-options-Bwi8g09M.js","assets/download-DekBnaol.js","assets/useLabels-DBk8okj_.js","assets/circle-check-qpBrm1C8.js"])))=>i.map(i=>d[i]);
2
+ import{R as H,c as Uf,r as l,a as $e,j as r,C as Qt,b as Ms,X as Nt,d as W,B as ie,e as kt,S as Xt,f as Dt,g as Pt,L as hs,h as Kf,i as qf,k as tc,l as mn,T as Lt,m as Hf,u as nr,n as Hn,o as sc,I as nc,F as Pa,p as rc,q as La,s as Wf,A as Fa,D as Vf,t as hn,v as Qf,w as rr,O as Gf,M as Yf,x as Xf,y as ac,z as oc,E as ic,G as $a,H as Jf,J as Zf,K as em,N as pn,P as tm,Q as sm,U as nm,V as rm,W as lc,Y as ps,Z as am,_ as cc,$ as om,a0 as im,a1 as lm,a2 as _a,a3 as za,a4 as Kt,a5 as uc,a6 as cm,a7 as Ba,a8 as um,a9 as dm,aa as fm,ab as fa,ac as mm,ad as hm,ae as Te,af as pm,ag as gm,ah as xm,ai as bm,aj as vm,ak as ym,al as si,am as wm,an as Sm,ao as Cm,ap as Ua,aq as dc,ar as fc,as as Jt,at as Qe,au as it,av as Ka,aw as We,ax as ar,ay as Wn,az as Le,aA as Ls,aB as Ft,aC as mc,aD as hc,aE as qa,aF as Ha,aG as Wa,aH as Vn,aI as pc,aJ as ye,aK as Va,aL as gc,aM as ze,aN as km,aO as jm,aP as or,aQ as ir,aR as $t,aS as nt,aT as Nm,aU as Em,aV as ft,aW as xc,aX as ds,aY as lr,aZ as Im,a_ as Rm,a$ as Tm,b0 as cr,b1 as Qa,b2 as Ga,b3 as ur,b4 as Zt,b5 as Mm,b6 as Am,b7 as Om,b8 as Dm,b9 as Pm,ba as ma,bb as Lm,bc,bd as As,be as Ya,bf as Xa,bg as Fm,bh as dr,bi as $m,bj as _m,bk as vc,bl as Ja,bm as zm,bn as ni,bo as Bm,bp as Um,bq as Km,br as qm,bs as qt,bt as ha,bu as Hm,bv as Wm,bw as Vm,bx as yc,by as Qm,bz as Gm,bA as Ym,bB as Xm,bC as ri,bD as Jm,bE as Zm,bF as eh,bG as th,bH as Za,bI as pa,bJ as ga,bK as sh,bL as wc,bM as nh,bN as rh,bO as eo,bP as ah,bQ as oh,bR as ih,bS as lh,bT as ch,bU as uh,bV as dh,bW as fh,bX as Bt,bY as At,bZ as mh}from"./index-Dqztfk9h.js";import{P as hh}from"./pencil-B71AilUG.js";import{A as jt,M as fr,C as ph}from"./avatar-DlxfC_TE.js";import{K as Is}from"./kbd-BKV6skNA.js";import{S as gn,C as to,R as gh}from"./shield-check-D2LdE9P6.js";import{M as Sc,a as xh}from"./account-form-helpers-BCPF7T2c.js";import{R as bh,u as vh}from"./useSignature-9qqSUS1h.js";import{u as mr}from"./useDebouncedValue-zwE87nl2.js";import{D as Cc,B as yh,u as es,a as ai,b as oi,c as wh,d as Sh,e as Ch,n as kh,o as jh,f as Nh,g as Eh,S as Ih}from"./useFilters-Bpjv-7Lu.js";import{E as ts,f as kc}from"./ErrorState-D2lY6diG.js";import{f as jc,a as gt,b as Nc,c as Gt,d as Qn,t as Rh}from"./format-CKZmh-Ru.js";import{P as ii,u as so,a as Ec,b as no,f as ro,C as Th,M as ot,D as li}from"./move-options-Bwi8g09M.js";import{D as Mh}from"./download-DekBnaol.js";import{u as ao}from"./useLabels-DBk8okj_.js";import{C as oo}from"./confirm-dialog-ivDrzWwQ.js";import{C as Ah}from"./circle-check-qpBrm1C8.js";function on(e){if(Oh())e.focus({preventScroll:!0});else{let t=Dh(e);e.focus(),Ph(t)}}let Nn=null;function Oh(){if(Nn==null){Nn=!1;try{document.createElement("div").focus({get preventScroll(){return Nn=!0,!0}})}catch{}}return Nn}function Dh(e){let t=e.parentNode,s=[],n=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==n;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return n instanceof HTMLElement&&s.push({element:n,scrollTop:n.scrollTop,scrollLeft:n.scrollLeft}),s}function Ph(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const Wt=e=>e?.ownerDocument??document,Yt=e=>e&&"window"in e&&e.window===e?e:Wt(e).defaultView||window;function Lh(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function Fh(e){return Lh(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let $h=!1;function Ic(){return $h}function Ct(e,t){if(!Ic())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:Fh(s)?s=s.host:s=s.parentNode}return!1}function Ze(e){if(Ic()&&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 _h=typeof Element<"u"&&"checkVisibility"in Element.prototype;function zh(e){const t=Yt(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:n}=e.style,a=s!=="none"&&n!=="hidden"&&n!=="collapse";if(a){const{getComputedStyle:o}=Yt(e);let{display:i,visibility:c}=o(e);a=i!=="none"&&c!=="hidden"&&c!=="collapse"}return a}function Bh(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 Rc(e,t){return _h?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&zh(e)&&Bh(e,t)&&(!e.parentElement||Rc(e.parentElement,e))}const Tc=["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"],Uh=Tc.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";Tc.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function Kh(e,t){return e.matches(Uh)&&!qh(e)&&(t?.skipVisibilityCheck||Rc(e))}function qh(e){let t=e;for(;t!=null;){if(t instanceof Yt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const io=typeof document<"u"?H.useLayoutEffect:()=>{};function Hh(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function Wh(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function Vh(e){for(;e&&!Kh(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Yt(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=d=>{(Ze(d)===s||n)&&d.stopImmediatePropagation()},o=d=>{(Ze(d)===s||n)&&(d.stopImmediatePropagation(),!e&&!n&&(n=!0,on(s),u()))},i=d=>{(Ze(d)===e||n)&&d.stopImmediatePropagation()},c=d=>{(Ze(d)===e||n)&&(d.stopImmediatePropagation(),n||(n=!0,on(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",c,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",c,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function hr(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 lo(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function ss(e){let t=null;return()=>(t==null&&(t=e()),t)}const Gn=ss(function(){return lo(/^Mac/i)}),Qh=ss(function(){return lo(/^iPhone/i)}),Mc=ss(function(){return lo(/^iPad/i)||Gn()&&navigator.maxTouchPoints>1}),Ac=ss(function(){return Qh()||Mc()}),Gh=ss(function(){return hr(/AppleWebKit/i)&&!Yh()}),Yh=ss(function(){return hr(/Chrome/i)}),Oc=ss(function(){return hr(/Android/i)}),Xh=ss(function(){return hr(/Firefox/i)});function Jh(e){return e.pointerType===""&&e.isTrusted?!0:Oc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function Zh(e){return!Oc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function ln(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;Xh()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Gn()?n=!0:a=!0);let c=Gh()&&Gn()&&!Mc()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});ln.isOpening=s,on(e),e.dispatchEvent(c),ln.isOpening=!1}ln.isOpening=!1;let Ht=new Map,xa=new Set;function ci(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=Ze(n);if(!e(n)||!a)return;let o=Ht.get(a);o||(o=new Set,Ht.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=Ze(n);if(!e(n)||!a)return;let o=Ht.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Ht.delete(a)),Ht.size===0)){for(let i of xa)i();xa.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?ci():document.addEventListener("DOMContentLoaded",ci));function ep(){for(const[e]of Ht)"isConnected"in e&&!e.isConnected&&Ht.delete(e)}function tp(e){requestAnimationFrame(()=>{ep(),Ht.size===0?e():xa.add(e)})}function Dc(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let ba=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{ba.delete(e)});function sp(e,t){if(e===t)return e;let s=ba.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=ba.get(t);return n?(n.forEach(a=>a.current=e),e):t}function np(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=ui(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():ui(e[o],null)})}}}function ui(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Fs(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let n=e[s];for(let a in n){let o=t[a],i=n[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=Dc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=Uf(o,i):a==="id"&&o&&i?t.id=sp(o,i):a==="ref"&&o&&i?t.ref=np(o,i):t[a]=i!==void 0?i:o}}return t}function rp(e,t){io(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const ap=H.useInsertionEffect??io;function zr(e){const t=l.useRef(null);return ap(()=>{t.current=e},[e]),l.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let Es="default",va="",_n=new WeakMap;function op(e){if(Ac()){if(Es==="default"){const t=Wt(e);va=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}Es="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";_n.set(e,e.style[t]),e.style[t]="none"}}function di(e){if(Ac()){if(Es!=="disabled")return;Es="restoring",setTimeout(()=>{tp(()=>{if(Es==="restoring"){const t=Wt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=va||""),va="",Es="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&_n.has(e)){let t=_n.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),_n.delete(e)}}function fi(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Br=new WeakMap;function ip(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return fi(t);if(Br.has(t))return Br.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof Yt(s).HTMLMetaElement&&(s.nonce||s.content)||fi(t)||void 0;return n!==void 0&&Br.set(t,n),n}const Pc=H.createContext({register:()=>{}});Pc.displayName="PressResponderContext";function Lc(){let e=l.useRef(new Map),t=l.useCallback((a,o,i,c)=>{let u=c?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:c}),a.addEventListener(o,u,c)},[]),s=l.useCallback((a,o,i,c)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,c),e.current.delete(i)},[]),n=l.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return l.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function lp(e){let t=l.useContext(Pc);if(t){let{register:s,ref:n,...a}=t;e=Fs(a,e),s()}return rp(t,e.ref),e}class En{#s;constructor(t,s,n,a){this.#s=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let c,u=0,m,d=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,d=n.clientY),i&&(m!=null&&d!=null?(c=m-i.left,u=d-i.top):(c=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=n.currentTarget,this.shiftKey=n.shiftKey,this.metaKey=n.metaKey,this.ctrlKey=n.ctrlKey,this.altKey=n.altKey,this.x=c,this.y=u,this.key=n.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const mi=Symbol("linkClicked"),hi="react-aria-pressable-style",pi="data-react-aria-pressable";function cp(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:c,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:f,ref:h,...v}=lp(e),[g,p]=l.useState(!1),b=l.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:y,removeAllGlobalListeners:S}=Lc(),x=l.useCallback((j,I)=>{let P=b.current;if(c||P.didFirePressStart)return!1;let R=!0;if(P.isTriggeringEvent=!0,n){let F=new En("pressstart",I,j);n(F),R=F.shouldStopPropagation}return s&&s(!0),P.isTriggeringEvent=!1,P.didFirePressStart=!0,p(!0),R},[c,n,s]),w=l.useCallback((j,I,P=!0)=>{let R=b.current;if(!R.didFirePressStart)return!1;R.didFirePressStart=!1,R.isTriggeringEvent=!0;let F=!0;if(a){let N=new En("pressend",I,j);a(N),F=N.shouldStopPropagation}if(s&&s(!1),p(!1),t&&P&&!c){let N=new En("press",I,j);t(N),F&&=N.shouldStopPropagation}return R.isTriggeringEvent=!1,F},[c,a,s,t]),C=zr(w),T=l.useCallback((j,I)=>{let P=b.current;if(c)return!1;if(o){P.isTriggeringEvent=!0;let R=new En("pressup",I,j);return o(R),P.isTriggeringEvent=!1,R.shouldStopPropagation}return!0},[c,o]),A=zr(T),k=l.useCallback(j=>{let I=b.current;if(I.isPressed&&I.target){I.didFirePressStart&&I.pointerType!=null&&w(os(I.target,j),I.pointerType,!1),I.isPressed=!1,I.isOverTarget=!1,I.activePointerId=null,I.pointerType=null,S(),f||di(I.target);for(let P of I.disposables)P();I.disposables=[]}},[f,S,w]),M=zr(k);l.useEffect(()=>{c&&b.current.isPressed&&M({currentTarget:b.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[c]);let D=l.useCallback(j=>{d&&k(j)},[d,k]),E=l.useCallback(j=>{c||i?.(j)},[c,i]),L=l.useCallback((j,I)=>{if(!c&&i){let P=new MouseEvent("click",j);Wh(P,I),i(Hh(P))}},[c,i]),O=l.useMemo(()=>{let j=b.current,I={onKeyDown(R){if(Ur(R.nativeEvent,R.currentTarget)&&Ct(R.currentTarget,Ze(R))){gi(Ze(R),R.key)&&R.preventDefault();let F=!0;!j.isPressed&&!R.repeat&&(j.target=R.currentTarget,j.isPressed=!0,j.pointerType="keyboard",F=x(R,"keyboard"));let N=R.currentTarget,V=Q=>{Ur(Q,N)&&!Q.repeat&&Ct(N,Ze(Q))&&j.target&&A(os(j.target,Q),"keyboard")};y(Wt(R.currentTarget),"keyup",Dc(V,P),!0),F&&R.stopPropagation(),R.metaKey&&Gn()&&j.metaKeyEvents?.set(R.key,R.nativeEvent)}else R.key==="Meta"&&(j.metaKeyEvents=new Map)},onClick(R){if(!(R&&!Ct(R.currentTarget,Ze(R)))&&R&&R.button===0&&!j.isTriggeringEvent&&!ln.isOpening){let F=!0;if(c&&R.preventDefault(),!j.ignoreEmulatedMouseEvents&&!j.isPressed&&(j.pointerType==="virtual"||Jh(R.nativeEvent))){let N=x(R,"virtual"),V=A(R,"virtual"),Q=C(R,"virtual");E(R),F=N&&V&&Q}else if(j.isPressed&&j.pointerType!=="keyboard"){let N=j.pointerType||R.nativeEvent.pointerType||"virtual",V=A(os(R.currentTarget,R),N),Q=C(os(R.currentTarget,R),N,!0);F=V&&Q,j.isOverTarget=!1,E(R),M(R)}j.ignoreEmulatedMouseEvents=!1,F&&R.stopPropagation()}}},P=R=>{if(j.isPressed&&j.target&&Ur(R,j.target)){gi(Ze(R),R.key)&&R.preventDefault();let F=Ze(R),N=Ct(j.target,F);C(os(j.target,R),"keyboard",N),N&&L(R,j.target),S(),R.key!=="Enter"&&co(j.target)&&Ct(j.target,F)&&!R[mi]&&(R[mi]=!0,ln(j.target,R,!1)),j.isPressed=!1,j.metaKeyEvents?.delete(R.key)}else if(R.key==="Meta"&&j.metaKeyEvents?.size){let F=j.metaKeyEvents;j.metaKeyEvents=void 0;for(let N of F.values())j.target?.dispatchEvent(new KeyboardEvent("keyup",N))}};if(typeof PointerEvent<"u"){I.onPointerDown=N=>{if(N.button!==0||!Ct(N.currentTarget,Ze(N)))return;if(Zh(N.nativeEvent)){j.pointerType="virtual";return}j.pointerType=N.pointerType;let V=!0;if(!j.isPressed){j.isPressed=!0,j.isOverTarget=!0,j.activePointerId=N.pointerId,j.target=N.currentTarget,f||op(j.target),V=x(N,j.pointerType);let Q=Ze(N);"releasePointerCapture"in Q&&("hasPointerCapture"in Q?Q.hasPointerCapture(N.pointerId)&&Q.releasePointerCapture(N.pointerId):Q.releasePointerCapture(N.pointerId)),y(Wt(N.currentTarget),"pointerup",R,!1),y(Wt(N.currentTarget),"pointercancel",F,!1)}V&&N.stopPropagation()},I.onMouseDown=N=>{if(Ct(N.currentTarget,Ze(N))&&N.button===0){if(m){let V=Vh(N.target);V&&j.disposables.push(V)}N.stopPropagation()}},I.onPointerUp=N=>{!Ct(N.currentTarget,Ze(N))||j.pointerType==="virtual"||N.button===0&&!j.isPressed&&A(N,j.pointerType||N.pointerType)},I.onPointerEnter=N=>{N.pointerId===j.activePointerId&&j.target&&!j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!0,x(os(j.target,N),j.pointerType))},I.onPointerLeave=N=>{N.pointerId===j.activePointerId&&j.target&&j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!1,C(os(j.target,N),j.pointerType,!1),D(N))};let R=N=>{if(N.pointerId===j.activePointerId&&j.isPressed&&N.button===0&&j.target){if(Ct(j.target,Ze(N))&&j.pointerType!=null){let V=!1,Q=setTimeout(()=>{j.isPressed&&j.target instanceof HTMLElement&&(V?M(N):(on(j.target),j.target.click()))},80);y(N.currentTarget,"click",()=>V=!0,!0),j.disposables.push(()=>clearTimeout(Q))}else M(N);j.isOverTarget=!1}},F=N=>{M(N)};I.onDragStart=N=>{Ct(N.currentTarget,Ze(N))&&M(N)}}return I},[y,c,m,S,f,D,x,E,L]);return l.useEffect(()=>{if(!h)return;const j=Wt(h.current);if(!j||!j.head||j.getElementById(hi))return;const I=j.createElement("style");I.id=hi;let P=ip(j);P&&(I.nonce=P),I.textContent=`
3
3
  @layer {
4
4
  [${pi}] {
5
5
  touch-action: pan-x pan-y pinch-zoom;
@@ -112,7 +112,7 @@ a, a:visited {
112
112
  `)},cl=function(){var e=parseInt(document.body.getAttribute(Ts)||"0",10);return isFinite(e)?e:0},Gv=function(){l.useEffect(function(){return document.body.setAttribute(Ts,(cl()+1).toString()),function(){var e=cl()-1;e<=0?document.body.removeAttribute(Ts):document.body.setAttribute(Ts,e.toString())}},[])},Yv=function(e){var t=e.noRelative,s=e.noImportant,n=e.gapMode,a=n===void 0?"margin":n;Gv();var o=l.useMemo(function(){return Wv(a)},[a]);return l.createElement(Vv,{styles:Qv(o,!t,a,s?"":"!important")})},Ca=!1;if(typeof window<"u")try{var An=Object.defineProperty({},"passive",{get:function(){return Ca=!0,!0}});window.addEventListener("test",An,An),window.removeEventListener("test",An,An)}catch{Ca=!1}var ks=Ca?{passive:!1}:!1,Xv=function(e){return e.tagName==="TEXTAREA"},Au=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!Xv(e)&&s[t]==="visible")},Jv=function(e){return Au(e,"overflowY")},Zv=function(e){return Au(e,"overflowX")},ul=function(e,t){var s=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=Ou(e,n);if(a){var o=Du(e,n),i=o[1],c=o[2];if(i>c)return!0}n=n.parentNode}while(n&&n!==s.body);return!1},ey=function(e){var t=e.scrollTop,s=e.scrollHeight,n=e.clientHeight;return[t,s,n]},ty=function(e){var t=e.scrollLeft,s=e.scrollWidth,n=e.clientWidth;return[t,s,n]},Ou=function(e,t){return e==="v"?Jv(t):Zv(t)},Du=function(e,t){return e==="v"?ey(t):ty(t)},sy=function(e,t){return e==="h"&&t==="rtl"?-1:1},ny=function(e,t,s,n,a){var o=sy(e,window.getComputedStyle(t).direction),i=o*n,c=s.target,u=t.contains(c),m=!1,d=i>0,f=0,h=0;do{if(!c)break;var v=Du(e,c),g=v[0],p=v[1],b=v[2],y=p-b-o*g;(g||y)&&Ou(e,c)&&(f+=y,h+=g);var S=c.parentNode;c=S&&S.nodeType===Node.DOCUMENT_FRAGMENT_NODE?S.host:S}while(!u&&c!==document.body||u&&(t.contains(c)||t===c));return(d&&Math.abs(f)<1||!d&&Math.abs(h)<1)&&(m=!0),m},On=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},dl=function(e){return[e.deltaX,e.deltaY]},fl=function(e){return e&&"current"in e?e.current:e},ry=function(e,t){return e[0]===t[0]&&e[1]===t[1]},ay=function(e){return`
113
113
  .block-interactivity-`.concat(e,` {pointer-events: none;}
114
114
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
115
- `)},oy=0,js=[];function iy(e){var t=l.useRef([]),s=l.useRef([0,0]),n=l.useRef(),a=l.useState(oy++)[0],o=l.useState(Mu)[0],i=l.useRef(e);l.useEffect(function(){i.current=e},[e]),l.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=cm([e.lockRef.current],(e.shards||[]).map(fl),!0).filter(Boolean);return p.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var c=l.useCallback(function(p,b){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var y=On(p),S=s.current,x="deltaX"in p?p.deltaX:S[0]-y[0],w="deltaY"in p?p.deltaY:S[1]-y[1],C,T=p.target,A=Math.abs(x)>Math.abs(w)?"h":"v";if("touches"in p&&A==="h"&&T.type==="range")return!1;var k=window.getSelection(),M=k&&k.anchorNode,D=M?M===T||M.contains(T):!1;if(D)return!1;var E=ul(A,T);if(!E)return!0;if(E?C=A:(C=A==="v"?"h":"v",E=ul(A,T)),!E)return!1;if(!n.current&&"changedTouches"in p&&(x||w)&&(n.current=C),!C)return!0;var L=n.current||C;return ny(L,b,p,L==="h"?x:w)},[]),u=l.useCallback(function(p){var b=p;if(!(!js.length||js[js.length-1]!==o)){var y="deltaY"in b?dl(b):On(b),S=t.current.filter(function(C){return C.name===b.type&&(C.target===b.target||b.target===C.shadowParent)&&ry(C.delta,y)})[0];if(S&&S.should){b.cancelable&&b.preventDefault();return}if(!S){var x=(i.current.shards||[]).map(fl).filter(Boolean).filter(function(C){return C.contains(b.target)}),w=x.length>0?c(b,x[0]):!i.current.noIsolation;w&&b.cancelable&&b.preventDefault()}}},[]),m=l.useCallback(function(p,b,y,S){var x={name:p,delta:b,target:y,should:S,shadowParent:ly(y)};t.current.push(x),setTimeout(function(){t.current=t.current.filter(function(w){return w!==x})},1)},[]),d=l.useCallback(function(p){s.current=On(p),n.current=void 0},[]),f=l.useCallback(function(p){m(p.type,dl(p),p.target,c(p,e.lockRef.current))},[]),h=l.useCallback(function(p){m(p.type,On(p),p.target,c(p,e.lockRef.current))},[]);l.useEffect(function(){return js.push(o),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",u,ks),document.addEventListener("touchmove",u,ks),document.addEventListener("touchstart",d,ks),function(){js=js.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,ks),document.removeEventListener("touchmove",u,ks),document.removeEventListener("touchstart",d,ks)}},[]);var v=e.removeScrollBar,g=e.inert;return l.createElement(l.Fragment,null,g?l.createElement(o,{styles:ay(a)}):null,v?l.createElement(Yv,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function ly(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const cy=Fv(Tu,iy);var Pu=l.forwardRef(function(e,t){return l.createElement(wr,Kt({},e,{ref:t,sideCar:cy}))});Pu.classNames=wr.classNames;var uy=class extends Ba{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,n=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:c}=n,u=s.fetchMeta?.fetchMore?.direction,m=i&&u==="forward",d=a&&u==="forward",f=i&&u==="backward",h=a&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:dm(t,s.data),hasPreviousPage:um(t,s.data),isFetchNextPageError:m,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:c&&!m&&!f,isRefetching:o&&!d&&!h}}};function ml(e,t){const s=new Set(t);return e.filter(n=>!s.has(n))}function dy(e,t,s){const n=e.slice(0);return n[t]=s,n}var fy=class extends fm{#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,fa.batch(()=>{const s=this.#t,n=this.#f(this.#a);n.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=n.map(d=>d.observer),o=a.map(d=>d.getCurrentResult()),i=s.length!==a.length,c=a.some((d,f)=>d!==s[f]),u=i||c,m=u?!0:o.some((d,f)=>{const h=this.#e[f];return!h||!mm(d,h)});!u&&!m||(u&&(this.#c=n,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(ml(s,a).forEach(d=>{d.destroy()}),ml(a,s).forEach(d=>{d.subscribe(f=>{this.#m(d,f)})})),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),n=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[n,o=>this.#d(o??n,t,a),()=>this.#u(n,s)]}#u(e,t){return t.map((s,n)=>{const a=e[n];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const n=this.#l,a=s!==void 0&&n!==void 0&&(n.length!==s.length||s.some((o,i)=>o!==n[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=hm(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(n=>{const a=n.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(n):t.set(a,[n])});const s=[];return e.forEach(n=>{const a=this.#s.defaultQueryOptions(n),i=t.get(a.queryHash)?.shift()??new Ba(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=dy(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,n=t?s:this.#d(e,this.#r?.combine);(t||s!==n)&&fa.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function mt({queries:e,...t},s){const n=Te(),a=pm(),o=gm(),i=l.useMemo(()=>e.map(p=>{const b=n.defaultQueryOptions(p);return b._optimisticResults=a?"isRestoring":"optimistic",b}),[e,n,a]);i.forEach(p=>{xm(p);const b=n.getQueryCache().get(p.queryHash);bm(p,o,b)}),vm(o);const[c]=l.useState(()=>new fy(n,i,t)),[u,m,d]=c.getOptimisticResult(i,t.combine),f=!a&&t.subscribed!==!1;l.useSyncExternalStore(l.useCallback(p=>f?c.subscribe(fa.batchCalls(p)):ym,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),l.useEffect(()=>{c.setQueries(i,t)},[i,t,c]);const v=u.some((p,b)=>si(i[b],p))?u.flatMap((p,b)=>{const y=i[b];if(y&&si(y,p)){const S=new Ba(n,y);return wm(y,S,o)}return[]}):[];if(v.length>0)throw Promise.all(v);const g=u.find((p,b)=>{const y=i[b];return y&&Sm({result:p,errorResetBoundary:o,throwOnError:y.throwOnError,query:n.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(g?.error)throw g.error;return m(d())}function Lu(e,t){return Cm(e,uy)}function my(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),n=e.blockerFn;return{shouldBlockFn:async()=>s&&n!==void 0?await n():s,enableBeforeUnload:s,withResolver:n===void 0}}function Fu(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:a=!1,withResolver:o=!1}=my(e),i=Ua(),{history:c}=i,[u,m]=l.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return l.useEffect(()=>{const d=async f=>{function h(y){const S=i.parseLocation(y),x=i.getMatchedRoutes(S.pathname);return x.foundRoute===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:x.routeParams,search:i.options.parseSearch(y.search)}:{routeId:x.foundRoute.id,fullPath:x.foundRoute.fullPath,pathname:S.pathname,params:x.routeParams,search:i.options.parseSearch(y.search)}}const v=h(f.currentLocation),g=h(f.nextLocation);if(v.routeId==="__notFound__"&&g.routeId!=="__notFound__")return!1;const p=await s({action:f.action,current:v,next:g});if(!o)return p;if(!p)return!1;const b=await new Promise(y=>{m({status:"blocked",current:v,next:g,action:f.action,proceed:()=>y(!1),reset:()=>y(!0)})});return m({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),b};return a?void 0:c.block({blockerFn:d,enableBeforeUnload:n})},[s,n,a,o,c,i]),u}function Ot(e){const t=Ua({warn:e?.router===void 0}),s=e?.router||t;return dc(s.stores.__store,fc(e,s))}function Sr(e){const t=Ua();return dc(t.stores.location,fc(e,t))}const hy=new Set(["outbox","flagged"]),py=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!hy.has(s)};function gy(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,n]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Ka(n.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function $u(e){const{openCompose:t}=Jt(),s=Qe(),n=Sr(),a=gy(e);return l.useCallback(()=>{if(py(n.pathname)){l.startTransition(()=>{t({mode:"new"})});return}a&&(l.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,n.pathname,a])}const xy=e=>e.startsWith("/mail")||e.startsWith("/settings"),by=({accounts:e})=>{const{state:t}=Jt(),s=Sr(),n=$u(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!xy(s.pathname)||t.isOpen||o?null:r.jsx("button",{type:"button",onClick:n,"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:r.jsx(hh,{className:"size-6"})})},_u=({trigger:e,children:t,align:s="right"})=>{const[n,a]=l.useState(!1),o=l.useRef(null),i=l.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),c=l.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return l.useEffect(()=>(n&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",c)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",c)}),[n,i,c]),r.jsxs("div",{ref:o,className:"relative",children:[r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!n)},className:We("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}),n&&r.jsx("div",{className:We("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})]})},nn=({onClick:e,disabled:t,destructive:s,children:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:We("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:n}),zu=()=>r.jsx("div",{className:"my-1 h-px bg-line"}),Bu=({children:e})=>{const{Account:t}=ar();return r.jsx(t,{children:e})},vy=({email:e,onSignOut:t})=>{const s=e??"Account";return r.jsxs(_u,{trigger:r.jsx(jt,{name:s,email:e??void 0,size:"sm"}),align:"right",children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),r.jsx(zu,{})]}),r.jsxs(nn,{onClick:t,children:[r.jsx(Kc,{className:"size-4"}),"Sign out"]})]})},yy=()=>r.jsx(Bu,{children:({email:e,signOut:t})=>r.jsx(vy,{email:e,onSignOut:t})}),wy=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function jo(e){return!!e&&wy.has(e)}const Uu=3e3,Sy=Uu*2,hl={syncing:!1,resolved:!1,synced:0,total:0};function Cy(e,t){const s=e.join(","),[n,a]=l.useState(!1),[o,i]=l.useState(!1);l.useEffect(()=>{a(!1),i(!1)},[s,t]),l.useEffect(()=>{if(!t)return;const g=setTimeout(()=>i(!0),Sy);return()=>clearTimeout(g)},[s,t]);const c=mt({queries:e.map(g=>({...Wn({path:{accountId:g}}),enabled:t&&!n,refetchInterval:Uu,meta:{softError:!0}}))}),u=c.every(g=>g.isSuccess||g.isError),m=c.length===0||u||o;let d=!1,f=0,h=0;for(const g of c)if(jo(g.data?.syncPhase)){d=!0;for(const p of g.data?.mailboxes??[])f+=p.messagesSynced,h+=p.messagesTotal}const v=t&&m&&!d;return l.useEffect(()=>{v&&a(!0)},[v]),!t||!m?hl:{syncing:d,resolved:!0,synced:f,total:h}}const pl=6e4,ky=new Set(["sent","drafts","trash","archive"]),gl=(e,t)=>{const s=new Map;for(const n of e){const a=t.get(n.mailboxId)?.role;a&&ky.has(a)||s.set(n.mailboxId,n.messagesTotal)}return s},jy=(e,t)=>{for(const[s,n]of t)if(n>(e.get(s)??0))return!0;return!1},Ku=l.createContext(null),Cr=()=>{const e=l.useContext(Ku);if(!e)throw new Error("useMailFreshness must be used inside <MailFreshnessProvider>");return e};function Ny({accountIds:e,children:t}){const s=Te(),{resultFolderIndex:n}=Le(),a=l.useRef(new Map),o=l.useRef(new Set),[i,c]=l.useState(new Set),u=mt({queries:e.map(g=>({...Wn({path:{accountId:g}}),refetchInterval:pl,staleTime:pl,meta:{softError:!0}}))}),m=u.map(g=>g.dataUpdatedAt).join(","),d=e.join(",");l.useEffect(()=>{let g=!1;const p=new Set(i);e.forEach((b,y)=>{const S=u[y]?.data;if(!S)return;const x=gl(S.mailboxes??[],n);if(!o.current.has(b)){o.current.add(b),a.current.set(b,x);return}if(p.has(b))return;const w=a.current.get(b)??new Map;jy(w,x)&&(p.add(b),g=!0)}),g&&c(p)},[d,m]);const f=l.useCallback(g=>g.some(p=>i.has(p)),[i]),h=l.useCallback(g=>{c(p=>{if(g.every(y=>!p.has(y)))return p;const b=new Set(p);for(const y of g)b.delete(y);return b});for(const p of g){const b=s.getQueryData(Wn({path:{accountId:p}}).queryKey);a.current.set(p,gl(b?.mailboxes??[],n)),o.current.add(p)}},[s,n]),v=l.useMemo(()=>({hasNewMail:f,acknowledge:h}),[f,h]);return r.jsx(Ku.Provider,{value:v,children:t})}const Ey=2e3,Iy=45e3,Ry=e=>new Promise(t=>setTimeout(t,e)),ka=e=>e instanceof Error&&e.message?e.message:"Something went wrong",Ty=e=>{hc(e,{softError:!0})&&qa(e)},qu=e=>e.reduce((t,s)=>Math.max(t,s.lastSyncedAt??0),0),Hu=(e,t)=>e.fetchQuery({...Wn({path:{accountId:t}}),staleTime:0}),My=async(e,t,s,n)=>{let a=!1;for(;;){const o=await Hu(e,t).then(u=>({ok:!0,data:u})).catch(u=>({ok:!1,error:u}));if(!o.ok)return{accountId:t,message:ka(o.error)};const{syncPhase:i,mailboxes:c}=o.data;if(jo(i))a=!0;else if(a||qu(c??[])>s)return i==="error"?{accountId:t,message:"Sync failed for this account"}:void 0;if(Date.now()>=n)return{accountId:t,message:"Refresh is taking longer than usual"};await Ry(Ey)}},Ay=async(e,t,s,n)=>{const a=await Hu(e,s).then(c=>({ok:!0,maxLastSynced:qu(c.mailboxes??[])})).catch(c=>({ok:!1,error:c}));if(!a.ok)return{accountId:s,enqueued:!1,ok:!1,message:ka(a.error)};const o=await mc({path:{accountId:s},throwOnError:!0}).then(()=>({ok:!0})).catch(c=>({ok:!1,error:c}));if(!o.ok)return Ty(o.error),{accountId:s,enqueued:!1,ok:!1,message:ka(o.error)};t.recordEvent("sync.triggered");const i=await My(e,s,a.maxLastSynced,n);return i?{accountId:s,enqueued:!0,ok:!1,message:i.message}:{accountId:s,enqueued:!0,ok:!0}},No=(e,t={})=>{const s=Te(),n=Ls(),{acknowledge:a}=Cr(),[o,i]=l.useState("idle"),[c,u]=l.useState(),m=l.useRef(0),d=l.useRef(e);d.current=e;const f=l.useRef(t);f.current=t,l.useEffect(()=>{if(o!=="success")return;const v=setTimeout(()=>i("idle"),2e3);return()=>clearTimeout(v)},[o]);const h=l.useCallback(()=>{const v=d.current;if(v.length===0){i("error"),u("Nothing to refresh yet");return}const g=++m.current;i("refreshing"),u(void 0),(async()=>{const p=Date.now()+Iy,b=await Promise.all(v.map(x=>Ay(s,n,x,p)));if(m.current!==g)return;const y=b.filter(x=>x.enqueued).map(x=>x.accountId);for(const x of y)s.invalidateQueries({queryKey:Ft({path:{accountId:x}})});y.length>0&&(f.current.onSettled?.(),a(y));const S=b.filter(x=>!x.ok);S.length===0?i("success"):(i("error"),u(S[0]?.message))})()},[a,s,n]);return{state:o,errorMessage:c,refresh:h}},Wu="/mail/",Eo="/mail/$mailboxId",Vu="/mail/outbox",Qu="/mail/flagged";function Io(e){return e.some(t=>t.routeId===Wu)}function xn(e){return e.some(t=>t.routeId===Qu)}function kr(e){return e.some(t=>t.routeId===Vu)}function Gu(e){return e.some(t=>t.routeId===Eo)}function Oy(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Eo}:${t}`:xn(e)?Qu:kr(e)?Vu:Io(e)?Wu:""}const Un="search-scope";function Dy(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function Yu(e){return xn(e)||kr(e)||Gu(e)}function Xu(e){return e.find(t=>t.routeId===Eo)?.params?.mailboxId}function Py(e){const t=Xu(e.matches);return t||(Yu(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function Ly(e,t){return Io(e)?{kind:"global"}:xn(e)?{kind:"scoped",chip:{id:Un,label:"is:starred"}}:kr(e)?{kind:"scoped",chip:{id:Un,label:"in:outbox"}}:Gu(e)?t?{kind:"scoped",chip:{id:Un,label:Dy(t)}}:{kind:"pending"}:{kind:"global"}}function Fy(e,t,s){return t.kind==="global"?{kind:"global"}:xn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const Ju=({accounts:e})=>{const t=Ha({strict:!1}),s=Sr(),n=t.mailboxId,{t:a}=Wa("mail",{useSuspense:!1}),o=l.useCallback((c,u)=>a(c,{defaultValue:u}),[a]),i=mt({queries:e.map(c=>({...it({path:{accountId:c.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!n)return null;for(let c=0;c<e.length;c++){const u=i[c]?.data?.items;if(!u)continue;const m=u.find(f=>f.mailboxId===n);if(!m)continue;const d=Ka(e[c].folderAppointments);return Vn(m,d.get(n),o)}return null},$y=({accounts:e})=>{const s=Ha({strict:!1}).mailboxId,n=mt({queries:e.map(a=>({...it({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of n){const o=a.data?.items;if(!o)continue;const i=o.find(c=>c.mailboxId===s);if(i)return i.unseenCount}return null};function Zu(e){const t=Qe(),{searchInput:s}=Le(),n=Ju({accounts:e}),a=Ot({select:c=>c.matches}),o=Ly(a,n),i=l.useCallback(c=>{c===Un&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}function _y({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:n,onSearchClearQuery:a}=Le(),o=Qe(),i=$u(e),{scope:c,clearScope:u}=Zu(e),m=c.kind==="scoped"?[{id:c.chip.id,label:c.chip.label,tone:"scope"}]:void 0,d=l.useMemo(()=>e.map(p=>p.accountId),[e]),{hasNewMail:f}=Cr(),{state:h,errorMessage:v,refresh:g}=No(d);return r.jsx(Gx,{search:{value:t,scope:c.kind,chips:m,onChange:s,onClear:n,onClearQuery:a,onRemoveChip:u},onCompose:i,onReportBug:pc,onOpenSettings:()=>o({to:"/settings/accounts"}),composeShortcut:Gc("compose"),refreshControl:r.jsx(yo,{state:h,onRefresh:g,label:"Refresh all accounts",errorMessage:v,hasUpdate:f(d)}),account:r.jsx(yy,{})})}const Ro=({isOpen:e,onClose:t,children:s,ariaLabel:n="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=l.useRef(null),c=l.useRef(null);if(l.useEffect(()=>{if(!e)return;c.current=document.activeElement;const m=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",m),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=f,c.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 r.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":n,children:[r.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"}),r.jsxs("div",{ref:i,className:We("safe-area-frame absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[r.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:r.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:r.jsx(Nt,{className:"size-5"})})}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},zy=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 n=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return n?{kind:"text",contentUrl:n.contentUrl}:null},ja={all:["messages"],detail:e=>[...ja.all,"detail",e],body:e=>[...ja.detail(e),"body"]};class cs extends Error{reason;status;retryAfterSeconds;constructor(t,s,n,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=n,this.retryAfterSeconds=a}}const By=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},Uy=8,Ky="x-remit-403-reason",ed=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},qy=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,Hy=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},Wy=async(e,t,s=async()=>null)=>{const n={},a=await s();a&&(n.Authorization=`Bearer ${a}`);const o=await gc(e,{headers:n});if(o.status===202)throw new cs("not-ready","Message body is still syncing",202,By(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(Ky),m=ed(o.status,u);throw new cs(m,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(Hy(t,i))throw new cs("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const c=await o.text();if(qy(c,i))throw new cs("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return c},Vy=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),td=({messageId:e,bodyParts:t,enabled:s=!0})=>{const n=t?zy(t):null,a=Ls(),{getToken:o}=ar(),i=l.useRef(null),c=Te(),u=l.useRef(!1),m=l.useRef(null),d=e&&n?`${e}:${n.contentUrl}`:null;m.current!==d&&(m.current=d,u.current=!1);const f=ye({queryKey:e?[...ja.body(e),n?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!n)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const g=u.current;return u.current=!1,Vy({fetchContent:(p,b)=>Wy(p,b,o),refetchDescribeMessage:()=>c.refetchQueries({queryKey:Va({path:{messageId:e}})})},{contentUrl:n.contentUrl,kind:n.kind,isRetryAfterNotReady:g})},enabled:s&&!!e&&!!n,staleTime:300*1e3,gcTime:1800*1e3,retry:(g,p)=>p instanceof cs&&p.reason==="not-ready"?g<Uy:g<1,retryDelay:(g,p)=>p instanceof cs&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=f.isLoading&&!!n;l.useEffect(()=>{h&&(i.current=performance.now())},[h]),l.useEffect(()=>{f.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[f.isSuccess,a]);const v=f.data&&n?{kind:n.kind,body:f.data}:void 0;return{picked:n,data:v,isLoading:h,isError:f.isError,error:f.error,refetch:f.refetch}},Qy=e=>e.then(()=>{},()=>{}),Gy=({outboxMessageId:e,onDraftCreated:t})=>{const[s,n]=l.useState("idle"),[a,o]=l.useState(null),i=l.useRef(void 0),c=l.useRef(new Set),u=Te(),m=l.useRef(e),d=l.useRef(e);m.current!==e&&(m.current=e,d.current=e);const f=ze(km()),h=ze(jm()),v=l.useCallback(async x=>{n("saving"),o(null);const w=d.current;if(w){const T=await h.mutateAsync({path:{outboxMessageId:w},body:{toAddresses:x.toAddresses,ccAddresses:x.ccAddresses,bccAddresses:x.bccAddresses,subject:x.subject,textBody:x.textBody,htmlBody:x.htmlBody,inReplyTo:x.inReplyTo,references:x.references}});return n("saved"),T}const C=await f.mutateAsync({body:{...x,sendImmediately:!1}});return d.current=C.outboxMessageId,t(C.outboxMessageId),n("saved"),u.invalidateQueries({queryKey:or().queryKey}),C},[f,h,t,u]),g=l.useRef(Promise.resolve()),p=l.useCallback(x=>{const w=g.current.then(()=>v(x));return g.current=Qy(w),w},[v]),b=l.useCallback(x=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{const w=d.current;w&&c.current.has(w)||p(x).catch(C=>{o(C),n("error")})},2e3)},[p]),y=l.useCallback(x=>(i.current&&clearTimeout(i.current),p(x).then(w=>({outcome:"saved",outboxMessageId:w.outboxMessageId})).catch(w=>(n("error"),{outcome:"failed",error:w}))),[p]),S=l.useCallback(x=>{i.current&&clearTimeout(i.current),x&&c.current.add(x)},[]);return{saveStatus:s,saveError:a,saveDraft:b,saveImmediately:y,stopAutoSave:S}},ta=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=l.useState(""),i=mr(a,200),{data:c}=ye({...ir({query:{q:i,limit:8}}),enabled:i.length>=2}),u=l.useMemo(()=>(c?.items??[]).map(m=>({email:m.normalizedEmail,displayName:m.displayName})),[c]);return r.jsx(lx,{label:e,addresses:t,onChange:s,placeholder:n,suggestions:u,onQueryChange:o})},Yy=({accountId:e})=>{const t=Qe();return r.jsx(fx,{onConfigure:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})}})},xl=150,Xy=()=>{const[e,t]=l.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>xl}});return l.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>xl})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},Jy=({selectedAccountId:e,onSelect:t})=>{const{data:s}=ye({...$t(),staleTime:1/0}),n=s?.accounts??[];if(l.useEffect(()=>{!e&&n.length===1&&n[0]&&t(n[0])},[e,n,t]),n.length<=1){const a=n[0];return a?r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=n.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:n.map(a=>r.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},Zy=l.lazy(()=>Tm(()=>import("./rich-text-Cch_7nLF.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}))),e0=()=>r.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[r.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),r.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),t0=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),s0=e=>e.split(`
115
+ `)},oy=0,js=[];function iy(e){var t=l.useRef([]),s=l.useRef([0,0]),n=l.useRef(),a=l.useState(oy++)[0],o=l.useState(Mu)[0],i=l.useRef(e);l.useEffect(function(){i.current=e},[e]),l.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=cm([e.lockRef.current],(e.shards||[]).map(fl),!0).filter(Boolean);return p.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var c=l.useCallback(function(p,b){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var y=On(p),S=s.current,x="deltaX"in p?p.deltaX:S[0]-y[0],w="deltaY"in p?p.deltaY:S[1]-y[1],C,T=p.target,A=Math.abs(x)>Math.abs(w)?"h":"v";if("touches"in p&&A==="h"&&T.type==="range")return!1;var k=window.getSelection(),M=k&&k.anchorNode,D=M?M===T||M.contains(T):!1;if(D)return!1;var E=ul(A,T);if(!E)return!0;if(E?C=A:(C=A==="v"?"h":"v",E=ul(A,T)),!E)return!1;if(!n.current&&"changedTouches"in p&&(x||w)&&(n.current=C),!C)return!0;var L=n.current||C;return ny(L,b,p,L==="h"?x:w)},[]),u=l.useCallback(function(p){var b=p;if(!(!js.length||js[js.length-1]!==o)){var y="deltaY"in b?dl(b):On(b),S=t.current.filter(function(C){return C.name===b.type&&(C.target===b.target||b.target===C.shadowParent)&&ry(C.delta,y)})[0];if(S&&S.should){b.cancelable&&b.preventDefault();return}if(!S){var x=(i.current.shards||[]).map(fl).filter(Boolean).filter(function(C){return C.contains(b.target)}),w=x.length>0?c(b,x[0]):!i.current.noIsolation;w&&b.cancelable&&b.preventDefault()}}},[]),m=l.useCallback(function(p,b,y,S){var x={name:p,delta:b,target:y,should:S,shadowParent:ly(y)};t.current.push(x),setTimeout(function(){t.current=t.current.filter(function(w){return w!==x})},1)},[]),d=l.useCallback(function(p){s.current=On(p),n.current=void 0},[]),f=l.useCallback(function(p){m(p.type,dl(p),p.target,c(p,e.lockRef.current))},[]),h=l.useCallback(function(p){m(p.type,On(p),p.target,c(p,e.lockRef.current))},[]);l.useEffect(function(){return js.push(o),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",u,ks),document.addEventListener("touchmove",u,ks),document.addEventListener("touchstart",d,ks),function(){js=js.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,ks),document.removeEventListener("touchmove",u,ks),document.removeEventListener("touchstart",d,ks)}},[]);var v=e.removeScrollBar,g=e.inert;return l.createElement(l.Fragment,null,g?l.createElement(o,{styles:ay(a)}):null,v?l.createElement(Yv,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function ly(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const cy=Fv(Tu,iy);var Pu=l.forwardRef(function(e,t){return l.createElement(wr,Kt({},e,{ref:t,sideCar:cy}))});Pu.classNames=wr.classNames;var uy=class extends Ba{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,n=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:c}=n,u=s.fetchMeta?.fetchMore?.direction,m=i&&u==="forward",d=a&&u==="forward",f=i&&u==="backward",h=a&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:dm(t,s.data),hasPreviousPage:um(t,s.data),isFetchNextPageError:m,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:c&&!m&&!f,isRefetching:o&&!d&&!h}}};function ml(e,t){const s=new Set(t);return e.filter(n=>!s.has(n))}function dy(e,t,s){const n=e.slice(0);return n[t]=s,n}var fy=class extends fm{#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,fa.batch(()=>{const s=this.#t,n=this.#f(this.#a);n.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=n.map(d=>d.observer),o=a.map(d=>d.getCurrentResult()),i=s.length!==a.length,c=a.some((d,f)=>d!==s[f]),u=i||c,m=u?!0:o.some((d,f)=>{const h=this.#e[f];return!h||!mm(d,h)});!u&&!m||(u&&(this.#c=n,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(ml(s,a).forEach(d=>{d.destroy()}),ml(a,s).forEach(d=>{d.subscribe(f=>{this.#m(d,f)})})),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),n=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[n,o=>this.#d(o??n,t,a),()=>this.#u(n,s)]}#u(e,t){return t.map((s,n)=>{const a=e[n];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const n=this.#l,a=s!==void 0&&n!==void 0&&(n.length!==s.length||s.some((o,i)=>o!==n[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=hm(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(n=>{const a=n.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(n):t.set(a,[n])});const s=[];return e.forEach(n=>{const a=this.#s.defaultQueryOptions(n),i=t.get(a.queryHash)?.shift()??new Ba(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=dy(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,n=t?s:this.#d(e,this.#r?.combine);(t||s!==n)&&fa.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function mt({queries:e,...t},s){const n=Te(),a=pm(),o=gm(),i=l.useMemo(()=>e.map(p=>{const b=n.defaultQueryOptions(p);return b._optimisticResults=a?"isRestoring":"optimistic",b}),[e,n,a]);i.forEach(p=>{xm(p);const b=n.getQueryCache().get(p.queryHash);bm(p,o,b)}),vm(o);const[c]=l.useState(()=>new fy(n,i,t)),[u,m,d]=c.getOptimisticResult(i,t.combine),f=!a&&t.subscribed!==!1;l.useSyncExternalStore(l.useCallback(p=>f?c.subscribe(fa.batchCalls(p)):ym,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),l.useEffect(()=>{c.setQueries(i,t)},[i,t,c]);const v=u.some((p,b)=>si(i[b],p))?u.flatMap((p,b)=>{const y=i[b];if(y&&si(y,p)){const S=new Ba(n,y);return wm(y,S,o)}return[]}):[];if(v.length>0)throw Promise.all(v);const g=u.find((p,b)=>{const y=i[b];return y&&Sm({result:p,errorResetBoundary:o,throwOnError:y.throwOnError,query:n.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(g?.error)throw g.error;return m(d())}function Lu(e,t){return Cm(e,uy)}function my(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),n=e.blockerFn;return{shouldBlockFn:async()=>s&&n!==void 0?await n():s,enableBeforeUnload:s,withResolver:n===void 0}}function Fu(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:a=!1,withResolver:o=!1}=my(e),i=Ua(),{history:c}=i,[u,m]=l.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return l.useEffect(()=>{const d=async f=>{function h(y){const S=i.parseLocation(y),x=i.getMatchedRoutes(S.pathname);return x.foundRoute===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:x.routeParams,search:i.options.parseSearch(y.search)}:{routeId:x.foundRoute.id,fullPath:x.foundRoute.fullPath,pathname:S.pathname,params:x.routeParams,search:i.options.parseSearch(y.search)}}const v=h(f.currentLocation),g=h(f.nextLocation);if(v.routeId==="__notFound__"&&g.routeId!=="__notFound__")return!1;const p=await s({action:f.action,current:v,next:g});if(!o)return p;if(!p)return!1;const b=await new Promise(y=>{m({status:"blocked",current:v,next:g,action:f.action,proceed:()=>y(!1),reset:()=>y(!0)})});return m({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),b};return a?void 0:c.block({blockerFn:d,enableBeforeUnload:n})},[s,n,a,o,c,i]),u}function Ot(e){const t=Ua({warn:e?.router===void 0}),s=e?.router||t;return dc(s.stores.__store,fc(e,s))}function Sr(e){const t=Ua();return dc(t.stores.location,fc(e,t))}const hy=new Set(["outbox","flagged"]),py=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!hy.has(s)};function gy(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,n]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Ka(n.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function $u(e){const{openCompose:t}=Jt(),s=Qe(),n=Sr(),a=gy(e);return l.useCallback(()=>{if(py(n.pathname)){l.startTransition(()=>{t({mode:"new"})});return}a&&(l.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,n.pathname,a])}const xy=e=>e.startsWith("/mail")||e.startsWith("/settings"),by=({accounts:e})=>{const{state:t}=Jt(),s=Sr(),n=$u(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!xy(s.pathname)||t.isOpen||o?null:r.jsx("button",{type:"button",onClick:n,"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:r.jsx(hh,{className:"size-6"})})},_u=({trigger:e,children:t,align:s="right"})=>{const[n,a]=l.useState(!1),o=l.useRef(null),i=l.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),c=l.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return l.useEffect(()=>(n&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",c)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",c)}),[n,i,c]),r.jsxs("div",{ref:o,className:"relative",children:[r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!n)},className:We("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}),n&&r.jsx("div",{className:We("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})]})},nn=({onClick:e,disabled:t,destructive:s,children:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:We("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:n}),zu=()=>r.jsx("div",{className:"my-1 h-px bg-line"}),Bu=({children:e})=>{const{Account:t}=ar();return r.jsx(t,{children:e})},vy=({email:e,onSignOut:t})=>{const s=e??"Account";return r.jsxs(_u,{trigger:r.jsx(jt,{name:s,email:e??void 0,size:"sm"}),align:"right",children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),r.jsx(zu,{})]}),r.jsxs(nn,{onClick:t,children:[r.jsx(Kc,{className:"size-4"}),"Sign out"]})]})},yy=()=>r.jsx(Bu,{children:({email:e,signOut:t})=>r.jsx(vy,{email:e,onSignOut:t})}),wy=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function jo(e){return!!e&&wy.has(e)}const Uu=3e3,Sy=Uu*2,hl={syncing:!1,resolved:!1,synced:0,total:0};function Cy(e,t){const s=e.join(","),[n,a]=l.useState(!1),[o,i]=l.useState(!1);l.useEffect(()=>{a(!1),i(!1)},[s,t]),l.useEffect(()=>{if(!t)return;const g=setTimeout(()=>i(!0),Sy);return()=>clearTimeout(g)},[s,t]);const c=mt({queries:e.map(g=>({...Wn({path:{accountId:g}}),enabled:t&&!n,refetchInterval:Uu,meta:{softError:!0}}))}),u=c.every(g=>g.isSuccess||g.isError),m=c.length===0||u||o;let d=!1,f=0,h=0;for(const g of c)if(jo(g.data?.syncPhase)){d=!0;for(const p of g.data?.mailboxes??[])f+=p.messagesSynced,h+=p.messagesTotal}const v=t&&m&&!d;return l.useEffect(()=>{v&&a(!0)},[v]),!t||!m?hl:{syncing:d,resolved:!0,synced:f,total:h}}const pl=6e4,ky=new Set(["sent","drafts","trash","archive"]),gl=(e,t)=>{const s=new Map;for(const n of e){const a=t.get(n.mailboxId)?.role;a&&ky.has(a)||s.set(n.mailboxId,n.messagesTotal)}return s},jy=(e,t)=>{for(const[s,n]of t)if(n>(e.get(s)??0))return!0;return!1},Ku=l.createContext(null),Cr=()=>{const e=l.useContext(Ku);if(!e)throw new Error("useMailFreshness must be used inside <MailFreshnessProvider>");return e};function Ny({accountIds:e,children:t}){const s=Te(),{resultFolderIndex:n}=Le(),a=l.useRef(new Map),o=l.useRef(new Set),[i,c]=l.useState(new Set),u=mt({queries:e.map(g=>({...Wn({path:{accountId:g}}),refetchInterval:pl,staleTime:pl,meta:{softError:!0}}))}),m=u.map(g=>g.dataUpdatedAt).join(","),d=e.join(",");l.useEffect(()=>{let g=!1;const p=new Set(i);e.forEach((b,y)=>{const S=u[y]?.data;if(!S)return;const x=gl(S.mailboxes??[],n);if(!o.current.has(b)){o.current.add(b),a.current.set(b,x);return}if(p.has(b))return;const w=a.current.get(b)??new Map;jy(w,x)&&(p.add(b),g=!0)}),g&&c(p)},[d,m]);const f=l.useCallback(g=>g.some(p=>i.has(p)),[i]),h=l.useCallback(g=>{c(p=>{if(g.every(y=>!p.has(y)))return p;const b=new Set(p);for(const y of g)b.delete(y);return b});for(const p of g){const b=s.getQueryData(Wn({path:{accountId:p}}).queryKey);a.current.set(p,gl(b?.mailboxes??[],n)),o.current.add(p)}},[s,n]),v=l.useMemo(()=>({hasNewMail:f,acknowledge:h}),[f,h]);return r.jsx(Ku.Provider,{value:v,children:t})}const Ey=2e3,Iy=45e3,Ry=e=>new Promise(t=>setTimeout(t,e)),ka=e=>e instanceof Error&&e.message?e.message:"Something went wrong",Ty=e=>{hc(e,{softError:!0})&&qa(e)},qu=e=>e.reduce((t,s)=>Math.max(t,s.lastSyncedAt??0),0),Hu=(e,t)=>e.fetchQuery({...Wn({path:{accountId:t}}),staleTime:0}),My=async(e,t,s,n)=>{let a=!1;for(;;){const o=await Hu(e,t).then(u=>({ok:!0,data:u})).catch(u=>({ok:!1,error:u}));if(!o.ok)return{accountId:t,message:ka(o.error)};const{syncPhase:i,mailboxes:c}=o.data;if(jo(i))a=!0;else if(a||qu(c??[])>s)return i==="error"?{accountId:t,message:"Sync failed for this account"}:void 0;if(Date.now()>=n)return{accountId:t,message:"Refresh is taking longer than usual"};await Ry(Ey)}},Ay=async(e,t,s,n)=>{const a=await Hu(e,s).then(c=>({ok:!0,maxLastSynced:qu(c.mailboxes??[])})).catch(c=>({ok:!1,error:c}));if(!a.ok)return{accountId:s,enqueued:!1,ok:!1,message:ka(a.error)};const o=await mc({path:{accountId:s},throwOnError:!0}).then(()=>({ok:!0})).catch(c=>({ok:!1,error:c}));if(!o.ok)return Ty(o.error),{accountId:s,enqueued:!1,ok:!1,message:ka(o.error)};t.recordEvent("sync.triggered");const i=await My(e,s,a.maxLastSynced,n);return i?{accountId:s,enqueued:!0,ok:!1,message:i.message}:{accountId:s,enqueued:!0,ok:!0}},No=(e,t={})=>{const s=Te(),n=Ls(),{acknowledge:a}=Cr(),[o,i]=l.useState("idle"),[c,u]=l.useState(),m=l.useRef(0),d=l.useRef(e);d.current=e;const f=l.useRef(t);f.current=t,l.useEffect(()=>{if(o!=="success")return;const v=setTimeout(()=>i("idle"),2e3);return()=>clearTimeout(v)},[o]);const h=l.useCallback(()=>{const v=d.current;if(v.length===0){i("error"),u("Nothing to refresh yet");return}const g=++m.current;i("refreshing"),u(void 0),(async()=>{const p=Date.now()+Iy,b=await Promise.all(v.map(x=>Ay(s,n,x,p)));if(m.current!==g)return;const y=b.filter(x=>x.enqueued).map(x=>x.accountId);for(const x of y)s.invalidateQueries({queryKey:Ft({path:{accountId:x}})});y.length>0&&(f.current.onSettled?.(),a(y));const S=b.filter(x=>!x.ok);S.length===0?i("success"):(i("error"),u(S[0]?.message))})()},[a,s,n]);return{state:o,errorMessage:c,refresh:h}},Wu="/mail/",Eo="/mail/$mailboxId",Vu="/mail/outbox",Qu="/mail/flagged";function Io(e){return e.some(t=>t.routeId===Wu)}function xn(e){return e.some(t=>t.routeId===Qu)}function kr(e){return e.some(t=>t.routeId===Vu)}function Gu(e){return e.some(t=>t.routeId===Eo)}function Oy(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Eo}:${t}`:xn(e)?Qu:kr(e)?Vu:Io(e)?Wu:""}const Un="search-scope";function Dy(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function Yu(e){return xn(e)||kr(e)||Gu(e)}function Xu(e){return e.find(t=>t.routeId===Eo)?.params?.mailboxId}function Py(e){const t=Xu(e.matches);return t||(Yu(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function Ly(e,t){return Io(e)?{kind:"global"}:xn(e)?{kind:"scoped",chip:{id:Un,label:"is:starred"}}:kr(e)?{kind:"scoped",chip:{id:Un,label:"in:outbox"}}:Gu(e)?t?{kind:"scoped",chip:{id:Un,label:Dy(t)}}:{kind:"pending"}:{kind:"global"}}function Fy(e,t,s){return t.kind==="global"?{kind:"global"}:xn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const Ju=({accounts:e})=>{const t=Ha({strict:!1}),s=Sr(),n=t.mailboxId,{t:a}=Wa("mail",{useSuspense:!1}),o=l.useCallback((c,u)=>a(c,{defaultValue:u}),[a]),i=mt({queries:e.map(c=>({...it({path:{accountId:c.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!n)return null;for(let c=0;c<e.length;c++){const u=i[c]?.data?.items;if(!u)continue;const m=u.find(f=>f.mailboxId===n);if(!m)continue;const d=Ka(e[c].folderAppointments);return Vn(m,d.get(n),o)}return null},$y=({accounts:e})=>{const s=Ha({strict:!1}).mailboxId,n=mt({queries:e.map(a=>({...it({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of n){const o=a.data?.items;if(!o)continue;const i=o.find(c=>c.mailboxId===s);if(i)return i.unseenCount}return null};function Zu(e){const t=Qe(),{searchInput:s}=Le(),n=Ju({accounts:e}),a=Ot({select:c=>c.matches}),o=Ly(a,n),i=l.useCallback(c=>{c===Un&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}function _y({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:n,onSearchClearQuery:a}=Le(),o=Qe(),i=$u(e),{scope:c,clearScope:u}=Zu(e),m=c.kind==="scoped"?[{id:c.chip.id,label:c.chip.label,tone:"scope"}]:void 0,d=l.useMemo(()=>e.map(p=>p.accountId),[e]),{hasNewMail:f}=Cr(),{state:h,errorMessage:v,refresh:g}=No(d);return r.jsx(Gx,{search:{value:t,scope:c.kind,chips:m,onChange:s,onClear:n,onClearQuery:a,onRemoveChip:u},onCompose:i,onReportBug:pc,onOpenSettings:()=>o({to:"/settings/accounts"}),composeShortcut:Gc("compose"),refreshControl:r.jsx(yo,{state:h,onRefresh:g,label:"Refresh all accounts",errorMessage:v,hasUpdate:f(d)}),account:r.jsx(yy,{})})}const Ro=({isOpen:e,onClose:t,children:s,ariaLabel:n="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=l.useRef(null),c=l.useRef(null);if(l.useEffect(()=>{if(!e)return;c.current=document.activeElement;const m=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",m),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=f,c.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 r.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":n,children:[r.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"}),r.jsxs("div",{ref:i,className:We("safe-area-frame absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[r.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:r.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:r.jsx(Nt,{className:"size-5"})})}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},zy=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 n=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return n?{kind:"text",contentUrl:n.contentUrl}:null},ja={all:["messages"],detail:e=>[...ja.all,"detail",e],body:e=>[...ja.detail(e),"body"]};class cs extends Error{reason;status;retryAfterSeconds;constructor(t,s,n,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=n,this.retryAfterSeconds=a}}const By=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},Uy=8,Ky="x-remit-403-reason",ed=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},qy=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,Hy=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},Wy=async(e,t,s=async()=>null)=>{const n={},a=await s();a&&(n.Authorization=`Bearer ${a}`);const o=await gc(e,{headers:n});if(o.status===202)throw new cs("not-ready","Message body is still syncing",202,By(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(Ky),m=ed(o.status,u);throw new cs(m,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(Hy(t,i))throw new cs("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const c=await o.text();if(qy(c,i))throw new cs("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return c},Vy=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),td=({messageId:e,bodyParts:t,enabled:s=!0})=>{const n=t?zy(t):null,a=Ls(),{getToken:o}=ar(),i=l.useRef(null),c=Te(),u=l.useRef(!1),m=l.useRef(null),d=e&&n?`${e}:${n.contentUrl}`:null;m.current!==d&&(m.current=d,u.current=!1);const f=ye({queryKey:e?[...ja.body(e),n?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!n)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const g=u.current;return u.current=!1,Vy({fetchContent:(p,b)=>Wy(p,b,o),refetchDescribeMessage:()=>c.refetchQueries({queryKey:Va({path:{messageId:e}})})},{contentUrl:n.contentUrl,kind:n.kind,isRetryAfterNotReady:g})},enabled:s&&!!e&&!!n,staleTime:300*1e3,gcTime:1800*1e3,retry:(g,p)=>p instanceof cs&&p.reason==="not-ready"?g<Uy:g<1,retryDelay:(g,p)=>p instanceof cs&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=f.isLoading&&!!n;l.useEffect(()=>{h&&(i.current=performance.now())},[h]),l.useEffect(()=>{f.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[f.isSuccess,a]);const v=f.data&&n?{kind:n.kind,body:f.data}:void 0;return{picked:n,data:v,isLoading:h,isError:f.isError,error:f.error,refetch:f.refetch}},Qy=e=>e.then(()=>{},()=>{}),Gy=({outboxMessageId:e,onDraftCreated:t})=>{const[s,n]=l.useState("idle"),[a,o]=l.useState(null),i=l.useRef(void 0),c=l.useRef(new Set),u=Te(),m=l.useRef(e),d=l.useRef(e);m.current!==e&&(m.current=e,d.current=e);const f=ze(km()),h=ze(jm()),v=l.useCallback(async x=>{n("saving"),o(null);const w=d.current;if(w){const T=await h.mutateAsync({path:{outboxMessageId:w},body:{toAddresses:x.toAddresses,ccAddresses:x.ccAddresses,bccAddresses:x.bccAddresses,subject:x.subject,textBody:x.textBody,htmlBody:x.htmlBody,inReplyTo:x.inReplyTo,references:x.references}});return n("saved"),T}const C=await f.mutateAsync({body:{...x,sendImmediately:!1}});return d.current=C.outboxMessageId,t(C.outboxMessageId),n("saved"),u.invalidateQueries({queryKey:or().queryKey}),C},[f,h,t,u]),g=l.useRef(Promise.resolve()),p=l.useCallback(x=>{const w=g.current.then(()=>v(x));return g.current=Qy(w),w},[v]),b=l.useCallback(x=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{const w=d.current;w&&c.current.has(w)||p(x).catch(C=>{o(C),n("error")})},2e3)},[p]),y=l.useCallback(x=>(i.current&&clearTimeout(i.current),p(x).then(w=>({outcome:"saved",outboxMessageId:w.outboxMessageId})).catch(w=>(n("error"),{outcome:"failed",error:w}))),[p]),S=l.useCallback(x=>{i.current&&clearTimeout(i.current),x&&c.current.add(x)},[]);return{saveStatus:s,saveError:a,saveDraft:b,saveImmediately:y,stopAutoSave:S}},ta=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=l.useState(""),i=mr(a,200),{data:c}=ye({...ir({query:{q:i,limit:8}}),enabled:i.length>=2}),u=l.useMemo(()=>(c?.items??[]).map(m=>({email:m.normalizedEmail,displayName:m.displayName})),[c]);return r.jsx(lx,{label:e,addresses:t,onChange:s,placeholder:n,suggestions:u,onQueryChange:o})},Yy=({accountId:e})=>{const t=Qe();return r.jsx(fx,{onConfigure:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})}})},xl=150,Xy=()=>{const[e,t]=l.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>xl}});return l.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>xl})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},Jy=({selectedAccountId:e,onSelect:t})=>{const{data:s}=ye({...$t(),staleTime:1/0}),n=s?.accounts??[];if(l.useEffect(()=>{!e&&n.length===1&&n[0]&&t(n[0])},[e,n,t]),n.length<=1){const a=n[0];return a?r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=n.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:n.map(a=>r.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},Zy=l.lazy(()=>Tm(()=>import("./rich-text-D1qTHV73.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}))),e0=()=>r.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[r.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),r.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),t0=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),s0=e=>e.split(`
116
116
  `).map(t=>`<p>${t0(t)}</p>`).join(""),bl=e=>e?`<p></p><p>-- </p>${s0(e)}`:"",n0=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",r0=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",a0=(e,t,s)=>{const{envelope:n}=e,o=(n.replyTo.length>0?n.replyTo:n.from).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),c=new Set(o.map(m=>m.email.toLowerCase())),u=[...n.to,...n.cc].filter(m=>m.normalizedEmail.toLowerCase()!==i&&!c.has(m.normalizedEmail.toLowerCase())).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));return{to:o,cc:u}},o0=e=>{const t=e.envelope.messageIdValue,n=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!n.includes(t)&&n.push(t),{inReplyTo:t,references:n}},vl=(e,t,s)=>({textBody:t.text||void 0,htmlBody:e==="plain"?"":t.html?Rm(t.html,s):void 0}),i0=(e,t,s,n,a)=>e.length===0&&t.length===0&&s.length===0&&n.trim()===""&&a.text.trim()==="",l0=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:n,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:c,showCc:u,setShowCc:m,showBcc:d,setShowBcc:f,subject:h,setSubject:v})=>{const g=es(),{isKeyboardOpen:p}=Xy();return r.jsx(dx,{collapsed:!g&&p,summary:ux({to:s,cc:a,bcc:i,subject:h}),from:r.jsx(Jy,{selectedAccountId:e,onSelect:t}),to:r.jsx(ta,{label:"To",addresses:s,onChange:n,placeholder:"Recipients"}),cc:u?r.jsx(ta,{label:"Cc",addresses:a,onChange:o}):void 0,bcc:d?r.jsx(ta,{label:"Bcc",addresses:i,onChange:c}):void 0,subject:r.jsx(mx,{value:h,onChange:v}),onShowCc:()=>m(!0),onShowBcc:()=>f(!0)})},To=({mode:e,account:t,sourceMessage:s,onClose:n,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:c}=Jt(),{pushError:u}=nt(),{outboxMessageId:m}=o,[d,f]=l.useState([]),[h,v]=l.useState([]),[g,p]=l.useState([]),[b,y]=l.useState(""),[S,x]=l.useState(!1),[w,C]=l.useState(!1),[T,A]=l.useState(t?.accountId),[k,M]=l.useState(!1),D=l.useRef(m);l.useEffect(()=>{const he=D.current;he!==m&&(D.current=m,!(!m||he===void 0)&&(f([]),v([]),p([]),y(""),x(!1),C(!1),I(""),R(""),N("rich"),se(void 0),Z(Vx),O(Se=>Se+1),M(!1)))},[m]);const{signature:E}=vh(T),[L,O]=l.useState(0),[j,I]=l.useState(()=>bl(E.plainText)),[P,R]=l.useState(E.plainText),[F,N]=l.useState("rich"),[V,Q]=l.useState("en"),[re,se]=l.useState(),[fe,Z]=l.useState(()=>({html:bl(E.plainText),text:E.plainText,formatting:[]})),{data:ne}=ye({...Nm({path:{outboxMessageId:m??""}}),enabled:!!m&&!k});l.useEffect(()=>{if(!ne||k)return;f(ne.toAddresses.map(ve=>({email:ve,displayName:void 0}))),ne.ccAddresses&&ne.ccAddresses.length>0&&(v(ne.ccAddresses.map(ve=>({email:ve,displayName:void 0}))),x(!0)),ne.bccAddresses&&ne.bccAddresses.length>0&&(p(ne.bccAddresses.map(ve=>({email:ve,displayName:void 0}))),C(!0)),ne.subject&&y(ne.subject);const he=Em(ne.htmlBody??""),Se=he.html,Ae=ne.textBody??"";N(ib(ne.htmlBody)),se(he.language??void 0),I(Se),R(Ae),Z({html:Se,text:Ae,formatting:[]}),O(ve=>ve+1),A(ne.accountId),M(!0)},[ne,k]),l.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:he,cc:Se}=a0(s,e,t?.email);f(he),v(Se),Se.length>0&&x(!0),y(n0(s.envelope.subject))}e==="forward"&&y(r0(s.envelope.subject))}},[e,s,t?.email]);const le=e==="reply"||e==="reply_all"||e==="forward",{data:U}=td({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:le&&!!s}),_=U?.kind==="text"?U.body:"",de=U?.kind==="html"?ob(U.body):void 0,ge=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,we=l.useCallback(he=>{M(!0),i(he)},[i]),{saveStatus:Re,saveError:q,saveDraft:Ce,saveImmediately:xe,stopAutoSave:Ne}=Gy({outboxMessageId:m,onDraftCreated:we});l.useEffect(()=>{q&&u({title:"Couldn't save draft",detail:ft(q)??"Saving the draft failed.",error:q})},[q,u]);const ue=ze(xc()),te=ze({...lr(),onError:he=>{u(ds("Couldn't discard draft","The draft wasn't discarded.",he))}}),{data:be}=ye({...$t(),staleTime:1/0}),De=be?.accounts.find(he=>he.accountId===T),Ue=De?xh(De):!1,G=De?.composeLanguages,Ge=l.useMemo(()=>G&&G.length>0?G:Im(navigator.languages),[G]),ke=l.useRef(!1),[Ke,$]=l.useState(!1),ce=d.length>0&&!!T&&!Ue;l.useEffect(()=>{if(!T||m&&!k||i0(d,h,g,b,fe))return;const{htmlBody:he,textBody:Se}=vl(F,fe,V);Ce({accountId:T,toAddresses:d.map(Ae=>Ae.email),ccAddresses:h.length>0?h.map(Ae=>Ae.email):void 0,bccAddresses:g.length>0?g.map(Ae=>Ae.email):void 0,subject:b||void 0,textBody:Se,htmlBody:he})},[T,m,k,d,h,g,b,fe,F,V,Ce]);const ae=l.useCallback(async()=>{if(!ke.current&&!(!T||d.length===0)){ke.current=!0,$(!0);try{Ne();const he=s&&(e==="reply"||e==="reply_all")?o0(s):{},{htmlBody:Se,textBody:Ae}=vl(F,fe,V),ve=!m,Ye=await xe({accountId:T,toAddresses:d.map(K=>K.email),ccAddresses:h.length>0?h.map(K=>K.email):void 0,bccAddresses:g.length>0?g.map(K=>K.email):void 0,subject:b||void 0,textBody:Ae,htmlBody:Se,...he});if(Ye.outcome==="failed"){u({title:"Couldn't send message",detail:ft(Ye.error)??"Saving the message failed, so nothing was sent. Try again.",error:Ye.error});return}const Xe=Ye.outboxMessageId;if(await ue.mutateAsync({path:{outboxMessageId:Xe}}).catch(K=>(u({title:"Couldn't send message",detail:ft(K)??(ve?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:K}),null))===null)return;Ne(Xe),c(Xe),n()}finally{ke.current=!1,$(!1)}}},[T,d,h,g,b,fe,F,V,e,s,m,xe,ue,Ne,c,u,n]),me=l.useCallback(()=>{Ne(m),m&&te.mutate({path:{outboxMessageId:m}}),n()},[Ne,m,te,n]),Me=l.useCallback(he=>{A(he.accountId),a?.(he)},[a]);return r.jsx(cx,{banner:De&&Ue?r.jsx(Yy,{accountId:De.accountId}):void 0,header:r.jsx(l0,{selectedAccountId:T,onAccountChange:Me,toAddresses:d,setToAddresses:f,ccAddresses:h,setCcAddresses:v,bccAddresses:g,setBccAddresses:p,showCc:S,setShowCc:x,showBcc:w,setShowBcc:C,subject:b,setSubject:y}),quoted:_||de?r.jsx(Ox,{text:_,html:de,senderName:ge}):void 0,actionBar:r.jsx(ax,{onSend:ae,onDiscard:me,sending:Ke,canSend:ce,saveStatus:Re,unavailableReason:Ue?"SMTP not configured":void 0,onUnavailable:he=>u({title:"Can't send yet",detail:he})}),children:r.jsx(l.Suspense,{fallback:r.jsx(e0,{}),children:r.jsx(Zy,{mode:F,onModeChange:N,initialHtml:j,initialText:P,onChange:Z,onSubmit:ae,autoFocus:e==="new",onConversionError:u,languages:Ge,initialLanguage:re,onLanguageChange:Q},L)})})},yl=({mode:e,account:t,sourceMessage:s,onClose:n})=>r.jsx("div",{className:"border-t border-line bg-canvas max-h-[min(400px,60dvh)] flex flex-col",children:r.jsx(To,{mode:e,account:t,sourceMessage:s,onClose:n})}),sd=({message:e,icon:t})=>r.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&r.jsx("div",{className:"mb-4 text-fg-muted",children:t}),r.jsx("p",{className:"text-fg-muted",children:e})]}),Mo=({enabled:e=!0,bindings:t,capture:s=!1})=>{const n=l.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 m=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(m&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);l.useEffect(()=>{if(e)return window.addEventListener("keydown",n,s),()=>window.removeEventListener("keydown",n,s)},[e,n,s])},Ao=e=>{const{data:t,isLoading:s}=ye({...$t(),staleTime:1/0}),n=l.useMemo(()=>(t?.accounts??[]).map(c=>c.accountId),[t?.accounts]),a=mt({queries:n.map(c=>({...it({path:{accountId:c}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(c=>c.isLoading);return{accountId:l.useMemo(()=>{if(e){for(let c=0;c<n.length;c++)if((a[c].data?.items??[]).some(d=>d.mailboxId===e))return n[c]}},[e,n,a]),isLoading:o}},c0=100,Na=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),u0=(e,t=c0)=>{if(e.length===0)return[];const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s},nd=async(e,t,s,n)=>{const a=u0(e),o=e.length;let i=0;const c=[];for(let u=0;u<a.length;u++){if(n())return c.push(...a.slice(u).flat()),{done:i,failedIds:c,cancelled:!0};const m=a[u],d=await Na(t(m));if(!d.ok)return c.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:c,cancelled:!1,error:d.error};i+=m.length,s({done:i,total:o})}return{done:i,failedIds:c,cancelled:!1}},Os=async(e,t)=>{await nd(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},d0=async(e,t,s,n,a)=>{let o=0;const i=[];let c;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await Na(e(c));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const m=u.value;if(m.ids.length>0){const d=await Na(s(m.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=m.ids.length,n({done:o,total:t})}c=m.continuationToken}while(c);return{done:o,failedIds:i,cancelled:!1}},f0=e=>({done:e.done,total:Math.max(e.total,e.done)}),rd=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),ad=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),od=(e,t)=>e===void 0?e:rd(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:ad(e)?{...e,items:t(e.items)}:e,Et=e=>{const t=[];for(const s of new Set(e))t.push(cr({path:{mailboxId:s}})),t.push(Qa({path:{mailboxId:s}}));return t.push(Ga()),t},bn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),vn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,n])=>({queryKey:s,data:n})),yn=(e,t,s)=>{const n=a=>od(a,s);for(const a of t)e.setQueriesData({queryKey:a},n)},wn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},It=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},m0=3e3,h0=(e,t,s)=>{if(e.length===0)return()=>{};const n=setTimeout(()=>s(e),t);return()=>clearTimeout(n)},jr=(e,t,s)=>{const n=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(n.get(o)??s);return[...a]},Jn=(e,t,s)=>e.map(n=>t.has(n.messageId)?{...n,isRead:s}:n),p0=(e,t,s,n)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!n.has(a.messageId)).map(a=>a.messageId),g0=({messages:e,expandedIds:t,threadId:s,mailboxId:n,accountId:a})=>{const o=Te(),{pushError:i}=nt(),c=l.useRef(new Set),u=l.useRef(new Set),{mutate:m}=ze({...ur(),onMutate:async h=>{const v=new Set(h.body.messageIds??[]),g=h.body.isRead??!0,p=Zt({path:{threadId:s}}),b=Et(jr(v,e,n));await Promise.all([o.cancelQueries({queryKey:p}),bn(o,b)]);const y=o.getQueriesData({queryKey:p}).filter(x=>x[1]!==void 0).map(([x,w])=>({queryKey:x,data:w})),S=vn(o,b);return o.setQueriesData({queryKey:p},x=>x&&{...x,items:Jn(x.items,v,g)}),yn(o,b,x=>Jn(x,v,g)),{threadMessagesPrefix:p,listPrefixes:b,previousThreadMessages:y,previousThreadsList:S}},onSuccess:(h,v)=>{const g=v.body.messageIds??[];for(const p of g)c.current.add(p),u.current.delete(p)},onError:(h,v,g)=>{const p=v.body.messageIds??[];for(const y of p)u.current.delete(y);if(g){for(const y of g.previousThreadMessages)o.setQueryData(y.queryKey,y.data);wn(o,g.previousThreadsList)}const b=v.body.isRead??!0;i({title:b?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(h),error:h})},onSettled:(h,v,g,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),It(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:Ft({path:{accountId:a}})}))}}),d=l.useCallback(h=>{const v=h.filter(g=>!c.current.has(g)&&!u.current.has(g));if(v.length!==0){for(const g of v)u.current.add(g);m({body:{messageIds:v,isRead:!0}})}},[m]),f=l.useMemo(()=>p0(e,t,c.current,u.current),[e,t]);l.useEffect(()=>h0(f,m0,d),[f,d]),l.useEffect(()=>{c.current.clear(),u.current.clear()},[s])},Nr=e=>{const{mailboxId:t,accountId:s,messages:n}=e,a=Te(),{pushError:o}=nt(),{mutateAsync:i,isPending:c}=ze({...ur(),onError:(m,d)=>{const f=d.body.isRead??!0;o({title:f?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(m),error:m})},onSettled:(m,d,f)=>{It(a,Et(jr(f.body.messageIds??[],n??[],t))),s&&a.invalidateQueries({queryKey:Ft({path:{accountId:s}})})}});return{toggleReadFor:l.useCallback((m,d)=>{m.length!==0&&Os(m,f=>i({body:{messageIds:f,isRead:d}}))},[i]),isPending:c}},x0=60,b0=1.5,v0=(e,t,s)=>{const n=Math.abs(e),a=Math.abs(t);return n<s?{direction:null}:n<a*b0?{direction:null}:{direction:e<0?"left":"right"}},y0=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=x0})=>{const n=l.useRef(null),a=l.useCallback(u=>{if(u.pointerType==="mouse"){n.current=null;return}n.current={x:u.clientX,y:u.clientY}},[]),o=l.useCallback(()=>{},[]),i=l.useCallback(u=>{const m=n.current;if(n.current=null,!m)return;const{direction:d}=v0(u.clientX-m.x,u.clientY-m.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),c=l.useCallback(()=>{n.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:c}}},w0=(e,t,s)=>t?.find(n=>n.messageId===e)?.mailboxId??s,wl=(e,t,s)=>e.map(n=>n.messageId===t?{...n,hasStars:s}:n),Oo=({threadId:e,mailboxId:t,messages:s})=>{const n=Te(),{pushError:a}=nt(),{mutate:o,isPending:i,variables:c}=ze({...Mm(),onMutate:async m=>{const d=m.path.messageId,f=m.body.isStarred??!1,h=Zt({path:{threadId:e}}),v=Et([w0(d,s,t)]);await Promise.all([n.cancelQueries({queryKey:h}),bn(n,v)]);const g=n.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})),p=vn(n,v);return n.setQueriesData({queryKey:h},b=>od(b,y=>wl(y,d,f))),yn(n,v,b=>wl(b,d,f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:g,previousThreadsList:p}},onError:(m,d,f)=>{if(f){for(const v of f.previousThreadMessages)n.setQueryData(v.queryKey,v.data);wn(n,f.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:ft(m),error:m})},onSettled:(m,d,f,h)=>{h&&(n.invalidateQueries({queryKey:h.threadMessagesPrefix}),It(n,h.listPrefixes))}});return{toggleStar:(m,d)=>{o({path:{messageId:m},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?c?.path.messageId:void 0}};function Er(e){return e===void 0?"uncategorized":e}const S0={inbox:"Inbox",junk:"Junk"},Do=e=>e.destinationMailboxId!==void 0,C0=(e,t)=>{if(Do(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${S0[s]??"another folder"} by Remit`},k0=(e,t)=>{if(e===ii.MoveToInbox)return t.inboxMailboxId;if(e===ii.MoveToJunk)return t.junkMailboxId},j0=(e,t,s)=>{if(!e||!t)return!1;const n=Do(e)?e.destinationMailboxId:k0(e.action,s);return n!==void 0&&n===t},N0="Reported as spam",E0=(e,t)=>{if(e){if(Do(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},Ir=(e,t)=>{const{data:s,isLoading:n}=ye({...$t(),staleTime:1/0,enabled:!!e});return{mailboxId:l.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:n}},I0=e=>{const{mailboxId:t,isLoading:s}=Ir(e,"Archive");return{archiveMailboxId:t,isLoading:s}},R0=e=>{const{mailboxId:t,isLoading:s}=Ir(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},id=e=>{const{mailboxId:t,isLoading:s}=Ir(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},Sn=e=>{const{mailboxId:t,isLoading:s}=Ir(e,"Junk");return{junkMailboxId:t,isLoading:s}},Po=e=>{const{data:t}=ye({...$t(),staleTime:1/0,enabled:!!e});return l.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Sl=(e,t)=>e.filter(s=>!t.has(s.messageId)),Ds=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=Te(),{pushError:o}=nt(),{mutateAsync:i,isPending:c,isError:u}=ze({...Am(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],v=Et([e,d.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:h})]:[],bn(a,v)]);const g=t?a.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})):[],p=vn(a,v);return t&&a.setQueriesData({queryKey:h},b=>b&&{...b,items:Sl(b.items,f)}),yn(a,v,b=>Sl(b,f)),n?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:g,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const g of h.previousThreadMessages)a.setQueryData(g.queryKey,g.data);wn(a,h.previousThreadsList)}const v=f.body.messageIds?.length??0;o({title:v>1?`Couldn't move ${v} messages`:"Couldn't move this message",detail:ft(d),error:d})},onSettled:(d,f,h,v)=>{v&&(t&&a.invalidateQueries({queryKey:v.threadMessagesPrefix}),It(a,v.listPrefixes),s&&a.invalidateQueries({queryKey:Ft({path:{accountId:s}})}))}});return{moveMessages:l.useCallback((d,f)=>{d.length!==0&&Os(d,h=>i({body:{messageIds:h,destinationMailboxId:f}}))},[i]),isPending:c,isError:u}},T0="This message could not be processed. Please try again.",M0=(e,t)=>e.replace(`Message ${t}'s`,"This message's"),Cl=e=>{if(e.failureCount===0)return;const t=e.failures?.[0],s=t?.reason??T0,n=t?M0(s,t.messageId):s;throw new Pm(n,422)};function ld({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n}){const a=Te(),{pushError:o}=nt(),i=Et([e]),c=t?Zt({path:{threadId:t}}):[],u=()=>{t&&a.invalidateQueries({queryKey:c}),It(a,i),s&&a.invalidateQueries({queryKey:Ft({path:{accountId:s}})})},m=()=>(p,b)=>{u(),n?.(b.body.messageIds)},d=p=>(b,y)=>{o({title:p(y.body.messageIds.length),detail:ft(b),error:b})},f=ze({mutationFn:async p=>{const{data:b}=await Om({...p,throwOnError:!0});return Cl(b),b},meta:{softError:!0},onSuccess:m(),onError:d(p=>p>1?`Couldn't report ${p} messages as spam`:"Couldn't report this message as spam")}),h=ze({mutationFn:async p=>{const{data:b}=await Dm({...p,throwOnError:!0});return Cl(b),b},meta:{softError:!0},onSuccess:m(),onError:d(p=>p>1?`Couldn't undo the spam report for ${p} messages`:"Couldn't undo the spam report")}),v=l.useCallback(p=>{p.length!==0&&Os(p,b=>f.mutateAsync({body:{messageIds:b}}))},[f.mutateAsync]),g=l.useCallback(p=>{p.length!==0&&Os(p,b=>h.mutateAsync({body:{messageIds:b}}))},[h.mutateAsync]);return{reportSpam:v,notSpam:g,isReporting:f.isPending,isRestoring:h.isPending}}const A0=({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o})=>{const{inboxMailboxId:i}=id(e),{junkMailboxId:c}=Sn(e),{moveMessages:u,isPending:m}=Ds({mailboxId:n,threadId:s,accountId:e}),{notSpam:d,isRestoring:f}=ld({mailboxId:n,threadId:s,accountId:e}),{data:h}=ye({...it({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),v={inboxMailboxId:i,junkMailboxId:c},g=E0(a,v),p=l.useCallback(()=>{g&&u([t],g)},[u,t,g]),b=l.useCallback(()=>{d([t])},[d,t]);if(o)return{show:!0,label:N0,onUndo:b,isUndoing:f};if(!j0(a,n,v)||!a)return{show:!1,label:"",isUndoing:!1};const S=a.fromMailboxId?h?.items.filter(x=>x.mailboxId===a.fromMailboxId).map(x=>ma(x.fullPath))[0]:void 0;return{show:!0,label:C0(a,S),onUndo:g?p:void 0,isUndoing:m,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function O0({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o}){const i=A0({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o});return i.show?r.jsx(ex,{label:i.label,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:i.filtersHref}):null}const kl=(e,t)=>e.filter(s=>!t.has(s.messageId)),D0=e=>e.filter(t=>t.isDeleted!==!0),ms=({mailboxId:e,threadId:t,accountId:s,messages:n,onAfterOptimisticRemove:a})=>{const o=Te(),{pushError:i}=nt(),{mutateAsync:c,isPending:u}=ze({...Lm(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],v=Et(jr(f,n??[],e));await Promise.all([o.cancelQueries({queryKey:h}),bn(o,v)]);const g=t?o.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})):[],p=vn(o,v);return t&&o.setQueriesData({queryKey:h},b=>b&&{...b,items:kl(b.items,f)}),yn(o,v,b=>kl(b,f)),a?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:g,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const g of h.previousThreadMessages)o.setQueryData(g.queryKey,g.data);wn(o,h.previousThreadsList)}const v=f.body.messageIds?.length??0;i({title:v>1?`Couldn't delete ${v} messages`:"Couldn't delete this message",detail:ft(d),error:d})},onSettled:(d,f,h,v)=>{v&&(t&&o.invalidateQueries({queryKey:v.threadMessagesPrefix}),It(o,v.listPrefixes),s&&o.invalidateQueries({queryKey:Ft({path:{accountId:s}})}))}});return{deleteMessages:l.useCallback(d=>{d.length!==0&&Os(d,f=>c({body:{messageIds:f}}))},[c]),isPending:u}},cd=(e,t=Date.now())=>({value:e,setAt:t}),P0=(e,t,s,n)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=cd(!0,n):delete a.trusted,{...e,flags:a}},L0=(e,t,s,n)=>{const a=o=>o.map(i=>P0(i,t,s,n));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)}}},Lo=({messageId:e})=>{const t=Te(),{pushError:s}=nt(),{mutate:n,isPending:a,error:o,reset:i}=ze({...bc(),onMutate:async u=>{const m=u.path.addressId,f=u.body.flags?.trusted?.value===!0,h=Va({path:{messageId:e}});await t.cancelQueries({queryKey:h});const v=t.getQueriesData({queryKey:h}).filter(g=>g[1]!==void 0).map(([g,p])=>({queryKey:g,data:p}));return t.setQueriesData({queryKey:h},g=>g&&L0(g,m,f)),{describePrefix:h,previous:v}},onError:(u,m,d)=>{if(d)for(const f of d.previous)t.setQueryData(f.queryKey,f.data);s(ds("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,m,d,f)=>{f&&t.invalidateQueries({queryKey:f.describePrefix})}});return{toggleTrusted:(u,m)=>{n({path:{addressId:u},body:{flags:{trusted:cd(!m)}}})},isPending:a,error:o,reset:i}};var Rr="Dialog",[ud]=$b(Rr),[F0,xt]=ud(Rr),dd=e=>{const{__scopeDialog:t,children:s,open:n,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,c=l.useRef(null),u=l.useRef(null),[m,d]=Bb({prop:n,defaultProp:a??!1,onChange:o,caller:Rr});return r.jsx(F0,{scope:t,triggerRef:c,contentRef:u,contentId:Yr(),titleId:Yr(),descriptionId:Yr(),open:m,onOpenChange:d,onOpenToggle:l.useCallback(()=>d(f=>!f),[d]),modal:i,children:s})};dd.displayName=Rr;var fd="DialogTrigger",$0=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(fd,s),o=gs(t,a.triggerRef);return r.jsx(_t.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":$o(a.open),...n,ref:o,onClick:Vt(e.onClick,a.onOpenToggle)})});$0.displayName=fd;var Fo="DialogPortal",[_0,md]=ud(Fo,{forceMount:void 0}),hd=e=>{const{__scopeDialog:t,forceMount:s,children:n,container:a}=e,o=xt(Fo,t);return r.jsx(_0,{scope:t,forceMount:s,children:l.Children.map(n,i=>r.jsx(yr,{present:s||o.open,children:r.jsx(Eu,{asChild:!0,container:a,children:i})}))})};hd.displayName=Fo;var Zn="DialogOverlay",pd=l.forwardRef((e,t)=>{const s=md(Zn,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(Zn,e.__scopeDialog);return o.modal?r.jsx(yr,{present:n||o.open,children:r.jsx(B0,{...a,ref:t})}):null});pd.displayName=Zn;var z0=Su("DialogOverlay.RemoveScroll"),B0=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Zn,s),o=ov(),i=gs(t,o);return r.jsx(Pu,{as:z0,allowPinchZoom:!0,shards:[a.contentRef],children:r.jsx(_t.div,{"data-state":$o(a.open),...n,ref:i,style:{pointerEvents:"auto",...n.style}})})}),Ps="DialogContent",gd=l.forwardRef((e,t)=>{const s=md(Ps,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(Ps,e.__scopeDialog);return r.jsx(yr,{present:n||o.open,children:o.modal?r.jsx(U0,{...a,ref:t}):r.jsx(K0,{...a,ref:t})})});gd.displayName=Ps;var U0=l.forwardRef((e,t)=>{const s=xt(Ps,e.__scopeDialog),n=l.useRef(null),a=gs(t,s.contentRef,n);return l.useEffect(()=>{const o=n.current;if(o)return Iv(o)},[]),r.jsx(xd,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Vt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Vt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&o.preventDefault()}),onFocusOutside:Vt(e.onFocusOutside,o=>o.preventDefault())})}),K0=l.forwardRef((e,t)=>{const s=xt(Ps,e.__scopeDialog),n=l.useRef(!1),a=l.useRef(!1);return r.jsx(xd,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(n.current||s.triggerRef.current?.focus(),o.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(n.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()}})}),xd=l.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,c=xt(Ps,s);return uv(),r.jsx(r.Fragment,{children:r.jsx(ju,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:r.jsx(Cu,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":$o(c.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})}),bd="DialogTitle",vd=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(bd,s);return r.jsx(_t.h2,{id:a.titleId,...n,ref:t})});vd.displayName=bd;var yd="DialogDescription",q0=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(yd,s);return r.jsx(_t.p,{id:a.descriptionId,...n,ref:t})});q0.displayName=yd;var wd="DialogClose",H0=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(wd,s);return r.jsx(_t.button,{type:"button",...n,ref:t,onClick:Vt(e.onClick,()=>a.onOpenChange(!1))})});H0.displayName=wd;function $o(e){return e?"open":"closed"}function W0(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 Sd=H.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}),Cn=()=>{const e=H.useContext(Sd);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};W0(`[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 V0(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function Q0(){return _o(/^Mac/)}function G0(){return _o(/^iPhone/)}function jl(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Y0(){return _o(/^iPad/)||Q0()&&navigator.maxTouchPoints>1}function Cd(){return G0()||Y0()}function _o(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const X0=24,J0=typeof window<"u"?l.useLayoutEffect:l.useEffect;function Nl(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const sa=typeof document<"u"&&window.visualViewport;function El(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function kd(e){for(El(e)&&(e=e.parentElement);e&&!El(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Z0=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Dn=0,na;function ew(e={}){let{isDisabled:t}=e;J0(()=>{if(!t)return Dn++,Dn===1&&Cd()&&(na=tw()),()=>{Dn--,Dn===0&&na?.()}},[t])}function tw(){let e,t=0,s=f=>{e=kd(f.target),!(e===document.documentElement&&e===document.body)&&(t=f.changedTouches[0].pageY)},n=f=>{if(!e||e===document.documentElement||e===document.body){f.preventDefault();return}let h=f.changedTouches[0].pageY,v=e.scrollTop,g=e.scrollHeight-e.clientHeight;g!==0&&((v<=0&&h>t||v>=g&&h<t)&&f.preventDefault(),t=h)},a=f=>{let h=f.target;Ea(h)&&h!==document.activeElement&&(f.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=f=>{let h=f.target;Ea(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",sa&&(sa.height<window.innerHeight?requestAnimationFrame(()=>{Il(h)}):sa.addEventListener("resize",()=>Il(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},c=window.pageXOffset,u=window.pageYOffset,m=Nl(sw(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=Nl(Xs(document,"touchstart",s,{passive:!1,capture:!0}),Xs(document,"touchmove",n,{passive:!1,capture:!0}),Xs(document,"touchend",a,{passive:!1,capture:!0}),Xs(document,"focus",o,!0),Xs(window,"scroll",i));return()=>{m(),d(),window.scrollTo(c,u)}}function sw(e,t,s){let n=e.style[t];return e.style[t]=s,()=>{e.style[t]=n}}function Xs(e,t,s,n){return e.addEventListener(t,s,n),()=>{e.removeEventListener(t,s,n)}}function Il(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=kd(e);if(s!==document.documentElement&&s!==document.body&&s!==e){let n=s.getBoundingClientRect().top,a=e.getBoundingClientRect().top,o=e.getBoundingClientRect().bottom;const i=s.getBoundingClientRect().bottom+X0;o>i&&(s.scrollTop+=a-n)}e=s.parentElement}}function Ea(e){return e instanceof HTMLInputElement&&!Z0.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function nw(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function rw(...e){return t=>e.forEach(s=>nw(s,t))}function jd(...e){return l.useCallback(rw(...e),e)}const Nd=new WeakMap;function Ve(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let n={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}n[a]=e.style[a],e.style[a]=o}),!s&&Nd.set(e,n)}function aw(e,t){if(!e||!(e instanceof HTMLElement))return;let s=Nd.get(e);s&&(e.style[t]=s[t])}const He=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function Pn(e,t){if(!e)return null;const s=window.getComputedStyle(e),n=s.transform||s.webkitTransform||s.mozTransform;let a=n.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[He(t)?13:12]):(a=n.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[He(t)?5:4]):null)}function ow(e){return 8*(Math.log(e+1)-2)}function ra(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function iw(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const Fe={DURATION:.5,EASE:[.32,.72,0,1]},Ed=.4,lw=.25,cw=100,Id=8,is=16,Ia=26,aa="vaul-dragging";function Rd(e){const t=H.useRef(e);return H.useEffect(()=>{t.current=e}),H.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function uw({defaultProp:e,onChange:t}){const s=H.useState(e),[n]=s,a=H.useRef(n),o=Rd(t);return H.useEffect(()=>{a.current!==n&&(o(n),a.current=n)},[n,a,o]),s}function Td({prop:e,defaultProp:t,onChange:s=()=>{}}){const[n,a]=uw({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:n,c=Rd(s),u=H.useCallback(m=>{if(o){const f=typeof m=="function"?m(e):m;f!==e&&c(f)}else a(m)},[o,e,a,c]);return[i,u]}function dw({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:n,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:c="bottom",container:u,snapToSequentialPoint:m}){const[d,f]=Td({prop:e,defaultProp:s?.[0],onChange:t}),[h,v]=H.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);H.useEffect(()=>{function A(){v({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)},[]);const g=H.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=H.useMemo(()=>{var A;return(A=s?.findIndex(k=>k===d))!=null?A:null},[s,d]),b=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,y=H.useMemo(()=>{const A=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var k;return(k=s?.map(M=>{const D=typeof M=="string";let E=0;if(D&&(E=parseInt(M,10)),He(c)){const O=D?E:h?M*A.height:0;return h?c==="bottom"?A.height-O:-A.height+O:O}const L=D?E:h?M*A.width:0;return h?c==="right"?A.width-L:-A.width+L:L}))!=null?k:[]},[s,h,u]),S=H.useMemo(()=>p!==null?y?.[p]:null,[y,p]),x=H.useCallback(A=>{var k;const M=(k=y?.findIndex(D=>D===A))!=null?k:null;i(M),Ve(n.current,{transition:`transform ${Fe.DURATION}s cubic-bezier(${Fe.EASE.join(",")})`,transform:He(c)?`translate3d(0, ${A}px, 0)`:`translate3d(${A}px, 0, 0)`}),y&&M!==y.length-1&&o!==void 0&&M!==o&&M<o?Ve(a.current,{transition:`opacity ${Fe.DURATION}s cubic-bezier(${Fe.EASE.join(",")})`,opacity:"0"}):Ve(a.current,{transition:`opacity ${Fe.DURATION}s cubic-bezier(${Fe.EASE.join(",")})`,opacity:"1"}),f(s?.[Math.max(M,0)])},[n.current,s,y,o,a,f]);H.useEffect(()=>{if(d||e){var A;const k=(A=s?.findIndex(M=>M===e||M===d))!=null?A:-1;y&&k!==-1&&typeof y[k]=="number"&&x(y[k])}},[d,e,s,y,x]);function w({draggedDistance:A,closeDrawer:k,velocity:M,dismissible:D}){if(o===void 0)return;const E=c==="bottom"||c==="right"?(S??0)-A:(S??0)+A,L=p===o-1,O=p===0,j=A>0;if(L&&Ve(a.current,{transition:`opacity ${Fe.DURATION}s cubic-bezier(${Fe.EASE.join(",")})`}),!m&&M>2&&!j){D?k():x(y[0]);return}if(!m&&M>2&&j&&y&&s){x(y[s.length-1]);return}const I=y?.reduce((R,F)=>typeof R!="number"||typeof F!="number"?R:Math.abs(F-E)<Math.abs(R-E)?F:R),P=He(c)?window.innerHeight:window.innerWidth;if(M>Ed&&Math.abs(A)<P*.4){const R=j?1:-1;if(R>0&&g&&s){x(y[s.length-1]);return}if(O&&R<0&&D&&k(),p===null)return;x(y[p+R]);return}x(I)}function C({draggedDistance:A}){if(S===null)return;const k=c==="bottom"||c==="right"?S-A:S+A;(c==="bottom"||c==="right")&&k<y[y.length-1]||(c==="top"||c==="left")&&k>y[y.length-1]||Ve(n.current,{transform:He(c)?`translate3d(0, ${k}px, 0)`:`translate3d(${k}px, 0, 0)`})}function T(A,k){if(!s||typeof p!="number"||!y||o===void 0)return null;const M=p===o-1;if(p>=o&&k)return 0;if(M&&!k)return 1;if(!b&&!M)return null;const E=M?p+1:p-1,L=M?y[E]-y[E-1]:y[E+1]-y[E],O=A/Math.abs(L);return M?1-O:O}return{isLastSnapPoint:g,activeSnapPoint:d,shouldFade:b,getPercentageDragged:T,setActiveSnapPoint:f,activeSnapPointIndex:p,onRelease:w,onDrag:C,snapPointsOffset:y}}const fw=()=>()=>{};function mw(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:n,noBodyStyles:a}=Cn(),o=H.useRef(null),i=l.useMemo(()=>document.body.style.backgroundColor,[]);function c(){return(window.innerWidth-Ia)/window.innerWidth}H.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;iw(n&&!a?ra(document.body,{background:"black"}):fw,ra(u,{transformOrigin:He(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Fe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Fe.EASE.join(",")})`}));const m=ra(u,{borderRadius:`${Id}px`,overflow:"hidden",...He(e)?{transform:`scale(${c()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${c()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{m(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},Fe.DURATION*1e3)}}},[t,s,i])}let Js=null;function hw({isOpen:e,modal:t,nested:s,hasBeenOpened:n,preventScrollRestoration:a,noBodyStyles:o}){const[i,c]=H.useState(()=>typeof window<"u"?window.location.href:""),u=H.useRef(0),m=H.useCallback(()=>{if(jl()&&Js===null&&e&&!o){Js={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:f,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-f}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const v=h-window.innerHeight;v&&u.current>=h&&(document.body.style.top=`${-(u.current+v)}px`)}),300)}},[e]),d=H.useCallback(()=>{if(jl()&&Js!==null&&!o){const f=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Js),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){c(window.location.href);return}window.scrollTo(h,f)}),Js=null}},[i]);return H.useEffect(()=>{function f(){u.current=window.scrollY}return f(),window.addEventListener("scroll",f),()=>{window.removeEventListener("scroll",f)}},[]),H.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),H.useEffect(()=>{s||!n||(e?(!window.matchMedia("(display-mode: standalone)").matches&&m(),t||window.setTimeout(()=>{d()},500)):d())},[e,n,i,t,s,m,d]),{restorePositionSetting:d}}function pw({open:e,onOpenChange:t,children:s,onDrag:n,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:c=!0,closeThreshold:u=lw,scrollLockTimeout:m=cw,dismissible:d=!0,handleOnly:f=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:v,setActiveSnapPoint:g,fixed:p,modal:b=!0,onClose:y,nested:S,noBodyStyles:x=!1,direction:w="bottom",defaultOpen:C=!1,disablePreventScroll:T=!0,snapToSequentialPoint:A=!1,preventScrollRestoration:k=!1,repositionInputs:M=!0,onAnimationEnd:D,container:E,autoFocus:L=!1}){var O,j;const[I=!1,P]=Td({defaultProp:C,prop:e,onChange:K=>{t?.(K),!K&&!S&&$(),setTimeout(()=>{D?.(K)},Fe.DURATION*1e3),K&&!b&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),K||(document.body.style.pointerEvents="auto")}}),[R,F]=H.useState(!1),[N,V]=H.useState(!1),[Q,re]=H.useState(!1),se=H.useRef(null),fe=H.useRef(null),Z=H.useRef(null),ne=H.useRef(null),le=H.useRef(null),U=H.useRef(!1),_=H.useRef(null),de=H.useRef(0),ge=H.useRef(!1),we=H.useRef(!C),Re=H.useRef(0),q=H.useRef(null),Ce=H.useRef(((O=q.current)==null?void 0:O.getBoundingClientRect().height)||0),xe=H.useRef(((j=q.current)==null?void 0:j.getBoundingClientRect().width)||0),Ne=H.useRef(0),ue=H.useCallback(K=>{o&&K===G.length-1&&(fe.current=new Date)},[]),{activeSnapPoint:te,activeSnapPointIndex:be,setActiveSnapPoint:De,onRelease:Ue,snapPointsOffset:G,onDrag:Ge,shouldFade:ke,getPercentageDragged:Ke}=dw({snapPoints:o,activeSnapPointProp:v,setActiveSnapPointProp:g,drawerRef:q,fadeFromIndex:h,overlayRef:se,onSnapPointChange:ue,direction:w,container:E,snapToSequentialPoint:A});ew({isDisabled:!I||N||!b||Q||!R||!M||!T});const{restorePositionSetting:$}=hw({isOpen:I,modal:b,nested:S??!1,hasBeenOpened:R,preventScrollRestoration:k,noBodyStyles:x});function ce(){return(window.innerWidth-Ia)/window.innerWidth}function ae(K){var pe,oe;!d&&!o||q.current&&!q.current.contains(K.target)||(Ce.current=((pe=q.current)==null?void 0:pe.getBoundingClientRect().height)||0,xe.current=((oe=q.current)==null?void 0:oe.getBoundingClientRect().width)||0,V(!0),Z.current=new Date,Cd()&&window.addEventListener("touchend",()=>U.current=!1,{once:!0}),K.target.setPointerCapture(K.pointerId),de.current=He(w)?K.pageY:K.pageX)}function me(K,pe){var oe;let J=K;const je=(oe=window.getSelection())==null?void 0:oe.toString(),Pe=q.current?Pn(q.current,w):null,_e=new Date;if(J.tagName==="SELECT"||J.hasAttribute("data-vaul-no-drag")||J.closest("[data-vaul-no-drag]"))return!1;if(w==="right"||w==="left")return!0;if(fe.current&&_e.getTime()-fe.current.getTime()<500)return!1;if(Pe!==null&&(w==="bottom"?Pe>0:Pe<0))return!0;if(je&&je.length>0)return!1;if(le.current&&_e.getTime()-le.current.getTime()<m&&Pe===0||pe)return le.current=_e,!1;for(;J;){if(J.scrollHeight>J.clientHeight){if(J.scrollTop!==0)return le.current=new Date,!1;if(J.getAttribute("role")==="dialog")return!0}J=J.parentNode}return!0}function Me(K){if(q.current&&N){const pe=w==="bottom"||w==="right"?1:-1,oe=(de.current-(He(w)?K.pageY:K.pageX))*pe,J=oe>0,je=o&&!d&&!J;if(je&&be===0)return;const Pe=Math.abs(oe),_e=document.querySelector("[data-vaul-drawer-wrapper]"),Je=w==="bottom"||w==="top"?Ce.current:xe.current;let qe=Pe/Je;const Ee=Ke(Pe,J);if(Ee!==null&&(qe=Ee),je&&qe>=1||!U.current&&!me(K.target,J))return;if(q.current.classList.add(aa),U.current=!0,Ve(q.current,{transition:"none"}),Ve(se.current,{transition:"none"}),o&&Ge({draggedDistance:oe}),J&&!o){const Be=ow(oe),lt=Math.min(Be*-1,0)*pe;Ve(q.current,{transform:He(w)?`translate3d(0, ${lt}px, 0)`:`translate3d(${lt}px, 0, 0)`});return}const et=1-qe;if((ke||h&&be===h-1)&&(n?.(K,qe),Ve(se.current,{opacity:`${et}`,transition:"none"},!0)),_e&&se.current&&i){const Be=Math.min(ce()+qe*(1-ce()),1),lt=8-qe*8,tt=Math.max(0,14-qe*14);Ve(_e,{borderRadius:`${lt}px`,transform:He(w)?`scale(${Be}) translate3d(0, ${tt}px, 0)`:`scale(${Be}) translate3d(${tt}px, 0, 0)`,transition:"none"},!0)}if(!o){const Be=Pe*pe;Ve(q.current,{transform:He(w)?`translate3d(0, ${Be}px, 0)`:`translate3d(${Be}px, 0, 0)`})}}}H.useEffect(()=>{window.requestAnimationFrame(()=>{we.current=!0})},[]),H.useEffect(()=>{var K;function pe(){if(!q.current||!M)return;const oe=document.activeElement;if(Ea(oe)||ge.current){var J;const je=((J=window.visualViewport)==null?void 0:J.height)||0,Pe=window.innerHeight;let _e=Pe-je;const Je=q.current.getBoundingClientRect().height||0,qe=Je>Pe*.8;Ne.current||(Ne.current=Je);const Ee=q.current.getBoundingClientRect().top;if(Math.abs(Re.current-_e)>60&&(ge.current=!ge.current),o&&o.length>0&&G&&be){const et=G[be]||0;_e+=et}if(Re.current=_e,Je>je||ge.current){const et=q.current.getBoundingClientRect().height;let Be=et;et>je&&(Be=je-(qe?Ee:Ia)),p?q.current.style.height=`${et-Math.max(_e,0)}px`:q.current.style.height=`${Math.max(Be,je-Ee)}px`}else V0()||(q.current.style.height=`${Ne.current}px`);o&&o.length>0&&!ge.current?q.current.style.bottom="0px":q.current.style.bottom=`${Math.max(_e,0)}px`}}return(K=window.visualViewport)==null||K.addEventListener("resize",pe),()=>{var oe;return(oe=window.visualViewport)==null?void 0:oe.removeEventListener("resize",pe)}},[be,o,G]);function he(K){Ae(),y?.(),K||P(!1),setTimeout(()=>{o&&De(o[0])},Fe.DURATION*1e3)}function Se(){if(!q.current)return;const K=document.querySelector("[data-vaul-drawer-wrapper]"),pe=Pn(q.current,w);Ve(q.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${Fe.DURATION}s cubic-bezier(${Fe.EASE.join(",")})`}),Ve(se.current,{transition:`opacity ${Fe.DURATION}s cubic-bezier(${Fe.EASE.join(",")})`,opacity:"1"}),i&&pe&&pe>0&&I&&Ve(K,{borderRadius:`${Id}px`,overflow:"hidden",...He(w)?{transform:`scale(${ce()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${ce()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${Fe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Fe.EASE.join(",")})`},!0)}function Ae(){!N||!q.current||(q.current.classList.remove(aa),U.current=!1,V(!1),ne.current=new Date)}function ve(K){if(!N||!q.current)return;q.current.classList.remove(aa),U.current=!1,V(!1),ne.current=new Date;const pe=Pn(q.current,w);if(!K||!me(K.target,!1)||!pe||Number.isNaN(pe)||Z.current===null)return;const oe=ne.current.getTime()-Z.current.getTime(),J=de.current-(He(w)?K.pageY:K.pageX),je=Math.abs(J)/oe;if(je>.05&&(re(!0),setTimeout(()=>{re(!1)},200)),o){Ue({draggedDistance:J*(w==="bottom"||w==="right"?1:-1),closeDrawer:he,velocity:je,dismissible:d}),a?.(K,!0);return}if(w==="bottom"||w==="right"?J>0:J<0){Se(),a?.(K,!0);return}if(je>Ed){he(),a?.(K,!1);return}var Pe;const _e=Math.min((Pe=q.current.getBoundingClientRect().height)!=null?Pe:0,window.innerHeight);var Je;const qe=Math.min((Je=q.current.getBoundingClientRect().width)!=null?Je:0,window.innerWidth),Ee=w==="left"||w==="right";if(Math.abs(pe)>=(Ee?qe:_e)*u){he(),a?.(K,!1);return}a?.(K,!0),Se()}H.useEffect(()=>(I&&(Ve(document.documentElement,{scrollBehavior:"auto"}),fe.current=new Date),()=>{aw(document.documentElement,"scrollBehavior")}),[I]);function Ye(K){const pe=K?(window.innerWidth-is)/window.innerWidth:1,oe=K?-is:0;_.current&&window.clearTimeout(_.current),Ve(q.current,{transition:`transform ${Fe.DURATION}s cubic-bezier(${Fe.EASE.join(",")})`,transform:He(w)?`scale(${pe}) translate3d(0, ${oe}px, 0)`:`scale(${pe}) translate3d(${oe}px, 0, 0)`}),!K&&q.current&&(_.current=setTimeout(()=>{const J=Pn(q.current,w);Ve(q.current,{transition:"none",transform:He(w)?`translate3d(0, ${J}px, 0)`:`translate3d(${J}px, 0, 0)`})},500))}function Xe(K,pe){if(pe<0)return;const oe=(window.innerWidth-is)/window.innerWidth,J=oe+pe*(1-oe),je=-is+pe*is;Ve(q.current,{transform:He(w)?`scale(${J}) translate3d(0, ${je}px, 0)`:`scale(${J}) translate3d(${je}px, 0, 0)`,transition:"none"})}function Oe(K,pe){const oe=He(w)?window.innerHeight:window.innerWidth,J=pe?(oe-is)/oe:1,je=pe?-is:0;pe&&Ve(q.current,{transition:`transform ${Fe.DURATION}s cubic-bezier(${Fe.EASE.join(",")})`,transform:He(w)?`scale(${J}) translate3d(0, ${je}px, 0)`:`scale(${J}) translate3d(${je}px, 0, 0)`})}return H.useEffect(()=>{b||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[b]),H.createElement(dd,{defaultOpen:C,onOpenChange:K=>{!d&&!K||(K?F(!0):he(!0),P(K))},open:I},H.createElement(Sd.Provider,{value:{activeSnapPoint:te,snapPoints:o,setActiveSnapPoint:De,drawerRef:q,overlayRef:se,onOpenChange:t,onPress:ae,onRelease:ve,onDrag:Me,dismissible:d,shouldAnimate:we,handleOnly:f,isOpen:I,isDragging:N,shouldFade:ke,closeDrawer:he,onNestedDrag:Xe,onNestedOpenChange:Ye,onNestedRelease:Oe,keyboardIsOpen:ge,modal:b,snapPointsOffset:G,activeSnapPointIndex:be,direction:w,shouldScaleBackground:i,setBackgroundColorOnScale:c,noBodyStyles:x,container:E,autoFocus:L}},s))}const Md=H.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:n,onRelease:a,shouldFade:o,isOpen:i,modal:c,shouldAnimate:u}=Cn(),m=jd(t,s),d=n&&n.length>0;if(!c)return null;const f=H.useCallback(h=>a(h),[a]);return H.createElement(pd,{onMouseUp:f,ref:m,"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})});Md.displayName="Drawer.Overlay";const Ad=H.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...n},a){const{drawerRef:o,onPress:i,onRelease:c,onDrag:u,keyboardIsOpen:m,snapPointsOffset:d,activeSnapPointIndex:f,modal:h,isOpen:v,direction:g,snapPoints:p,container:b,handleOnly:y,shouldAnimate:S,autoFocus:x}=Cn(),[w,C]=H.useState(!1),T=jd(a,o),A=H.useRef(null),k=H.useRef(null),M=H.useRef(!1),D=p&&p.length>0;mw();const E=(O,j,I=0)=>{if(M.current)return!0;const P=Math.abs(O.y),R=Math.abs(O.x),F=R>P,N=["bottom","right"].includes(j)?1:-1;if(j==="left"||j==="right"){if(!(O.x*N<0)&&R>=0&&R<=I)return F}else if(!(O.y*N<0)&&P>=0&&P<=I)return!F;return M.current=!0,!0};H.useEffect(()=>{D&&window.requestAnimationFrame(()=>{C(!0)})},[]);function L(O){A.current=null,M.current=!1,c(O)}return H.createElement(gd,{"data-vaul-drawer-direction":g,"data-vaul-drawer":"","data-vaul-delayed-snap-points":w?"true":"false","data-vaul-snap-points":v&&D?"true":"false","data-vaul-custom-container":b?"true":"false","data-vaul-animate":S?.current?"true":"false",...n,ref:T,style:d&&d.length>0?{"--snap-point-height":`${d[f??0]}px`,...t}:t,onPointerDown:O=>{y||(n.onPointerDown==null||n.onPointerDown.call(n,O),A.current={x:O.pageX,y:O.pageY},i(O))},onOpenAutoFocus:O=>{s?.(O),x||O.preventDefault()},onPointerDownOutside:O=>{if(e?.(O),!h||O.defaultPrevented){O.preventDefault();return}m.current&&(m.current=!1)},onFocusOutside:O=>{if(!h){O.preventDefault();return}},onPointerMove:O=>{if(k.current=O,y||(n.onPointerMove==null||n.onPointerMove.call(n,O),!A.current))return;const j=O.pageY-A.current.y,I=O.pageX-A.current.x,P=O.pointerType==="touch"?10:2;E({x:I,y:j},g,P)?u(O):(Math.abs(I)>P||Math.abs(j)>P)&&(A.current=null)},onPointerUp:O=>{n.onPointerUp==null||n.onPointerUp.call(n,O),A.current=null,M.current=!1,c(O)},onPointerOut:O=>{n.onPointerOut==null||n.onPointerOut.call(n,O),L(k.current)},onContextMenu:O=>{n.onContextMenu==null||n.onContextMenu.call(n,O),k.current&&L(k.current)}})});Ad.displayName="Drawer.Content";const gw=250,xw=120,Od=H.forwardRef(function({preventCycle:e=!1,children:t,...s},n){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:c,setActiveSnapPoint:u,dismissible:m,handleOnly:d,isOpen:f,onPress:h,onDrag:v}=Cn(),g=H.useRef(null),p=H.useRef(!1);function b(){if(p.current){x();return}window.setTimeout(()=>{y()},xw)}function y(){if(o||e||p.current){x();return}if(x(),!i||i.length===0){m||a();return}if(c===i[i.length-1]&&m){a();return}const C=i.findIndex(A=>A===c);if(C===-1)return;const T=i[C+1];u(T)}function S(){g.current=window.setTimeout(()=>{p.current=!0},gw)}function x(){g.current&&window.clearTimeout(g.current),p.current=!1}return H.createElement("div",{onClick:b,onPointerCancel:x,onPointerDown:w=>{d&&h(w),S()},onPointerMove:w=>{d&&v(w)},ref:n,"data-vaul-drawer-visible":f?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},H.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});Od.displayName="Drawer.Handle";function bw(e){const t=Cn(),{container:s=t.container,...n}=e;return H.createElement(hd,{container:s,...n})}const dt={Root:pw,Content:Ad,Overlay:Md,Portal:bw,Handle:Od,Title:vd},Dd="inline-flex items-center justify-center transition-colors",vw=We(Dd,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),yw=We(Dd,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),zo=({accountId:e,currentMailboxId:t,onMove:s,disabled:n=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[c,u]=l.useState(!1),[m,d]=l.useState(),f=es(),h=l.useRef(null),v=i??"Move to folder",g=l.useId(),{t:p}=Wa("mail",{useSuspense:!1}),b=so(),{data:y,isLoading:S,isError:x,error:w,refetch:C}=ye({...it({path:{accountId:e}}),staleTime:1/0,enabled:c}),T=Po(e),{createFolderIn:A}=Ec(e),k=l.useMemo(()=>no({mailboxes:y?.items??[],folderAppointments:T,currentMailboxId:t,translator:b}),[y?.items,T,t,b]),M=ro(y?.items??[]),D=k.find(R=>R.id===m),E=l.useCallback(()=>{u(!1),d(void 0)},[]),L=l.useCallback(()=>{D&&(E(),s(D.id))},[D,E,s]);l.useEffect(()=>{if(!c||!f)return;const R=N=>{h.current&&!h.current.contains(N.target)&&E()},F=N=>{N.key==="Escape"&&E()};return document.addEventListener("mousedown",R),document.addEventListener("keydown",F),()=>{document.removeEventListener("mousedown",R),document.removeEventListener("keydown",F)}},[c,f,E]);const O=n||!!a,j=r.jsxs("button",{type:"button",onClick:R=>{R.stopPropagation(),!O&&u(F=>!F)},"aria-label":v,"aria-haspopup":f?"tree":"dialog","aria-expanded":c,"aria-controls":c?g:void 0,title:a,className:o==="icon-only"?vw:yw,children:[r.jsx(Pa,{className:o==="icon-only"?"size-5":"size-4"}),o==="compact"&&r.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),I=S?r.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):x?r.jsx("div",{className:"p-3",children:r.jsx(ts,{variant:"inline",title:"Couldn't load folders",error:w,onRetry:()=>C()})}):r.jsx(cc,{folders:k,selectedId:m,delimiter:M,onSelect:d,onCreateFolder:A,onCancel:E,labels:{filterPlaceholder:p("move_picker_filter_placeholder",{defaultValue:"Filter folders…"}),filterAriaLabel:p("move_picker_filter_label",{defaultValue:"Filter folders"})}}),P=D&&r.jsx("div",{className:"shrink-0 border-t border-line p-2",children:r.jsx(ie,{variant:"primary",onClick:L,className:"h-11 w-full font-semibold",children:`Move to ${D.label}`})});return f?r.jsxs("div",{ref:h,className:"relative inline-block",children:[j,c&&r.jsxs("div",{id:g,className:We("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:[I,P]})]}):r.jsxs(r.Fragment,{children:[j,r.jsx(dt.Root,{open:c,onOpenChange:R=>R?u(!0):E(),children:r.jsxs(dt.Portal,{children:[r.jsx(dt.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(dt.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-lg bg-canvas pb-[env(safe-area-inset-bottom,0px)]",style:{maxHeight:"85dvh"},id:g,children:[r.jsx(dt.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),r.jsx(dt.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),r.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:I}),P]})]})})]})},ww=({messageId:e,threadId:t,mailboxId:s,isRead:n,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:c=!1,onToggleRaw:u})=>{const m=Te(),d=Qe(),{pushError:f}=nt(),{selectedMessageId:h}=As({strict:!1}),{mutate:v,isPending:g}=ze({...ur(),onMutate:async I=>{const P=I.body.isRead??!0,R=new Set(I.body.messageIds??[]),F=Zt({path:{threadId:t}}),N=Et([s]);await Promise.all([m.cancelQueries({queryKey:F}),bn(m,N)]);const V=m.getQueriesData({queryKey:F}).filter(re=>re[1]!==void 0).map(([re,se])=>({queryKey:re,data:se})),Q=vn(m,N);return m.setQueriesData({queryKey:F},re=>re&&{...re,items:Jn(re.items,R,P)}),yn(m,N,re=>Jn(re,R,P)),{threadMessagesPrefix:F,listPrefixes:N,previousThreadMessages:V,previousThreadsList:Q}},onError:(I,P,R)=>{if(R){for(const N of R.previousThreadMessages)m.setQueryData(N.queryKey,N.data);wn(m,R.previousThreadsList)}const F=P.body.isRead??!0;f({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(I),error:I})},onSettled:(I,P,R,F)=>{F&&(m.invalidateQueries({queryKey:F.threadMessagesPrefix}),It(m,F.listPrefixes))}}),p=l.useCallback(I=>{h&&I.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:P=>({...P,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:b,isPending:y}=ms({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:S,isPending:x}=Ds({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:w,isPending:C,error:T,reset:A}=Lo({messageId:e}),k=()=>{v({body:{messageIds:[e],isRead:!1}})},M=()=>{b([e])},D=()=>{o&&w(o,i)},E=g||y||x||C,L=E||!o,O=l.useCallback(I=>{S([e],I)},[S,e]),j=o?void 0:"Sender has no parseable address";return r.jsxs("div",{className:"flex flex-col items-end gap-1",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[a&&r.jsx(zo,{accountId:a,currentMailboxId:s,onMove:O,disabled:E,label:"Move this message"}),r.jsxs(_u,{trigger:r.jsx(Bc,{className:"size-4"}),children:[r.jsxs(nn,{onClick:D,disabled:L,children:[i?r.jsx(pr,{className:"size-4 text-positive"}):r.jsx(mn,{className:"size-4 opacity-0"}),r.jsx("span",{title:j,children:"Trusted sender"})]}),n&&r.jsxs(nn,{onClick:k,disabled:E,children:[r.jsx(gr,{className:"size-4"}),"Mark as unread"]}),u&&r.jsxs(nn,{onClick:u,children:[r.jsx(zc,{className:"size-4"}),c?"Show formatted":"Show raw email"]}),r.jsx(zu,{}),r.jsxs(nn,{onClick:M,disabled:E,destructive:!0,children:[r.jsx(Lt,{className:"size-4"}),"Delete"]})]})]}),T&&r.jsx("div",{className:"w-64",children:r.jsx(ts,{variant:"inline",title:"Couldn't update trust",error:T,onRetry:()=>{A(),D()}})})]})},Sw=e=>e==="link-expired"||e==="not-ready";class Ra extends Error{reason;status;constructor(t,s,n){super(s),this.name="AttachmentFetchError",this.reason=t,this.status=n}}const Cw="x-remit-403-reason",kw="expired",jw=(e,t)=>{if(t?.trim()===kw)return"link-expired";const s=ed(e,t);return s==="auth"?"auth":s==="body-missing"?"missing":"generic"},Nw=300*1e3,Rl=async(e,t)=>{const s={},n=await t();n&&(s.Authorization=`Bearer ${n}`);const a=await gc(e,{headers:s,signal:AbortSignal.timeout(Nw)});if(a.status===202)throw new Ra("not-ready","Attachment is still being fetched from the mail server",202);if(!a.ok)throw new Ra(jw(a.status,a.headers.get(Cw)),`Failed to download attachment (${a.status} ${a.statusText})`,a.status);return a.blob()},Ew=(e,t,s)=>{switch(e){case"auth":return{title:"Your session expired",detail:`Sign in again, then download ${t} once more. Other parts of the app may also stop responding until you do.`};case"link-expired":return{title:"This download link expired and could not be renewed",detail:`Reload the page, then download ${t} again. If that keeps failing, this is worth reporting.`};case"missing":return{title:"This attachment is missing from storage",detail:"Remit has the message but not the file. Re-sync the account from Settings, then try again."};case"not-ready":return{title:"Still fetching this attachment",detail:"Remit is downloading it from the mail server now. Try again in a few seconds."};default:return{title:"Couldn't download this attachment",detail:s}}},Tl=e=>e instanceof Ra?e.reason:"generic",Iw=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while downloading this attachment.",Rw=(e,t,s)=>{if(e!=="auth")return Ya(Xa({title:`Bug: attachment download failed (${e})`,errorMessage:`Downloading "${t}" failed: ${s}`}))},Tw=(e,t)=>{const s=URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,n.rel="noopener",document.body.append(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(s),0)},Mw=e=>{const t=e.toUpperCase();return t==="OCTET-STREAM"?"FILE":t},Aw=e=>{const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return t.length>0?`attachment.${t}`:"attachment"},Ml=e=>e.filter(t=>!t.isMultipart&&t.disposition===Th.Attachment&&t.contentUrl.length>0).map(t=>({bodyPartId:t.bodyPartId,filename:Yg(t.dispositionFilename??"",Aw(t.mediaSubtype)),typeLabel:Mw(t.mediaSubtype),sizeOctets:t.sizeOctets,contentUrl:t.contentUrl})),Al={status:"idle"},Ow=({messageId:e,bodyParts:t,hasAttachment:s=!1,className:n})=>{const{getToken:a}=ar(),o=Te(),[i,c]=l.useState({}),u=l.useMemo(()=>Ml(t??[]),[t]),m=Va({path:{messageId:e}}),d=g=>Rl(g.contentUrl,a).catch(p=>{if(!Sw(Tl(p)))throw p;return o.refetchQueries({queryKey:m}).then(()=>{const b=o.getQueryData(m),y=b?Ml(b.bodyParts).find(S=>S.bodyPartId===g.bodyPartId):void 0;return Rl(y?.contentUrl??g.contentUrl,a)})}),f=(g,p)=>c(b=>({...b,[g]:p})),h=g=>{const p=u.find(b=>b.bodyPartId===g);if(!p)throw new Error(`No attachment part ${g} on message ${e}`);f(g,{status:"downloading"}),d(p).then(b=>{Tw(b,p.filename),f(g,Al)}).catch(b=>{const y=Tl(b),S=Iw(b),{title:x,detail:w}=Ew(y,p.filename,S);f(g,{status:"failed",title:x,detail:w,reportUrl:Rw(y,p.filename,S)})})},v=s&&t!==void 0&&u.length===0;return r.jsx(Zg,{className:n,attachments:u.map(g=>({attachmentId:g.bodyPartId,filename:g.filename,typeLabel:g.typeLabel,sizeOctets:g.sizeOctets,download:i[g.bodyPartId]??Al})),onDownload:h,hasUnlistedAttachment:v})},Dw=()=>{const[e,t]=l.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return l.useEffect(()=>{const s=document.documentElement,n=new MutationObserver(()=>{t(s.classList.contains("dark"))});return n.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e},Pw=({blockedImageCount:e,canAlwaysTrust:t,isTrustPending:s,onLoadOnce:n,onAlwaysTrust:a})=>r.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-md bg-surface-sunken/50 px-3 py-2 text-sm",children:[r.jsxs("span",{className:"text-fg-muted",children:[e," image",e>1?"s":""," blocked for privacy"]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("button",{type:"button",onClick:n,className:"text-accent hover:underline",children:"Load once"}),t&&r.jsx("button",{type:"button",onClick:a,"aria-busy":s,className:"text-accent hover:underline aria-busy:opacity-50",children:s?"Trusting…":"Always trust"})]})]}),Lw=(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}}},Fw=e=>e instanceof cs?e.reason:"generic",$w=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",_w=({error:e,onRetry:t})=>{const s=Fw(e),n=$w(e),{title:a,detail:o}=Lw(s,n),[i,c]=l.useState(!1),{Account:u}=ar();return i?null:r.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:[r.jsx(Pt,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"font-medium text-danger",children:a}),r.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&r.jsx(u,{children:({signOut:m})=>r.jsx("button",{type:"button",onClick:()=>m(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&r.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),r.jsx("button",{type:"button",onClick:()=>c(!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:r.jsx(Nt,{className:"size-4","aria-hidden":"true"})})]})]})},zw=()=>r.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),Ol=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Pd=({bodyParts:e,html:t,text:s,isTrusted:n=!1,messageId:a,fromAddressId:o,category:i,className:c})=>{const[u,m]=l.useState(!1),d=n||u,f=Dw(),{toggleTrusted:h,isPending:v}=Lo({messageId:a??""}),g=!!e&&e.length>0,{picked:p,data:b,isLoading:y,isError:S,error:x,refetch:w}=td({messageId:a,bodyParts:e,enabled:g}),C=l.useMemo(()=>ug(e??[]),[e]),T=g&&b?.kind==="html"?b.body:t,A=g&&b?.kind==="text"?b.body:s;if(g){if(y)return r.jsx("div",{className:We("message-body",c),children:r.jsx(zw,{})});if(S)return r.jsx("div",{className:We("message-body",c),children:r.jsx(_w,{error:x,onRetry:()=>w()})});if(!p)return r.jsx("div",{className:We("message-body",c),children:r.jsx(Ol,{})})}else if(!t&&!s)return r.jsx("div",{className:We("message-body",c),children:r.jsx(Ol,{})});const k=!!(o&&a),M=()=>{!o||v||(m(!0),h(o,!1))};return r.jsx(cu,{className:c,html:T,text:A,isDark:f,category:i,allowImages:d,resolveCid:C,renderBlockedNotice:D=>r.jsx(Pw,{blockedImageCount:D,canAlwaysTrust:k,isTrustPending:v,onLoadOnce:()=>m(!0),onAlwaysTrust:M})})},Bw=({messageId:e,threadId:t,mailboxId:s,accountId:n,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:c,isTrusted:u,showRaw:m,onToggleRaw:d,onReply:f,onReplyAll:h,onForward:v})=>{const g=Te(),{deleteMessages:p}=ms({mailboxId:s,threadId:t}),{moveMessages:b}=Ds({mailboxId:s,threadId:t,accountId:n}),{toggleTrusted:y}=Lo({messageId:e}),{mutate:S}=ze({...ur(),onSettled:()=>{g.invalidateQueries({queryKey:Zt({path:{threadId:t}})}),It(g,Et([s]))}}),x=l.useCallback(A=>{b([e],A)},[b,e]),w=l.useCallback(()=>{p([e])},[p,e]),C=l.useCallback(()=>{S({body:{messageIds:[e],isRead:!a}})},[S,e,a]),T=[];return c&&T.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?r.jsx(pr,{className:"size-4 text-positive"}):r.jsx(mn,{className:"size-4"}),onSelect:()=>y(c,u)}),d&&T.push({key:"raw",label:m?"Show formatted":"Show raw email",icon:r.jsx(zc,{className:"size-4"}),onSelect:d}),r.jsx(lu,{hasThread:!0,onReply:f,onReplyAll:h,onForward:v,isStarred:o,onToggleStar:i,onDelete:w,isRead:a,onToggleRead:C,overflowItems:T,moveSlot:n?r.jsx(zo,{accountId:n,currentMailboxId:s,onMove:x,label:"Move this message"}):void 0})},Uw=()=>r.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading raw email",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"})]}),Kw=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:n,isError:a,error:o,refetch:i}=ye({...Fm({path:{messageId:e}}),enabled:t});if(n)return r.jsx("div",{className:"message-body",children:r.jsx(Uw,{})});if(a)return r.jsx("div",{className:"message-body",children:r.jsx(ts,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const c=s?.raw??"";return c===""?r.jsx("div",{className:"message-body",children:r.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):r.jsx("div",{className:"message-body",children:r.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:c})})},qw=()=>r.jsx(pr,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),Ld=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),Fd=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:We("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":We("text-fg-subtle hover:text-warning",n&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:r.jsx(Xt,{className:We("size-3.5",e&&"fill-current")})}),Hw=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:n,isStarPending:a})=>{const o=jc(e.sentDate,"datetime"),i=Ld(e,o);return r.jsx(uu,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:r.jsxs(r.Fragment,{children:[e.hasAttachment&&r.jsx(xr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"}),r.jsx(Fd,{isStarred:e.hasStars,onToggleStar:n,isStarPending:a,hoverReveal:!0}),r.jsx("span",{"data-testid":"message-date",className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:o})]})})},Ww=({threadMessage:e,messageData:t,isLoading:s,isError:n,error:a,onRetry:o,isFocused:i,onToggle:c,onToggleStar:u,isStarPending:m,accountId:d,showRaw:f,onToggleRaw:h,mobile:v,onReply:g,onReplyAll:p,onForward:b})=>{const y=jc(e.sentDate,"long"),S=!e.isRead,x=t?.envelope.from[0]?.flags?.trusted?.value===!0,w=t?.envelope.from[0]?.addressId,C=Ld(e,y),T=e.autoMoved||e.spamReport?r.jsx(O0,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,spamReport:e.spamReport}):null;return r.jsx(du,{message:C,isFocused:v?!1:i,onHeaderClick:c,senderBadge:x?r.jsx(qw,{}):void 0,trailing:r.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:y}),to:t?r.jsx(jp,{label:"To",addresses:t.envelope.to}):null,indicators:T||!v?r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[T,!v&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"flex items-center justify-end gap-1",children:r.jsx(Fd,{isStarred:e.hasStars,onToggleStar:u,isStarPending:m})}),S&&r.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:v?void 0:r.jsx(ww,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:w,isTrusted:x,showRaw:f,onToggleRaw:h}),actionBar:v?r.jsx(Bw,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:w,isTrusted:x,showRaw:f,onToggleRaw:h,onReply:g,onReplyAll:p,onForward:b}):void 0,body:s?r.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):n&&$m(a)?r.jsx("div",{className:"mt-3",children:r.jsx(sd,{message:"This message has been deleted"})}):n?r.jsx("div",{className:"mt-3",children:r.jsx(ts,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):f?r.jsx("div",{className:"mt-3",children:r.jsx(Kw,{messageId:e.messageId})}):r.jsxs("div",{className:"mt-3",children:[r.jsx(Pd,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:x,category:Er(e.category)}),r.jsx(Ow,{messageId:e.messageId,bodyParts:t?.bodyParts,hasAttachment:e.hasAttachment,className:"mt-4 px-2 lg:px-0"})]})})},Vw=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,mobile:c,onReply:u,onReplyAll:m,onForward:d})=>{const[f,h]=l.useState(!1),{data:v,isLoading:g,isError:p,error:b,refetch:y}=ye({...dr({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?r.jsx(Ww,{threadMessage:e,messageData:v,isLoading:g,isError:p,error:b,onRetry:()=>y(),isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,showRaw:f,onToggleRaw:()=>h(S=>!S),mobile:c,onReply:u,onReplyAll:m,onForward:d}):r.jsx(Hw,{threadMessage:e,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o})},Qw=()=>r.jsxs("div",{className:"animate-pulse p-4",children:[r.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),r.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>r.jsxs("div",{className:"flex gap-3 py-3",children:[r.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function Dl({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?r.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:[r.jsx($s,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",r.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&r.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const Bs=({threadId:e,mailboxId:t,subject:s,selectedMessageId:n,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:c,onComposeClose:u,onSwipeNext:m,onSwipePrevious:d,mobileIntelligenceOpen:f})=>{const h=es(),{handlers:v}=y0({onSwipeLeft:m,onSwipeRight:d}),{accountId:g}=Ao(t),{data:p,isLoading:b,isError:y,error:S,refetch:x}=ye({..._m({path:{threadId:e}})}),w=l.useMemo(()=>p?.items??[],[p?.items]),C=w[w.length-1],T=l.useRef(new Map),[A,k]=l.useState(new Set),[M,D]=l.useState(null),[E,L]=l.useState(0);l.useEffect(()=>{if(w.length>0&&e!==M){D(e);const ue=new Set([w[w.length-1].threadMessageId]);if(n){const te=w.find(be=>be.messageId===n);te&&ue.add(te.threadMessageId)}k(ue),L(w.length-1)}},[e,w,M,n]);const O=l.useCallback(ue=>{k(te=>{const be=new Set(te);return be.has(ue)?be.delete(ue):be.add(ue),be})},[]),j=l.useCallback(ue=>{const te=w[ue];if(!te)return;T.current.get(te.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[w]),I=l.useCallback(()=>{if(w.length===0)return;const ue=Math.min(E+1,w.length-1);L(ue),j(ue)},[w.length,E,j]),P=l.useCallback(()=>{if(w.length===0)return;const ue=Math.max(E-1,0);L(ue),j(ue)},[w.length,E,j]),R=l.useCallback(()=>{const ue=w[E];ue&&O(ue.threadMessageId)},[w,E,O]),{data:F}=ye({...$t(),staleTime:1/0}),N=F?.accounts?.[0];g0({messages:w,expandedIds:A,threadId:e,mailboxId:t,accountId:N?.accountId});const{toggleStar:V,isPending:Q,pendingMessageId:re}=Oo({threadId:e,mailboxId:t,messages:w}),[se,fe]=l.useState(null),[Z,ne]=l.useState(0),le=l.useCallback(ue=>{fe(ue),ne(te=>te+1)},[]);l.useEffect(()=>{c&&c!=="new"&&(le(c),u?.())},[c,u,le]);const{data:U}=ye({...dr({path:{messageId:C?.messageId??""}}),enabled:!!C&&se!==null}),_=l.useCallback(()=>le("reply"),[le]),de=l.useCallback(()=>le("reply_all"),[le]),ge=l.useCallback(()=>le("forward"),[le]),we=l.useCallback(()=>{fe(null),u?.()},[u]),Re=l.useRef(null);if(l.useEffect(()=>{if(se===null||Z===0)return;const ue=Re.current;if(!ue)return;const te=()=>ue.scrollIntoView({behavior:"smooth",block:"end"});if(te(),typeof ResizeObserver>"u")return;const be=new ResizeObserver(te);return be.observe(ue),()=>be.disconnect()},[Z,se]),Mo({enabled:!b&&w.length>0&&se===null,bindings:[{key:"j",handler:I,preventDefault:!0},{key:"ArrowDown",handler:I,preventDefault:!0},{key:"k",handler:P,preventDefault:!0},{key:"ArrowUp",handler:P,preventDefault:!0},{key:"Enter",handler:R,preventDefault:!0},{key:"o",handler:R,preventDefault:!0},{key:"r",handler:_,preventDefault:!0},{key:"R",handler:de,noModifiers:!1,preventDefault:!0},{key:"f",handler:ge,preventDefault:!0}]}),b)return r.jsx(Qw,{});if(y)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(ts,{title:"Couldn't load this conversation",error:S,onRetry:()=>x()})});if(w.length===0)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(sd,{message:"No messages in this thread"})});const q=s||w[0]?.subject||"(No subject)",Ce=w.length,xe=ue=>r.jsx("div",{children:w.map((te,be)=>r.jsx("div",{ref:De=>{De&&T.current.set(te.threadMessageId,De)},children:r.jsx(Vw,{threadMessage:te,isExpanded:A.has(te.threadMessageId),isFocused:be===E,onToggle:()=>O(te.threadMessageId),onToggleStar:()=>V(te.messageId,te.hasStars),isStarPending:Q&&re===te.messageId,accountId:g,mobile:ue,onReply:ue?_:void 0,onReplyAll:ue?de:void 0,onForward:ue?ge:void 0})},te.threadMessageId))}),Ne=r.jsxs("header",{className:"border-b border-line px-5 pt-5 pb-3",children:[r.jsx("h1",{className:"max-w-2xl text-lg font-semibold leading-snug text-fg",children:q}),r.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Ce," ",Ce===1?"message":"messages"]})]});return h?r.jsxs("article",{className:"h-full flex flex-col",children:[Ne,a?.dkimMismatch&&r.jsx(Dl,{authenticity:a,onOpenIntelligence:o}),r.jsx("div",{className:"flex-1 overflow-auto",children:xe(!1)}),se!==null&&r.jsx(yl,{mode:se,account:N,sourceMessage:U,onClose:we})]}):r.jsxs(Pg,{thread:{subject:q,messages:[]},onBack:i??(()=>{}),intelligenceOpen:f,onToggleIntelligence:o,touchHandlers:v,children:[a?.dkimMismatch&&r.jsx(Dl,{authenticity:a,onOpenIntelligence:o}),xe(!0),se!==null&&r.jsx("div",{ref:Re,children:r.jsx(yl,{mode:se,account:N,sourceMessage:U,onClose:we})})]})};function xs(){const{mailboxNameIndex:e,accountNameIndex:t}=Le();return{...Ot({select:n=>Yu(n.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Bo=e=>e.trim().toLocaleLowerCase(),$d={personal:"Personal",uncategorized:"Unclassified",transactional:"Transactional",newsletter:"Newsletter",marketing:"Marketing",social:"Social",automated:"Automated"},Gw=Object.values(ot).map(e=>({value:e,label:$d[e]})),Yw={unclassified:"uncategorized"},Ta=[{name:"from",label:"Sender",values:"contact"},{name:"subject",label:"Subject",values:"text"},{name:"category",label:"Category",values:"fixed",options:Gw},{name:"is",label:"State",values:"fixed",options:[{value:"unread",label:"Unread"},{value:"read",label:"Read"},{value:"starred",label:"Starred"}]},{name:"has",label:"Contents",values:"fixed",options:[{value:"attachment",label:"Has attachment"}]},{name:"in",label:"Folder",values:"mailbox"},{name:"account",label:"Account",values:"account"},{name:"after",label:"Sent on or after",values:"date"},{name:"before",label:"Sent before",values:"date"}],Xw=new Map(Ta.map(e=>[e.name,e])),_d=e=>Xw.get(e.toLowerCase()),Jw=/^\d{4}-\d{2}-\d{2}$/,Zw=e=>/[\s"]/.test(e),eS=e=>Zw(e)?`"${e.replace(/"/g,"")}"`:e,zd=(e,t)=>`${e}:${eS(t)}`,tS=e=>{if(!e.startsWith('"'))return e;const t=e.slice(1);return t.endsWith('"')?t.slice(0,-1):t};function Uo(e){const t=[];let s=-1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];if(o==='"'){n=!n,s<0&&(s=a);continue}if(!n&&/\s/.test(o)){s>=0&&t.push({raw:e.slice(s,a),start:s,end:a}),s=-1;continue}s<0&&(s=a)}return s>=0&&t.push({raw:e.slice(s),start:s,end:e.length}),t}function Bd(e){const t=e.indexOf(":");if(t<=0)return;const s=e.slice(t+1);return{name:e.slice(0,t).toLowerCase(),value:tS(s),rawValue:s}}function sS(e,t,s){if(!Jw.test(s))return;const n=Date.parse(`${s}T00:00:00Z`);if(!Number.isNaN(n))return{type:e,raw:t,value:s,epochSeconds:Math.floor(n/1e3)}}function nS(e){const t=e.toLowerCase(),s=Yw[t];return s||Object.values(ot).find(a=>a===t)}function rS(e,t){switch(t.toLowerCase()){case"unread":return{type:"isUnread",raw:e};case"read":return{type:"isRead",raw:e};case"starred":case"flagged":return{type:"isStarred",raw:e};default:return}}function aS(e,t){const s=Bd(e);if(!s||s.value.length===0)return;const{name:n,value:a}=s;switch(n){case"from":return{type:"from",raw:e,value:a};case"subject":return{type:"subject",raw:e,value:a};case"category":{const o=nS(a);return o?{type:"category",raw:e,value:a,category:o}:void 0}case"is":return rS(e,a);case"has":return a.toLowerCase()==="attachment"?{type:"hasAttachment",raw:e}:void 0;case"before":case"after":return sS(n,e,a);case"in":{const o=t.mailboxesByName?.get(a.toLowerCase());return o?{type:"in",raw:e,value:a,mailboxId:o}:void 0}case"account":{const o=t.accountsByName?.get(a.toLowerCase());return o?{type:"account",raw:e,value:a,accountId:o}:void 0}default:return}}function Us(e,t={}){const s=[],n=[];for(const a of Uo(e)){const o=aS(a.raw,t);o?s.push(o):n.push(a.raw)}return{freeText:n.join(" "),tokens:s}}function oS(e,t){return Uo(e).filter(s=>s.raw!==t.raw).map(s=>s.raw).join(" ")}function Ud(e){switch(e.type){case"from":return`From: ${e.value}`;case"subject":return`Subject: ${e.value}`;case"category":return`Category: ${$d[e.category]}`;case"hasAttachment":return"Has attachment";case"isUnread":return"Unread";case"isRead":return"Read";case"isStarred":return"Starred";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 iS=20,lS=new Set(Object.values(ot)),cS=e=>e!==void 0&&lS.has(e)?e:void 0,uS=e=>{if(e.some(t=>t.type==="isUnread"))return!1;if(e.some(t=>t.type==="isRead"))return!0};function Kd({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Le(),n=xs(),a=Ot({select:w=>w.matches}),o=Bo(s),{freeText:i,tokens:c}=Us(o,n),u=i.length>0,m=c.find(w=>w.type==="category"),d=cS(t)??m?.category,f=c.some(w=>w.type==="hasAttachment")?!0:void 0,h=c.some(w=>w.type==="isStarred")?!0:void 0,v=uS(c),g=c.find(w=>w.type==="after"),p=c.find(w=>w.type==="before"),b=c.find(w=>w.type==="in"),y=Py({matches:a,callerMailboxId:e,inTokenMailboxId:b?.mailboxId}),{data:S,isLoading:x}=ye({...vc({query:{query:i,mailboxId:y,limit:iS,...d!==void 0?{category:d}:{},...f!==void 0?{hasAttachment:f}:{},...h!==void 0?{hasStars:h}:{},...v!==void 0?{isRead:v}:{},...g?{sentDateFrom:g.epochSeconds}:{},...p?{sentDateTo:p.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:S?.items??[],isLoading:u&&x}}const dS=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),fS=e=>[...e].sort(dS);function er(e){const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId,mailboxId:e.mailboxId,threadId:e.threadId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:gt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Er(e.category),suspicious:t}}function Pl(e){return e.filter(t=>t.muted!==!0)}function mS(e,t){const s=new Set,n=[];for(const a of[...e,...t])s.has(a.id)||(s.add(a.id),n.push(a));return n.sort((a,o)=>(o.sentDate??0)-(a.sentDate??0))}const Ll=[{id:"personal",label:"Personal",category:ot.personal},{id:"transactional",label:"Transactional",category:ot.transactional},{id:"newsletter",label:"Newsletter",category:ot.newsletter},{id:"marketing",label:"Marketing",category:ot.marketing},{id:"social",label:"Social",category:ot.social},{id:"automated",label:"Automated",category:ot.automated},{id:"uncategorized",label:"Unclassified",category:ot.uncategorized}];function hS(e){const t=new Map(Ll.map(n=>[n.category,[]]));for(const n of e){const a=n.category??ot.uncategorized;(t.get(a)??t.get(ot.uncategorized))?.push(n)}const s=[];for(const n of Ll){const a=t.get(n.category);a&&a.length>0&&s.push({id:n.id,label:n.label,threads:a})}return s}function qd(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Ko(e,t){return t.every(s=>{switch(s.type){case"from":{const n=s.value.toLowerCase();return e.fromEmail.toLowerCase().includes(n)||e.fromName.toLowerCase().includes(n)}case"subject":return e.subject.toLowerCase().includes(s.value.toLowerCase());case"category":return(e.category??"uncategorized")===s.category;case"hasAttachment":return e.hasAttachment===!0;case"isUnread":return!e.isRead;case"isRead":return e.isRead===!0;case"isStarred":return e.starred===!0;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 Hd="This account has no Junk folder appointed, so there is nowhere to file these. Appoint one under Settings › Folders.",pS="These are already in Junk, so there is nowhere to file them.",Tr=(e,t)=>e!==void 0&&e!==t?e:void 0,gS=(e,t)=>{if(Tr(e,t)===void 0)return e===void 0?Hd:pS},xS={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function bS(e){return xS[e]??e}function vS(e,t){const{folder:s}=Ja(t,[e.mailboxId]);return{id:e.messageId,sender:e.fromName??e.fromEmail??"Unknown",...e.fromEmail?{senderEmail:e.fromEmail}:{},subject:e.subject??"(No subject)",snippet:e.snippet??"",date:gt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Kn(e,t){const{folder:s}=Ja(t,e.mailboxId?[e.mailboxId]:[]);return{id:e.id,sender:e.fromName,...e.fromEmail?{senderEmail:e.fromEmail}:{},subject:e.subject,snippet:e.snippet,date:e.timeLabel,unread:!e.isRead,flagged:e.starred===!0,...e.threadId?{threadId:e.threadId}:{},...e.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function yS(e,t){const{mailboxId:s,folder:n}=Ja(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?gt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:bS(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...n?{folder:n}:{}}}function Wd(e,t,s){const n=new Set(t),a=[];for(const o of[...e].sort((i,c)=>c.score-i.score))n.has(o.threadId)||(n.add(o.threadId),a.push(yS(o,s)));return a}function Vd(e){const{spam:t}=vo([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let n;for(const[a,o]of s)(!n||o>n.count)&&(n={mailboxId:a,count:o});return n}const wS=e=>{const{mailboxId:t,messages:s}=e,n=Te(),{pushError:a}=nt(),{mutateAsync:o,isPending:i}=ze({...zm(),onError:(u,m)=>{a({title:m.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:ft(u),error:u})},onSettled:(u,m,d)=>{It(n,Et(jr(d.body.messageIds??[],s??[],t)))}});return{applyLabel:l.useCallback((u,m,d)=>{u.length!==0&&Os(u,f=>o({body:{messageIds:f,labelId:m,action:d}}))},[o]),isPending:i}};function Qd({accountId:e,mailboxId:t,messageIds:s}){const{labels:n}=ao(e),{applyLabel:a}=wS({mailboxId:t}),o=l.useMemo(()=>n.map(i=>({key:i.labelId,label:i.name,icon:r.jsx("span",{className:`size-2.5 rounded-full ${Bm(i.color)?ni[i.color]:ni.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[n,s,a]);return o.length===0?null:r.jsx(go,{triggerLabel:"Apply label to selected messages",triggerIcon:r.jsx(Um,{className:"size-4 text-fg-subtle"}),triggerText:"Apply label",items:o,align:"start",nested:!0,touch:!1,triggerClassName:"min-h-11 w-full justify-start gap-3 px-4 py-2.5 text-sm font-normal text-fg"})}const SS=768,Gd=e=>e!=="desktop",Mr=()=>{const e=ai(`(min-width: ${SS}px)`);return ai(Cc)?"desktop":e?"tablet":"phone"},Yd=8;function qo(e,t){const s=Math.max(0,Math.min(t,e.length)),n=Uo(e).find(o=>s>=o.start&&s<=o.end);if(!n)return{start:s,end:s,raw:""};const a=Bd(n.raw);return a?{start:n.start,end:n.end,raw:n.raw,name:a.name,value:a.value}:{start:n.start,end:n.end,raw:n.raw}}function CS(e,t){const s=qo(e,t);if(s.name===void 0)return{kind:"token",query:s.raw};const n=_d(s.name);if(n)return{kind:"value",token:n.name,source:n.values,query:s.value??""}}const kS={mailbox:"mailboxes",account:"accounts",contact:"contacts"},jS=(e,t)=>{if(e.values==="fixed")return e.options??[];const s=kS[e.values];return s?t[s]??[]:[]},NS=(e,t)=>{if(t==="")return 1;const s=e.toLowerCase();return s.startsWith(t)?0:s.includes(t)?1:-1},Ma=(e,...t)=>{let s=-1;for(const n of t){if(n===void 0)continue;const a=NS(n,e);a<0||(s<0||a<s)&&(s=a)}return s},Xd=e=>{const t=new Set;return e.filter(s=>s.rank>=0).sort((s,n)=>s.rank-n.rank).filter(s=>{const n=s.suggestion.value.toLowerCase();return t.has(n)?!1:(t.add(n),!0)}).slice(0,Yd).map(s=>s.suggestion)},Fl=e=>({value:`${e.name}:`,label:`${e.name}:`,hint:e.label});function ES(e){const t=e.trim().toLowerCase();if(t==="")return Ta.map(Fl);const s=[];for(const n of Ta)if(s.push({rank:Ma(t,`${n.name}:`,n.label),suggestion:Fl(n)}),n.values==="fixed")for(const a of n.options??[]){const o=zd(n.name,a.value);s.push({rank:Ma(t,o,a.label),suggestion:{value:o,label:a.label??o,hint:o}})}return Xd(s)}function IS(e,t,s){const n=t.trim().toLowerCase(),a=jS(e,s).map(o=>({rank:Ma(n,o.value,o.label),suggestion:{value:zd(e.name,o.value),label:o.label??o.value,...o.hint?{hint:o.hint}:{}}}));return Xd(a)}function RS(e,t,s={}){const n=qo(e,t);if(n.name===void 0)return ES(n.raw);const a=_d(n.name);return a?IS(a,n.value??"",s):[]}function TS(e,t,s){const n=qo(e,t),a=!s.value.endsWith(":"),o=/\s/.test(e.slice(n.end,n.end+1)),i=a&&!o?`${s.value} `:s.value;return{query:e.slice(0,n.start)+i+e.slice(n.end),cursor:n.start+i.length+(a&&o?1:0)}}const MS=e=>({value:e.normalizedEmail,...e.displayName?{label:e.displayName,hint:e.normalizedEmail}:{}});function AS(e){const t=new Map;for(const s of e){const n=s.email.toLowerCase(),a=n.split("@")[0];a&&!t.has(a)&&t.set(a,s.accountId),t.has(n)||t.set(n,s.accountId)}return t}function OS(e){const t=new Map;for(const s of e)for(const n of s){const a=n.fullPath?.toLowerCase();if(!a)continue;const o=a.split("/").pop();t.has(a)||t.set(a,n.mailboxId),o&&!t.has(o)&&t.set(o,n.mailboxId)}return t}function DS(e,t=[]){const s=e.flat().filter(o=>o.fullPath),n=new Map;for(const o of s){const i=ma(o.fullPath).toLowerCase();n.set(i,(n.get(i)??0)+1)}const a=new Map(t.map(o=>[o.accountId,o.email]));return s.map(o=>{const i=ma(o.fullPath),c=n.get(i.toLowerCase())===1,u=t.length>1?a.get(o.accountId):void 0;return{value:c?i:o.fullPath,label:o.displayNameOverride?.trim()||i,...u?{hint:u}:{}}})}function PS(e){const t=new Map;for(const s of e){const n=s.email.toLowerCase().split("@")[0]??"";t.set(n,(t.get(n)??0)+1)}return e.map(s=>{const n=s.email.split("@")[0]??s.email,a=t.get(n.toLowerCase())===1,o=s.displayName?.trim();return{value:a?n:s.email,label:o||s.email,...o?{hint:s.email}:{}}})}const LS=250,FS=2;function $S({query:e,cursor:t,enabled:s}){const{accounts:n}=Le(),{mailboxesByName:a}=xs(),o=a!==void 0,i=s?CS(e,t):void 0,c=i?.source==="contact"?i.query.trim():"",u=mr(c,LS),{data:m}=ye({...ir({query:{q:u,limit:Yd}}),enabled:u.length>=FS}),d=mt({queries:n.map(g=>({...it({path:{accountId:g.accountId}}),staleTime:1/0}))}),f=l.useMemo(()=>o?DS(d.map(g=>g.data?.items??[]),n):[],[o,d,n]),h=l.useMemo(()=>PS(n),[n]),v=l.useMemo(()=>(m?.items??[]).map(MS),[m]);return l.useMemo(()=>{if(!s)return[];const g=RS(e,t,{mailboxes:f,accounts:h,contacts:v});return o?g:g.filter(p=>p.value!=="in:")},[s,e,t,f,h,v,o])}const _S={title:"",navSlot:null,titleMeta:null,searchSlot:null,searchField:null,searchResults:null,makeFilterSlot:null},Aa=l.createContext(_S),Ar=()=>l.useContext(Aa),zS=new Set(["hasAttachment","isUnread","isRead","isStarred","category","before","after"]),BS=e=>zS.has(e),US=(e,{searchHadSemanticReach:t})=>{const s=[],n=[];let a,o;for(const u of e.tokens){if(u.type==="from"){s.push({field:"From",value:u.value});continue}if(u.type==="subject"){s.push({field:"Subject",value:u.value});continue}if(u.type==="in"){a={mailboxId:u.mailboxId,label:u.value};continue}if(u.type==="account"){o=u.accountId;continue}BS(u.type)&&n.push({type:u.type,label:Ud(u)})}const i=e.freeText.trim(),c=i.length>0;return c&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:n,targetAccountId:o,keptTerms:c,droppedSemantic:c&&t}},KS=(e,t,s)=>e.targetAccountId??t??s[0]?.accountId,Jd="remit.recentSearches",qS=5;function Oa(){try{const e=localStorage.getItem(Jd);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function $l(e){const t=e.trim();if(!t)return Oa();const s=[t,...Oa().filter(n=>n!==t)].slice(0,qS);try{localStorage.setItem(Jd,JSON.stringify(s))}catch{return s}return s}const HS=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function Zd({title:e,unreadCount:t,children:s,selectionBar:n,paneOverlay:a,footer:o,searchFilter:i,searchResults:c,searchLoading:u,relatedResults:m,relatedLoading:d,onSelectSearchResult:f,searchResultsLabel:h="Top matches",relatedResultsLabel:v="Related",searchResultsInBody:g=!1,refreshControl:p}){const{accounts:b,resultFolderIndex:y,searchQuery:S,searchInput:x,onSearchChange:w,onSearchClear:C,searchViewKey:T}=Le(),A=xs(),k=Qe(),M=ps(),D=Mr(),[E,L]=l.useState(!1),[O,j]=l.useState(Oa),I=Km(),P=l.useRef(T);l.useEffect(()=>{P.current!==T&&(P.current=T,L(!1))},[T]);const[R,F]=l.useState(0),[N,V]=l.useState(!1),[Q,re]=l.useState(void 0),se=$S({query:x,cursor:R,enabled:N&&x.trim().length>0}),fe=l.useCallback(oe=>{const J=TS(x,R,oe);w(J.query),re({cursor:J.cursor})},[x,R,w]),Z=oc({count:se.length,onAccept:oe=>{const J=se[oe];J&&fe(J)}}),{comboboxProps:ne,handleKeyDown:le}=Z,U=l.useMemo(()=>({comboboxProps:ne,onKeyDown:le,onCaretChange:F,onFocusChange:V,...Q?{caret:Q}:{}}),[ne,le,Q]),_=Z.open?r.jsx(ic,{id:Z.listId,suggestions:se,activeIndex:Z.activeIndex,optionId:Z.optionId,onPick:fe,onHighlight:Z.setActiveIndex,label:"Search suggestions",className:"mx-row-inset mt-1 shrink-0"}):null,de=x.trim().length>0,{mailboxesByName:ge,accountsByName:we}=A,Re=l.useMemo(()=>Us(x,{mailboxesByName:ge,accountsByName:we}),[x,ge,we]),q=Re.tokens.map(oe=>({label:Ud(oe),onRemove:()=>w(oS(x,oe))})),Ce=c??[],xe=m??[],Ne=de?[{id:"top",label:h,results:Ce},{id:"related",label:v,results:xe}]:[],te=!(Ce.length+xe.length>0)&&(u===!0||d===!0),{scope:be}=Zu(b),De=Ot({select:oe=>oe.matches}),Ue=Xu(De),G=Fy(De,be,Ue?y.get(Ue)?.role:void 0),Ge=G.kind==="global"?Vd([...Ce,...xe]):void 0,ke=Ge?{kind:"global",onScopeToSpam:()=>k({to:"/mail/$mailboxId",params:{mailboxId:Ge.mailboxId},search:{q:S||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:G,Ke=xe.length>0,$=l.useMemo(()=>US(Re,{searchHadSemanticReach:Ke}),[Re,Ke]),ce=de?$:void 0,ae=de?{onClick:()=>{L(!1),I("properties","search")},blockedReason:Ob($)?void 0:"Add a sender or words to filter on"}:void 0,me=ae?r.jsx(mu,{...ae}):null,Me=HS({tier:D,hasLiveInput:de,hasCommittedQuery:S.trim().length>0,bodyRendersCommittedResults:g}),he=oe=>{j($l(x)),f?.(oe)},Se=r.jsx(hu,{value:x,sections:Ne,loading:te,onSelectResult:he,tokens:q,scope:ke}),Ae=n===void 0,ve=Me?r.jsx("div",{className:"h-full overflow-y-auto",children:Se}):null,Ye=ve&&!Ae?ve:s,Xe=ve&&Ae?ve:null,Oe=Gd(D),K=Oe&&(E||de),pe=l.useMemo(()=>({title:e,searchResults:Xe,makeFilterSlot:me,searchConversion:ce,navSlot:M&&!M.showNavPane&&r.jsx(ie,{variant:"ghost",size:"touch",icon:r.jsx(fr,{className:"size-5"}),onClick:()=>M.openNav(),"aria-label":"Menu",className:"-ml-2 shrink-0"}),titleMeta:r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[t.toLocaleString()," unread"]}),r.jsx(qm,{}),p]}),searchSlot:Oe&&!K&&r.jsx(ie,{variant:"ghost",size:"touch",icon:r.jsx(rr,{className:"size-5"}),onClick:()=>L(!0),"aria-label":"Search",className:"shrink-0"}),searchField:K&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(bo,{value:x,onChange:w,onClear:C,globalFocusKey:!1,showClearButton:!1,suggest:U})}),r.jsx(ie,{variant:"ghost",size:"touch",icon:r.jsx(Nt,{className:"size-5"}),onClick:()=>{C(),L(!1)},"aria-label":"Close search",className:"shrink-0"})]})}),[e,t,M,Oe,K,x,w,C,U,Xe,me,ce,p]);if(D==="phone"&&E){const oe=J=>{j($l(x)),L(!1),f?.(J)};return r.jsxs(Aa.Provider,{value:pe,children:[r.jsx(Nx,{value:x,onChange:w,onClear:C,onCancel:()=>{L(!1),C()},filter:i,recentSearches:O,onPickRecent:w,makeFilter:ae,sections:Ne,loading:te,onSelectResult:oe,tokens:q,scope:ke,suggest:U,suggestList:_}),a]})}return r.jsx(Aa.Provider,{value:pe,children:r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[n?.(pe),_,r.jsx("div",{className:"min-h-0 flex-1",children:Ye}),o,a]})})}const WS=120,ef=({keyboardFocusedMessageId:e,openMessageId:t,enabled:s,open:n,delayMs:a=WS})=>{const o=l.useRef(n);o.current=n;const i=l.useRef(void 0);l.useEffect(()=>{const c=e;if(!s){i.current=c;return}if(c===void 0||c===t)return;if(c===i.current){i.current=void 0;return}const u=setTimeout(()=>o.current(c),a);return()=>clearTimeout(u)},[s,e,t,a])};function tf(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Ho=l.createContext(null),VS=e=>{const t=l.useContext(Ho);return t?t.rowInteraction(e):null},Wo=()=>{const e=l.useContext(Ho);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},QS="[data-message-id]",GS=e=>Array.from(e.querySelectorAll(QS)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),YS=(e,t)=>e.length===t.length&&e.every((s,n)=>s===t[n]),XS=e=>{const[t,s]=l.useState([]);return l.useEffect(()=>{const n=e.current;if(!n)return;const a=()=>{const i=GS(n);s(c=>YS(c,i)?c:i)};a();const o=new MutationObserver(a);return o.observe(n,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function sf({selectedMessageId:e,onOpen:t,onDeleteMessages:s,onSelectionVerb:n,wizardOpen:a=!1,isDeleting:o=!1,commandsRef:i,onTriageContextChange:c,children:u}){const m=es(),d=l.useRef(null),f=XS(d),h=Pb({orderedIds:f,isDesktop:m,initialFocusedId:e}),{focusedMessageId:v,setFocusedMessageId:g,pendingDomFocusRef:p,cursorMovedByPointerRef:b,selection:y,isMultiSelectMode:S,exitSelection:x,handleRowSelect:w}=h,{selectedIds:C,selectedCount:T,isSelected:A,toggle:k,select:M,toggleAll:D}=y,E=f.length>0&&f.every(_=>C.has(_)),L=l.useCallback(()=>{f.length>0&&D(f)},[f,D]),{intersectWith:O}=y;l.useEffect(()=>{O(f)},[O,f]),l.useEffect(()=>{const _=p.current;_!==null&&(p.current=null,d.current?.querySelector(`[data-message-id="${_}"]`)?.focus())});const j=l.useCallback(_=>{b.current=!0,g(_)},[b,g]),I=l.useCallback(_=>{m||M(_)},[m,M]),P=l.useCallback(()=>{v&&t(v)},[v,t]),R=l.useCallback(_=>t(_,{replace:!0}),[t]);ef({keyboardFocusedMessageId:h.keyboardFocusedMessageId,openMessageId:e,enabled:m&&T===0,open:R});const[F,N]=l.useState(null),V=l.useCallback(_=>F!==null?!0:T>0?(n(_),!0):_!=="delete"||!v?!1:(N([v]),!0),[F,T,n,v]),Q=l.useCallback(()=>{F!==null&&(s(F),N(null),x())},[F,s,x]),re=l.useCallback(()=>N(null),[]),se=l.useCallback(()=>T===0?!1:(x(),!0),[T,x]),fe=f.length>0;l.useEffect(()=>{if(i){if(!fe){i.current=null;return}return i.current={focusNext:h.focusNext,focusPrevious:h.focusPrevious,focusFirst:h.focusFirst,focusLast:h.focusLast,openFocused:P,toggleSelect:h.toggleFocusedSelection,extendSelectDown:h.extendRangeDown,extendSelectUp:h.extendRangeUp,selectAll:h.selectAllLoaded,clearSelection:se,requestVerb:V,toggleDensity:()=>{}},()=>{i.current=null}}},[i,fe,h.focusNext,h.focusPrevious,h.focusFirst,h.focusLast,h.toggleFocusedSelection,h.extendRangeDown,h.extendRangeUp,h.selectAllLoaded,P,se,V]);const Z=l.useMemo(()=>Array.from(C),[C]),ne=F!==null;l.useEffect(()=>{c?.({focusedMessageId:v,selectedIds:Z,orderedIds:f,hasList:fe,blocksKeyboard:ne||a})},[c,v,Z,f,fe,ne,a]);const le=tf(f,v),U=l.useMemo(()=>({selectedIds:C,selectedCount:T,exitSelection:x,startSelectionVerb:n,orderedIds:f,allSelected:E,toggleAllLoaded:L,rowInteraction:_=>({focused:_===v,isTabStop:_===le,isDesktop:m,onFocusRow:j,selection:{isChecked:A(_),onToggleCheck:k,onRowSelect:w,isMultiSelectMode:S,onLongPress:I}})}),[C,T,x,n,f,E,L,v,le,m,j,A,k,w,S,I]);return r.jsxs(Ho.Provider,{value:U,children:[r.jsx("div",{ref:d,className:"contents",children:u}),r.jsx(oo,{isOpen:ne,title:Nc(F?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:o,onConfirm:Q,onCancel:re})]})}function JS({title:e,isDeleting:t}){const s=Ar(),{selectedCount:n,exitSelection:a,startSelectionVerb:o,orderedIds:i,allSelected:c,toggleAllLoaded:u}=Wo();return r.jsx(So,{title:s.title||e,navSlot:s.navSlot,titleMeta:s.titleMeta,searchSlot:s.searchSlot,searchField:s.searchField,idleSlot:s.makeFilterSlot,count:n,onCancel:a,onDelete:()=>o("delete"),onMarkRead:()=>o("markRead"),isBusy:t,selectAll:i.length>0?{checked:c,indeterminate:n>0&&!c,onChange:u}:void 0})}const oa=e=>{e.preventDefault(),e.stopPropagation()},nf=(e,t)=>{const s=l.useRef(!1),n=l.useCallback(i=>{if(s.current=!1,i.button!==0)return;const c=Yn(i);xi(c)&&t?.(e,c)&&(oa(i),s.current=!0,i.currentTarget.focus(),c.shiftKey&&window.getSelection()?.removeAllRanges())},[t,e]),a=l.useCallback(i=>{!i.ctrlKey||!t||i.preventDefault()},[t]),o=l.useCallback(i=>{if(s.current)return s.current=!1,oa(i),!0;const c=Yn(i);return!xi(c)||!t?.(e,c)?!1:(oa(i),c.shiftKey&&window.getSelection()?.removeAllRanges(),!0)},[t,e]);return{onMouseDown:n,onContextMenu:a,claimClick:o}},ZS=({thread:e,active:t=!1,focused:s,isTabStop:n,density:a="comfortable",isDesktop:o,badge:i,selection:c,inListbox:u=!1,linkMailboxId:m,onClick:d,onFocusRow:f})=>{const h=Te(),v=e.id,g=VS(v),p=s??g?.focused??!1,b=n??g?.isTabStop??!1,y=c??g?.selection,S=f??g?.onFocusRow,x=o??g?.isDesktop??!0,w=y?.isChecked??!1,C=y?.isMultiSelectMode??!1,T=y?.onToggleCheck,A=y?.onRowSelect,k=y?.onLongPress,M=l.useCallback(N=>{N.preventDefault(),N.stopPropagation(),T?.(v)},[T,v]),D=nf(v,A),E=l.useCallback(N=>{if(!D.claimClick(N)){if(!x){if(C){N.preventDefault(),N.stopPropagation(),T?.(v);return}d?.();return}A?.(v,Yn(N)),d?.()}},[D,x,C,T,A,d,v]),L=l.useCallback(()=>{k?.(v)},[k,v]),{longPressProps:O}=au({onLongPress:L,accessibilityDescription:w?"Deselect message":"Select message"}),j=l.useCallback(()=>{h.prefetchQuery(dr({path:{messageId:v}}))},[h,v]),I=l.useCallback(()=>{j(),S?.(v)},[j,S,v]),P=Fs({"data-list-row":"","data-message-row":!0,"data-message-id":v,...u?{role:"option","aria-selected":w}:{},tabIndex:b?0:-1,onClick:E,onMouseDown:D.onMouseDown,onContextMenu:D.onContextMenu,onMouseEnter:j,onFocus:I},x||!y?{}:O),R=We(a==="compact"?tu({active:t,focused:p}):We("group",_s({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",w&&"bg-accent-soft",!x&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?r.jsx(su,{thread:e}):r.jsx(po,{thread:e,badge:i,selection:y?{checked:w,alwaysVisible:C,onToggle:M}:void 0});return m===void 0?r.jsx("button",{type:"button",...P,className:R,children:F}):r.jsx(qt,{to:"/mail/$mailboxId",params:{mailboxId:m},search:N=>({...N,selectedMessageId:v}),...P,className:R,children:F})},Vo=l.memo(ZS),rf=8,af=e=>e==="From"||e==="FromDomain",eC=e=>({value:e.email,label:e.displayName??e.email,...e.displayName?{hint:e.email}:{},...e.fromSelection?{source:"selected"}:{}}),tC=e=>{const t=yu(e.email);if(t!==null)return{value:t,...e.fromSelection?{source:"selected"}:{}}},sC=(e,t)=>e.value.toLowerCase().includes(t)||(e.label??"").toLowerCase().includes(t),nC=(e,t,s)=>{if(!af(e))return[];const n=t.trim().toLowerCase(),a=new Set,o=[];for(const i of s){if(i.email.trim()==="")continue;const c=e==="From"?eC(i):tC(i);if(!c)continue;const u=c.value.toLowerCase();if(!(u===""||a.has(u))&&(a.add(u),u!==n&&!(n!==""&&!sC(c,n))&&(o.push(c),o.length===rf)))break}return o},rC=250,aC=2,oC=(e,t,s)=>{const n=t.trim(),a=mr(n,rC),o=e!==void 0&&af(e),{data:i}=ye({...ir({query:{q:a,limit:rf}}),enabled:o&&a.length>=aC});if(!o||e===void 0)return[];const c=[...s.map(u=>({email:u,fromSelection:!0})),...(i?.items??[]).map(u=>({email:u.normalizedEmail,...u.displayName?{displayName:u.displayName}:{}}))];return nC(e,n,c)},iC={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},of={delete:"moved to Trash",move:"moved",markRead:"marked as read"},lC={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},cC={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},uC={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},dC=(e,t,s)=>iC[e](Gt(t),Gt(s)),_l=(e,t)=>`${Gt(t)} ${of[e]}. Your mail server is still catching up.`,fC=e=>`Stopped after ${Gt(e)}`,mC=(e,t,s)=>`${Gt(t)} of ${Gt(s)} ${of[e]}. Nothing was sent for the rest, so they are untouched.`,hC=(e,t)=>t>0?`Stopped after ${Gt(t)} — some messages ${lC[e]}`:cC[e],pC=e=>uC[e],gC=e=>e==="delete"?"danger":"info",xC=100,bC=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],lf=({mailboxId:e,accountId:t,enabled:s,predicateKey:n,searchQuery:a})=>{const[o,i]=l.useState({kind:"idle"}),[c,u]=l.useState(void 0),[m,d]=l.useState(void 0),f=l.useRef(!1),h=l.useRef(!1),v=Te(),{pushError:g}=nt();l.useEffect(()=>{h.current||(f.current=!0),i({kind:"idle"})},[s,n]);const p=l.useRef(a);p.current=a;const b=l.useCallback(k=>async M=>{const{data:D}=await ha({path:{mailboxId:e},query:{...k,continuationToken:M,limit:xC},throwOnError:!0});return{ids:(D.items??[]).map(E=>E.messageId),continuationToken:D.continuationToken}},[e]),y=l.useCallback(async()=>{const{data:k}=await ha({path:{mailboxId:e},query:{...p.current,count:!0,results:!1},throwOnError:!0});if(k.count===void 0)throw new Error("the search returned no count for the selection");return k.count},[e]),S=l.useCallback(k=>async M=>{if(k.kind==="move"){const{data:E}=await Hm({body:{messageIds:M,destinationMailboxId:k.destinationMailboxId},throwOnError:!0});return E}if(k.kind==="markRead"){const{data:E}=await Wm({body:{messageIds:M,isRead:!0},throwOnError:!0});return E}const{data:D}=await Vm({body:{messageIds:M},throwOnError:!0});return D},[]),x=l.useCallback(k=>{It(v,Et(bC(k,e))),t&&v.invalidateQueries({queryKey:Ft({path:{accountId:t}})})},[v,e,t]),w=l.useCallback(()=>{f.current=!1,i({kind:"counting"}),y().then(k=>{if(f.current){i({kind:"idle"});return}i({kind:"escalated",total:k})},k=>{g(ds("Couldn't count matching messages","The count didn't finish.",k)),i({kind:"idle"})})},[y,g]),C=l.useCallback(()=>{f.current=!0},[]),T=l.useCallback(()=>{h.current||(f.current=!0,i({kind:"idle"}))},[]),A=l.useCallback(async(k,M)=>{f.current=!1,h.current=!0,u(k);const D=j=>d(f0(j)),E=S(k),L=b(p.current);let O;try{O=M!==void 0?await nd(M,E,D,()=>f.current):await d0(L,o.kind==="escalated"?o.total:0,E,D,()=>f.current)}finally{h.current=!1}return u(void 0),d(void 0),i({kind:"idle"}),O.error&&g(ds(hC(k.kind,O.done),pC(k.kind),O.error)),O.done>0&&x(k),O},[S,b,o,g,x]);return{phase:o,escalate:w,stop:C,clear:T,isRunning:c!==void 0,runningAction:c,progress:m,runAction:A}},cf=12,vC=e=>{const{envelope:t}=e,s=t.from[0];return{id:t.messageId,sender:s?wu({normalizedEmail:s.normalizedEmail,displayName:s.displayName}):"Unknown",subject:t.subject??"(No subject)",date:gt(t.date)}},yC=(e,t)=>{const s=e!==void 0&&t!==void 0,{data:n,isLoading:a}=ye({...yc({path:{mailboxId:e??""},query:{...t,limit:cf}}),enabled:s,staleTime:3e4});return{messages:(n?.items??[]).map(wC),isPending:s&&a}},wC=e=>({id:e.messageId,sender:e.fromName||e.fromEmail||"Unknown",subject:e.subject??"(No subject)",date:gt(e.sentDate)}),SC=e=>mt({queries:e.slice(0,cf).map(t=>({...dr({path:{messageId:t}}),staleTime:Number.POSITIVE_INFINITY})),combine:t=>({messages:t.map(s=>s.data).filter(s=>s!==void 0).map(vC),isPending:t.some(s=>s.isPending)})}),CC=e=>({matchOperator:"Or",literalClauses:vr(e)}),kC=(e,t,s)=>{const n=ze(Qm()),{mutate:a,reset:o}=n,[i,c]=l.useState(!1),u=l.useMemo(()=>br(s),[s]),m=l.useCallback(()=>{!e||!t||(c(!1),a({path:{accountId:e},body:oi({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=l.useCallback(()=>{c(!1),o()},[o]),f=n.data,h=f?.semanticUnavailable===!0&&!i&&u.length>0;l.useEffect(()=>{!h||!e||(c(!0),a({path:{accountId:e},body:oi(CC(u))}))},[h,e,u,a]);const v=i||(f?.semanticUnavailable??!1),g=n.isPending||h,p=i?{matchOperator:"Or",literalClauses:vr(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:m,reset:d,matchedCount:g?void 0:f?.matchedCount,messageIds:g?void 0:f?.messageIds,semanticUnavailable:v,senderFallback:i,senders:u,matchPredicate:p,isPending:g,isError:n.isError,error:n.error}},jC=()=>[cr({path:{mailboxId:""}}),Qa({path:{mailboxId:""}}),Ga()].map(e=>[{_id:e[0]._id}]),NC=e=>rd(e)?e.pages:ad(e)?[e]:[],EC=e=>typeof e=="object"&&e!==null&&typeof e.messageId=="string",IC=(e,t)=>{const s=new Set(t),n=new Map;for(const a of e)for(const o of NC(a))for(const i of o.items){if(!EC(i)||!s.has(i.messageId))continue;const c=i.subject?.trim();c&&n.set(i.messageId,c)}return t.map(a=>n.get(a)).filter(a=>a!==void 0)},RC=e=>{const t=Te(),s=e.join("\0");return l.useMemo(()=>{const n=jC().flatMap(a=>t.getQueriesData({queryKey:a}).map(([,o])=>o));return IC(n,e)},[t,s])},TC=({failure:e,isStarting:t,isRunning:s,isDone:n,failedCount:a,ruleSaved:o})=>e?.kind==="restartFailed"?"backApplyRestartFailed":e?.kind==="startFailed"?o?"backApplyStartFailed":"commitFailed":n?a>0?"backApplyFailed":"backApplyComplete":e?.kind==="statusUnreadable"?"statusUnknown":t||s?"backApplyRunning":"saving",MC={clauses:[],matchOperator:"any"},AC={clauses:[],matchOperator:"all",droppedFacets:[],keptTerms:!1,droppedSemantic:!1},OC=[],ls={state:"saving",matched:0,applied:0,failed:0,failures:[]},ia=(e,t)=>e.map((s,n)=>({...s,id:`${t}-${n}`})),zl=(e,t,s)=>{if(e==="delete")return{kind:"delete"};if(e==="markRead")return{kind:"markRead"};const n=e==="junk"?s:t;return n?{kind:"move",destinationMailboxId:n}:void 0},la=e=>e==="move"||e==="junk"||e==="organize",Bl=e=>e==="junk"?Hd:"No destination was chosen, so there is nowhere to file these. Go back and pick a folder.";function DC({verb:e,accountId:t,mailboxId:s,selection:n,crossAccount:a=!1,escalated:o,escalatedProgress:i,searchConversion:c,onFinished:u,onRunEnded:m,step:d,goToStep:f,goBack:h,closeWizard:v}){const[g]=l.useState(()=>c),[p]=l.useState(()=>o),b=g!==void 0,[y,S]=l.useState(b?"properties":"selected"),x=p?"escalated":y,[w,C]=l.useState(()=>g?{clauses:ia(g.clauses,"search"),matchOperator:g.matchOperator}:MC),[T,A]=l.useState(void 0),[k,M]=l.useState(void 0),[D,E]=l.useState(!1),[L,O]=l.useState(void 0),[j,I]=l.useState(void 0),[P,R]=l.useState(),F=l.useRef(!1),N=l.useRef(!1),V=l.useMemo(()=>n.map(B=>B.id),[n]),Q=l.useMemo(()=>n.map(B=>B.email).filter(Boolean),[n]),re=V[0],se=RC(V),{junkMailboxId:fe}=Sn(t),Z=kC(p?void 0:t,re,Q),{preview:ne}=Z;l.useEffect(()=>{ne()},[ne]);const le=x==="similar"||x==="properties",U=l.useMemo(()=>({matchOperator:w.matchOperator==="all"?"And":"Or",literalClauses:w.clauses.map(B=>({field:B.field,value:B.value}))}),[w.clauses,w.matchOperator]),_=x==="similar"?Z.matchPredicate:U,{count:de,matchedIds:ge}=wh(le?t:void 0,_),we=SC(le?ge:[]),Re=yC(p?s:void 0,p?.searchQuery),q=p?{status:"ready",count:p.total}:le?de:{status:"ready",count:n.length},{data:Ce}=ye({...it({path:{accountId:t??""}}),enabled:!!t,staleTime:Number.POSITIVE_INFINITY}),xe=Po(t),Ne=so(),ue=l.useMemo(()=>no({mailboxes:Ce?.items??[],folderAppointments:xe,currentMailboxId:s,translator:Ne}),[Ce?.items,xe,s,Ne]),{createFolderIn:te}=Ec(t),be=ue.find(B=>B.id===w.moveMailboxId)?.label,De=kb(n.map(B=>({normalizedEmail:B.email,displayName:B.sender}))),Ue=Ab({match:x==="properties"&&w.clauses[0]?.value.trim()||void 0,sender:De?wu(De):void 0,folder:be}),G=l.useMemo(()=>({...w,name:w.name??Ue}),[w,Ue]),Ge=oC(T?.draft.field,T?.draft.value??"",Q),ke=Sh(t),Ke=Ch(t),$=lf({mailboxId:s??"",accountId:t,enabled:!1,predicateKey:"selection-wizard",searchQuery:{}}),{runAction:ce}=$,ae=Xm({verb:e,mode:x,scope:w.scope,fromSearch:b}),me=ae[ri(ae,d)],Me=!a&&!!t,he=Me?void 0:eh,Se=Me?void 0:th,ve=(B=>{if(B==="folder")return Se;if(B==="rule")return G.scope==="standing"||G.scope==="until"?he:void 0})(me)??Jm(me,G,q),Ye=l.useCallback(()=>ia(Mb(Q,se),"seed"),[Q,se]),Xe=l.useCallback(B=>{S(B),C(X=>({...X,widen:B==="similar"&&re?{anchorCount:Math.max(n.length,1)}:void 0,...B==="properties"&&X.clauses.length===0?{clauses:Ye()}:{}}))},[re,n.length,Ye]),Oe=l.useCallback(()=>{E(!0),S("properties"),C(B=>({...B,widen:void 0,clauses:ia(vr(Q),"sender"),matchOperator:"any"})),f("properties")},[Q,f]),K=Z.semanticUnavailable||Z.isError;l.useEffect(()=>{me==="match"&&(x!=="similar"||!K||D||Oe())},[me,x,K,D,Oe]);const pe=l.useCallback(()=>{A({mode:"add",draft:{field:"From",value:""}})},[]),oe=l.useCallback(B=>{const X=w.clauses.find(Ie=>Ie.id===B);X&&A({mode:"edit",clauseId:B,draft:{field:X.field,value:X.value}})},[w.clauses]),J=l.useCallback(B=>{C(X=>({...X,clauses:X.clauses.filter(Ie=>Ie.id!==B)}))},[]),je=l.useCallback(B=>{A(X=>X&&{...X,draft:B})},[]),Pe=l.useCallback(()=>{A(B=>{if(!B)return;const X=kh(B.draft.field,B.draft.value),Ie={...B.draft,value:X};C(pt=>({...pt,clauses:B.clauseId?pt.clauses.map(yt=>yt.id===B.clauseId?{...yt,...Ie}:yt):[...pt.clauses,{id:crypto.randomUUID(),...Ie}]}))})},[]),_e=l.useCallback(()=>{if(ve){M(me);return}M(void 0);const B=ae[ri(ae,me)+1];B&&f(B)},[ve,me,ae,f]),Je=l.useCallback(async B=>{const X=zl(e,G.moveMailboxId,fe);if(!X){I({matched:B.length,failureReason:Bl(e)});return}I({matched:B.length});const Ie=await ce(X,[...B]);I({matched:B.length,outcome:Ie}),N.current&&m?.(X.kind,B.length,Ie)},[e,G.moveMailboxId,fe,ce,m]),qe=l.useCallback(async()=>{if(!p)return;const B=zl(e,G.moveMailboxId,fe);if(!B){I({matched:p.total,failureReason:Bl(e)});return}I({matched:p.total});const X=await p.run(B);I({matched:p.total,outcome:X}),N.current&&m?.(B.kind,p.total,X)},[p,e,G.moveMailboxId,fe,m]),{start:Ee}=ke,{createFilterAsync:et}=Ke,Be=l.useCallback(()=>{if(p){qe();return}const B=jh({mode:y,ruleScope:G.scope}),X=Nh({mode:y,ruleScope:G.scope,anchorMessageId:re,clauses:G.clauses,matchOperator:G.matchOperator,moveMailboxId:G.moveMailboxId,until:G.until});if(O(B),B==="standing"||B==="temporary"){const Ie=Eh(X)?X:void 0;R(Ie),et(X,B,(G.name??"").trim()).then(pt=>{pt&&Ie&&Ee(Ie)});return}if(B==="all-like-these"&&la(e)){Ee(X);return}Je(B==="just-these"?V:ge)},[p,qe,y,G,re,e,V,ge,et,Ee,Je]),lt=l.useCallback(()=>{if(ve){M(me);return}F.current||(F.current=!0,f("run"),Be())},[ve,me,f,Be]),tt=l.useCallback(B=>{const X=ke.progress,Ie=TC({failure:ke.failure,isStarting:ke.isStarting,isRunning:ke.isRunning,isDone:ke.isDone,failedCount:X.failedCount,ruleSaved:B});return Ie==="saving"||Ie==="commitFailed"||Ie==="backApplyStartFailed"?{...ls,state:Ie}:{state:Ie,matched:X.matchedCount,applied:X.appliedCount,failed:Ie==="backApplyFailed"||Ie==="backApplyRestartFailed"?X.failedCount:0,failures:[]}},[ke]),zt=l.useMemo(()=>{const B=new Map;for(const X of[...n,...we.messages,...Re.messages])B.set(X.id,X);return B},[n,we.messages,Re.messages]),Rt=p?i:$.progress,ns=l.useCallback(()=>{if(!j)return ls;const{matched:B,outcome:X,failureReason:Ie}=j;if(Ie!==void 0)return{...ls,state:"commitFailed",failureReason:Ie};if(!X){const wt=Rt?.done??0;return{state:"backApplyRunning",matched:Math.max(B,wt),applied:wt,failed:0,failures:[]}}if(!(X.cancelled||X.error!==void 0))return{state:"backApplyComplete",matched:Math.max(B,X.done),applied:X.done,failed:0,failures:[]};if(X.done===0)return{...ls,state:"commitFailed"};const yt=X.failedIds.map(wt=>zt.get(wt)).filter(wt=>wt!==void 0),vs=X.failedIds.length>0?X.failedIds.length:Math.max(B-X.done,1);return{state:"runStopped",matched:Math.max(B,X.done),applied:X.done,failed:vs,failures:yt}},[j,Rt,zt]),rt=p?ns():L==="standing"||L==="temporary"?Ke.isError?{...ls,state:"commitFailed"}:Ke.isSuccess?P?tt(!0):{...ls,state:"filterSaved"}:ls:L==="all-like-these"&&la(e)?tt(!1):ns(),Tt=()=>{if(rt.state==="statusUnknown"){ke.refreshStatus();return}if(p){qe();return}if(L==="standing"||L==="temporary"){if(Ke.isError){Ke.reset(),Be();return}P&&Ee(P);return}if(L==="all-like-these"&&la(e)){Be();return}const B=j?.outcome?.failedIds??[];Je(B.length>0?B:V)},bt=l.useCallback(()=>{v(ae,me)},[v,ae,me]),vt=l.useCallback(()=>{N.current=!0,v(ae,me),u()},[v,ae,me,u]),{stop:ht}=$,rs=j!==void 0&&j.outcome===void 0&&j.failureReason===void 0,qs=l.useCallback(()=>{if(p){p.stop();return}ht()},[p,ht]);Fu({shouldBlockFn:({action:B})=>B!=="BACK"?!1:(vt(),!0),enableBeforeUnload:!1,disabled:me!=="run"});const ct={messages:p?Re.messages:le?we.messages:n,count:q,label:x==="selected"?"Your selection":"A sample of what matches",emptyReason:x==="similar"&&K?"notIndexed":"noMatch",loading:p?Re.isPending:le&&(q.status==="loading"||we.isPending)};return r.jsx(Zm,{verb:e,steps:ae,step:me,blockedReason:ve,nudged:k===me,onBack:h,onExit:me==="run"?vt:bt,onContinue:_e,onCommit:lt,match:{selectedCount:n.length,mode:x,onModeChange:Xe,semanticUnavailable:K,semanticErrorDetail:Z.error instanceof Error?Z.error.message:void 0,semanticFallbackTaken:D,onSemanticFallback:Oe,escalatedScope:p?.scope,sample:ct},properties:{clauses:G.clauses,matchOperator:G.matchOperator,onMatchOperatorChange:B=>C(X=>({...X,matchOperator:B})),clauseEdit:T,onStartAddClause:pe,onStartEditClause:oe,onRemoveClause:J,onChangeDraft:je,onSubmitClause:Pe,onCancelClause:()=>A(void 0),clauseFields:Ih,clauseSuggestions:Ge,conversionNotice:g?Db(g):void 0,semanticFallbackTaken:D,sample:{...ct,label:"What this matches"}},folder:{folders:ue,mailboxId:G.moveMailboxId,delimiter:ro(Ce?.items??[]),onSelect:B=>C(X=>({...X,moveMailboxId:B})),onCreateFolder:t?te:void 0,restriction:Se},rule:{draft:G,onScopeChange:B=>C(X=>({...X,scope:B})),onUntilChange:B=>C(X=>({...X,until:B})),restriction:he},name:{name:G.name??"",onNameChange:B=>C(X=>({...X,name:B})),nudged:k===me},review:{verb:e,mode:x,selectedCount:n.length,clauses:G.clauses,matchOperator:G.matchOperator,folder:be,scope:G.scope,until:G.until,ruleName:ae.includes("name")?G.name:void 0,escalatedScope:p?.scope,sample:ct},run:{state:rt.state,verb:e,scope:G.scope,matched:rt.matched,applied:rt.applied,failedCount:rt.failed,failures:rt.failures,failureReason:rt.failureReason,onRetry:Tt,onDismiss:vt,onCancelRun:rs?qs:void 0}})}function Qo(e){const t=Gm()==="search",{searchConversion:s}=Ar(),{accounts:n}=Le(),{step:a,goToStep:o,goBack:i,closeWizard:c}=Ym(t?"properties":"match");if(!a)return null;const u=t?s??AC:void 0;return r.jsx(DC,{...e,...u?{verb:"organize",accountId:KS(u,e.accountId,n),selection:OC,crossAccount:!1,escalated:void 0,searchConversion:u}:{},step:a,goToStep:o,goBack:i,closeWizard:c})}const PC=200,Ul=()=>r.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>r.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[r.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsxs("div",{className:"flex justify-between gap-2",children:[r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),LC=({accountEmail:e})=>{const t=Qe();return r.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:[r.jsx(Pt,{className:"size-3.5 shrink-0"}),r.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),r.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})},FC=(e,t)=>{if(t.size===0)return{};const s=new Set,n=new Set;for(const o of e)t.has(o.id)&&(o.accountId&&s.add(o.accountId),o.mailboxId&&n.add(o.mailboxId));if(s.size>1)return{moveDisabledHint:"Move only works within one account — clear selection or pick messages from a single account"};const a=s.size===1?[...s][0]:void 0;return n.size>1?{accountId:a,moveDisabledHint:`Move only works within one folder — this selection spans ${n.size} folders`}:{accountId:a,mailboxId:n.size===1?[...n][0]:void 0}};function $C({header:e,rows:t,wizard:s,children:n}){const{selectedIds:a,selectedCount:o,exitSelection:i,orderedIds:c,allSelected:u,toggleAllLoaded:m}=Wo(),d=l.useMemo(()=>FC(t,a),[t,a]),{junkMailboxId:f}=Sn(d.accountId),{labels:h}=ao(d.accountId),v=l.useMemo(()=>Array.from(a),[a]),g=l.useMemo(()=>t.filter(x=>a.has(x.id)).map(x=>({id:x.id,sender:x.fromName,email:x.fromEmail,subject:x.subject,date:x.timeLabel})),[t,a]),p=Tr(f,d.mailboxId),b=l.useMemo(()=>c.length>0?{checked:u,indeterminate:o>0&&!u,onChange:m}:void 0,[c.length,u,o,m]),y=d.moveDisabledHint?{tone:"warning",text:d.moveDisabledHint}:void 0,S=x=>r.jsx(So,{title:x.title,navSlot:x.navSlot,titleMeta:x.titleMeta,searchSlot:x.searchSlot,searchField:x.searchField,idleSlot:x.makeFilterSlot,count:o,onCancel:i,onDelete:()=>s.start("delete"),onMove:()=>s.start("move"),onOrganize:()=>s.start("organize"),onJunk:p?()=>s.start("junk"):void 0,onMarkRead:()=>s.start("markRead"),overflowSlot:d.accountId&&d.mailboxId&&o>0&&h.length>0?r.jsx(Qd,{accountId:d.accountId,mailboxId:d.mailboxId,messageIds:v}):void 0,selectAll:b,notice:y});return r.jsx(Zd,{...e,selectionBar:S,paneOverlay:r.jsx(Qo,{verb:s.verb,accountId:d.accountId,mailboxId:d.mailboxId,selection:g,crossAccount:d.moveDisabledHint!==void 0,onFinished:i}),children:n})}function _C({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:n,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i}){const{searchQuery:c,searchInput:u,resultFolderIndex:m}=Le(),d=xs(),f=es(),h=Za(),v=Qe(),g=l.useMemo(()=>fS(e.filter($=>!$.muted?.value)),[e]),[p,b]=l.useState("all"),[y,S]=l.useState("all"),[x,w]=l.useState(new Set),[C,T]=l.useState(!1),A=l.useCallback($=>{w(ce=>{const ae=new Set(ce);return ae.has($)?ae.delete($):ae.add($),ae})},[]),k=l.useCallback(()=>w(new Set),[]),M=u.trim().length>0,{data:D,isLoading:E,isError:L,refetch:O}=ye({...pa(),staleTime:6e4}),j=mt({queries:g.map($=>({...it({path:{accountId:$.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),I=l.useMemo(()=>{const $=new Map;for(let ce=0;ce<g.length;ce++){const ae=g[ce].accountId,Me=(j[ce]?.data?.items??[]).reduce((he,Se)=>he+(Se.unseenCount??0),0);$.set(ae,Me)}return $},[g,j]),P=l.useMemo(()=>g.filter(($,ce)=>{const ae=j[ce];return ae?.isError?!ga(ae.error):!1}),[g,j]),{freeText:R,tokens:F}=Us(c.trim().toLowerCase(),d),{data:N,isFetching:V}=ye({...pa({query:{query:R,limit:PC}}),enabled:R.length>0,staleTime:3e4}),Q=l.useMemo(()=>{const $=Pl(D?.items??[]).map(er);return(R?mS($.filter(ae=>qd(ae,R)),Pl(N?.items??[]).map(er)):$).filter(ae=>(p==="all"||ae.accountId===p)&&Ko(ae,F))},[D,N,p,R,F]),{bodyRows:re,briefSpamOffer:se}=l.useMemo(()=>{if(!R)return{bodyRows:Q,briefSpamOffer:void 0};const $=Q.map(me=>Kn(me,m)),{spam:ce}=vo($);if(ce.length===0)return{bodyRows:Q,briefSpamOffer:void 0};const ae=new Set(ce.map(me=>me.id));return{bodyRows:Q.filter(me=>!ae.has(me.id)),briefSpamOffer:Vd($)}},[Q,R,m]),fe=l.useMemo(()=>hS(re),[re]),Z=l.useCallback(($,ce)=>{const ae=R?re.find(me=>me.id===$):void 0;if(ae?.threadId&&ae.mailboxId&&n){n(Kn(ae,m),ce);return}s?.($,ce)},[R,re,m,n,s]),ne=l.useMemo(()=>g.length<=1?[]:[{id:"all",label:"All",active:p==="all"},...g.map($=>({id:$.accountId,label:$.email.split("@")[0]??$.email,count:I.get($.accountId),active:p===$.accountId}))],[g,I,p]),le=l.useMemo(()=>e.filter($=>$.muted?.value).length,[e]),U=l.useMemo(()=>Array.from(I.values()).reduce(($,ce)=>$+ce,0),[I]),_=l.useMemo(()=>g.map($=>$.accountId),[g]),{hasNewMail:de}=Cr(),{state:ge,errorMessage:we,refresh:Re}=No(_,{onSettled:()=>O()}),q=l.useMemo(()=>r.jsx(yo,{state:ge,onRefresh:Re,label:"Refresh daily brief",errorMessage:we,hasUpdate:de(_)}),[ge,Re,we,de,_]),Ce=l.useMemo(()=>Q.filter($=>(y==="all"||$.category===y)&&sh($,x)).map($=>Kn($,m)),[Q,y,x,m]),{hits:xe,isLoading:Ne}=Kd(),ue=l.useMemo(()=>{const $=new Map;for(const ae of D?.items??[])$.set(ae.messageId,ae.threadId);const ce=Ce.map(ae=>$.get(ae.id)).filter(ae=>ae!=null);return Wd(xe,ce,m)},[xe,Ce,D,m]),te=l.useMemo(()=>{const $=Jx(ne.map(ce=>({id:ce.id,label:ce.label,count:ce.count,active:ce.active})));return{categories:$.categories,filters:$.filters,sources:$.sources,sourcesNote:le>0?`+${le} muted`:void 0,selectedCategory:y,activeFilters:x,expanded:C,onExpandedChange:T,onSelectCategory:ce=>S(ce),onSelectSource:b,onToggleFilter:ce=>A(ce),onClear:()=>{S("all"),b("all"),k()}}},[ne,le,y,x,C,A,k]),be=fe.length===0&&p==="all"&&R.length===0&&F.length===0,De=l.useMemo(()=>g.map($=>$.accountId),[g]),Ue=l.useMemo(()=>g.some($=>jo($.syncPhase)),[g]),G=Cy(De,be||Ue),Ge=r.jsxs("div",{className:"h-full overflow-y-auto",children:[r.jsx(Ul,{}),r.jsx(Ul,{})]}),ke=!E&&!L&&!be,Ke=ke?r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[se&&r.jsx(fu,{count:se.count,onScopeToSpam:()=>v({to:"/mail/$mailboxId",params:{mailboxId:se.mailboxId},search:{q:c||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}),r.jsx("div",{className:"min-h-0 flex-1",children:r.jsx(sc,{sections:fe,briefCategory:y,Row:Vo,selectedThreadId:t,onSelectThread:Z,onSelectBriefCategory:S,sources:ne,sourcesNote:le>0?`+${le} muted`:void 0,onSelectSource:b,activeFilters:x,onToggleFilter:A,onClearFilters:k,hideChrome:M})})]}):E?Ge:L?r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[r.jsx(Pt,{className:"size-8 text-danger"}),r.jsx("p",{children:"Couldn't load your messages"}),r.jsxs("button",{type:"button",onClick:()=>O(),className:"flex items-center gap-1 text-accent underline text-xs",children:[r.jsx(fo,{className:"size-3.5"}),"Try again"]})]}):G.resolved?r.jsx(tx,{sync:G.syncing?{synced:G.synced,total:G.total}:void 0}):Ge;return r.jsx(wc,{hasSheet:ke&&!M,children:r.jsx(sf,{selectedMessageId:t,onOpen:Z,onDeleteMessages:i,onSelectionVerb:h.start,wizardOpen:h.isOpen,commandsRef:a,onTriageContextChange:o,children:r.jsx($C,{wizard:h,header:{title:"Daily brief",unreadCount:U,footer:f?r.jsx(Jc,{}):void 0,searchFilter:te,searchResults:Ce,searchLoading:E||V,relatedResults:ue,relatedLoading:Ne,onSelectSearchResult:n,searchResultsInBody:!0,refreshControl:q},rows:Q,children:r.jsxs("div",{className:"flex h-full flex-col",children:[P.map($=>r.jsx(LC,{accountEmail:$.email,accountId:$.accountId},$.accountId)),r.jsx("div",{className:"min-h-0 flex-1",children:Ke})]})})})})}const zC=10,uf=e=>({q:e?.toLowerCase()??"",limit:zC}),BC=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(n=>n.normalizedEmail===s)};function UC(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Qn(t,{month:"short",year:"numeric"})}function df(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const KC="We can't verify the sender of this email, which could mean it's from an insecure source.",qC="We couldn't read this sender's address, so we can't confirm who really sent this message.";function HC(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?UC(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:df(e.fromEmail)}}function WC(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 Kl(e){if(e.fromName&&e.fromName!==e.fromEmail)return e.fromName}function VC(e){return e.length===1?e[0]:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function QC(e,t){const s=[],n=e.displayNameCorrespondence;t&&(n===li.Unrelated?s.push(`The name it shows, "${t}", has nothing to do with ${e.fromDomain}.`):n===li.Lookalike&&s.push(`The name it shows, "${t}", only looks like ${e.fromDomain}.`));const a=GC(e.offDomainLinkDomains);return a.length>0&&s.push(`Its links go to ${VC(a.slice(0,3))}.`),s}function GC(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function YC(e,t){const s=t>0?t:void 0;if(df(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:qC,similarCount:s};const n=e.authenticity;if(!n)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:KC};if(!n.dkimMismatch){const m=Kl(e),d=QC(n,m);return d.length>0?{verdict:"caution",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,claimedBrand:m,summary:d.join(" ")}:{verdict:"aligned",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,summary:n.dkimDomain?`This message was signed by ${n.dkimDomain}.`:"Nothing looks unusual about this sender."}}const a=n.fromDomain,o=n.dkimDomain,i=Kl(e),c=o?`it was actually sent from ${o}`:"its signature failed to verify",u=i?`The display name claims "${i}", but ${c}${o?` — not ${a}`:""}. Real senders use their own address.`:`This message claims to be from ${a}, but ${c}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:u,similarCount:s}}function ff(e,t){const s=e?.fromEmail??null,n=e?.subject??"",{data:a,error:o}=ye({...ir({query:uf(s??void 0)}),enabled:!!s,staleTime:3e4}),i=BC(a?.items,s??void 0),c=[n,s].filter(Boolean).join(" "),{data:u,isLoading:m,error:d}=ye({...vc({query:{query:c,limit:5}}),enabled:!!(e&&c.length>3),staleTime:6e4,retry:1});return{data:l.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(y=>y.messageId!==e.messageId).map(y=>({id:y.messageId,mailboxId:t!=null&&y.mailboxIds.includes(t)?t:y.mailboxIds[0]??"",fromName:y.fromName??"",subject:y.subject??"(No subject)",timeLabel:y.sentDate!=null?gt(y.sentDate*1e3):"",matched:y.matchedChunkType})),v=HC(e,i),g=YC(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},b=WC(i);return{sender:v,authenticity:g,category:p,flags:b,similar:h}},[e,i,u,t]),isSimilarLoading:m,similarError:d,similarErrorIsFatal:ga(d),addressErrorIsFatal:ga(o),addressId:i?.addressId,address:i}}function XC(e,t){const s={...e??{}};for(const[n,a]of Object.entries(t))a==null?delete s[n]:s[n]={...a,setAt:a.setAt??Date.now()};return s}function mf({addressId:e,senderEmail:t}){const s=Te(),{pushError:n}=nt(),a=nh({query:uf(t)}),{mutate:o,isPending:i}=ze({...bc(),onMutate:async u=>{const m=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,f=>f&&{...f,items:f.items.map(h=>h.addressId===u.path.addressId?{...h,flags:XC(h.flags,m)}:h)}),{previous:d}},onError:(u,m,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),n({title:"Couldn't update sender preference",detail:ft(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:l.useCallback(u=>{if(!e){qa(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 JC=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",hf=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function ZC(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function ek(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function tk(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function pf(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const sk=["personal","newsletter","marketing","automated","transactional","social"],nk=e=>e.spamReport?"notSpam":"reportSpam",rk=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:n}=e;return t&&!s?"error":n?"loading":"ready"};function ak(){return r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Dt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"h-8 rounded bg-surface"})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>r.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function ok({isOpen:e,current:t,onSelect:s,onCancel:n}){return e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:n,children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.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:[r.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),r.jsx("div",{className:"mt-4 flex flex-col gap-1",children:sk.map(a=>r.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&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"current"})]},a))}),r.jsx("div",{className:"mt-6 flex justify-end",children:r.jsx("button",{type:"button",onClick:n,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 ik({thread:e,onClose:t,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o}){const{data:i,addressId:c,isSimilarLoading:u,similarError:m,similarErrorIsFatal:d}=ff(e,s),[f,h]=l.useState(!1),v=e.fromEmail??void 0,{updateFlags:g}=mf({addressId:c,senderEmail:v}),{reportSpam:p,notSpam:b,isReporting:y,isRestoring:S}=ld({mailboxId:e.mailboxId,threadId:e.threadId,accountId:n,onAfterOptimisticRemove:o}),x=Ls(),w=nk(e),C=l.useCallback(()=>{b([e.messageId])},[b,e.messageId]),T=l.useCallback(()=>{pf(x,{count:1,senderTrust:e.senderTrust,wasRescuable:hf(e)}),p([e.messageId])},[p,e,x]),A=l.useCallback(()=>{},[]),k=l.useCallback(()=>{const P=i?.flags?.vip!==!0;g({vip:{value:P}})},[i?.flags?.vip,g]),M=l.useCallback(()=>{const P=i?.flags?.muted!==!0;g({muted:{value:P}})},[i?.flags?.muted,g]),D=l.useCallback(()=>{const P=i?.flags?.unsubscribed!==!0;g({unsubscribed:{value:P}})},[i?.flags?.unsubscribed,g]),E=l.useCallback(P=>{h(!1),g({category:{value:P}})},[g]),L=c!==void 0,O={onToggleVip:L?k:void 0,onToggleMute:L?M:void 0,onToggleUnsubscribe:L?D:void 0,onReclassify:L?()=>h(!0):void 0,onNotSpam:w==="notSpam"?C:void 0,onReportSpam:w==="reportSpam"?T:void 0},j=({mailboxId:P,messageId:R,className:F,ariaLabel:N,children:V})=>r.jsx(qt,{to:"/mail/$mailboxId",params:{mailboxId:P},search:Q=>({...Q,selectedMessageId:R}),className:F,"aria-label":N,children:V});if(!i)return r.jsx(ak,{});const I=rk({similarError:m,similarErrorIsFatal:d,isSimilarLoading:u});return r.jsxs(r.Fragment,{children:[r.jsx(Vc,{data:i,onClose:t,hideCloseButton:a,onShowSimilar:A,actions:O,similarState:I,similarLinkComponent:j,reportSpamPending:y,notSpamPending:S,className:"border-l-0 h-full w-full"}),r.jsx(ok,{isOpen:f,current:i.category.value,onSelect:E,onCancel:()=>h(!1)})]})}const Ks=({onClose:e,thread:t,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o})=>t?r.jsx(ik,{thread:t,onClose:e,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o}):r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Dt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[r.jsx(Dt,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),ca="Open a message first",Go=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:n,onReply:a,onReplyAll:o,onForward:i,onDelete:c,canDelete:u,onToggleStar:m,isStarred:d,moveContext:f})=>{const[h,v]=l.useState(null),g=u??e,p=b=>()=>v(b);return r.jsx(ig,{hasThread:e,isStarred:d,onUnavailable:b=>v(ca),unavailableHint:h,replyTitle:`Reply ${Vs("reply")}`,replyAllTitle:`Reply all ${Vs("replyAll")}`,forwardTitle:`Forward ${Vs("forward")}`,deleteTitle:`Move to Trash ${Vs("delete")}`,flagTitle:`Star ${Vs("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:g?c:p(ca),onToggleStar:m,onMove:p(ca),moveSlot:f?r.jsx(zo,{accountId:f.accountId,currentMailboxId:f.currentMailboxId,onMove:f.onMove,label:"Move to mailbox"}):void 0,children:r.jsx(og,{open:t,enabled:s,onToggle:n})})},gf=()=>{const e=Te();return l.useCallback(t=>{const s=Zt({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])},fn=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=t??e?.mailboxId,o=s??e?.accountId,{accountId:i}=Ao(o?void 0:a),c=o??i,u=gf(),{deleteMessages:m}=ms({mailboxId:a??"",threadId:e?.threadId,accountId:c,onAfterOptimisticRemove:n}),{moveMessages:d}=Ds({mailboxId:a??"",threadId:e?.threadId,accountId:c,onAfterOptimisticRemove:n}),{toggleStar:f}=Oo({threadId:e?.threadId??"",mailboxId:a??""}),h=l.useCallback(()=>{e&&m(u(e))},[e,u,m]),v=l.useCallback(S=>{e&&d(u(e),S)},[e,u,d]),g=l.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[p,b]=l.useState(null),y=l.useCallback(()=>b(null),[]);return{mailboxId:a,accountId:c,isStarred:e?.hasStars,deleteThread:h,moveThread:v,toggleStar:g,composeRequest:p,requestCompose:b,clearComposeRequest:y}},ql=(e,t,s)=>{if(!t)return null;const n=e.indexOf(t);if(n===-1)return null;const a=s==="next"?n+1:n-1;return a<0||a>=e.length?null:e[a]},Yo=()=>{const[e,t]=l.useState(void 0),[s,n]=l.useState([]),[a,o]=l.useState([]),i=l.useRef(null),[c,u]=l.useState(!1),[m,d]=l.useState(!1),f=l.useCallback(h=>{t(h.focusedMessageId),n(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:f,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:c,blocksKeyboard:m}},Xo=({context:e,orderedIds:t,selectedMessageId:s,enabled:n=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:c,blocksKeyboard:u}=e,m=l.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return Lb({enabled:n&&!u,handlers:{...c?{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:m,...o}}),{goBack:m,nextMessageId:ql(t,s,"next")??void 0,previousMessageId:ql(t,s,"previous")??void 0}};function lk(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function xf(e,t){if(e)return lk(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const bf=l.createContext(null);function Or(){const e=l.useContext(bf);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function ck({selectedMessageId:e,children:t}){const s=Qe(),{searchInput:n}=Le(),{selectedThreadId:a,selectedMailboxId:o}=As({strict:!1}),{data:i}=ye({...pa(),staleTime:6e4}),c=l.useMemo(()=>{if(e)return i?.items.find(M=>M.messageId===e)},[i,e]),u=l.useMemo(()=>xf(c,{messageId:e,threadId:a,mailboxId:o}),[c,e,a,o]),m=l.useCallback((M,D)=>{s({to:"/mail",search:E=>({...E,selectedMessageId:M,selectedThreadId:void 0,selectedMailboxId:void 0}),replace:D?.replace})},[s]),d=l.useCallback((M,D)=>{s({to:"/mail",replace:D?.replace,search:E=>({...E,q:n||void 0,selectedMessageId:M.id,selectedThreadId:M.threadId,selectedMailboxId:M.mailboxId})})},[s,n]),f=l.useCallback(M=>{e&&M.includes(e)&&s({to:"/mail",search:D=>({...D,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=fn({thread:c,onAfterOptimisticRemove:f}),v=l.useCallback(()=>{s({to:"/mail",search:M=>({...M,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),g=Yo(),p=l.useMemo(()=>i?.items??[],[i]),{deleteMessages:b}=ms({mailboxId:c?.mailboxId??"",messages:p,onAfterOptimisticRemove:f}),{toggleReadFor:y}=Nr({mailboxId:c?.mailboxId??"",messages:p}),S=g.focusedMessageId,w=l.useMemo(()=>i?.items.find(M=>M.messageId===S),[i,S])??c,C=fn({thread:w}),{nextMessageId:T,previousMessageId:A}=Xo({context:g,orderedIds:g.orderedIds,selectedMessageId:e,onClose:v,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{g.listCommandsRef.current?.requestVerb("delete")||C.deleteThread()},toggleStar:C.toggleStar,toggleRead:()=>{g.listCommandsRef.current?.requestVerb("markRead")||w&&y([w.messageId],!w.isRead)},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),k={selectedMessageId:e,selectedThread:c,conversation:u,onSelectMessage:m,onSelectSearchResult:d,onCloseThread:v,actions:h,triage:g,onDeleteMessages:b,nextMessageId:T,previousMessageId:A,handleDeselectIfRemoved:f};return r.jsx(bf.Provider,{value:k,children:t})}function vf(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:n,onDeleteMessages:a}=Or(),{accounts:o}=Le();return r.jsx(_C,{accounts:o,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:n.listCommandsRef,onTriageContextChange:n.onTriageContextChange,onDeleteMessages:a})}function uk(){const{conversation:e,actions:t}=Or(),{intelligenceOpen:s,onToggleIntelligence:n}=Le(),a=ps()?.showIntelligencePane??!1,o=!!e,i=a&&o;return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Go,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,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}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(zs,{})})]})}function dk(){const{selectedThread:e,handleDeselectIfRemoved:t}=Or(),{onToggleIntelligence:s}=Le();return r.jsx(Ks,{onClose:s,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,onAfterOptimisticRemove:t})}function fk(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:n,nextMessageId:a,previousMessageId:o,handleDeselectIfRemoved:i}=Or(),{intelligenceOpen:c,onToggleIntelligence:u}=Le();return t?r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:n,onOpenIntelligence:u,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:c}),r.jsx(Ro,{isOpen:c,onClose:u,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:u,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,hideCloseButton:!0,onAfterOptimisticRemove:i})})]}):r.jsx("div",{className:"h-full",children:r.jsx(vf,{})})}const Zs=Object.assign(ck,{List:vf,Reading:uk,Intelligence:dk,Phone:fk}),mk=()=>Ga({query:{starred:!0,order:"desc"}});function yf(){const{data:e,isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:c}=Lu({queryKey:mk(),queryFn:async({pageParam:m})=>{const{data:d}=await rh({query:{starred:!0,order:"desc",continuationToken:m},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:m=>m.continuationToken,staleTime:6e4});return{threads:l.useMemo(()=>(e?.pages??[]).flatMap(m=>m.items??[]),[e]),isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:c}}const hk=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function wf({title:e,unreadCount:t,preset:s,selectedCategory:n,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:c,onClearFilters:u,children:m,footer:d,searchResults:f,searchLoading:h,relatedResults:v,relatedLoading:g,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:y,searchResultsInBody:S,refreshControl:x}){const{searchInput:w}=Le(),C=w.trim().length>0,T={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:n,activeFilters:a,onSelectCategory:o,onSelectSource:c,onToggleFilter:i,onClear:u};return r.jsx(wc,{hasSheet:!C,children:r.jsx(Zd,{title:e,unreadCount:t,footer:d,searchFilter:T,searchResults:f,searchLoading:h,relatedResults:v,relatedLoading:g,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:y,searchResultsInBody:S,refreshControl:x,children:r.jsx(lc,{...T,hideChrome:C,children:m})})})}const pk={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function gk({rows:e,verb:t}){const{selectedIds:s,exitSelection:n}=Wo(),a=l.useMemo(()=>e.filter(o=>s.has(o.id)).map(o=>({id:o.id,sender:o.fromName,email:o.fromEmail,subject:o.subject,date:o.timeLabel})),[e,s]);return r.jsx(Qo,{verb:t,selection:a,crossAccount:!0,onFinished:n})}function xk({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:n,onDeleteMessages:a}){const{searchQuery:o,resultFolderIndex:i}=Le(),c=xs(),u=es(),m=Za(),[d,f]=l.useState("all"),[h,v]=l.useState(new Set),g=l.useCallback(F=>{v(N=>{const V=new Set(N);return V.has(F)?V.delete(F):V.add(F),V})},[]),p=l.useCallback(()=>{f("all"),v(new Set)},[]),{threads:b,isLoading:y,isError:S,error:x,refetch:w,fetchNextPage:C,hasNextPage:T,isFetchingNextPage:A}=yf(),{freeText:k,tokens:M}=Us(o.trim().toLowerCase(),c),D=l.useMemo(()=>{const F=Array.from(h).map(N=>pk[N]).filter(N=>N!=null);return hk(b).map(er).filter(N=>(d==="all"||N.category===d)&&F.every(V=>V(N))&&(!k||qd(N,k))&&Ko(N,M))},[b,d,h,k,M]),E=l.useMemo(()=>Zx(),[]),L=l.useMemo(()=>D.map(F=>Kn(F,i)),[D,i]),O=l.useMemo(()=>D.filter(F=>!F.isRead).length,[D]),j=y?"loading":S?"error":D.length===0?"empty":"ready",I=l.useCallback(()=>{const F=Ya(Xa());window.open(F,"_blank","noopener,noreferrer")},[]),P=Ar(),R=r.jsx("div",{className:"flex h-full min-h-0 flex-col",children:r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r.jsx("div",{className:"divide-y divide-line",children:D.map(F=>r.jsx(Vo,{thread:F,active:F.id===e,onClick:()=>t?.(F.id)},F.id))}),T?r.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>C(),disabled:A,children:A?"Loading…":"Load more"}):null]})});return r.jsx(wf,{title:"Starred",unreadCount:O,preset:E,selectedCategory:d,activeFilters:h,onSelectCategory:f,onToggleFilter:g,onClearFilters:p,searchResults:L,searchLoading:y,onSelectSearchResult:F=>t?.(F.id),searchResultsInBody:!0,children:r.jsxs(sf,{selectedMessageId:e,onOpen:(F,N)=>t?.(F,N),onDeleteMessages:a,onSelectionVerb:m.start,wizardOpen:m.isOpen,commandsRef:s,onTriageContextChange:n,children:[r.jsx(iu,{listTitle:"Starred",sections:[{id:"flagged",threads:D}],flatList:!0,hideHeader:!0,listState:P.searchResults?"ready":j,searchQuery:k?o:void 0,errorMessage:S?kc(x):void 0,onRetry:()=>w(),onReportError:I,selectedThreadId:e,onSelectThread:t,isDesktop:u,selectionBar:r.jsx(JS,{title:"Starred"}),listBody:P.searchResults??(j==="ready"?R:void 0)}),r.jsx(gk,{rows:D,verb:m.verb})]})})}const Sf=l.createContext(null);function Dr(){const e=l.useContext(Sf);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function bk({selectedMessageId:e,children:t}){const s=Qe(),{threads:n}=yf(),a=l.useMemo(()=>{if(e)return n.find(x=>x.messageId===e)},[n,e]),o=l.useCallback((x,w)=>{s({to:"/mail/flagged",search:C=>({...C,selectedMessageId:x}),replace:w?.replace})},[s]),i=l.useCallback(()=>{s({to:"/mail/flagged",search:x=>({...x,selectedMessageId:void 0})})},[s]),c=l.useCallback(x=>{e&&x.includes(e)&&i()},[e,i]),u=fn({thread:a,onAfterOptimisticRemove:c}),m=Yo(),{deleteMessages:d}=ms({mailboxId:a?.mailboxId??"",messages:n,onAfterOptimisticRemove:c}),{toggleReadFor:f}=Nr({mailboxId:a?.mailboxId??"",messages:n}),h=m.focusedMessageId,g=l.useMemo(()=>n.find(x=>x.messageId===h),[n,h])??a,p=fn({thread:g}),{nextMessageId:b,previousMessageId:y}=Xo({context:m,orderedIds:m.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{m.listCommandsRef.current?.requestVerb("delete")||p.deleteThread()},toggleStar:p.toggleStar,toggleRead:()=>{m.listCommandsRef.current?.requestVerb("markRead")||g&&f([g.messageId],!g.isRead)},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),S={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:m,onDeleteMessages:d,nextMessageId:b,previousMessageId:y,handleDeselectIfRemoved:c};return r.jsx(Sf.Provider,{value:S,children:t})}function Cf(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:n}=Dr();return r.jsx(xk,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:n})}function vk(){const{selectedThread:e,actions:t}=Dr(),{intelligenceOpen:s,onToggleIntelligence:n}=Le(),a=ps()?.showIntelligencePane??!1,o=!!e,i=a&&o;return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Go,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,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}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(zs,{})})]})}function yk(){const{selectedThread:e,handleDeselectIfRemoved:t}=Dr(),{onToggleIntelligence:s}=Le();return r.jsx(Ks,{onClose:s,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,onAfterOptimisticRemove:t})}function wk(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:n,previousMessageId:a,handleDeselectIfRemoved:o}=Dr(),{intelligenceOpen:i,onToggleIntelligence:c}=Le();return e?r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:c,onSwipeNext:n?()=>s(n):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:i}),r.jsx(Ro,{isOpen:i,onClose:c,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:c,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,hideCloseButton:!0,onAfterOptimisticRemove:o})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Cf,{})})}const en=Object.assign(bk,{List:Cf,Reading:vk,Intelligence:yk,Phone:wk}),Sk={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Ck=()=>{const e=l.useRef(!1);return l.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector('[data-testid="compose-body"]')?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},kk=()=>{const{state:e,closeCompose:t}=Jt(),s=Ck(),[n,a]=l.useState(!1),{isError:o,error:i,refetch:c}=ye({...$t(),staleTime:1/0}),u=l.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),m=l.useCallback(()=>{a(!1),t()},[t]),d=l.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const f=Sk[e.mode]??"New Message";return r.jsxs(dt.Root,{open:e.isOpen,onOpenChange:u,children:[r.jsxs(dt.Portal,{children:[r.jsx(dt.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(dt.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-lg bg-canvas pb-[env(safe-area-inset-bottom,0px)]",style:{height:"95dvh"},children:[r.jsx(dt.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),r.jsx(dt.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:f}),o?r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(ts,{title:"Couldn't load compose",error:i,onRetry:()=>{c()}})}):r.jsx("div",{className:"flex-1 overflow-hidden",children:r.jsx(To,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),r.jsx(oo,{isOpen:n,title:"Discard draft?",description:"Your message has unsaved content. Are you sure you want to discard it?",confirmLabel:"Discard",cancelLabel:"Keep editing",destructive:!0,onConfirm:m,onCancel:d})]})},jk={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},kf=()=>{const{state:e,closeCompose:t}=Jt(),s=es(),{isError:n,error:a,refetch:o}=ye({...$t(),staleTime:1/0});if(!s)return r.jsx(kk,{});if(!e.isOpen)return null;const i=jk[e.mode]??"New Message",c=r.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[r.jsx("div",{className:"flex items-center gap-2 min-w-0",children:r.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),r.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:r.jsx(Nt,{className:"size-5"})})]});return n?r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[c,r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(ts,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):r.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[c,r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:r.jsx(To,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function Nk(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:gt(e.updatedAt),isRead:!0}}function Ek(e){return{id:e.messageId,accountId:e.accountId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:gt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function Ik({outboxMessages:e,accountId:t,imapThreads:s}){const n=e.filter(i=>i.status==="draft"&&i.accountId===t).map(Nk),a=s.map(Ek),o=[];return n.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:n}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function Jo(){const e=ps();return!e||e.showNavPane?null:r.jsx(ie,{variant:"ghost",size:"sm",icon:r.jsx(fr,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const Rk=({label:e,count:t})=>r.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:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:t})]}),Tk=({row:e,isSelected:t,onOpen:s,onDelete:n,isDeleting:a})=>r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:W("group",_s({active:t})),children:[r.jsx(ac,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),r.jsx(cn,{thread:e}),r.jsx("div",{className:"flex items-center gap-1 shrink-0",children:r.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),n(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:r.jsx(Lt,{className:"size-3.5"})})})]}),Mk=({row:e,isSelected:t,onOpen:s})=>{const n=!e.isRead;return r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:W("group",_s({active:t})),children:[n&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx(jt,{name:e.fromName,email:e.fromEmail,size:"sm"}),r.jsx(cn,{thread:e})]})};function Ak({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:n,title:a,unreadCount:o}){const{openCompose:i,state:c}=Jt(),u=Qe(),m=Te(),{data:d}=ye(or()),f=l.useMemo(()=>Ik({outboxMessages:d?.items??[],accountId:t,imapThreads:n}),[d?.items,t,n]),h=ze({...lr(),onSuccess:()=>{m.invalidateQueries({queryKey:eo()})}}),v=y=>{h.mutate({path:{outboxMessageId:y}})},g=y=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:y})},p=y=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:y}})},b=f.length===0;return r.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(Jo,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:a}),(o??0)>0&&r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:[o," unread"]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:b?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[r.jsx(La,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):f.map(y=>r.jsxs("div",{children:[y.label&&r.jsx(Rk,{label:y.label,count:y.threads.length}),r.jsx("div",{className:"divide-y divide-line",children:y.threads.map(S=>y.id==="remit-drafts"?r.jsx(Tk,{row:S,isSelected:c.isOpen&&S.id===c.outboxMessageId,onOpen:g,onDelete:v,isDeleting:h.isPending},S.id):r.jsx(Mk,{row:S,isSelected:S.id===s,onOpen:p},S.id))})]},y.id))})]})}function Ok(e,t,s){const n=new Array(e);return new Proxy(n,{get(a,o,i){if(typeof o=="string"){const c=o.charCodeAt(0);if(c>=48&&c<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let m=a[u];if(!m){const d=t[u*2];m=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return m}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function Ns(e,t,s){let n=s.initialDeps??[],a,o=!0;function i(){const c=e();return(c.length!==n.length||c.some((m,d)=>n[d]!==m))&&(n=c,a=t(...c),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=c=>{n=c},i}function Hl(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const Dk=(e,t)=>Math.abs(e-t)<1.01,Pk=(e,t,s)=>{let n;return function(...a){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,a),s)}};let tn;const ua=()=>{if(tn!==void 0)return tn;if(typeof navigator>"u")return tn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return tn=!0;const e=navigator.maxTouchPoints;return tn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Wl=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},Lk=e=>e,Fk=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,a=new Array(n);for(let o=0;o<n;o++)a[o]=t+o;return a},$k=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const a=i=>{const{width:c,height:u}=i;t({width:Math.round(c),height:Math.round(u)})};if(a(Wl(s)),!n.ResizeObserver)return()=>{};const o=new n.ResizeObserver(i=>{const c=()=>{const u=i[0];if(u?.borderBoxSize){const m=u.borderBoxSize[0];if(m){a({width:m.inlineSize,height:m.blockSize});return}}a(Wl(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},tr={passive:!0},_k=typeof window>"u"?!0:"onscrollend"in window,zk=(e,t,s)=>{const n=e.scrollElement;if(!n)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&_k;let i=0;const c=o?null:Pk(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=f=>()=>{i=s(n),c?.(),t(i,f)},m=u(!0),d=u(!1);return n.addEventListener("scroll",m,tr),o&&n.addEventListener("scrollend",d,tr),()=>{n.removeEventListener("scroll",m),o&&n.removeEventListener("scrollend",d)}},Bk=(e,t)=>zk(e,t,s=>{const{horizontal:n,isRtl:a}=e.options;return n?s.scrollLeft*(a&&-1||1):s.scrollTop}),Uk=(e,t,s)=>{if(s.options.useCachedMeasurements){const n=s.indexFromElement(e),a=s.options.getItemKey(n);return s.itemSizeCache.get(a)??s.options.estimateSize(n)}if(t?.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}if(!t){const n=s.indexFromElement(e),a=s.options.getItemKey(n),o=s.itemSizeCache.get(a);if(o!==void 0)return o}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},Kk=(e,{adjustments:t=0,behavior:s},n)=>{var a,o;(o=(a=n.scrollElement)==null?void 0:a.scrollTo)==null||o.call(a,{[n.options.horizontal?"left":"top"]:e+t,behavior:s})},qk=Kk;class Hk{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,n,a;return((a=(n=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:n.now)==null?void 0:a.call(n))??Date.now()},this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const c=o.target,u=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);for(const[m,d]of this.elementsCache)if(d===c){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(c,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=n())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=n())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=n())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var n,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Lk,rangeExtractor:Fk,onChange:()=>{},measureElement:Uk,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 v=s[h];v!==void 0&&(o[h]=v)}const i=this.options;let c=null,u=null,m=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,v=o.count,g=this.getMeasurements(),p=h>0?((n=g[0])==null?void 0:n.key)??i.getItemKey(0):null,b=h>0?((a=g[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(v!==h||h>0&&v>0&&(o.getItemKey(0)!==p||o.getItemKey(v-1)!==b)){m=!0;const x=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??g[0]:null;x&&(c=[x.key,this.getScrollOffset()-x.start]);const w=o.followOnAppend===!0?"auto":o.followOnAppend||null;w&&v>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(v-1)!==b)&&(u=w)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(c&&this.scrollOffset!==null){const[h,v]=c,g=this.getMeasurements(),{count:p,getItemKey:b}=this.options;let y=0;for(;y<p&&b(y)!==h;)y++;if(y<p){const S=g[y];if(S){const x=S.start+v;x!==this.scrollOffset&&(f=x-this.scrollOffset,this.scrollOffset=x,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?c[0]:null,d?c[1]:0,u,f])},this.notify=s=>{var n,a;(a=(n=this.options).onChange)==null||a.call(n,this,s)},this.maybeNotify=Ns(()=>(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 n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}if(this.scrollElement=n,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 c=this.getScrollOffset();this.scrollDirection=i?c===o?this.scrollDirection:c<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)},c=()=>{this._iosTouching=!1,!(!ua()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,tr),o.addEventListener("touchend",c,tr),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",c),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,c,u]=a;o!==null&&!c&&(ua()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),c&&this.scrollToEnd({behavior:c})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),n=this.getMaxScrollOffset();if(s<0||s>n)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=Ns(()=>[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,n,a,o,i,c,u,m)=>(this.prevLanes!==void 0&&this.prevLanes!==c&&(this.lanesChangedFlag=!0),this.prevLanes=c,this.pendingMin=null,{count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:c,laneAssignmentMode:u,gap:m}),{key:!1}),this.getMeasurements=Ns(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:c,laneAssignmentMode:u,gap:m},d)=>{const f=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const y of this.laneAssignments.keys())y>=s&&this.laneAssignments.delete(y);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(y=>{this.itemSizeCache.set(y.key,y.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),c===1){const y=s*2;let S=this._flatMeasurements;if(!S||S.length<y){const C=new Float64Array(y);S&&h>0&&C.set(S.subarray(0,h*2)),S=C,this._flatMeasurements=S}let x;if(h===0)x=n+a;else{const C=h-1;x=S[C*2]+S[C*2+1]+m}for(let C=h;C<s;C++){const T=o(C),A=f.get(T),k=typeof A=="number"?A:this.options.estimateSize(C);S[C*2]=x,S[C*2+1]=k,x+=k+m}const w=Ok(s,S,o);return this.measurementsCache=w,w}const v=this.measurementsCache.slice(0,h),g=new Array(c).fill(void 0),p=new Float64Array(c);let b=0;for(let y=0;y<h;y++){const S=v[y];S&&(g[S.lane]===void 0&&b++,g[S.lane]=y,p[S.lane]=S.end)}for(let y=h;y<s;y++){const S=o(y),x=this.laneAssignments.get(y);let w,C;const T=u==="estimate"||f.has(S);if(x!==void 0&&this.options.lanes>1){w=x;const D=g[w],E=D!==void 0?v[D]:void 0;C=E?E.end+m:n+a}else if(b===c){let D=0,E=p[0],L=g[0];for(let O=1;O<c;O++){const j=p[O];(j<E||j===E&&g[O]<L)&&(D=O,E=j,L=g[O])}w=D,C=E+m,T&&this.laneAssignments.set(y,w)}else w=y%this.options.lanes,C=n+a,T&&this.laneAssignments.set(y,w);const A=f.get(S),k=typeof A=="number"?A:this.options.estimateSize(y),M=C+k;v[y]={index:y,start:C,size:k,end:M,key:S,lane:w},g[w]===void 0&&b++,g[w]=y,p[w]=M}return this.measurementsCache=v,v},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ns(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,a,o)=>s.length===0||n===0?(this.range=null,null):(this.range=Vk(s,n,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ns(()=>{let s=null,n=null;const a=this.calculateRange();return a&&(s=a.startIndex,n=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:n,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,a=s.getAttribute(n);return a?parseInt(a,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.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),c=Math.min(this.options.count-1,a+o);return s>=i&&s<=c}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,c)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(c))});return}const n=this.indexFromElement(s),a=this.options.getItemKey(n),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(n)&&this.resizeItem(n,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,n)=>{var a,o;if(s<0||s>=this.options.count)return;let i,c,u;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)u=this.options.getItemKey(s),c=m[s*2],i=m[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,c=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,f=n-d;if(f!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,v=h?this.getTotalSize():0,g=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:c,size:i,end:c+i,lane:0},f,this):c<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,n),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-v):g&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=Ns(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const c=s[o],u=n[c];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=jf(0,n.length-1,o?c=>a[c*2]:c=>Hl(n[c]).start,s);return Hl(n[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,n,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+o?"end":"start"),n==="center"?s+=(a-o)/2:n==="end"&&(s-=o);const c=this.getMaxScrollOffset();return Math.max(Math.min(c,s),0)},this.getOffsetForIndex=(s,n="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(n==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)n="end";else if(i.start<=o+this.options.scrollPaddingStart)n="start";else return[o,n];if(n==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),n];const c=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(c,n,i.size),n]},this.scrollToOffset=(s,{align:n="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,n),i=this.now();this.scrollState={index:null,align:n,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:n="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,n);if(!o)return;const[i,c]=o,u=this.now();this.scrollState={index:s,align:c,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:n="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:n}),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 n=this.getMeasurements();let a;if(n.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=n.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=n[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&o.some(c=>c===null);){const c=n[i];o[c.lane]===null&&(o[c.lane]=c.end),i--}a=Math.max(...o.filter(c=>c!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const n=this.getMeasurements();for(const a of n)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:n,behavior:a})=>{this._intendedScrollOffset=s+(n??0),this.options.scrollToFn(s,{behavior:a,adjustments:n},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&&(ua()&&(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 n=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=n?n[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&Dk(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 c=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&u>c;this.scrollState.lastTargetOffset=a,m||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const jf=(e,t,s,n)=>{for(;e<=t;){const a=(e+t)/2|0,o=s(a);if(o<n)e=a+1;else if(o>n)t=a-1;else return a}return e>0?e-1:0};function Wk(e,t,s){let n=0;for(;n<=t;){const a=(n+t)/2|0,o=e[a*2];if(o<s)n=a+1;else if(o>s)t=a-1;else return a}return n>0?n-1:0}function Vk(e,t,s,n,a){const o=e.length-1;if(e.length<=n)return{startIndex:0,endIndex:o};if(n===1&&a!==null){const m=Wk(a,o,s);let d=m;const f=s+t;for(;d<o&&a[d*2]+a[d*2+1]<f;)d++;return{startIndex:m,endIndex:d}}let c=jf(0,o,m=>e[m].start,s),u=c;if(n===1)for(;u<o&&e[u].end<s+t;)u++;else if(n>1){const m=Array(n).fill(0);for(;u<o&&m.some(f=>f<s+t);){const f=e[u];m[f.lane]=f.end,u++}const d=Array(n).fill(s+t);for(;c>=0&&d.some(f=>f>=s);){const f=e[c];d[f.lane]=f.start,c--}c=Math.max(0,c-c%n),u=Math.min(o,u+(n-1-u%n))}return{startIndex:c,endIndex:u}}const da=typeof document<"u"?l.useLayoutEffect:l.useEffect;function Qk({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...n}){const a=l.useReducer(m=>m+1,0)[1],o=l.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=m=>{const d=o.current;if(!d.enabled||!d.container)return;const f=m.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const y=m.options.horizontal?"width":"height";d.container.style[y]=`${f}px`}const h=!!m.options.horizontal,v=d.mode==="transform",g=h?"left":"top",p=m.options.scrollMargin,b=m.getVirtualItems();for(const y of b){const S=y.start-p,x=m.elementsCache.get(y.key);x&&d.lastPositions.get(x)!==S&&(d.lastPositions.set(x,S),v?x.style.transform=h?`translate3d(${S}px, 0, 0)`:`translate3d(0, ${S}px, 0)`:x.style[g]=`${S}px`)}},c={...n,onChange:(m,d)=>{var f;const h=o.current;let v=!0;if(h.enabled){i(m);const g=m.range,p=h.prevRange;v=!p||p.isScrolling!==m.isScrolling||p.startIndex!==g?.startIndex||p.endIndex!==g?.endIndex,v&&(h.prevRange=g?{startIndex:g.startIndex,endIndex:g.endIndex,isScrolling:m.isScrolling}:null)}v&&(e&&d?za.flushSync(a):a()),(f=n.onChange)==null||f.call(n,m,d)}},[u]=l.useState(()=>{const m=new Hk(c);return Object.assign(m,{containerRef:d=>{const f=o.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const h=m.getTotalSize();f.lastSize=h;const v=m.options.horizontal?"width":"height";d.style[v]=`${h}px`}}})});return u.setOptions(c),da(()=>u._didMount(),[]),da(()=>u._willUpdate()),da(()=>{i(u)}),u}function Gk(e){return Qk({observeElementRect:$k,observeElementOffset:Bk,scrollToFn:qk,...e})}const Zo=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",Yk=e=>`Select all ${Zo(e)}`,Xk=(e,t)=>`All ${Gt(t)} ${Zo(e)} selected`,Jk=({verb:e,confirmingDelete:t,hasSelection:s,junkMailboxId:n,currentMailboxId:a,deletableMessageId:o})=>{if(t)return{kind:"withheld"};if(e==="junk"){const i=gS(n,a);if(i!==void 0)return{kind:"unavailable",reason:i}}return s?{kind:"openWizard"}:e!=="delete"||o===void 0?{kind:"declined"}:{kind:"confirmDelete",messageId:o}},Zk=(e,t,s)=>e==="BACK"&&t&&s===void 0,ej=(e,t)=>({id:e.messageId,accountId:e.accountId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:gt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Er(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),tj=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,messageCount:m,isMultiSelectMode:d,onLongPress:f,isDesktop:h,density:v})=>r.jsx(Vo,{thread:ej(e,m),linkMailboxId:t,inListbox:!0,active:s,focused:n,isTabStop:a,density:v,isDesktop:h,onFocusRow:o,selection:{isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:d,onLongPress:f}}),sj=l.memo(tj),nj=e=>{const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:gt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Er(e.category),suspicious:t}},rj=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,onDelete:h,onToggleRead:v,density:g})=>{const[p,b]=l.useState("none"),y=Qe(),S=l.useCallback(A=>{navigator.vibrate?.(10),A==="trailing"?h(e.messageId):v(e.messageId,e.isRead),b("none")},[h,v,e.messageId,e.isRead]),x=l.useCallback(()=>{d(e.messageId)},[d,e.messageId]),w=l.useCallback(()=>{c(e.messageId)},[c,e.messageId]),C=l.useCallback(()=>{y({to:"/mail/$mailboxId",params:{mailboxId:t},search:A=>({...A,selectedMessageId:e.messageId})})},[y,t,e.messageId]),T=nf(e.messageId,u);return f||m?r.jsx(sj,{thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,density:g}):r.jsx("div",{role:"presentation",onPointerDownCapture:T.onMouseDown,onClickCapture:T.claimClick,onContextMenu:T.onContextMenu,children:r.jsx(ou,{thread:nj(e),selectionMode:!1,checked:!1,active:s,peek:p,onPeek:b,onToggleCheck:w,onLongPress:x,onOpen:C,onAct:S})})},aj=72,oj=32,ij=5,Nf="remit:list-density",lj=()=>{try{const e=localStorage.getItem(Nf);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},cj=({query:e})=>r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[r.jsx(rr,{className:"size-4 text-fg-muted"}),r.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),uj=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:n,isError:a=!1,error:o,onRetry:i,searchQuery:c,searchPredicate:u,onDeleteMessages:m,isDeleting:d=!1,isMoving:f=!1,onLoadMore:h,hasMore:v=!1,isLoadingMore:g=!1,accountId:p,listTitle:b,listMeta:y,listFilter:S,listScopeLabel:x,onTriageContextChange:w,commandsRef:C,hideHeader:T=!1})=>{const A=l.useRef(null),k=Qe(),M=es(),D=Za(),{verb:E,start:L,startFromSearch:O}=D,j=ah(),I=!!c?.trim(),P=Ar(),{labels:R}=ao(p),{pushError:F}=nt(),[N,V]=l.useState(s),[Q,re]=l.useState(),se=l.useCallback(z=>{re(Y=>Y===z?Y:void 0),V(z)},[]),[fe,Z]=l.useState(lj),ne=l.useCallback(()=>{Z(z=>{const Y=z==="comfortable"?"compact":"comfortable";try{localStorage.setItem(Nf,Y)}catch{}return Y})},[]),{toggleReadFor:le}=Nr({mailboxId:e}),{junkMailboxId:U}=Sn(p),_=Tr(U,e),{selectedIds:de,selectedCount:ge,hasSelection:we,isSelected:Re,toggle:q,select:Ce,clearSelection:xe,selectRange:Ne,setAnchor:ue,selectAll:te,toggleAll:be,intersectWith:De}=Xc(),Ue=ho(ge,M),[G,Ge]=l.useState(null),ke=I&&!!u,Ke=`${e}|${JSON.stringify(u??{})}`,$=lf({mailboxId:e,accountId:p,enabled:ke,predicateKey:Ke,searchQuery:u??{}}),ce=l.useCallback((z,Y,St)=>{if(St.error===void 0){if(St.cancelled){F({severity:"warning",title:fC(St.done),detail:mC(z,St.done,Y)});return}F({severity:"info",title:_l(z,St.done)})}},[F]),ae=$.phase.kind,me=$.clear,Me=l.useCallback(()=>{ae==="escalated"&&me(),xe()},[xe,me,ae]),[he,Se]=l.useState(null),Ae=l.useRef(null),ve=l.useRef(!1),Ye=l.useRef(null),Xe=!n&&t.length>0,Oe=G!==null,K=Gk({count:t.length,getScrollElement:()=>A.current,estimateSize:()=>fe==="compact"?oj:aj,overscan:ij}),pe=s?t.findIndex(z=>z.messageId===s):-1,oe=N?t.findIndex(z=>z.messageId===N):-1,J=l.useCallback(z=>{if(z<0||z>=t.length)return;const Y=t[z];if(Ue){q(Y.messageId);return}Ae.current=Y.messageId,ve.current=!1,re(Y.messageId),V(Y.messageId)},[t,Ue,q]),je=l.useCallback(()=>{if(t.length===0)return;const z=oe<0?0:Math.min(oe+1,t.length-1);J(z)},[t.length,oe,J]),Pe=l.useCallback(()=>{if(t.length===0)return;const z=oe<=0?0:oe-1;J(z)},[t.length,oe,J]),_e=l.useCallback(()=>J(0),[J]),Je=l.useCallback(()=>J(t.length-1),[J,t.length]),qe=l.useCallback(()=>{N&&q(N)},[N,q]),Ee=l.useMemo(()=>t.map(z=>z.messageId),[t]),et=l.useMemo(()=>{const z=[];for(const Y of t)de.has(Y.messageId)&&z.push({id:Y.messageId,sender:Y.fromName??Y.fromEmail??"Unknown",email:Y.fromEmail??"",subject:Y.subject??"(No subject)",date:gt(Y.sentDate)});return z},[t,de]),Be=l.useCallback((z,Y)=>Y.shiftKey?(Ne(Ee,z,N),!0):Y.metaKey||Y.ctrlKey?(q(z),!0):(Me(),ue(z),!1),[Ee,N,Ne,q,Me,ue]),lt=l.useCallback(z=>{!m||z.length===0||(Ye.current=N??null,Ge(z))},[m,N]),tt=l.useCallback(z=>{const Y=Yc(Ee,N,z);Y!==void 0&&(Ne(Ee,Y),Ae.current=Y,ve.current=!1,re(void 0),V(Y))},[Ee,N,Ne]),zt=l.useCallback(()=>tt(-1),[tt]),Rt=l.useCallback(()=>tt(1),[tt]),ns=l.useCallback(()=>{Ee.length>0&&te(Ee)},[Ee,te]),bs=l.useCallback(z=>{const Y=Jk({verb:z,confirmingDelete:G!==null,hasSelection:we,junkMailboxId:U,currentMailboxId:e,deletableMessageId:m?N:void 0});return Y.kind==="openWizard"?(L(z),!0):Y.kind==="confirmDelete"?(lt([Y.messageId]),!0):Y.kind==="unavailable"?(F({severity:"warning",title:Y.reason}),!0):Y.kind==="withheld"},[G,m,we,U,e,L,N,lt,F]),rt=l.useCallback(()=>{N&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:z=>({...z,selectedMessageId:N})})},[N,k,e]),Tt=l.useCallback(z=>{k({to:"/mail/$mailboxId",params:{mailboxId:e},search:Y=>({...Y,selectedMessageId:z}),replace:!0})},[k,e]);ef({keyboardFocusedMessageId:Q,openMessageId:s,enabled:M&&ge===0,open:Tt});const bt=$.phase.kind==="escalated"?{scope:Zo(u??{}),total:$.phase.total,searchQuery:u??{},run:z=>$.runAction(z),stop:$.stop}:void 0,vt=l.useCallback(()=>{if(!G)return;const z=G;if(z.length===0){Ge(null);return}const Y=new Set(z),St=t.findIndex(st=>Y.has(st.messageId));let Mt;for(let st=St+1;st<t.length;st++)if(!Y.has(t[st].messageId)){Mt=t[st].messageId;break}if(Mt===void 0){for(let st=St-1;st>=0;st--)if(!Y.has(t[st].messageId)){Mt=t[st].messageId;break}}m?.(z),Me(),Ye.current=null,Ge(null),Mt!==void 0&&(Ae.current=Mt,ve.current=!1,se(Mt),M&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:st=>({...st,selectedMessageId:Mt}),replace:!0})),M||Se(_l("delete",z.length))},[G,t,m,Me,k,e,M,se]),ht=l.useCallback(()=>{const z=Ye.current;Ye.current=null,Ge(null),z!==null&&(Ae.current=z,ve.current=!1,se(z))},[se]),rs=l.useMemo(()=>{if(ge===0)return;const z=new Set;for(const Y of t)de.has(Y.messageId)&&z.add(Y.accountConfigId);if(z.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[ge,de,t]),qs=l.useCallback(()=>{if(bt){O();return}L("organize")},[bt,O,L]),kn=l.useCallback(z=>{m?.([z])},[m]),ct=l.useCallback((z,Y)=>{le([z],!Y)},[le]),B=l.useCallback(z=>{M||Ce(z)},[M,Ce]),X=l.useCallback(()=>{if($.isRunning||$.phase.kind==="counting"){$.stop();return}Me()},[$,Me]),Ie=l.useCallback(()=>{$.clear()},[$]);l.useEffect(()=>{if(ve.current||!M&&s)return;const z=oe>=0?oe:pe;z>=0&&K.scrollToIndex(z,{align:"auto"})},[oe,pe,K,M,s]),l.useEffect(()=>{s&&(ve.current=!1,se(s))},[s,se]),l.useEffect(()=>{N&&(t.some(z=>z.messageId===N)||se(t[0]?.messageId))},[t,N,se]),l.useEffect(()=>{w?.({focusedMessageId:N,selectedIds:Array.from(de),hasList:Xe,blocksKeyboard:Oe||D.isOpen})},[N,de,Xe,Oe,D.isOpen,w]);const pt=l.useRef(w);pt.current=w,l.useEffect(()=>()=>pt.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),l.useEffect(()=>{$.phase.kind!=="idle"||$.isRunning||De(t.map(z=>z.messageId))},[t,De,$.phase,$.isRunning]);const yt=l.useRef(e);l.useEffect(()=>{yt.current!==e&&(yt.current=e,Me())},[e,Me]),Fu({shouldBlockFn:({action:z})=>Zk(z,we,j)?(Me(),!0):!1,enableBeforeUnload:!1,disabled:!we||j!==void 0}),l.useEffect(()=>{const z=A.current;if(!z||!v||!h)return;const Y=()=>{if(g)return;const{scrollTop:St,scrollHeight:Mt,clientHeight:st}=z;St+st>=Mt-200&&h()};return z.addEventListener("scroll",Y,{passive:!0}),Y(),()=>z.removeEventListener("scroll",Y)},[v,g,h]),l.useEffect(()=>{const z=Ae.current;if(!z)return;const Y=A.current?.querySelector(`[data-message-id="${z}"]`);Y&&(Ae.current=null,Y.focus({preventScroll:!0}))}),l.useEffect(()=>{if(C){if(!Xe){C.current=null;return}return C.current={focusNext:je,focusPrevious:Pe,focusFirst:_e,focusLast:Je,openFocused:rt,toggleSelect:qe,extendSelectDown:Rt,extendSelectUp:zt,selectAll:ns,clearSelection:()=>we?(Me(),!0):!1,requestVerb:bs,toggleDensity:ne},()=>{C.current=null}}},[C,Xe,je,Pe,_e,Je,rt,qe,Rt,zt,ns,we,Me,bs,ne]);const vs=n?"loading":a?"error":t.length===0?"empty":"ready",wt=a?kc(o):void 0,as=l.useCallback(()=>{const z=Ya(Xa());window.open(z,"_blank","noopener,noreferrer")},[]),jn=[{id:"inbox",threads:[]}],ys=Ee.length>0&&Ee.every(z=>de.has(z)),Lr=ke&&v&&ys&&!d&&!f&&$.phase.kind==="idle"&&!$.isRunning,Fr=d||f||$.isRunning,Hs=$.phase.kind==="escalated"?$.phase.total:ge,$r=$.runningAction?dC($.runningAction.kind,$.progress?.done??0,$.progress?.total??Hs):$.phase.kind==="counting"?"Counting matches…":$.phase.kind==="escalated"?Xk(u??{},$.phase.total):void 0,_r=$.phase.kind!=="escalated"&&Ee.length>0?{checked:ys,indeterminate:ge>0&&!ys,onChange:()=>be(Ee)}:void 0,ee=$.runningAction?{value:$.progress?.done??0,max:$.progress?.total??Hs,tone:gC($.runningAction.kind)}:void 0,at=($.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:$.stop}}:$.phase.kind==="escalated"&&!$.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:Ie}}:Lr?{tone:"info",text:"",action:{label:Yk(u??{}),onClick:$.escalate}}:void 0)??(rs?{tone:"warning",text:rs}:void 0),$f=r.jsx(So,{title:P.title||b,navSlot:P.navSlot,titleMeta:P.titleMeta,searchSlot:P.searchSlot,searchField:P.searchField,idleSlot:P.makeFilterSlot,count:Hs,onCancel:X,onDelete:()=>L("delete"),onMove:()=>L("move"),onOrganize:qs,onJunk:_?()=>L("junk"):void 0,onMarkRead:()=>L("markRead"),overflowSlot:p&&e&&ge>0&&R.length>0?r.jsx(Qd,{accountId:p,mailboxId:e,messageIds:Array.from(de)}):void 0,isBusy:Fr,isCounting:$.phase.kind==="counting",selectAll:_r,statusLabel:$r,progress:ee,notice:at}),_f=tf(Ee,N),zf=l.useCallback(z=>{ve.current=!0,se(z)},[se]),Bf=r.jsxs(r.Fragment,{children:[I&&c&&r.jsx(cj,{query:c}),r.jsxs("div",{ref:A,role:"listbox","aria-multiselectable":!0,"aria-label":b,className:"flex-1 overflow-y-auto",children:[r.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${K.getTotalSize()}px`},children:K.getVirtualItems().map(z=>{const Y=t[z.index];return r.jsx("div",{role:"presentation","data-index":z.index,ref:K.measureElement,className:We("absolute left-0 top-0 w-full border-b border-line",$.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${z.start}px)`},children:r.jsx(rj,{thread:Y,mailboxId:e,isSelected:s===Y.messageId,isFocused:N===Y.messageId,isTabStop:_f===Y.messageId,onFocusRow:zf,isChecked:Re(Y.messageId),onToggleCheck:q,onRowSelect:Be,isMultiSelectMode:Ue,onLongPress:B,isDesktop:M,onDelete:kn,onToggleRead:ct,density:fe})},z.key)})}),g&&r.jsx(Kp,{})]})]});return r.jsxs(r.Fragment,{children:[he&&!M&&r.jsx(pn,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>Se(null),children:he}),r.jsx(iu,{listTitle:b,listMeta:y,sections:jn,flatList:!0,listState:P.searchResults?"ready":vs,searchQuery:I?c:void 0,listFilter:S,listScopeLabel:x,errorMessage:wt,onRetry:i,onReportError:as,density:fe,selectedThreadId:s,onSelectThread:z=>k({to:"/mail/$mailboxId",params:{mailboxId:e},search:Y=>({...Y,selectedMessageId:z})}),isDesktop:M,hideHeader:T,selectionBar:$f,listBody:P.searchResults??(vs==="ready"?Bf:void 0)}),r.jsx(oo,{isOpen:G!==null,title:Nc(G?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:d,onConfirm:vt,onCancel:ht}),r.jsx(Qo,{verb:E,accountId:p,mailboxId:e,selection:et,crossAccount:rs!==void 0,escalated:bt,escalatedProgress:$.progress,onFinished:Me,onRunEnded:ce})]})},dj=e=>Ft({path:{accountId:e}}),fj=e=>{const t=Te(),s=Ls(),n=ze({...oh(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:dj(e)})}});return{trigger:()=>{n.mutate({path:{accountId:e}})},triggerAsync:()=>n.mutateAsync({path:{accountId:e}}),isPending:n.isPending,error:n.error,reset:n.reset}},mj=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:n}=fj(e);return r.jsx(Ax,{onRefresh:s,isRefreshing:n,children:t})};function hj({accountId:e,currentMailboxId:t,candidates:s,onMove:n,children:a}){const[o,i]=l.useState(!1),c=Ls(),u=so(),{inboxMailboxId:m}=id(e),d=Po(e),{data:f}=ye({...it({path:{accountId:e}}),staleTime:1/0}),h=l.useMemo(()=>no({mailboxes:f?.items??[],folderAppointments:d,currentMailboxId:t,translator:u}),[f?.items,d,t,u]),v=l.useMemo(()=>m||(h.find(S=>S.label.toLowerCase()==="inbox")?.id??h.find(S=>!S.isCurrent)?.id??""),[m,h]),g=l.useRef(!1);l.useEffect(()=>{g.current||(g.current=!0,ZC(c,s.length))},[c,s.length]);const p=l.useCallback(()=>{ek(c,s.length),i(!0)},[c,s.length]),b=l.useCallback((y,S)=>{tk(c,{selected:y.length,total:s.length,toInbox:S===m}),n(y,S)},[c,s.length,m,n]);return r.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[r.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:r.jsx(Px,{count:s.length,onReview:p})}),r.jsx("div",{className:"min-h-0 flex-1",children:a}),r.jsx(Wx,{open:o,candidates:s,defaultDestinationId:v,availableFolders:h,delimiter:ro(f?.items??[]),onConfirmMove:b,onCancel:()=>i(!1)})]})}const pj="We can verify this sender";function gj(e){const{data:t}=ye({...yc({path:{mailboxId:e??""},query:{senderTrust:["vip","wellknown"],dkimMismatch:!1,results:!0,limit:500}}),enabled:!!e,staleTime:6e4});return{candidates:(t?.items??[]).map(n=>({id:n.messageId,senderName:n.fromName||n.fromEmail||"Unknown sender",senderAddress:n.fromEmail??"",subject:n.subject||"(no subject)",snippet:n.snippet??"",trustReason:pj,trustSubReason:JC(n.senderTrust),senderTrust:n.senderTrust}))}}const xj=e=>{const t=new Set,s=[];for(const n of e)t.has(n.threadMessageId)||(t.add(n.threadMessageId),s.push(n));return s},bj={unread:"unread",flagged:"starred",attachment:"attachments"},vj=new Set(Object.values(ot)),Ef=e=>vj.has(e),yj=e=>Ef(e.category)||e.attributes.size>0,wj=e=>{const t={};Ef(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const n=bj[s];n&&(t[n]=!0)}return t},Sj=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",Cj=["category","unread","starred","attachments"],Vl=e=>JSON.stringify(Cj.map(t=>e?.[t]??null)),kj=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},jj=(e,t)=>{const s=kj(e);return s?Vl(s)===Vl(t):!1},If="remit:intelligence-open";function Nj(){try{return localStorage.getItem(If)!=="closed"}catch{return!0}}function Ql(e){try{localStorage.setItem(If,e?"open":"closed")}catch{}}const Ej=(e,t)=>e!==t,Ij=(e,t,s)=>{if(!(s||!t))return e.find(n=>n.messageId===t)},Rj=(e,t,s,n)=>{if(e)return e;if(!(n||!s))return t?.messageId===s?t:void 0},Ln=e=>e[0],Tj=e=>{const t=Ln(e.filter(c=>c.type==="from").map(c=>c.value)),s=Ln(e.filter(c=>c.type==="subject").map(c=>c.value)),n=Ln(e.filter(c=>c.type==="category").map(c=>c.category)),a=Ln(e.filter(c=>c.type==="isUnread"||c.type==="isRead").map(c=>c.type==="isUnread")),o=e.some(c=>c.type==="isStarred")?!0:void 0,i=e.some(c=>c.type==="hasAttachment")?!0:void 0;return{...t!==void 0?{from:t}:{},...s!==void 0?{subject:s}:{},...n!==void 0?{category:[n]}:{},...a!==void 0?{unread:a}:{},...o!==void 0?{starred:o}:{},...i!==void 0?{attachments:i}:{}}},Mj=(e,t)=>{switch(t.type){case"from":return e.from?.toLowerCase()===t.value.toLowerCase();case"subject":return e.subject?.toLowerCase()===t.value.toLowerCase();case"category":return e.category?.length===1&&e.category[0]===t.category;case"isUnread":return e.unread===!0;case"isRead":return e.unread===!1;case"isStarred":return e.starred===!0;case"hasAttachment":return e.attachments===!0;case"before":case"after":case"in":case"account":return!1}};function Aj(e,t={}){const s=Tj(e),n={...s,...t};return{params:s,residual:e.filter(a=>!Mj(n,a))}}function Oj(e,t,s){if(t.length===0)return e;const n=[...t];return e.filter(a=>{const o=er(a);return Ko({...o,accountId:o.accountId??s},n)})}const Dj=50,Pj=new Map(bu().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),Rf=l.createContext(null);function Pr(){const e=l.useContext(Rf);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function Lj({mailboxId:e,selectedMessageId:t,children:s}){const n=Qe(),o=Mr()==="desktop",i=Ls(),{accounts:c,searchQuery:u,searchInput:m,intelligenceOpen:d,onToggleIntelligence:f,onSetIntelligenceOpen:h}=Le(),v=xs(),g=Bo(u),p=g.length>0,{freeText:b,tokens:y}=Us(g,v),[S,x]=l.useState("all"),[w,C]=l.useState(new Set),T=l.useMemo(()=>({category:S,attributes:w}),[S,w]),A=l.useMemo(()=>wj(T),[T]),k=p||yj(T),{params:M,residual:D}=Aj(y,A),E={order:"desc",limit:Dj,...b?{query:b}:{},...M,...A},L={category:E.category,unread:E.unread,starred:E.starred,attachments:E.attachments},O=k?Qa({path:{mailboxId:e},query:E}):cr({path:{mailboxId:e},query:{order:"desc"}}),{data:j,isLoading:I,isError:P,error:R,refetch:F,fetchNextPage:N,hasNextPage:V,isFetchingNextPage:Q}=Lu({queryKey:O,queryFn:async({pageParam:ee})=>{if(k){const{data:at}=await ha({path:{mailboxId:e},query:{...E,continuationToken:ee},throwOnError:!0});return at}const{data:ut}=await ih({path:{mailboxId:e},query:{order:"desc",continuationToken:ee},throwOnError:!0});return ut},initialPageParam:void 0,getNextPageParam:ee=>ee.continuationToken,placeholderData:(ee,ut)=>jj(ut?.queryKey,L)?ee:void 0}),re=l.useCallback(ee=>{t&&ee.includes(t)&&n({to:"/mail/$mailboxId",params:{mailboxId:e},search:ut=>({...ut,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,n]),{deleteMessages:se,isPending:fe}=ms({mailboxId:e,onAfterOptimisticRemove:re}),{accountId:Z}=Ao(e),ne=Ju({accounts:c}),{moveMessages:le,isPending:U}=Ds({mailboxId:e,accountId:Z,onAfterOptimisticRemove:re}),_=Oj(D0(xj(j?.pages.flatMap(ee=>ee.items??[])??[])),D,Z),de=l.useCallback(ee=>{x(ee)},[]),ge=l.useCallback(ee=>{C(ut=>{const at=new Set(ut);return at.has(ee)?at.delete(ee):at.add(ee),at})},[]),we=l.useCallback(()=>{x("all"),C(new Set)},[]),Re=Pj.get(S),q=Re?{label:Re,reach:D.length>0?"loaded-pages":Sj(E),onClear:we}:void 0,Ce=Ej(m,u),xe=Ij(_,t,Ce),[Ne,ue]=l.useState(void 0);l.useEffect(()=>{xe&&ue(xe)},[xe]);const te=Rj(xe,Ne,t,Ce),{selectedThreadId:be}=As({strict:!1}),De=l.useMemo(()=>xf(te,{messageId:t,threadId:Ce?void 0:be,mailboxId:e}),[te,t,be,Ce,e]),Ue=Yo(),{listCommandsRef:G,onTriageContextChange:Ge,focusedMessageId:ke,selectedIds:Ke}=Ue,$=_.find(ee=>ee.messageId===ke)??te,ce=l.useRef(null);l.useEffect(()=>{const ee=te?.messageId??null;ee&&ce.current!==ee&&te?.authenticity?.dkimMismatch&&(ce.current=ee,d||f())},[te?.messageId,te?.authenticity?.dkimMismatch,d,f]);const ae=l.useRef(!1);l.useEffect(()=>{ae.current||o&&te?.messageId&&(ae.current=!0,Nj()&&!d&&h(!0))},[o,te?.messageId,d,h]);const me=$y({accounts:c})??0,Me=Te(),{pushError:he}=nt(),Se=fn({thread:te,mailboxId:e,accountId:Z,onAfterOptimisticRemove:re}),{draftsMailboxId:Ae}=R0(Z),ve=Ae!==void 0&&Ae===e,{archiveMailboxId:Ye}=I0(Z),Xe=gf(),{requestCompose:Oe}=Se,K=l.useCallback(()=>{Oe("reply")},[Oe]),pe=l.useCallback(()=>{Oe("reply_all")},[Oe]),oe=l.useCallback(()=>{Oe("forward")},[Oe]),{state:J,openCompose:je,closeCompose:Pe}=Jt(),_e=l.useCallback(()=>{je({mode:"new"})},[je]),Je=ze({...lr(),onError:ee=>{he(ds("Couldn't discard draft","The draft wasn't deleted.",ee))}}),qe=l.useCallback(()=>{const ee=J.outboxMessageId;ee&&(Je.mutate({path:{outboxMessageId:ee}}),Me.invalidateQueries({queryKey:eo()}),Pe())},[J.outboxMessageId,Je,Me,Pe]),Ee=l.useCallback(()=>{n({to:"/mail/$mailboxId",params:{mailboxId:e},search:ee=>({...ee,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,n]),et=l.useCallback(ee=>ee?Xe(ee):[],[Xe]),{toggleStar:Be}=Oo({threadId:$?.threadId??"",mailboxId:e}),{toggleReadFor:lt}=Nr({mailboxId:e,accountId:Z}),{junkMailboxId:tt}=Sn(Z),zt=tt!=null&&tt===e,Rt=Tr(tt,e),{candidates:ns}=gj(zt?tt:void 0),{moveMessages:bs}=Ds({mailboxId:e,threadId:$?.threadId,accountId:Z,onAfterOptimisticRemove:re}),{deleteMessages:rt}=ms({mailboxId:e,threadId:$?.threadId,onAfterOptimisticRemove:re}),{addressId:Tt,address:bt}=ff($),{updateFlags:vt}=mf({addressId:Tt,senderEmail:$?.fromEmail??void 0}),ht=l.useCallback(()=>t||!ke?!1:(n({to:"/mail/$mailboxId",params:{mailboxId:e},search:ee=>({...ee,selectedMessageId:ke})}),!0),[t,ke,e,n]),rs=l.useCallback(()=>{ht()||te&&Oe("reply")},[ht,te,Oe]),qs=l.useCallback(()=>{ht()||te&&Oe("reply_all")},[ht,te,Oe]),kn=l.useCallback(()=>{ht()||te&&Oe("forward")},[ht,te,Oe]),ct=l.useCallback(()=>et($),[et,$]),B=l.useCallback(()=>{if(G.current?.requestVerb("delete"))return;const ee=ct();ee.length>0&&rt(ee)},[G,ct,rt]),X=l.useCallback(()=>{if(G.current?.requestVerb("junk")||!Rt)return;const ee=ct();ee.length!==0&&(pf(i,{count:ee.length,senderTrust:$?.senderTrust??"unknown",wasRescuable:$?hf($):!1}),bs(ee,Rt))},[G,Rt,ct,bs,i,$]),Ie=l.useCallback(()=>{if(Ke.length>0){const ee=!($?.hasStars??!1),ut=new Set(Ke);for(const at of _)ut.has(at.messageId)&&at.hasStars!==ee&&Be(at.messageId,at.hasStars);return}$&&Be($.messageId,$.hasStars)},[Ke,_,$,Be]),pt=l.useCallback(()=>{if(G.current?.requestVerb("markRead"))return;const ee=ct();if(ee.length===0)return;const ut=!($?.isRead??!1);lt(ee,ut)},[G,ct,$,lt]),yt=l.useCallback(()=>{if(!Tt)return;const ee=bt?.flags?.muted?.value!==!0;vt({muted:{value:ee}})},[Tt,bt,vt]),vs=l.useCallback(()=>{if(!Tt)return;const ee=bt?.flags?.vip?.value!==!0;vt({vip:{value:ee}})},[Tt,bt,vt]),wt=l.useCallback(()=>{d||f()},[d,f]),as=l.useCallback(ee=>{n({to:ee})},[n]),jn=ve?"drafts":Ye===e?"archive":tt===e?"junk":"inbox",ys=l.useRef("");l.useEffect(()=>{const ee=ys.current;ys.current=g,g.length>0&&ee.length===0&&i.recordEvent("search.submitted",{mailboxType:jn})},[g,jn,i]);const Lr=ve&&J.isOpen&&!!J.outboxMessageId&&!te,{goBack:Fr,nextMessageId:Hs,previousMessageId:$r}=Xo({context:Ue,orderedIds:_.map(ee=>ee.messageId),selectedMessageId:t,enabled:!J.isOpen,onClose:Ee,handlers:{reply:rs,replyAll:qs,forward:kn,delete:B,toggleStar:Ie,toggleRead:pt,muteSender:yt,blockSender:wt,vipSender:vs,markJunk:X,toggleIntelligence:te?f:void 0,compose:_e,goBrief:()=>as("/mail"),goInbox:()=>as("/mail"),goSent:()=>as("/mail"),goFlagged:()=>as("/mail/flagged"),goSettings:()=>as("/settings")}});Mo({enabled:J.isOpen,bindings:[{key:"Escape",handler:Pe,preventDefault:!0}]});const _r={mailboxId:e,selectedMessageId:t,selectedThread:te,conversation:De,threads:_,isLoading:I,isError:P,error:R,mailboxAccountId:Z,mailboxName:ne,unreadCount:me,isDraftsMailbox:ve,isSpamFolder:zt,rescueCandidates:ns,filterCategory:S,filterAttributes:w,onSelectFilterCategory:de,onToggleFilterAttribute:ge,onClearFilters:we,listFilter:q,intelligenceOpen:d,onToggleIntelligence:f,handleDeselectIfRemoved:re,searchPredicate:p&&D.length===0?E:void 0,onDeleteMessages:se,onMoveMessages:le,isDeleting:fe,isMoving:U,onLoadMore:N,hasMore:V,isLoadingMore:Q,onTriageContextChange:Ge,listCommandsRef:G,onRetry:()=>F(),toolbarComposeRequest:Se.composeRequest,onToolbarReply:K,onToolbarReplyAll:pe,onToolbarForward:oe,onClearComposeRequest:Se.clearComposeRequest,onToolbarDelete:Se.deleteThread,onToolbarStar:Se.toggleStar,onToolbarDiscardDraft:qe,onToolbarMove:Se.moveThread,composeState:J,closeCompose:Pe,hasRemitDraftOpen:Lr,onBack:Fr,nextMessageId:Hs,previousMessageId:$r};return r.jsx(Rf.Provider,{value:_r,children:s})}function Tf(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:n,isError:a,error:o,onDeleteMessages:i,onMoveMessages:c,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,mailboxAccountId:v,mailboxName:g,unreadCount:p,isDraftsMailbox:b,isSpamFolder:y,rescueCandidates:S,onTriageContextChange:x,listCommandsRef:w,onRetry:C,filterCategory:T,filterAttributes:A,onSelectFilterCategory:k,onToggleFilterAttribute:M,onClearFilters:D,listFilter:E,searchPredicate:L}=Pr(),{searchQuery:O,searchInput:j,accounts:I,resultFolderIndex:P}=Le(),R=Mr(),F=Qe(),N=g??"Inbox",V=l.useMemo(()=>bu(),[]),Q=l.useMemo(()=>v?[v]:[],[v]),{hasNewMail:re}=Cr(),{state:se,errorMessage:fe,refresh:Z}=No(Q,{onSettled:C}),ne=l.useMemo(()=>r.jsx(yo,{state:se,onRefresh:Z,label:`Refresh ${N}`,errorMessage:fe,hasUpdate:re(Q)}),[se,Z,N,fe,re,Q]),le=l.useMemo(()=>s.map(xe=>vS(xe,P)),[s,P]),{hits:U,isLoading:_}=Kd({mailboxId:e,filterCategory:T}),de=l.useMemo(()=>Wd(U,s.map(xe=>xe.threadId),P),[U,s,P]),ge=l.useCallback(xe=>F({to:"/mail/$mailboxId",params:{mailboxId:xe.mailboxId??e},search:Ne=>({...Ne,q:j||void 0,selectedMessageId:xe.id,selectedThreadId:xe.threadId})}),[e,F,j]);if(b&&v)return r.jsx(Ak,{mailboxId:e,accountId:v,selectedMessageId:t,imapThreads:s,title:g??"Drafts",unreadCount:p??void 0});const we=r.jsx(uj,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:n,isError:a,error:o,onRetry:C,searchQuery:O,searchPredicate:L,onDeleteMessages:i,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,accountId:v,listTitle:N,listFilter:E,listScopeLabel:N,hideHeader:!0,onTriageContextChange:x,commandsRef:w}),Re=I[0]?.accountId,q=R==="phone"&&Re?r.jsx(mj,{accountId:Re,children:we}):we,Ce=y&&S.length>0&&v?r.jsx(hj,{accountId:v,currentMailboxId:e,candidates:S,onMove:c,children:q}):q;return r.jsx(wf,{title:N,unreadCount:p,preset:V,selectedCategory:T,activeFilters:A,onSelectCategory:k,onToggleFilter:M,onClearFilters:D,searchResults:le,searchLoading:n,relatedResults:de,relatedLoading:_,onSelectSearchResult:ge,searchResultsInBody:!0,refreshControl:ne,children:Ce})}function Fj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:c,onToolbarReply:u,onToolbarReplyAll:m,onToolbarForward:d,onClearComposeRequest:f,onToolbarDelete:h,onToolbarStar:v,onToolbarDiscardDraft:g,onToolbarMove:p,composeState:b}=Pr(),y=ps()?.showIntelligencePane??!1,S=!!n,x=y&&S,w=b.isOpen&&!n?r.jsx(kf,{}):n?r.jsx(Bs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onOpenIntelligence:n.authenticity?.dkimMismatch?i:void 0,composeRequest:c,onComposeClose:f}):r.jsx(zs,{});return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Go,{hasThread:S,intelligenceOpen:x&&o,canToggleIntelligence:x,onToggleIntelligence:i,onReply:S?u:void 0,onReplyAll:S?m:void 0,onForward:S?d:void 0,canDelete:S||a,onDelete:S?h:a?g:void 0,onToggleStar:S?v:void 0,isStarred:s?.hasStars,moveContext:S&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:w})]})}function $j(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:n,handleDeselectIfRemoved:a}=Pr();return r.jsx(Ks,{onClose:n,thread:s,mailboxId:e,accountId:t,onAfterOptimisticRemove:a})}function _j(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,intelligenceOpen:a,onToggleIntelligence:o,onBack:i,nextMessageId:c,previousMessageId:u,composeState:m,handleDeselectIfRemoved:d}=Pr(),f=Qe();if(n){const h=v=>f({to:"/mail/$mailboxId",params:{mailboxId:e},search:g=>({...g,selectedMessageId:v,selectedThreadId:void 0})});return r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onBack:i,onOpenIntelligence:o,onSwipeNext:c?()=>h(c):void 0,onSwipePrevious:u?()=>h(u):void 0,mobileIntelligenceOpen:a}),r.jsx(Ro,{isOpen:a,onClose:o,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:o,thread:s,mailboxId:e,accountId:t,hideCloseButton:!0,onAfterOptimisticRemove:d})})]})}return m.isOpen?r.jsx("div",{className:"h-full",children:r.jsx(kf,{})}):r.jsx(Tf,{})}const sn=Object.assign(Lj,{List:Tf,Reading:Fj,Intelligence:$j,Phone:_j}),Mf=e=>e==="failed"||e==="blocked",Af=e=>e!=="draft"&&e!=="sent",ei="remit.savedSearches",zj=25;function sr(){try{const e=localStorage.getItem(ei);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Bj(e){const t=e.trim();if(!t)return sr();const s=[t,...sr().filter(n=>n!==t)].slice(0,zj);try{localStorage.setItem(ei,JSON.stringify(s))}catch{return s}return s}function Uj(e){const t=sr().filter(s=>s!==e);try{localStorage.setItem(ei,JSON.stringify(t))}catch{return t}return t}const Gl=e=>/^\d/.test(e),Kj=(e,t)=>{const s=Gl(e),n=Gl(t);return s&&!n?-1:!s&&n?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function qj(e,t,s){const n=[],a=[];for(const o of e)t.has(o.mailboxId)?n.push(o):a.push(o);return a.sort((o,i)=>Kj(Vn(o,void 0,s),Vn(i,void 0,s))),{system:n,labels:a}}function Hj(e,t,s){const n=lh(t)&&e.unseenCount>0;return{id:e.mailboxId,name:Vn(e,t,s),unseen:n?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function Wj(){const e=Sr(),t=Ha({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 Yl({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const n=Te(),a=Qe(),o=Wj(),{searchInput:i,onSearchChange:c}=Le(),[u,m]=l.useState(sr),{t:d}=Wa("mail",{useSuspense:!1}),f=l.useCallback((k,M)=>d(k,{defaultValue:M}),[d]),h=mt({queries:e.map(k=>({...it({path:{accountId:k.accountId}}),staleTime:1/0}))}),{data:v}=ye(or()),g=l.useMemo(()=>(v?.items??[]).filter(k=>Af(k.status)).length,[v?.items]),p=l.useMemo(()=>e.map((k,M)=>{const D=h[M],E=D?.data?.items??[],L=Ka(k.folderAppointments),{system:O,labels:j}=qj(E,L,f),I=D?.isError?"error":D?.isLoading?"loading":"ready";return{id:k.accountId,label:k.email,email:k.email,muted:!!k.muted,outboxPending:g,status:I,onRetry:()=>D?.refetch(),mailboxes:[...O,...j].map(P=>Hj(P,L.get(P.mailboxId),f))}}),[e,h,g,f]),b=k=>{n.invalidateQueries({queryKey:cr({path:{mailboxId:k},query:{order:"desc"}})})},y=({navId:k,className:M,ariaLabel:D,title:E,children:L,onClick:O})=>k==="brief"?r.jsx(qt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>O?.(),className:M,"aria-label":D,title:E,children:L}):k==="outbox"?r.jsx(qt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>O?.(),className:M,"aria-label":D,title:E,children:L}):k==="flagged"?r.jsx(qt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>O?.(),className:M,"aria-label":D,title:E,children:L}):k==="settings"?r.jsx(qt,{to:"/settings/accounts",onClick:()=>O?.(),className:M,"aria-label":D,title:E,children:L}):r.jsx(qt,{to:"/mail/$mailboxId",params:{mailboxId:k},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{b(k),O?.()},className:M,"aria-label":D,title:E,children:L}),S=()=>{c(""),t?.()},x=i.trim(),w=x.length>0&&!u.includes(x)?x:void 0,C=l.useCallback(()=>{w&&m(Bj(w))},[w]),T=l.useCallback(k=>{m(Uj(k))},[]),A=l.useCallback(k=>{c(k),a({to:"/mail",search:{q:k,selectedMessageId:void 0}}),t?.()},[c,a,t]);return r.jsx(Kg,{accounts:p,selectedNavId:o,onSelectNav:S,linkComponent:y,variant:s,savedSearches:u,saveableQuery:w,onSaveCurrentSearch:C,onSelectSavedSearch:A,onRemoveSavedSearch:T})}function Vj(){return r.jsxs("button",{type:"button",onClick:pc,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:[r.jsx(_c,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]})}function Qj({accounts:e,onMailboxSelect:t}){return ps()?.showNavPane??!0?r.jsx(Yl,{accounts:e}):r.jsxs("div",{className:"flex h-full flex-col",children:[r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(Yl,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),r.jsxs("div",{className:"border-t border-line px-2 py-2",children:[r.jsxs(qt,{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:[r.jsx(Wc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),r.jsx(Vj,{}),r.jsx(Bu,{children:({signOut:a})=>r.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:[r.jsx(Kc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function Gj(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const n=[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||n.includes(a))}function Yj(e){return e.tokens.length>0&&e.freeText.trim().length===0}const Of={queued:{icon:to,label:"Queued",className:"text-warning"},sending:{icon:hs,label:"Sending…",className:"text-accent-2"},sent:{icon:uo,label:"Sent",className:"text-positive"},failed:{icon:Pt,label:"Failed",className:"text-danger"},blocked:{icon:$a,label:"Blocked",className:"text-warning"}},Xj=e=>Rh(e).toDateString()===new Date().toDateString()?Qn(e,{hour:"numeric",minute:"2-digit"}):Qn(e,{month:"short",day:"numeric"}),Xl=e=>Qn(e,{dateStyle:"medium",timeStyle:"short"}),Jj=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},Df=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",Pf=l.createContext(null);function ti(){const e=l.useContext(Pf);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function Zj({children:e}){const t=Qe(),{selectedOutboxMessageId:s}=As({strict:!1}),{data:n,isLoading:a}=ye(or()),{searchQuery:o}=Le(),i=xs(),c=Bo(o),u=Us(c,i),m=c.length>0,d=Yj(u),f=l.useMemo(()=>d?[]:(n?.items??[]).filter(p=>Af(p.status)).filter(p=>Gj(p,u.freeText)),[n,u.freeText,d]),h=l.useMemo(()=>f.find(p=>p.outboxMessageId===s),[f,s]),v=l.useCallback(p=>{t({to:"/mail/outbox",search:b=>({...b,selectedOutboxMessageId:p})})},[t]),g={messages:f,hasQuery:m,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:v};return r.jsx(Pf.Provider,{value:g,children:e})}function Lf({message:e,isSelected:t,onSelect:s}){const n=Te(),{openCompose:a}=Jt(),{pushError:o}=nt(),i=l.useCallback(()=>{n.invalidateQueries({queryKey:eo()})},[n]),c=ze({...xc(),onSuccess:i,onError:f=>{o(ds("Couldn't resend message","The message wasn't sent.",f))}}),u=ze({...lr(),onSuccess:i,onError:f=>{o(ds("Couldn't delete message","The message wasn't deleted.",f))}}),m=e.status;if(!Of[m])return null;const d=Mf(e.status);return r.jsx(Tx,{recipients:Jj(e),subject:e.subject||"",time:Xj(e.sentAt??e.updatedAt),status:m,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:m==="failed"?()=>c.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:c.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function Ff({message:e,onBack:t}){const s=e.status,n=Of[s],a=n?.icon??hn,o=e.sentAt?Xl(e.sentAt):Xl(e.updatedAt);return r.jsxs("div",{className:"h-full overflow-y-auto bg-canvas",children:[r.jsxs("div",{className:"border-b border-line p-4",children:[t&&r.jsxs("button",{type:"button",onClick:t,className:"mb-3 inline-flex items-center gap-1 text-sm text-fg-muted hover:text-fg",children:[r.jsx(Fa,{className:"size-4"}),r.jsx("span",{children:"Back"})]}),r.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),r.jsxs("div",{className:"space-y-1 text-sm",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),r.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),r.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),r.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),r.jsx("span",{className:"text-fg",children:o})]}),n&&r.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[r.jsx(a,{className:We("size-4",n.className,s==="sending"&&"animate-spin")}),r.jsx("span",{className:We("text-xs font-medium",n.className),children:n.label}),Mf(e.status)&&e.lastError&&r.jsxs("span",{className:"text-xs text-fg-muted",children:["— ",e.lastError]})]})]})]}),r.jsx("div",{className:"p-4",children:r.jsx(Pd,{html:e.htmlBody,text:e.textBody})})]})}function eN(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,onSelectMessage:o}=ti(),i=l.useRef(null);return nr({containerRef:i,itemSelector:Hn}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(zs,{message:Df(t,s),showHints:!1})}):r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(Jo,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(c=>r.jsx(Lf,{message:c,isSelected:a===c.outboxMessageId,onSelect:()=>o(c.outboxMessageId)},c.outboxMessageId))})]})}function tN(){const{selectedMessage:e}=ti();return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx("header",{className:"flex h-pane-header shrink-0 items-center border-b border-line px-3"}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Ff,{message:e}):r.jsx(zs,{message:"Select a message to read",showHints:!1})})]})}function sN(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=ti(),c=l.useRef(null);return nr({containerRef:c,itemSelector:Hn}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?r.jsx(Ff,{message:o,onBack:()=>i(void 0)}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(zs,{message:Df(t,s),showHints:!1})}):r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(Jo,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:c,className:"flex-1 overflow-y-auto",children:e.map(u=>r.jsx(Lf,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const Fn=Object.assign(Zj,{List:eN,Reading:tN,Phone:sN}),nN=({isOpen:e,onClose:t})=>{const s=l.useCallback(n=>{n.key==="Escape"&&(n.preventDefault(),t())},[t]);return l.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?r.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:n=>n.key==="Escape"&&t(),children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.jsxs("div",{className:We("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:n=>n.stopPropagation(),onKeyDown:n=>{n.key!=="Escape"&&n.stopPropagation()},children:[r.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),r.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:r.jsx(Nt,{className:"size-5"})})]}),r.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:Qc.map(n=>r.jsxs("div",{children:[r.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:n.title}),r.jsx("div",{className:"space-y-2",children:n.hints.map(a=>r.jsxs("div",{className:"flex items-center justify-between gap-4",children:[r.jsx("span",{className:"text-sm",children:a.description}),r.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>r.jsxs(l.Fragment,{children:[i>0&&a.keys[0]==="g"&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),r.jsx(Is,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},n.title))}),r.jsx("div",{className:"mt-6 border-t border-line pt-4",children:r.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",r.jsx(Is,{children:"Esc"})," to close"]})})]})]}):null};function rN(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});return l.useMemo(()=>OS(t.map(s=>s.data?.items??[])),[t])}const aN=e=>e.map(t=>t.data?.items??[]);function oN(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0})),combine:aN});return l.useMemo(()=>ch(e.map((s,n)=>({folderAppointments:s.folderAppointments,mailboxes:t[n]??[]}))),[e,t])}var $n={exports:{}},Jl;function iN(){if(Jl)return $n.exports;Jl=1;const e=(t,s,n)=>new Promise((a,o)=>{if(n=Object.assign({concurrency:1/0},n),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=n;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const c=[],u=t[Symbol.iterator]();let m=!1,d=!1,f=0,h=0;const v=()=>{if(m)return;const g=u.next(),p=h;if(h++,g.done){d=!0,f===0&&a(c);return}f++,Promise.resolve(g.value).then(b=>s(b,p)).then(b=>{c[p]=b,f--,v()},b=>{m=!0,o(b)})};for(let g=0;g<i&&(v(),!d);g++);});return $n.exports=e,$n.exports.default=e,$n.exports}var lN=iN();const cN=uh(lN),uN=900*1e3,dN=300,fN=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},mN=60*1e3,hN=e=>Math.max(fN(e,dN)*1e3,mN),qn=hN(dh().mailboxPollIntervalSeconds),pN=5,Da=new Set,gN=(e,t,s=uN)=>e.filter(n=>{const a=n.lastSyncAt;return a==null?!0:t-a>s}).map(n=>n.accountId),xN=(e,t,s=qn)=>e-t>=s,bN=(e,t)=>e.filter(s=>!t.has(s)),Zl=(e,t)=>{if(Da.delete(e),hc(t,{softError:!0})){qa(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},ec=(e,t)=>mc({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:Ft({path:{accountId:e}})})}),vN=e=>{const t=Te(),s=l.useRef(e);s.current=e;const n=e.map(a=>a.accountId).join(",");l.useEffect(()=>{const a=Date.now(),i=gN(s.current,a).filter(c=>!Da.has(c));if(i.length!==0)for(const c of i)Da.add(c),ec(c,t).catch(u=>{Zl(c,u)})},[n,t]),l.useEffect(()=>{let a=Date.now(),o;const i=new Set,c=()=>{a=Date.now();const d=bN(s.current.map(f=>f.accountId),i);for(const f of d)i.add(f);cN(d,f=>ec(f,t).catch(h=>{Zl(f,h)}).finally(()=>{i.delete(f)}),{concurrency:pN})},u=()=>{if(document.visibilityState==="visible"){c(),o=setTimeout(u,qn);return}},m=()=>{document.visibilityState==="visible"&&xN(Date.now(),a)&&(o!==void 0&&clearTimeout(o),c(),o=setTimeout(u,qn))};return o=setTimeout(u,qn),document.addEventListener("visibilitychange",m),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",m)}},[n,t])};function yN(e,t,s){if(e!==t)return s}function wN(e,t){return e===""?"":t}function SN(e,t,s){return t!==e?!1:t!==s}function CN(){const{q:e=""}=As({from:"/mail"}),t=Qe(),s=Mr(),n=Gd(s),[a,o]=l.useState(!1),[i,c]=l.useState(!1),[u,m]=l.useState(!1),d=l.useCallback(_=>{m(_),Ql(_)},[]),[f,h]=l.useState(e),v=mr(f,200),g=wN(f,v),p=l.useRef(e);p.current=e;const b=Ot({select:_=>Oy(_.matches)}),[y,S]=l.useState(b);if(y!==b){const _=yN(y,b,e);S(b),_!==void 0&&h(_)}l.useEffect(()=>{SN(f,g,p.current)&&t({to:".",search:_=>{const de=_.q===g;return{..._,q:g||void 0,...g&&!de?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[f,g,t]);const{data:x,isLoading:w,isError:C,error:T,refetch:A}=ye({...$t(),staleTime:1/0}),k=!!(x&&(x.accounts?.length??0)===0);l.useEffect(()=>{k&&t({to:"/onboarding",replace:!0})},[k,t]),Mo({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const M=l.useCallback(_=>{h(_)},[]),D=l.useCallback(()=>{h("")},[]),E=l.useCallback(()=>{h("")},[]),L=l.useCallback(()=>{m(_=>{const de=!_;return Ql(de),de})},[]),O=x?.accounts??[],j=l.useMemo(()=>O.map(_=>_.accountId),[O]),I=rN(O),P=oN(O),R=l.useMemo(()=>AS(O),[O]),F=Ot({select:_=>_.matches.find(ge=>"mailboxId"in ge.params)?.params.mailboxId}),{selectedMessageId:N}=As({strict:!1}),V=Ot({select:_=>Io(_.matches)}),Q=Ot({select:_=>xn(_.matches)}),re=Ot({select:_=>kr(_.matches)});vN(O);const se=l.useCallback(()=>{c(!1)},[]),fe={accounts:O,mailboxNameIndex:I,accountNameIndex:R,resultFolderIndex:P,searchQuery:g,searchInput:f,searchViewKey:b,onSearchChange:M,onSearchClear:D,onSearchClearQuery:E,intelligenceOpen:u,onToggleIntelligence:L,onSetIntelligenceOpen:d},Z=r.jsx(Qj,{accounts:O,onMailboxSelect:se}),ne=n?r.jsx(by,{accounts:O}):void 0,le=n?void 0:r.jsx(_y,{accounts:O}),U={navOpen:i,onOpenNav:()=>c(!0),onCloseNav:()=>c(!1)};return r.jsx(fh.Provider,{value:fe,children:r.jsxs(Ny,{accountIds:j,children:[C?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:r.jsx(ts,{title:"Couldn't load your account",error:T,onRetry:()=>{A()}})}):V?r.jsx(Zs,{selectedMessageId:N,children:n?r.jsx(Bt,{nav:Z,list:r.jsx(Zs.Phone,{}),intelligenceOpen:u,overlay:ne,skeleton:r.jsx(At,{}),isLoading:w||k,...U}):r.jsx(Bt,{nav:Z,topBar:le,list:r.jsx(Zs.List,{}),reading:r.jsx(Zs.Reading,{}),intelligence:r.jsx(Zs.Intelligence,{}),intelligenceOpen:u,hasThread:!!N,overlay:ne,skeleton:r.jsx(At,{}),isLoading:w||k,...U})}):Q?r.jsx(en,{selectedMessageId:N,children:n?r.jsx(Bt,{nav:Z,list:r.jsx(en.Phone,{}),intelligenceOpen:u,overlay:ne,skeleton:r.jsx(At,{}),isLoading:w||k,...U}):r.jsx(Bt,{nav:Z,topBar:le,list:r.jsx(en.List,{}),reading:r.jsx(en.Reading,{}),intelligence:r.jsx(en.Intelligence,{}),intelligenceOpen:u,hasThread:!!N,overlay:ne,skeleton:r.jsx(At,{}),isLoading:w||k,...U})}):F?r.jsx(sn,{mailboxId:F,selectedMessageId:N,children:n?r.jsx(Bt,{nav:Z,list:r.jsx(sn.Phone,{}),intelligenceOpen:u,overlay:ne,skeleton:r.jsx(At,{}),isLoading:w||k,...U}):r.jsx(Bt,{nav:Z,topBar:le,list:r.jsx(sn.List,{}),reading:r.jsx(sn.Reading,{}),intelligence:r.jsx(sn.Intelligence,{}),intelligenceOpen:u,hasThread:!!N,overlay:ne,skeleton:r.jsx(At,{}),isLoading:w||k,...U})}):re?r.jsx(Fn,{children:n?r.jsx(Bt,{nav:Z,list:r.jsx(Fn.Phone,{}),intelligenceOpen:!1,overlay:ne,skeleton:r.jsx(At,{}),isLoading:w||k,...U}):r.jsx(Bt,{nav:Z,topBar:le,list:r.jsx(Fn.List,{}),reading:r.jsx(Fn.Reading,{}),intelligenceOpen:!1,overlay:ne,skeleton:r.jsx(At,{}),isLoading:w||k,...U})}):r.jsx(At,{}),r.jsx(nN,{isOpen:a,onClose:()=>o(!1)}),r.jsx(mh,{})]})})}const qN=Object.freeze(Object.defineProperty({__proto__:null,component:CN,useMailContext:Le},Symbol.toStringTag,{value:"Module"}));export{Vx as E,Cp as U,UN as a,KN as c,qN as m,BN as s};