@remit/web-client-dist 0.0.183 → 0.0.185

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/assets/{ComposeBody-C_pJkiQs.js → ComposeBody-CTtNTugV.js} +1 -1
  2. package/assets/{ConfirmDialog-CJO6fTAl.js → ConfirmDialog-GL7gNRn9.js} +1 -1
  3. package/assets/{ErrorState-CqdtV3du.js → ErrorState-BXXl1_pQ.js} +1 -1
  4. package/assets/{OnboardingWizard-Ci-7H_I8.js → OnboardingWizard-DXUB9rSt.js} +1 -1
  5. package/assets/{account-form-helpers-CKx0TDTV.js → account-form-helpers-BlJvBmoN.js} +1 -1
  6. package/assets/{accounts-BWf0-V1g.js → accounts-CNeAywC3.js} +1 -1
  7. package/assets/{advanced-Csruk5V1.js → advanced-D0znnMqx.js} +1 -1
  8. package/assets/{appearance-CvQnrzm9.js → appearance-WphoRZ5Z.js} +1 -1
  9. package/assets/{avatar-hoXdVjQk.js → avatar-B9YIb5SM.js} +1 -1
  10. package/assets/{browser-ponyfill-COhxFSYg.js → browser-ponyfill-Bu53IBFa.js} +1 -1
  11. package/assets/{circle-check-AwyzKrYT.js → circle-check-DawkktF8.js} +1 -1
  12. package/assets/{download-DkNCbCbI.js → download-NPOjadLl.js} +1 -1
  13. package/assets/{filters-BBfSdj5w.js → filters-C7pZCQgx.js} +1 -1
  14. package/assets/{flagged-6YkmoMQ5.js → flagged-ZpxSHHQ-.js} +1 -1
  15. package/assets/{folders-C1OIKWdQ.js → folders-BeHo6d-I.js} +1 -1
  16. package/assets/index-CtIPty4w.js +1 -0
  17. package/assets/{index-CrM9np2N.js → index-PFTWhtMs.js} +1 -1
  18. package/assets/{index-LsIh6hfZ.js → index-UNmLTd6G.js} +4 -4
  19. package/assets/{kbd-BCVgPSlr.js → kbd-CSBQtv4K.js} +1 -1
  20. package/assets/{labels-DsKaKpDF.js → labels-uBSa1Yjd.js} +1 -1
  21. package/assets/{mail-DUvWvLGA.js → mail-MsrywAsk.js} +14 -14
  22. package/assets/{move-mailbox-picker-Dv6fPGxm.js → move-mailbox-picker-WjOZHj2B.js} +1 -1
  23. package/assets/{move-targets-BuMPmscn.js → move-targets-DjI1Tv8S.js} +1 -1
  24. package/assets/{onboarding-CiVSQwIz.js → onboarding-B1OlsK7y.js} +1 -1
  25. package/assets/{rotate-ccw-CBAUy40g.js → rotate-ccw-DmTx8ZTA.js} +1 -1
  26. package/assets/{search-DpcnsTF5.js → search-BxHTifee.js} +1 -1
  27. package/assets/{senders-CoXcwOWA.js → senders-BFDM-OqC.js} +1 -1
  28. package/assets/settings-DUQUPzA0.js +1 -0
  29. package/assets/{settings-screen-DCdcaO44.js → settings-screen-EcrvBQHC.js} +1 -1
  30. package/assets/{suggested-vips-DN_DflW-.js → suggested-vips-9yzA5QyP.js} +1 -1
  31. package/assets/{useDebouncedValue-YnLV_Pco.js → useDebouncedValue-CxajUBik.js} +1 -1
  32. package/assets/{useLabels-DGkC_3p5.js → useLabels-UMDQIppz.js} +1 -1
  33. package/assets/{useRulePreview-Bk0EH_0U.js → useRulePreview-Cnkwzpft.js} +1 -1
  34. package/assets/{useSignature-DttCOqiQ.js → useSignature-Cluo7-bu.js} +1 -1
  35. package/index.html +1 -1
  36. package/package.json +1 -1
  37. package/assets/index-CnYdFNIv.js +0 -1
  38. package/assets/settings-CxdYTd45.js +0 -1
@@ -1,11 +1,11 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-C_pJkiQs.js","assets/index-LsIh6hfZ.js","assets/index-DllQMXH0.css","assets/search-DpcnsTF5.js","assets/avatar-hoXdVjQk.js","assets/kbd-BCVgPSlr.js","assets/account-form-helpers-CKx0TDTV.js","assets/useSignature-DttCOqiQ.js","assets/useDebouncedValue-YnLV_Pco.js","assets/useRulePreview-Bk0EH_0U.js","assets/ErrorState-CqdtV3du.js","assets/format-B6Elex-n.js","assets/move-targets-BuMPmscn.js","assets/move-mailbox-picker-Dv6fPGxm.js","assets/rotate-ccw-CBAUy40g.js","assets/circle-check-AwyzKrYT.js","assets/ConfirmDialog-CJO6fTAl.js","assets/useLabels-DGkC_3p5.js"])))=>i.map(i=>d[i]);
2
- import{R as q,c as Dd,r as c,a as fe,j as n,C as Rt,X as We,b as H,B as G,d as lt,S as At,e as ut,f as Gt,L as oa,g as Od,h as Pd,i as Ys,k as nt,T as rt,l as Xt,u as Kn,m as ia,n as Qi,I as la,p as Yi,o as ca,q as Ld,D as ua,s as Gs,O as $d,M as Fd,A as _d,F as Gi,t as zd,v as Bd,w as Kd,x as Ud,y as da,z as fa,P as qd,E as Hd,G as ma,H as ha,_ as Nt,J as Xi,K as Wd,Q as pa,N as Vd,U as Qd,V as Yd,W as Br,Y as Gd,Z as Xd,$ as ye,a0 as Jd,a1 as Zd,a2 as ef,a3 as tf,a4 as sf,a5 as nf,a6 as vo,a7 as rf,a8 as af,a9 as of,aa as ga,ab as Ji,ac as Zi,ad as Dt,ae as Oe,af as _e,ag as Xs,ah as be,ai as xa,aj as ba,ak as va,al as ya,am as Un,an as bs,ao as Ce,ap as Js,aq as de,ar as el,as as lf,at as ve,au as tl,av as cf,aw as qn,ax as sl,ay as xt,az as Ve,aA as uf,aB as st,aC as nl,aD as Vt,aE as Hn,aF as df,aG as wa,aH as rl,aI as al,aJ as Jt,aK as Wn,aL as Zt,aM as ff,aN as mf,aO as Vn,aP as hf,aQ as ol,aR as vs,aS as pf,aT as ja,aU as gf,aV as xf,aW as il,aX as Sa,aY as ll,aZ as cl,a_ as Ss,a$ as bf,b0 as yo,b1 as vf,b2 as yf,b3 as pt,b4 as Kr,b5 as Ur,b6 as wf,b7 as ul,b8 as jf,b9 as ka,ba as dl,bb as Sf,bc as kf,bd as Cf,be as Nf,bf as Ef,bg as If,bh as Tf,bi as Rf,bj as Mf,bk as Af,bl as Df,bm as Of,bn as Pf,bo as Lf,bp as $f,bq as kt,br as ht,bs as Ff}from"./index-LsIh6hfZ.js";import{S as Qn}from"./search-DpcnsTF5.js";import{A as dt,M as Ca,C as _f}from"./avatar-hoXdVjQk.js";import{K as ps}from"./kbd-BCVgPSlr.js";import{M as fl,a as zf}from"./account-form-helpers-CKx0TDTV.js";import{R as Bf,u as Kf}from"./useSignature-DttCOqiQ.js";import{u as ml}from"./useDebouncedValue-YnLV_Pco.js";import{B as hl,u as Ot,a as wo,b as qr,n as Uf,S as Na,c as pl,r as Ea,d as gl,e as xl,f as bl,g as qf,h as Hf,i as Wf,j as Vf,k as Qf}from"./useRulePreview-Bk0EH_0U.js";import{E as Pt,f as vl}from"./ErrorState-CqdtV3du.js";import{f as yl,a as Lt,b as wl,c as Pn,d as ct,t as Yf}from"./format-B6Elex-n.js";import{P as jo,u as jl,b as Zs,M as it}from"./move-targets-BuMPmscn.js";import{F as Ia,a as Gf,M as Sl}from"./move-mailbox-picker-Dv6fPGxm.js";import{C as Ta,R as Xf}from"./rotate-ccw-CBAUy40g.js";import{C as Yn}from"./circle-check-AwyzKrYT.js";import{C as Ra}from"./ConfirmDialog-CJO6fTAl.js";import{u as kl,a as Jf}from"./useLabels-DGkC_3p5.js";function Us(e){if(Zf())e.focus({preventScroll:!0});else{let t=em(e);e.focus(),tm(t)}}let xn=null;function Zf(){if(xn==null){xn=!1;try{document.createElement("div").focus({get preventScroll(){return xn=!0,!0}})}catch{}}return xn}function em(e){let t=e.parentNode,s=[],r=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==r;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return r instanceof HTMLElement&&s.push({element:r,scrollTop:r.scrollTop,scrollLeft:r.scrollLeft}),s}function tm(e){for(let{element:t,scrollTop:s,scrollLeft:r}of e)t.scrollTop=s,t.scrollLeft=r}const It=e=>e?.ownerDocument??document,Mt=e=>e&&"window"in e&&e.window===e?e:It(e).defaultView||window;function sm(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function nm(e){return sm(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let rm=!1;function Cl(){return rm}function ot(e,t){if(!Cl())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:nm(s)?s=s.host:s=s.parentNode}return!1}function Me(e){if(Cl()&&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 am=typeof Element<"u"&&"checkVisibility"in Element.prototype;function om(e){const t=Mt(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:r}=e.style,a=s!=="none"&&r!=="hidden"&&r!=="collapse";if(a){const{getComputedStyle:o}=Mt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function im(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 Nl(e,t){return am?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&om(e)&&im(e,t)&&(!e.parentElement||Nl(e.parentElement,e))}const El=["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"],lm=El.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";El.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function cm(e,t){return e.matches(lm)&&!um(e)&&(t?.skipVisibilityCheck||Nl(e))}function um(e){let t=e;for(;t!=null;){if(t instanceof Mt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Ma=typeof document<"u"?q.useLayoutEffect:()=>{};function dm(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function fm(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function mm(e){for(;e&&!cm(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Mt(e),s=t.document.activeElement;if(!s||s===e)return;let r=!1,a=d=>{(Me(d)===s||r)&&d.stopImmediatePropagation()},o=d=>{(Me(d)===s||r)&&(d.stopImmediatePropagation(),!e&&!r&&(r=!0,Us(s),u()))},i=d=>{(Me(d)===e||r)&&d.stopImmediatePropagation()},l=d=>{(Me(d)===e||r)&&(d.stopImmediatePropagation(),r||(r=!0,Us(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(f),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),r=!1},f=requestAnimationFrame(u);return u}function Gn(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 Aa(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function $t(e){let t=null;return()=>(t==null&&(t=e()),t)}const Ln=$t(function(){return Aa(/^Mac/i)}),hm=$t(function(){return Aa(/^iPhone/i)}),Il=$t(function(){return Aa(/^iPad/i)||Ln()&&navigator.maxTouchPoints>1}),Tl=$t(function(){return hm()||Il()}),pm=$t(function(){return Gn(/AppleWebKit/i)&&!gm()}),gm=$t(function(){return Gn(/Chrome/i)}),Rl=$t(function(){return Gn(/Android/i)}),xm=$t(function(){return Gn(/Firefox/i)});function bm(e){return e.pointerType===""&&e.isTrusted?!0:Rl()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function vm(e){return!Rl()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function qs(e,t,s=!0){let{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}=t;xm()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Ln()?r=!0:a=!0);let l=pm()&&Ln()&&!Il()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});qs.isOpening=s,Us(e),e.dispatchEvent(l),qs.isOpening=!1}qs.isOpening=!1;let Et=new Map,Hr=new Set;function So(){if(typeof window>"u")return;function e(r){return"propertyName"in r}let t=r=>{let a=Me(r);if(!e(r)||!a)return;let o=Et.get(a);o||(o=new Set,Et.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(r.propertyName)},s=r=>{let a=Me(r);if(!e(r)||!a)return;let o=Et.get(a);if(o&&(o.delete(r.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Et.delete(a)),Et.size===0)){for(let i of Hr)i();Hr.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?So():document.addEventListener("DOMContentLoaded",So));function ym(){for(const[e]of Et)"isConnected"in e&&!e.isConnected&&Et.delete(e)}function wm(e){requestAnimationFrame(()=>{ym(),Et.size===0?e():Hr.add(e)})}function Ml(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let Wr=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{Wr.delete(e)});function jm(e,t){if(e===t)return e;let s=Wr.get(e);if(s)return s.forEach(a=>a.current=t),t;let r=Wr.get(t);return r?(r.forEach(a=>a.current=e),e):t}function Sm(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const r=e.map(a=>{const o=ko(a,t);return s||=typeof o=="function",o});if(s)return()=>{r.forEach((a,o)=>{typeof a=="function"?a():ko(e[o],null)})}}}function ko(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ks(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let r=e[s];for(let a in r){let o=t[a],i=r[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=Ml(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=Dd(o,i):a==="id"&&o&&i?t.id=jm(o,i):a==="ref"&&o&&i?t.ref=Sm(o,i):t[a]=i!==void 0?i:o}}return t}function km(e,t){Ma(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const Cm=q.useInsertionEffect??Ma;function yr(e){const t=c.useRef(null);return Cm(()=>{t.current=e},[e]),c.useCallback((...s)=>{const r=t.current;return r?.(...s)},[])}let ms="default",Vr="",Rn=new WeakMap;function Nm(e){if(Tl()){if(ms==="default"){const t=It(e);Vr=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}ms="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Rn.set(e,e.style[t]),e.style[t]="none"}}function Co(e){if(Tl()){if(ms!=="disabled")return;ms="restoring",setTimeout(()=>{wm(()=>{if(ms==="restoring"){const t=It(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=Vr||""),Vr="",ms="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Rn.has(e)){let t=Rn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Rn.delete(e)}}function No(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let wr=new WeakMap;function Em(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return No(t);if(wr.has(t))return wr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),r=s&&s instanceof Mt(s).HTMLMetaElement&&(s.nonce||s.content)||No(t)||void 0;return r!==void 0&&wr.set(t,r),r}const Al=q.createContext({register:()=>{}});Al.displayName="PressResponderContext";function Dl(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...f)=>{e.current.delete(i),i(...f)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),r=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>r,[r]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:r}}function Im(e){let t=c.useContext(Al);if(t){let{register:s,ref:r,...a}=t;e=ks(a,e),s()}return km(t,e.ref),e}class bn{#s;constructor(t,s,r,a){this.#s=!0;const i=(a?.target??r.currentTarget)?.getBoundingClientRect();let l,u=0,f,d=null;r.clientX!=null&&r.clientY!=null&&(f=r.clientX,d=r.clientY),i&&(f!=null&&d!=null?(l=f-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=r.currentTarget,this.shiftKey=r.shiftKey,this.metaKey=r.metaKey,this.ctrlKey=r.ctrlKey,this.altKey=r.altKey,this.x=l,this.y=u,this.key=r.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const Eo=Symbol("linkClicked"),Io="react-aria-pressable-style",To="data-react-aria-pressable";function Tm(e){let{onPress:t,onPressChange:s,onPressStart:r,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:f,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:m,ref:h,...g}=Im(e),[v,p]=c.useState(!1),x=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:w}=Dl(),j=c.useCallback((S,A)=>{let L=x.current;if(l||L.didFirePressStart)return!1;let T=!0;if(L.isTriggeringEvent=!0,r){let F=new bn("pressstart",A,S);r(F),T=F.shouldStopPropagation}return s&&s(!0),L.isTriggeringEvent=!1,L.didFirePressStart=!0,p(!0),T},[l,r,s]),y=c.useCallback((S,A,L=!0)=>{let T=x.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let F=!0;if(a){let R=new bn("pressend",A,S);a(R),F=R.shouldStopPropagation}if(s&&s(!1),p(!1),t&&L&&!l){let R=new bn("press",A,S);t(R),F&&=R.shouldStopPropagation}return T.isTriggeringEvent=!1,F},[l,a,s,t]),I=yr(y),N=c.useCallback((S,A)=>{let L=x.current;if(l)return!1;if(o){L.isTriggeringEvent=!0;let T=new bn("pressup",A,S);return o(T),L.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[l,o]),k=yr(N),C=c.useCallback(S=>{let A=x.current;if(A.isPressed&&A.target){A.didFirePressStart&&A.pointerType!=null&&y(Ut(A.target,S),A.pointerType,!1),A.isPressed=!1,A.isOverTarget=!1,A.activePointerId=null,A.pointerType=null,w(),m||Co(A.target);for(let L of A.disposables)L();A.disposables=[]}},[m,w,y]),M=yr(C);c.useEffect(()=>{l&&x.current.isPressed&&M({currentTarget:x.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let P=c.useCallback(S=>{d&&C(S)},[d,C]),D=c.useCallback(S=>{l||i?.(S)},[l,i]),O=c.useCallback((S,A)=>{if(!l&&i){let L=new MouseEvent("click",S);fm(L,A),i(dm(L))}},[l,i]),E=c.useMemo(()=>{let S=x.current,A={onKeyDown(T){if(jr(T.nativeEvent,T.currentTarget)&&ot(T.currentTarget,Me(T))){Ro(Me(T),T.key)&&T.preventDefault();let F=!0;!S.isPressed&&!T.repeat&&(S.target=T.currentTarget,S.isPressed=!0,S.pointerType="keyboard",F=j(T,"keyboard"));let R=T.currentTarget,$=z=>{jr(z,R)&&!z.repeat&&ot(R,Me(z))&&S.target&&k(Ut(S.target,z),"keyboard")};b(It(T.currentTarget),"keyup",Ml($,L),!0),F&&T.stopPropagation(),T.metaKey&&Ln()&&S.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(S.metaKeyEvents=new Map)},onClick(T){if(!(T&&!ot(T.currentTarget,Me(T)))&&T&&T.button===0&&!S.isTriggeringEvent&&!qs.isOpening){let F=!0;if(l&&T.preventDefault(),!S.ignoreEmulatedMouseEvents&&!S.isPressed&&(S.pointerType==="virtual"||bm(T.nativeEvent))){let R=j(T,"virtual"),$=k(T,"virtual"),z=I(T,"virtual");D(T),F=R&&$&&z}else if(S.isPressed&&S.pointerType!=="keyboard"){let R=S.pointerType||T.nativeEvent.pointerType||"virtual",$=k(Ut(T.currentTarget,T),R),z=I(Ut(T.currentTarget,T),R,!0);F=$&&z,S.isOverTarget=!1,D(T),M(T)}S.ignoreEmulatedMouseEvents=!1,F&&T.stopPropagation()}}},L=T=>{if(S.isPressed&&S.target&&jr(T,S.target)){Ro(Me(T),T.key)&&T.preventDefault();let F=Me(T),R=ot(S.target,F);I(Ut(S.target,T),"keyboard",R),R&&O(T,S.target),w(),T.key!=="Enter"&&Da(S.target)&&ot(S.target,F)&&!T[Eo]&&(T[Eo]=!0,qs(S.target,T,!1)),S.isPressed=!1,S.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&S.metaKeyEvents?.size){let F=S.metaKeyEvents;S.metaKeyEvents=void 0;for(let R of F.values())S.target?.dispatchEvent(new KeyboardEvent("keyup",R))}};if(typeof PointerEvent<"u"){A.onPointerDown=R=>{if(R.button!==0||!ot(R.currentTarget,Me(R)))return;if(vm(R.nativeEvent)){S.pointerType="virtual";return}S.pointerType=R.pointerType;let $=!0;if(!S.isPressed){S.isPressed=!0,S.isOverTarget=!0,S.activePointerId=R.pointerId,S.target=R.currentTarget,m||Nm(S.target),$=j(R,S.pointerType);let z=Me(R);"releasePointerCapture"in z&&("hasPointerCapture"in z?z.hasPointerCapture(R.pointerId)&&z.releasePointerCapture(R.pointerId):z.releasePointerCapture(R.pointerId)),b(It(R.currentTarget),"pointerup",T,!1),b(It(R.currentTarget),"pointercancel",F,!1)}$&&R.stopPropagation()},A.onMouseDown=R=>{if(ot(R.currentTarget,Me(R))&&R.button===0){if(f){let $=mm(R.target);$&&S.disposables.push($)}R.stopPropagation()}},A.onPointerUp=R=>{!ot(R.currentTarget,Me(R))||S.pointerType==="virtual"||R.button===0&&!S.isPressed&&k(R,S.pointerType||R.pointerType)},A.onPointerEnter=R=>{R.pointerId===S.activePointerId&&S.target&&!S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!0,j(Ut(S.target,R),S.pointerType))},A.onPointerLeave=R=>{R.pointerId===S.activePointerId&&S.target&&S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!1,I(Ut(S.target,R),S.pointerType,!1),P(R))};let T=R=>{if(R.pointerId===S.activePointerId&&S.isPressed&&R.button===0&&S.target){if(ot(S.target,Me(R))&&S.pointerType!=null){let $=!1,z=setTimeout(()=>{S.isPressed&&S.target instanceof HTMLElement&&($?M(R):(Us(S.target),S.target.click()))},80);b(R.currentTarget,"click",()=>$=!0,!0),S.disposables.push(()=>clearTimeout(z))}else M(R);S.isOverTarget=!1}},F=R=>{M(R)};A.onDragStart=R=>{ot(R.currentTarget,Me(R))&&M(R)}}return A},[b,l,f,w,m,P,j,D,O]);return c.useEffect(()=>{if(!h)return;const S=It(h.current);if(!S||!S.head||S.getElementById(Io))return;const A=S.createElement("style");A.id=Io;let L=Em(S);L&&(A.nonce=L),A.textContent=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-CTtNTugV.js","assets/index-UNmLTd6G.js","assets/index-DllQMXH0.css","assets/search-BxHTifee.js","assets/avatar-B9YIb5SM.js","assets/kbd-CSBQtv4K.js","assets/account-form-helpers-BlJvBmoN.js","assets/useSignature-Cluo7-bu.js","assets/useDebouncedValue-CxajUBik.js","assets/useRulePreview-Cnkwzpft.js","assets/ErrorState-BXXl1_pQ.js","assets/format-B6Elex-n.js","assets/move-targets-DjI1Tv8S.js","assets/move-mailbox-picker-WjOZHj2B.js","assets/rotate-ccw-DmTx8ZTA.js","assets/circle-check-DawkktF8.js","assets/ConfirmDialog-GL7gNRn9.js","assets/useLabels-UMDQIppz.js"])))=>i.map(i=>d[i]);
2
+ import{R as q,c as Od,r as c,a as fe,j as n,C as Rt,X as We,b as H,B as G,d as lt,S as At,e as ut,f as Gt,L as oa,g as Pd,h as Ld,i as Ys,k as nt,T as rt,l as Xt,u as Kn,m as ia,n as Yi,I as la,p as Gi,o as ca,q as $d,D as ua,s as Gs,O as Fd,M as _d,A as zd,F as Xi,t as Bd,v as Kd,w as Ud,x as qd,y as da,z as fa,P as Hd,E as Wd,G as ma,H as ha,_ as Nt,J as Ji,K as Vd,Q as pa,N as Qd,U as Yd,V as Gd,W as Br,Y as Xd,Z as Jd,$ as ye,a0 as Zd,a1 as ef,a2 as tf,a3 as sf,a4 as nf,a5 as rf,a6 as vo,a7 as af,a8 as of,a9 as lf,aa as ga,ab as Zi,ac as el,ad as Dt,ae as Oe,af as _e,ag as Xs,ah as be,ai as xa,aj as ba,ak as va,al as ya,am as Un,an as bs,ao as Ce,ap as Js,aq as de,ar as tl,as as cf,at as ve,au as sl,av as uf,aw as qn,ax as nl,ay as xt,az as Ve,aA as df,aB as st,aC as rl,aD as Vt,aE as Hn,aF as ff,aG as wa,aH as al,aI as ol,aJ as Jt,aK as Wn,aL as Zt,aM as mf,aN as hf,aO as Vn,aP as pf,aQ as il,aR as vs,aS as gf,aT as ja,aU as xf,aV as bf,aW as ll,aX as Sa,aY as cl,aZ as ul,a_ as Ss,a$ as vf,b0 as yo,b1 as yf,b2 as wf,b3 as pt,b4 as Kr,b5 as Ur,b6 as jf,b7 as dl,b8 as Sf,b9 as ka,ba as fl,bb as kf,bc as Cf,bd as Nf,be as Ef,bf as If,bg as Tf,bh as Rf,bi as Mf,bj as Af,bk as Df,bl as Of,bm as Pf,bn as Lf,bo as $f,bp as Ff,bq as kt,br as ht,bs as _f}from"./index-UNmLTd6G.js";import{S as Qn}from"./search-BxHTifee.js";import{A as dt,M as Ca,C as zf}from"./avatar-B9YIb5SM.js";import{K as ps}from"./kbd-CSBQtv4K.js";import{M as ml,a as Bf}from"./account-form-helpers-BlJvBmoN.js";import{R as Kf,u as Uf}from"./useSignature-Cluo7-bu.js";import{u as hl}from"./useDebouncedValue-CxajUBik.js";import{B as pl,u as Ot,a as wo,b as qr,n as qf,S as Na,c as gl,r as Ea,d as xl,e as bl,f as vl,g as Hf,h as Wf,i as Vf,j as Qf,k as Yf}from"./useRulePreview-Cnkwzpft.js";import{E as Pt,f as yl}from"./ErrorState-BXXl1_pQ.js";import{f as wl,a as Lt,b as jl,c as Pn,d as ct,t as Gf}from"./format-B6Elex-n.js";import{P as jo,u as Sl,b as Zs,M as it}from"./move-targets-DjI1Tv8S.js";import{F as Ia,a as Xf,M as kl}from"./move-mailbox-picker-WjOZHj2B.js";import{C as Ta,R as Jf}from"./rotate-ccw-DmTx8ZTA.js";import{C as Yn}from"./circle-check-DawkktF8.js";import{C as Ra}from"./ConfirmDialog-GL7gNRn9.js";import{u as Cl,a as Zf}from"./useLabels-UMDQIppz.js";function Us(e){if(em())e.focus({preventScroll:!0});else{let t=tm(e);e.focus(),sm(t)}}let xn=null;function em(){if(xn==null){xn=!1;try{document.createElement("div").focus({get preventScroll(){return xn=!0,!0}})}catch{}}return xn}function tm(e){let t=e.parentNode,s=[],r=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==r;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return r instanceof HTMLElement&&s.push({element:r,scrollTop:r.scrollTop,scrollLeft:r.scrollLeft}),s}function sm(e){for(let{element:t,scrollTop:s,scrollLeft:r}of e)t.scrollTop=s,t.scrollLeft=r}const It=e=>e?.ownerDocument??document,Mt=e=>e&&"window"in e&&e.window===e?e:It(e).defaultView||window;function nm(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function rm(e){return nm(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let am=!1;function Nl(){return am}function ot(e,t){if(!Nl())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:rm(s)?s=s.host:s=s.parentNode}return!1}function Me(e){if(Nl()&&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 om=typeof Element<"u"&&"checkVisibility"in Element.prototype;function im(e){const t=Mt(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:r}=e.style,a=s!=="none"&&r!=="hidden"&&r!=="collapse";if(a){const{getComputedStyle:o}=Mt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function lm(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 El(e,t){return om?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&im(e)&&lm(e,t)&&(!e.parentElement||El(e.parentElement,e))}const Il=["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"],cm=Il.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";Il.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function um(e,t){return e.matches(cm)&&!dm(e)&&(t?.skipVisibilityCheck||El(e))}function dm(e){let t=e;for(;t!=null;){if(t instanceof Mt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Ma=typeof document<"u"?q.useLayoutEffect:()=>{};function fm(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function mm(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function hm(e){for(;e&&!um(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Mt(e),s=t.document.activeElement;if(!s||s===e)return;let r=!1,a=d=>{(Me(d)===s||r)&&d.stopImmediatePropagation()},o=d=>{(Me(d)===s||r)&&(d.stopImmediatePropagation(),!e&&!r&&(r=!0,Us(s),u()))},i=d=>{(Me(d)===e||r)&&d.stopImmediatePropagation()},l=d=>{(Me(d)===e||r)&&(d.stopImmediatePropagation(),r||(r=!0,Us(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(f),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),r=!1},f=requestAnimationFrame(u);return u}function Gn(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 Aa(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function $t(e){let t=null;return()=>(t==null&&(t=e()),t)}const Ln=$t(function(){return Aa(/^Mac/i)}),pm=$t(function(){return Aa(/^iPhone/i)}),Tl=$t(function(){return Aa(/^iPad/i)||Ln()&&navigator.maxTouchPoints>1}),Rl=$t(function(){return pm()||Tl()}),gm=$t(function(){return Gn(/AppleWebKit/i)&&!xm()}),xm=$t(function(){return Gn(/Chrome/i)}),Ml=$t(function(){return Gn(/Android/i)}),bm=$t(function(){return Gn(/Firefox/i)});function vm(e){return e.pointerType===""&&e.isTrusted?!0:Ml()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function ym(e){return!Ml()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function qs(e,t,s=!0){let{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}=t;bm()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Ln()?r=!0:a=!0);let l=gm()&&Ln()&&!Tl()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});qs.isOpening=s,Us(e),e.dispatchEvent(l),qs.isOpening=!1}qs.isOpening=!1;let Et=new Map,Hr=new Set;function So(){if(typeof window>"u")return;function e(r){return"propertyName"in r}let t=r=>{let a=Me(r);if(!e(r)||!a)return;let o=Et.get(a);o||(o=new Set,Et.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(r.propertyName)},s=r=>{let a=Me(r);if(!e(r)||!a)return;let o=Et.get(a);if(o&&(o.delete(r.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Et.delete(a)),Et.size===0)){for(let i of Hr)i();Hr.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?So():document.addEventListener("DOMContentLoaded",So));function wm(){for(const[e]of Et)"isConnected"in e&&!e.isConnected&&Et.delete(e)}function jm(e){requestAnimationFrame(()=>{wm(),Et.size===0?e():Hr.add(e)})}function Al(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let Wr=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{Wr.delete(e)});function Sm(e,t){if(e===t)return e;let s=Wr.get(e);if(s)return s.forEach(a=>a.current=t),t;let r=Wr.get(t);return r?(r.forEach(a=>a.current=e),e):t}function km(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const r=e.map(a=>{const o=ko(a,t);return s||=typeof o=="function",o});if(s)return()=>{r.forEach((a,o)=>{typeof a=="function"?a():ko(e[o],null)})}}}function ko(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ks(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let r=e[s];for(let a in r){let o=t[a],i=r[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=Al(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=Od(o,i):a==="id"&&o&&i?t.id=Sm(o,i):a==="ref"&&o&&i?t.ref=km(o,i):t[a]=i!==void 0?i:o}}return t}function Cm(e,t){Ma(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const Nm=q.useInsertionEffect??Ma;function yr(e){const t=c.useRef(null);return Nm(()=>{t.current=e},[e]),c.useCallback((...s)=>{const r=t.current;return r?.(...s)},[])}let ms="default",Vr="",Rn=new WeakMap;function Em(e){if(Rl()){if(ms==="default"){const t=It(e);Vr=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}ms="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Rn.set(e,e.style[t]),e.style[t]="none"}}function Co(e){if(Rl()){if(ms!=="disabled")return;ms="restoring",setTimeout(()=>{jm(()=>{if(ms==="restoring"){const t=It(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=Vr||""),Vr="",ms="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Rn.has(e)){let t=Rn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Rn.delete(e)}}function No(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let wr=new WeakMap;function Im(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return No(t);if(wr.has(t))return wr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),r=s&&s instanceof Mt(s).HTMLMetaElement&&(s.nonce||s.content)||No(t)||void 0;return r!==void 0&&wr.set(t,r),r}const Dl=q.createContext({register:()=>{}});Dl.displayName="PressResponderContext";function Ol(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...f)=>{e.current.delete(i),i(...f)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),r=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>r,[r]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:r}}function Tm(e){let t=c.useContext(Dl);if(t){let{register:s,ref:r,...a}=t;e=ks(a,e),s()}return Cm(t,e.ref),e}class bn{#s;constructor(t,s,r,a){this.#s=!0;const i=(a?.target??r.currentTarget)?.getBoundingClientRect();let l,u=0,f,d=null;r.clientX!=null&&r.clientY!=null&&(f=r.clientX,d=r.clientY),i&&(f!=null&&d!=null?(l=f-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=r.currentTarget,this.shiftKey=r.shiftKey,this.metaKey=r.metaKey,this.ctrlKey=r.ctrlKey,this.altKey=r.altKey,this.x=l,this.y=u,this.key=r.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const Eo=Symbol("linkClicked"),Io="react-aria-pressable-style",To="data-react-aria-pressable";function Rm(e){let{onPress:t,onPressChange:s,onPressStart:r,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:f,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:m,ref:h,...g}=Tm(e),[v,p]=c.useState(!1),x=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:w}=Ol(),j=c.useCallback((S,A)=>{let L=x.current;if(l||L.didFirePressStart)return!1;let T=!0;if(L.isTriggeringEvent=!0,r){let F=new bn("pressstart",A,S);r(F),T=F.shouldStopPropagation}return s&&s(!0),L.isTriggeringEvent=!1,L.didFirePressStart=!0,p(!0),T},[l,r,s]),y=c.useCallback((S,A,L=!0)=>{let T=x.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let F=!0;if(a){let R=new bn("pressend",A,S);a(R),F=R.shouldStopPropagation}if(s&&s(!1),p(!1),t&&L&&!l){let R=new bn("press",A,S);t(R),F&&=R.shouldStopPropagation}return T.isTriggeringEvent=!1,F},[l,a,s,t]),I=yr(y),N=c.useCallback((S,A)=>{let L=x.current;if(l)return!1;if(o){L.isTriggeringEvent=!0;let T=new bn("pressup",A,S);return o(T),L.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[l,o]),k=yr(N),C=c.useCallback(S=>{let A=x.current;if(A.isPressed&&A.target){A.didFirePressStart&&A.pointerType!=null&&y(Ut(A.target,S),A.pointerType,!1),A.isPressed=!1,A.isOverTarget=!1,A.activePointerId=null,A.pointerType=null,w(),m||Co(A.target);for(let L of A.disposables)L();A.disposables=[]}},[m,w,y]),M=yr(C);c.useEffect(()=>{l&&x.current.isPressed&&M({currentTarget:x.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let P=c.useCallback(S=>{d&&C(S)},[d,C]),D=c.useCallback(S=>{l||i?.(S)},[l,i]),O=c.useCallback((S,A)=>{if(!l&&i){let L=new MouseEvent("click",S);mm(L,A),i(fm(L))}},[l,i]),E=c.useMemo(()=>{let S=x.current,A={onKeyDown(T){if(jr(T.nativeEvent,T.currentTarget)&&ot(T.currentTarget,Me(T))){Ro(Me(T),T.key)&&T.preventDefault();let F=!0;!S.isPressed&&!T.repeat&&(S.target=T.currentTarget,S.isPressed=!0,S.pointerType="keyboard",F=j(T,"keyboard"));let R=T.currentTarget,$=z=>{jr(z,R)&&!z.repeat&&ot(R,Me(z))&&S.target&&k(Ut(S.target,z),"keyboard")};b(It(T.currentTarget),"keyup",Al($,L),!0),F&&T.stopPropagation(),T.metaKey&&Ln()&&S.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(S.metaKeyEvents=new Map)},onClick(T){if(!(T&&!ot(T.currentTarget,Me(T)))&&T&&T.button===0&&!S.isTriggeringEvent&&!qs.isOpening){let F=!0;if(l&&T.preventDefault(),!S.ignoreEmulatedMouseEvents&&!S.isPressed&&(S.pointerType==="virtual"||vm(T.nativeEvent))){let R=j(T,"virtual"),$=k(T,"virtual"),z=I(T,"virtual");D(T),F=R&&$&&z}else if(S.isPressed&&S.pointerType!=="keyboard"){let R=S.pointerType||T.nativeEvent.pointerType||"virtual",$=k(Ut(T.currentTarget,T),R),z=I(Ut(T.currentTarget,T),R,!0);F=$&&z,S.isOverTarget=!1,D(T),M(T)}S.ignoreEmulatedMouseEvents=!1,F&&T.stopPropagation()}}},L=T=>{if(S.isPressed&&S.target&&jr(T,S.target)){Ro(Me(T),T.key)&&T.preventDefault();let F=Me(T),R=ot(S.target,F);I(Ut(S.target,T),"keyboard",R),R&&O(T,S.target),w(),T.key!=="Enter"&&Da(S.target)&&ot(S.target,F)&&!T[Eo]&&(T[Eo]=!0,qs(S.target,T,!1)),S.isPressed=!1,S.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&S.metaKeyEvents?.size){let F=S.metaKeyEvents;S.metaKeyEvents=void 0;for(let R of F.values())S.target?.dispatchEvent(new KeyboardEvent("keyup",R))}};if(typeof PointerEvent<"u"){A.onPointerDown=R=>{if(R.button!==0||!ot(R.currentTarget,Me(R)))return;if(ym(R.nativeEvent)){S.pointerType="virtual";return}S.pointerType=R.pointerType;let $=!0;if(!S.isPressed){S.isPressed=!0,S.isOverTarget=!0,S.activePointerId=R.pointerId,S.target=R.currentTarget,m||Em(S.target),$=j(R,S.pointerType);let z=Me(R);"releasePointerCapture"in z&&("hasPointerCapture"in z?z.hasPointerCapture(R.pointerId)&&z.releasePointerCapture(R.pointerId):z.releasePointerCapture(R.pointerId)),b(It(R.currentTarget),"pointerup",T,!1),b(It(R.currentTarget),"pointercancel",F,!1)}$&&R.stopPropagation()},A.onMouseDown=R=>{if(ot(R.currentTarget,Me(R))&&R.button===0){if(f){let $=hm(R.target);$&&S.disposables.push($)}R.stopPropagation()}},A.onPointerUp=R=>{!ot(R.currentTarget,Me(R))||S.pointerType==="virtual"||R.button===0&&!S.isPressed&&k(R,S.pointerType||R.pointerType)},A.onPointerEnter=R=>{R.pointerId===S.activePointerId&&S.target&&!S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!0,j(Ut(S.target,R),S.pointerType))},A.onPointerLeave=R=>{R.pointerId===S.activePointerId&&S.target&&S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!1,I(Ut(S.target,R),S.pointerType,!1),P(R))};let T=R=>{if(R.pointerId===S.activePointerId&&S.isPressed&&R.button===0&&S.target){if(ot(S.target,Me(R))&&S.pointerType!=null){let $=!1,z=setTimeout(()=>{S.isPressed&&S.target instanceof HTMLElement&&($?M(R):(Us(S.target),S.target.click()))},80);b(R.currentTarget,"click",()=>$=!0,!0),S.disposables.push(()=>clearTimeout(z))}else M(R);S.isOverTarget=!1}},F=R=>{M(R)};A.onDragStart=R=>{ot(R.currentTarget,Me(R))&&M(R)}}return A},[b,l,f,w,m,P,j,D,O]);return c.useEffect(()=>{if(!h)return;const S=It(h.current);if(!S||!S.head||S.getElementById(Io))return;const A=S.createElement("style");A.id=Io;let L=Im(S);L&&(A.nonce=L),A.textContent=`
3
3
  @layer {
4
4
  [${To}] {
5
5
  touch-action: pan-x pan-y pinch-zoom;
6
6
  }
7
7
  }
8
- `.trim(),S.head.prepend(A)},[h]),c.useEffect(()=>{let S=x.current;return()=>{m||Co(S.target??void 0);for(let A of S.disposables)A();S.disposables=[]}},[m]),{isPressed:u||v,pressProps:ks(g,E,{[To]:!0})}}function Da(e){return e.tagName==="A"&&e.hasAttribute("href")}function jr(e,t){const{key:s,code:r}=e,a=t,o=a.getAttribute("role");return(s==="Enter"||s===" "||s==="Spacebar"||r==="Space")&&!(a instanceof Mt(a).HTMLInputElement&&!Ol(a,s)||a instanceof Mt(a).HTMLTextAreaElement||a.isContentEditable)&&!((o==="link"||!o&&Da(a))&&s!=="Enter")}function Ut(e,t){let s=t.clientX,r=t.clientY;return{currentTarget:e,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,altKey:t.altKey,clientX:s,clientY:r,key:t.key}}function Rm(e){return e instanceof HTMLInputElement?!1:e instanceof HTMLButtonElement?e.type!=="submit"&&e.type!=="reset":!Da(e)}function Ro(e,t){return e instanceof HTMLInputElement?!Ol(e,t):Rm(e)}const Mm=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function Ol(e,t){return e.type==="checkbox"||e.type==="radio"?t===" ":Mm.has(e.type)}let Am=0;const Sr=new Map;function Dm(e){let[t,s]=c.useState();return Ma(()=>{if(!e)return;let r=Sr.get(e);if(r)s(r.element.id);else{let a=`react-aria-description-${Am++}`;s(a);let o=document.createElement("div");o.id=a,o.style.display="none",o.textContent=e,document.body.appendChild(o),r={refCount:0,element:o},Sr.set(e,r)}return r.refCount++,()=>{r&&--r.refCount===0&&(r.element.remove(),Sr.delete(e))}},[e]),{"aria-describedby":e?t:void 0}}const Om=500;function Pm(e){let{isDisabled:t,onLongPressStart:s,onLongPressEnd:r,onLongPress:a,threshold:o=Om,accessibilityDescription:i}=e;const l=c.useRef(void 0);let{addGlobalListener:u,removeGlobalListener:f}=Dl(),{pressProps:d}=Tm({isDisabled:t,onPressStart(h){if(h.continuePropagation(),(h.pointerType==="mouse"||h.pointerType==="touch")&&(s&&s({...h,type:"longpressstart"}),l.current=setTimeout(()=>{h.target.dispatchEvent(new PointerEvent("pointercancel",{bubbles:!0})),It(h.target).activeElement!==h.target&&Us(h.target),a&&a({...h,type:"longpress"}),l.current=void 0},o),h.pointerType==="touch")){let g=p=>{p.preventDefault()},v=Mt(h.target);u(h.target,"contextmenu",g,{once:!0}),u(v,"pointerup",()=>{setTimeout(()=>{f(h.target,"contextmenu",g)},30)},{once:!0})}},onPressEnd(h){l.current&&clearTimeout(l.current),r&&(h.pointerType==="mouse"||h.pointerType==="touch")&&r({...h,type:"longpressend"})}}),m=Dm(a&&!t?i:void 0);return{longPressProps:ks(d,m)}}const Pl=fe("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);const Lm=fe("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);const $m=fe("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const Xn=fe("BadgeCheck",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Fm=fe("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);const Ll=fe("BellOff",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]]);const _m=fe("BookmarkPlus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"12",x2:"12",y1:"7",y2:"13",key:"1cppfj"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);const Mo=fe("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]);const ys=fe("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const zm=fe("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);const $l=fe("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);const Fl=fe("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);const _l=fe("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);const Bm=fe("Flag",[["path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z",key:"i9b6wo"}],["line",{x1:"4",x2:"4",y1:"22",y2:"15",key:"1cm3nv"}]]);const zl=fe("Forward",[["polyline",{points:"15 17 20 12 15 7",key:"1w3sku"}],["path",{d:"M4 18v-2a4 4 0 0 1 4-4h12",key:"jmiej9"}]]);const Bl=fe("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);const Km=fe("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);const Cs=fe("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);const Um=fe("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);const qm=fe("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const Jn=fe("Paperclip",[["path",{d:"M13.234 20.252 21 12.3",key:"1cbrk9"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486",key:"1pkts6"}]]);const Hm=fe("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);const Kl=fe("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);const Ul=fe("ReplyAll",[["polyline",{points:"7 17 2 12 7 7",key:"t83bqg"}],["polyline",{points:"12 17 7 12 12 7",key:"1g4ajm"}],["path",{d:"M22 18v-2a4 4 0 0 0-4-4H7",key:"1fcyog"}]]);const ql=fe("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);const Oa=fe("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const Ns=fe("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);const en=fe("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Wm=fe("ShieldQuestion",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const Vm=fe("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);const Qm=fe("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);const Ym=fe("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]),Gm=({address:e,showTrustedBadge:t=!1})=>{const s=t?n.jsx(Xn,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}):null;return e.displayName?n.jsxs("span",{children:[n.jsx("span",{className:"text-fg",children:e.displayName}),n.jsxs("span",{className:"text-fg-muted",children:[" ","<",e.normalizedEmail,">"]}),s]}):n.jsxs("span",{className:"text-fg",children:[e.normalizedEmail,s]})},Xm=({label:e,addresses:t,showTrustedBadge:s=!1})=>{const[r,a]=c.useState(!1);if(t.length===0)return null;const o=t.length>3,i=l=>{const u=s&&l.flags?.trusted?.value===!0;return n.jsx(Gm,{address:l,showTrustedBadge:u})};return n.jsxs("div",{className:"flex gap-2 text-sm",children:[n.jsxs("span",{className:"text-fg-muted shrink-0 w-12",children:[e,":"]}),n.jsx("div",{className:"flex-1 min-w-0",children:r?n.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((l,u)=>n.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))}):n.jsx("div",{className:"truncate",children:t.map((l,u)=>n.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))})}),o&&n.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),a(!r)},className:"shrink-0 text-fg-muted hover:text-fg transition-colors","aria-label":r?"Collapse":"Expand",children:r?n.jsx(Rt,{className:"h-4 w-4"}):n.jsx(ys,{className:"h-4 w-4"})})]})},Jm=({email:e,displayName:t,onRemove:s,className:r})=>n.jsxs("span",{className:H("inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-accent-2-soft text-sm max-w-[200px]",r),children:[n.jsx("span",{className:"truncate",children:t||e}),n.jsx("button",{type:"button",onClick:s,className:"shrink-0 p-0.5 rounded-full hover:bg-fg-muted/20 transition-colors","aria-label":`Remove ${e}`,children:n.jsx(We,{className:"size-3"})})]}),Zm={unknown:{label:"Unknown sender",tone:"neutral"},wellknown:{label:"Known sender",tone:"positive"},vip:{label:"VIP",tone:"accent"}};function as({label:e,children:t,className:s}){return n.jsxs("section",{className:H("border-b border-line px-row-inset py-3",s),children:[n.jsx("h3",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),n.jsx("div",{className:"mt-2",children:t})]})}function eh({sender:e}){const t=Zm[e.trust],s=e.inboundCount==null?null:(e.replyCount??0)>0?`${e.inboundCount} received · you replied ${e.replyCount}×`:`${e.inboundCount} received · you've never replied`;return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(dt,{name:e.name,email:e.email,size:"md"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"truncate text-sm font-semibold text-fg",children:e.name}),n.jsx("div",{className:"truncate text-2xs text-fg-subtle",children:e.email})]})]}),n.jsx("div",{className:"mt-2 flex items-center gap-2",children:e.addressUnverified?n.jsx(lt,{tone:"danger",dot:!0,children:"Address couldn't be verified"}):n.jsx(lt,{tone:t.tone,dot:!0,children:t.label})}),n.jsxs("p",{className:"mt-2 text-xs text-fg-muted",children:["First seen ",e.firstSeenLabel,s?` · ${s}`:""]})]})}function th({auth:e,onShowSimilar:t}){if(e.verdict==="aligned")return n.jsxs("div",{className:"flex items-start gap-2 text-xs text-fg-muted",children:[n.jsx(en,{className:"mt-0.5 size-3.5 shrink-0 text-positive"}),n.jsx("span",{children:e.summary})]});if(e.verdict==="caution")return n.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-warning/10 p-3 text-warning",children:[n.jsx(Wm,{className:"mt-0.5 size-4 shrink-0"}),n.jsx("p",{className:"text-xs leading-relaxed",children:e.summary})]});const s=e.addressUnreadable?"This sender can't be verified":"This message may be impersonating someone";return n.jsxs("div",{className:"rounded-md bg-danger-soft p-3",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(Ns,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"text-sm font-semibold text-danger",children:s}),n.jsx("p",{className:"mt-1 text-xs leading-relaxed text-fg",children:e.summary}),!e.addressUnreadable&&e.dkimDomain&&n.jsxs("p",{className:"mt-1 text-2xs text-fg-muted",children:["Sent from"," ",n.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.dkimDomain}),", claims to be"," ",n.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.fromDomain})]})]})]}),e.similarCount!=null&&e.similarCount>0&&n.jsxs(G,{variant:"secondary",size:"sm",className:"mt-2 w-full border-danger/30 text-danger hover:bg-danger-soft",onClick:t,children:[e.similarCount," similar messages"]})]})}function os({icon:e,label:t,active:s,danger:r,onClick:a}){const o=a===void 0;return n.jsxs("button",{type:"button",onClick:a,disabled:o,className:H("flex items-center gap-2 rounded-md border px-2 py-1 text-xs transition-colors",s?"border-accent-2 bg-accent-2-soft text-accent-2":"border-line text-fg-muted hover:border-line-strong hover:text-fg",r&&!s&&"text-danger hover:bg-danger-soft",o&&"cursor-not-allowed opacity-50 hover:border-line"),children:[e,t]})}const sh={sender:"matched: sender",recipient:"matched: recipient",subject:"matched: subject",attachment:"matched: attachment",body:"matched: body",entities:"matched: entities"};function Hl({data:e,onClose:t,onShowSimilar:s,actions:r,similarState:a="ready",similarLinkComponent:o,className:i,hideCloseButton:l=!1}){const{sender:u,authenticity:f,category:d,flags:m={},similar:h}=e,g=f.verdict==="mismatch";return n.jsxs("aside",{className:H("flex w-76 shrink-0 flex-col overflow-y-auto border-l border-line bg-surface",i),children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center justify-between border-b border-line px-row-inset",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"}),!l&&n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(We,{className:"size-3.5"}),onClick:t,"aria-label":"Collapse intelligence sidebar"})]}),n.jsx(as,{label:"Sender",children:n.jsx(eh,{sender:u})}),n.jsx(as,{label:"Authenticity",children:n.jsx(th,{auth:f,onShowSimilar:s})}),n.jsx(as,{label:"Category",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(lt,{tone:g?"danger":"neutral",children:d.value}),d.overridden&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"your override"}),n.jsx("button",{type:"button",className:H("ml-auto text-2xs text-accent hover:underline",!r?.onReclassify&&"cursor-not-allowed opacity-50 hover:no-underline"),disabled:!r?.onReclassify,onClick:r?.onReclassify,children:"reclassify"})]})}),n.jsx(as,{label:"Quick actions",children:n.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[n.jsx(os,{icon:n.jsx(At,{className:"size-3.5"}),label:"VIP",active:m.vip,onClick:r?.onToggleVip}),n.jsx(os,{icon:n.jsx(Ll,{className:"size-3.5"}),label:"Mute",active:m.muted,onClick:r?.onToggleMute}),n.jsx(os,{icon:n.jsx(Fm,{className:"size-3.5"}),label:"Block",active:m.blocked,danger:!0,onClick:r?.onToggleBlock}),n.jsx(os,{icon:n.jsx(Um,{className:"size-3.5"}),label:"Unsubscribe",active:m.unsubscribed,onClick:r?.onToggleUnsubscribe}),r?.onNotSpam&&n.jsx(os,{icon:n.jsx(Km,{className:"size-3.5"}),label:"Not spam",onClick:r.onNotSpam}),r?.onMarkSpam&&n.jsx(os,{icon:n.jsx(Vm,{className:"size-3.5"}),label:"Mark spam",danger:!0,onClick:r.onMarkSpam})]})}),(a!=="ready"||h.length>0)&&n.jsx(as,{label:"Similar messages",children:a==="loading"?n.jsx("div",{className:"animate-pulse space-y-2",children:Array.from({length:3}).map((v,p)=>n.jsxs("div",{className:"space-y-1",children:[n.jsx("div",{className:"h-3 w-3/4 rounded bg-surface-sunken"}),n.jsx("div",{className:"h-2.5 w-1/2 rounded bg-surface-sunken"})]},p))}):a==="error"?n.jsx("p",{className:"text-xs text-fg-subtle",children:"Similarity search unavailable"}):n.jsx("ul",{className:"-mx-1 space-y-1",children:h.map(v=>{const p="block w-full rounded-md px-1 py-1 text-left hover:bg-surface-sunken",x=`Open message from ${v.fromName||"unknown sender"}: ${v.subject}`,b=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[n.jsx("span",{className:"truncate text-xs font-medium text-fg",children:v.fromName}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:v.timeLabel})]}),n.jsx("div",{className:"truncate text-xs text-fg-muted",children:v.subject}),n.jsx("span",{className:"mt-1 inline-block rounded-full bg-surface-sunken px-1.5 py-px text-2xs text-fg-subtle",children:sh[v.matched]})]});return n.jsx("li",{children:o?o({mailboxId:v.mailboxId,messageId:v.id,className:p,ariaLabel:x,children:b}):n.jsx("div",{className:p,children:b})},v.id)})})}),n.jsx(as,{label:"Coming soon",className:"border-b-0 opacity-70",children:n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[n.jsx(ut,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Suggested actions"}),n.jsx("div",{className:"text-2xs text-fg-subtle",children:'"Create a filter for messages like this" — on-device model'})]})]}),n.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[n.jsx(ut,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Thread summary"}),n.jsx("div",{className:"text-2xs text-fg-subtle",children:"One-paragraph digest — Bedrock"})]})]})]})})]})}const nh=[{keys:["j","k"],label:"navigate"},{keys:["m"],label:"mute"},{keys:["?"],label:"all shortcuts"}];function Wl({hints:e=nh,className:t}){return n.jsx("footer",{className:H("flex items-center gap-2 border-t border-line px-row-inset py-1 text-2xs text-fg-subtle",t),children:e.map(s=>n.jsx(rh,{hint:s},s.label))})}function rh({hint:e}){return n.jsxs("span",{className:"flex items-center gap-1",children:[e.keys.map(t=>n.jsx(ps,{children:t},t)),n.jsx("span",{children:e.label})]})}function ah(){return n.jsx("div",{className:"space-y-0",role:"status","aria-busy":"true","aria-label":"Loading messages",children:Array.from({length:8}).map((e,t)=>n.jsxs("div",{className:"animate-pulse border-b border-line px-3 py-2",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[n.jsx("div",{className:"h-4 w-32 rounded bg-surface-sunken"}),n.jsx("div",{className:"h-3 w-16 rounded bg-surface-sunken"})]}),n.jsx("div",{className:"mb-2 h-4 w-48 rounded bg-surface-sunken"}),n.jsx("div",{className:"h-3 w-full rounded bg-surface-sunken"})]},t))})}function oh({filter:e,scopeLabel:t,searchQuery:s}){const r=s?.trim();return e?n.jsxs(Ao,{children:[n.jsx("p",{className:"font-medium text-fg",children:ch(e.label,t,r)}),n.jsx("p",{className:"mt-1 text-sm text-fg-muted",children:ih[e.reach]}),n.jsx(G,{variant:"secondary",size:"sm",className:"mt-4",onClick:e.onClear,children:"Clear filter"})]}):n.jsx(Ao,{children:n.jsx("p",{className:"text-fg-muted",children:lh(r,t)})})}const ih={"whole-folder":"Every message in this folder was checked.","loaded-pages":"Only the messages loaded so far were checked."};function lh(e,t){return e?"No messages match your search":t?`No messages in ${t}`:"No messages in this mailbox"}function ch(e,t,s){return s?`No results for “${s}” in ${e}`:t?`No ${e} mail in ${t}`:`No ${e} mail`}function Ao({children:e}){return n.jsx("div",{className:"flex h-full flex-1 items-center justify-center",children:n.jsx("div",{className:"flex max-w-sm flex-col items-center justify-center p-8 text-center",children:e})})}function uh({message:e="Something went wrong loading this mailbox.",onRetry:t,onReport:s}){return n.jsx("div",{className:"flex h-full flex-1 items-center justify-center p-4",children:n.jsxs("div",{role:"alert",className:"flex max-w-sm flex-col items-center justify-center gap-3 text-center",children:[n.jsx(Gt,{className:"size-8 text-danger","aria-hidden":"true"}),n.jsxs("div",{children:[n.jsx("p",{className:"font-medium text-danger",children:"Couldn't load messages"}),n.jsx("p",{className:"mt-1 break-words text-sm text-fg-muted",children:e})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[t&&n.jsx(G,{variant:"secondary",size:"sm",onClick:t,children:"Retry"}),s&&n.jsx(G,{variant:"ghost",size:"sm",onClick:s,children:"Report a problem"})]})]})})}const Vl="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",Ql=({active:e,focused:t})=>H("relative flex h-8 w-full items-center gap-2 px-row-inset text-left",Vl,e?"bg-accent-2-soft":t?"bg-surface-sunken":"hover:bg-surface-sunken",t&&!e&&"before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-accent-2"),tn=({active:e,focused:t})=>H("relative flex w-full items-start gap-3 py-2 pl-5 pr-row-inset text-left transition-colors",Vl,e?"bg-accent-2-soft":t?"bg-surface-sunken":"hover:bg-surface-sunken",t&&!e&&"before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-accent-2");function Yl({thread:e}){const t=!e.isRead;return n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex w-4 shrink-0 items-center justify-center",children:e.suspicious?n.jsx(Ns,{className:"size-3.5 text-danger"}):e.starred?n.jsx(At,{className:"size-3 fill-warning text-warning"}):t?n.jsx("span",{className:"size-1.5 rounded-full bg-accent"}):null}),n.jsx("span",{className:H("w-36 shrink-0 truncate text-xs",t?"font-semibold text-fg":"text-fg-muted"),children:e.fromName}),n.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs",children:[n.jsx("span",{className:H(t?"font-medium text-fg":"text-fg-muted"),children:e.subject}),n.jsxs("span",{className:"text-fg-subtle",children:[" — ",e.snippet]})]}),e.hasAttachment&&n.jsx(Jn,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"w-11 shrink-0 text-right text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]})}function Hs({thread:e,badge:t}){const s=!e.isRead;return n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsxs("span",{className:"flex items-baseline justify-between gap-2",children:[n.jsxs("span",{className:H("flex min-w-0 items-center gap-1.5 truncate text-sm",s?"font-semibold text-fg":"font-medium text-fg-muted"),children:[e.trust==="vip"&&n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-accent-2"}),n.jsx("span",{className:"truncate",children:e.fromName}),e.messageCount!=null&&e.messageCount>1&&n.jsx("span",{className:"shrink-0 text-2xs font-normal text-fg-subtle",children:e.messageCount})]}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]}),n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:H("truncate text-sm",s?"text-fg":"text-fg-muted"),children:e.subject}),e.suspicious&&n.jsx(Ns,{className:"size-3.5 shrink-0 text-danger"}),e.starred&&n.jsx(At,{className:"size-3 shrink-0 fill-warning text-warning"}),e.hasAttachment&&n.jsx(Jn,{className:"size-3 shrink-0 text-fg-subtle"})]}),n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"line-clamp-1 min-w-0 flex-1 text-xs text-fg-subtle",children:e.snippet}),e.category&&e.category!=="personal"&&n.jsx(lt,{tone:Od[e.category],className:"shrink-0",children:e.category}),e.labels?.map(r=>n.jsx(Pd,{label:r,className:"max-w-20"},r.labelId)),t]})]})}function dh({thread:e,selection:t}){if(!t)return n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"sm"});const{checked:s,alwaysVisible:r}=t;return n.jsxs("span",{className:"relative size-7 shrink-0",children:[n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"sm",className:H("absolute inset-0 transition-opacity sm:group-hover:opacity-0",(s||r)&&"opacity-0")}),n.jsx("span",{role:"button",tabIndex:-1,onClick:t.onToggle,onKeyDown:a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),a.stopPropagation(),t.onToggle(a))},className:H("absolute inset-0 size-7 items-center justify-center rounded-full border transition-opacity",r?"flex":"hidden sm:flex",s?"bg-accent border-accent text-accent-fg opacity-100":r?"border-fg-subtle/40 bg-canvas opacity-100":"border-fg-subtle/40 bg-canvas opacity-0 group-hover:opacity-100"),"aria-label":s?"Deselect message":"Select message",children:s&&n.jsx(Ys,{className:"size-3"})})]})}function Gl({thread:e,selection:t,badge:s}){const r=!e.isRead;return n.jsxs(n.Fragment,{children:[r&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx(dh,{thread:e,selection:t}),n.jsx(Hs,{thread:e,badge:s})]})}function fh({thread:e,active:t,focused:s,onClick:r}){return n.jsx("button",{type:"button",...oa,onClick:r,className:Ql({active:t,focused:s}),children:n.jsx(Yl,{thread:e})})}function mh({thread:e,active:t,focused:s,selection:r,onClick:a}){return n.jsx("button",{type:"button",...oa,onClick:a,className:H("group",tn({active:t,focused:s})),children:n.jsx(Gl,{thread:e,selection:r})})}const hh="peer relative size-5 shrink-0 cursor-pointer appearance-none rounded-md border border-line-strong bg-surface outline-none transition-colors checked:border-positive checked:bg-positive indeterminate:border-positive indeterminate:bg-positive focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface",Do="pointer-events-none absolute inset-0 m-auto size-3.5 text-accent-fg";function sn({label:e,description:t,indeterminate:s=!1,checked:r,onChange:a,className:o,...i}){const l=c.useRef(null);c.useEffect(()=>{l.current&&(l.current.indeterminate=s)},[s]);const u=n.jsxs("span",{className:"relative inline-flex",children:[n.jsx("input",{ref:l,type:"checkbox",checked:r,onChange:a,className:hh,...i}),n.jsx(Ys,{className:H(Do,"hidden peer-checked:block"),"aria-hidden":!0}),n.jsx(qm,{className:H(Do,"hidden peer-indeterminate:block"),"aria-hidden":!0})]});return e===void 0&&t===void 0?n.jsx("span",{className:o,children:u}):n.jsxs("label",{className:H("flex min-h-11 cursor-pointer items-center gap-3 text-left",o),children:[u,n.jsxs("span",{className:"flex min-w-0 flex-col",children:[e!==void 0&&n.jsx("span",{className:"text-sm text-fg",children:e}),t!==void 0&&n.jsx("span",{className:"text-xs text-fg-subtle",children:t})]})]})}const ph={info:"bg-accent-2",success:"bg-positive",warning:"bg-warning",danger:"bg-danger"};function Pa({value:e,max:t,tone:s="info",indeterminate:r=!1,className:a}){const o=r?100:t<=0?0:Math.min(100,Math.max(0,e/t*100));return n.jsx("div",{role:"progressbar","aria-valuenow":r?void 0:e,"aria-valuemin":r?void 0:0,"aria-valuemax":r?void 0:t,className:H("h-1.5 w-full overflow-hidden rounded-full bg-surface-sunken",a),children:n.jsx("div",{className:H("h-full rounded-full transition-[width] duration-300 ease-out",ph[s],r&&"w-1/3 animate-pulse"),style:r?void 0:{width:`${o}%`}})})}const Oo=e=>e.toLocaleString();function gh({count:e,onCancel:t,onMarkRead:s,onDelete:r,moveSlot:a,isBusy:o=!1,isCounting:i=!1,selectAll:l,statusLabel:u,progress:f,notice:d}){const m=l?.checked?`All ${Oo(e)} loaded selected`:`${Oo(e)} ${e===1?"message":"messages"} selected`;return n.jsxs("header",{className:"flex shrink-0 flex-col border-b border-line bg-surface-sunken",children:[n.jsxs("div",{className:"flex h-pane-header items-center gap-2 px-row-inset",children:[n.jsx(G,{variant:"ghost",size:"touch",icon:n.jsx(We,{className:"size-4"}),onClick:t,"aria-label":"Cancel selection",className:"-ml-2 shrink-0"}),l&&n.jsx("label",{className:"-ml-1.5 flex size-11 shrink-0 cursor-pointer items-center justify-center",children:n.jsx(sn,{"aria-label":"Select all",checked:l.checked,indeterminate:l.indeterminate,onChange:l.onChange})}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-fg",role:"status","aria-live":"polite",children:u??m}),s&&!o&&n.jsx(G,{variant:"ghost",size:"touch",icon:n.jsx(Cs,{className:"size-4"}),onClick:s,"aria-label":"Mark as read",className:"shrink-0"}),a,!i&&n.jsx(G,{variant:"ghost",size:"touch",icon:o?n.jsx(nt,{className:"size-4 animate-spin"}):n.jsx(rt,{className:"size-4 text-danger"}),onClick:o?void 0:r,"aria-label":"Move selected messages to Trash","aria-busy":o||void 0,className:"ml-4 shrink-0"})]}),f&&n.jsx("div",{className:"px-row-inset pb-2",children:n.jsx(Pa,{value:f.value,max:f.max,tone:f.tone})}),d&&n.jsx(Xt,{tone:d.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-row-inset mb-2",children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.text&&n.jsx("span",{children:d.text}),d.action&&n.jsx(G,{variant:"ghost",size:"md",onClick:d.action.onClick,className:"-my-1 min-h-11 shrink-0",children:d.action.label})]})})]})}function Xl({onLongPress:e,isDisabled:t,delayMs:s=500,accessibilityDescription:r}){const{longPressProps:a}=Pm({isDisabled:t,threshold:s,accessibilityDescription:r,onLongPress:e}),o=c.useRef(""),i=c.useCallback(f=>{o.current=f.pointerType},[]),l=c.useCallback(()=>{o.current=""},[]),u=c.useCallback(f=>{const d=o.current;o.current="",(d==="touch"||d==="pen")&&f.preventDefault()},[]);return{longPressProps:ks(a,{onPointerDown:i,onPointerUp:l,onContextMenu:u})}}const ws=72,Po=10,Lo="__swipeableRowAxisCancel";function $o(e){return e==="leading"?ws:e==="trailing"?-ws:0}function xh(e){return e>=ws/2?"leading":e<=-ws/2?"trailing":"none"}function Jl({thread:e,selectionMode:t,checked:s,active:r,peek:a,onPeek:o,onToggleCheck:i,onLongPress:l,onOpen:u,onAct:f,linkComponent:d}){const m=c.useRef(null),[h,g]=c.useState(null),{longPressProps:v}=Xl({onLongPress:l,isDisabled:t,accessibilityDescription:"Select message"}),p=E=>{const S=new PointerEvent("pointercancel",{bubbles:!0});S[Lo]=!0,E.currentTarget.dispatchEvent(S)},y=ks(v,{onPointerDown:E=>{m.current={startX:E.clientX,startY:E.clientY,axis:"none",moved:!1}},onPointerMove:E=>{if(t)return;const S=m.current;if(!S)return;const A=E.clientX-S.startX,L=E.clientY-S.startY;if(S.axis==="none"){if(Math.abs(L)>Po&&Math.abs(L)>Math.abs(A)){S.axis="vertical",p(E),m.current=null;return}Math.abs(A)>Po&&(S.axis="horizontal",S.moved=!0,p(E),E.currentTarget.setPointerCapture(E.pointerId))}if(S.axis!=="horizontal")return;const T=$o(a),F=Math.max(-ws,Math.min(ws,T+A));g(F)},onPointerUp:()=>{const E=m.current;m.current=null;const S=h;if(g(null),!!E){if(E.axis==="horizontal"&&S!==null){o(xh(S));return}if(t){i();return}if(a!=="none"){o("none");return}d||u()}},onPointerCancel:E=>{E.nativeEvent[Lo]||(m.current=null,g(null))}}),I=E=>{a!=="none"&&E.preventDefault()},N=h??$o(a),k=N>0?"leading":N<0?"trailing":"none",C=H("relative touch-pan-y bg-surface","select-none [-webkit-touch-callout:none]",tn({active:s||r})),M={transform:N!==0?`translateX(${N}px)`:void 0,transition:h===null?"transform 150ms ease":"none",minHeight:44},P=!e.isRead,D=E=>E.stopPropagation(),O=t?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:H("inline-flex size-7 shrink-0 items-center justify-center rounded-full border",s?"border-accent bg-accent text-accent-fg":"border-line-strong bg-canvas"),children:s&&n.jsx(Ys,{className:"size-3.5"})}),n.jsx(Hs,{thread:e})]}):n.jsxs(n.Fragment,{children:[P&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx("button",{type:"button",role:"checkbox","aria-checked":s,"aria-label":`Select message from ${e.fromName}`,onPointerDown:D,onPointerMove:D,onPointerUp:D,onClick:E=>{E.preventDefault(),E.stopPropagation(),l()},className:"-m-2 inline-flex size-11 shrink-0 items-center justify-center rounded-full",children:n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"sm"})}),n.jsx(Hs,{thread:e})]});return n.jsxs("div",{className:"relative overflow-hidden",children:[k==="leading"&&n.jsx("button",{type:"button",onClick:()=>f("leading"),"aria-label":e.isRead?"Mark as unread":"Mark as read",className:"absolute inset-y-0 left-0 flex items-center justify-start bg-accent-2 px-6 text-accent-fg",children:e.isRead?n.jsx(fl,{className:"size-6"}):n.jsx(Cs,{className:"size-6"})}),k==="trailing"&&n.jsx("button",{type:"button",onClick:()=>f("trailing"),"aria-label":"Delete message",className:"absolute inset-y-0 right-0 flex items-center justify-end bg-danger px-6 text-canvas",children:n.jsx(rt,{className:"size-6"})}),d&&!t?d({...y,className:C,style:M,onOpenClick:I,children:O}):n.jsx("button",{type:"button",role:t?"checkbox":void 0,"aria-checked":t?s:void 0,...y,className:C,style:M,children:O})]})}function bh({sections:e,selectedThreadId:t,selectionMode:s,checkedIds:r,initialPeek:a,onToggleCheck:o,onEnterSelection:i,onOpenThread:l,onRefresh:u,refreshing:f,busy:d=!1}){const[m,h]=c.useState(()=>e.flatMap(x=>x.threads)),[g,v]=c.useState(a&&a!=="none"&&m[1]?{id:m[1].id,side:a}:null),p=(x,b)=>{h(b==="trailing"?w=>w.filter(j=>j.id!==x):w=>w.map(j=>j.id===x?{...j,isRead:!j.isRead}:j)),v(null)};return n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[f&&n.jsxs("div",{className:"flex items-center justify-center gap-2 border-b border-line py-3 text-fg-muted",children:[n.jsx(Kl,{className:"size-4 animate-spin"}),n.jsx("span",{className:"text-xs",children:"Checking for new mail…"})]}),n.jsx("div",{className:"divide-y divide-line",children:m.map(x=>n.jsx("div",{className:d?"pointer-events-none opacity-50":void 0,children:n.jsx(Jl,{thread:x,selectionMode:s,checked:r.has(x.id),active:x.id===t,peek:g?.id===x.id?g.side:"none",onPeek:b=>v(b==="none"?null:{id:x.id,side:b}),onToggleCheck:()=>o(x.id),onLongPress:()=>i(x.id),onOpen:()=>l(x.id),onAct:b=>p(x.id,b)})},x.id))}),!s&&!f&&!d&&n.jsx("button",{type:"button",onClick:u,className:"w-full border-t border-line py-2 text-center text-2xs text-fg-subtle transition-colors hover:bg-surface-sunken",children:"Pull to refresh"})]})}function Zl({listTitle:e,listMeta:t,sections:s,briefFilters:r,flatList:a,listState:o="ready",searchQuery:i,listFilter:l,listScopeLabel:u,errorMessage:f,onRetry:d,onReportError:m,briefCategory:h,selectedThreadId:g,density:v="comfortable",onSelectThread:p,onSelectBriefCategory:x,onOpenNav:b,isDesktop:w,initialTouchState:j,selectionBar:y,selectionSheet:I,listBody:N,hideHeader:k=!1}){const C=v==="compact"?fh:mh,M=c.useRef(null);Kn({containerRef:M,itemSelector:ia});const P=!w&&!r&&o==="ready",D=s.flatMap(X=>X.threads),[O,E]=c.useState(j==="selection"),[S,A]=c.useState(()=>j==="selection"?new Set(D.slice(0,2).map(X=>X.id)):new Set),[L,T]=c.useState(!1),F=j==="peek-trailing"?"trailing":j==="peek-leading"?"leading":void 0,R=X=>{A(Q=>{const le=new Set(Q);return le.has(X)?le.delete(X):le.add(X),le.size===0&&E(!1),le})},$=X=>{E(!0),A(new Set([X]))},z=()=>{E(!1),A(new Set)},V=()=>{T(!0),setTimeout(()=>T(!1),1400)},ee=!y&&P&&O&&S.size>0;return n.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[y??(ee?n.jsx(gh,{count:S.size,onCancel:z,onMarkRead:z,onDelete:z}):k?null:n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[b&&n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ca,{className:"size-4"}),onClick:b,"aria-label":"Open folders",className:"-ml-1 shrink-0"}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),t&&n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:t})]})),o==="loading"?n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(ah,{})}):o==="empty"?n.jsx(oh,{filter:l,scopeLabel:u,searchQuery:i}):o==="error"?n.jsx(uh,{message:f,onRetry:d,onReport:m}):r?n.jsx(Qi,{sections:s,briefCategory:h,selectedThreadId:g,Row:C,onSelectThread:p,onSelectBriefCategory:x}):N??(P?n.jsx(bh,{sections:s,selectedThreadId:g,selectionMode:O,checkedIds:S,initialPeek:F,onToggleCheck:R,onEnterSelection:$,onOpenThread:X=>p?.(X),onRefresh:V,refreshing:L}):n.jsx("div",{ref:M,className:"flex-1 overflow-y-auto",children:s.map(X=>n.jsxs("div",{children:[!a&&X.label&&n.jsxs("div",{className:"sticky top-0 flex h-section-row items-center justify-between border-b border-line bg-surface-sunken px-row-inset",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:X.label}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:X.threads.length})]}),n.jsx("div",{className:"divide-y divide-line",children:X.threads.map(Q=>n.jsx(C,{thread:Q,active:Q.id===g,onClick:()=>p?.(Q.id)},Q.id))})]},X.id))})),w&&n.jsx(Wl,{}),I]})}function ec({triggerLabel:e,triggerIcon:t,items:s,align:r="end",touch:a=!0,className:o}){const[i,l]=c.useState(!1),u=c.useRef(null);return c.useEffect(()=>{if(!i)return;const f=m=>{u.current&&!u.current.contains(m.target)&&l(!1)},d=m=>{m.key==="Escape"&&l(!1)};return document.addEventListener("mousedown",f),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",d)}},[i]),s.length===0?null:n.jsxs("div",{ref:u,className:H("relative",o),children:[n.jsx(G,{variant:"ghost",size:"sm",icon:t??n.jsx(_l,{className:"size-5"}),onClick:()=>l(f=>!f),"aria-label":e,"aria-haspopup":"menu","aria-expanded":i,className:H(a&&"min-h-11 min-w-11 px-0")}),i&&n.jsx("div",{role:"menu",className:H("absolute top-full z-50 mt-1 flex min-w-44 flex-col rounded-md border border-line bg-surface py-1 shadow-lg",r==="end"?"right-0":"left-0"),children:s.map(f=>n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{l(!1),f.onSelect()},className:"flex min-h-11 items-center gap-3 px-4 py-2.5 text-left text-sm text-fg transition-colors hover:bg-surface-sunken",children:[f.icon&&n.jsx("span",{className:"shrink-0 text-fg-subtle",children:f.icon}),f.label]},f.key))})]})}const Ds="min-h-11 min-w-11 px-0";function tc({hasThread:e,onReply:t,onReplyAll:s,onForward:r,isStarred:a,onToggleStar:o,onDelete:i,isRead:l,onToggleRead:u,moveSlot:f,overflowItems:d=[],onUnavailable:m,unavailableHint:h,className:g}){const v=(x,b)=>()=>{if(!e){m?.(x);return}b?.()},p=u?[{key:"toggle-read",label:l?"Mark as unread":"Mark as read",icon:l?n.jsx(fl,{className:"size-4"}):n.jsx(Cs,{className:"size-4"}),onSelect:v("toggleRead",u)}]:[];return n.jsxs("div",{className:H("relative",g),children:[n.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-0.5 bg-canvas px-1",children:[n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(ql,{className:"size-5"}),onClick:v("reply",t),"aria-label":"Reply",title:"Reply",className:Ds}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ul,{className:"size-5"}),onClick:v("replyAll",s),"aria-label":"Reply all",title:"Reply all",className:Ds}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(zl,{className:"size-5"}),onClick:v("forward",r),"aria-label":"Forward",title:"Forward",className:Ds}),n.jsx("div",{className:"flex-1"}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(At,{className:H("size-5",a&&"fill-warning text-warning")}),onClick:v("star",o),"aria-label":a?"Unstar":"Star","aria-pressed":a,title:a?"Unstar":"Star",className:Ds}),f,n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(rt,{className:"size-5"}),onClick:v("delete",i),"aria-label":"Move to Trash",title:"Move to Trash",className:Ds}),n.jsx(ec,{triggerLabel:"More actions",items:[...p,...d]})]}),!e&&h&&n.jsx("p",{role:"status",className:"bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:h})]})}function vh({open:e=!1,enabled:t=!0,onToggle:s,className:r}){return n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(la,{className:"size-4"}),title:"Intelligence","aria-label":e?"Hide intelligence sidebar":"Show intelligence sidebar","aria-pressed":e,disabled:!t,onClick:s,className:H(e&&"bg-accent-2-soft text-accent-2",r)})}function yh({hasThread:e,onUnavailable:t,unavailableHint:s,isStarred:r,showTriage:a=!0,onReply:o,onReplyAll:i,onForward:l,onDelete:u,onToggleStar:f,moveSlot:d,onMove:m,replyTitle:h="Reply (r)",replyAllTitle:g="Reply all (a)",forwardTitle:v="Forward (f)",deleteTitle:p="Move to Trash (#)",flagTitle:x="Star (s)",children:b,className:w}){const j=(y,I)=>()=>{if(!e){t?.(y);return}I?.()};return n.jsxs("div",{className:"relative",children:[n.jsxs("header",{className:H("flex h-pane-header shrink-0 items-center gap-1 border-b border-line bg-surface px-3",w),children:[n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(ql,{className:"size-4"}),title:h,"aria-label":"Reply",onClick:j("reply",o)}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ul,{className:"size-4"}),title:g,"aria-label":"Reply all",onClick:j("replyAll",i)}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(zl,{className:"size-4"}),title:v,"aria-label":"Forward",onClick:j("forward",l)}),a&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 h-4 w-px bg-line","aria-hidden":!0}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(rt,{className:"size-4"}),title:p,"aria-label":"Move to Trash",onClick:j("delete",u)}),d??n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ia,{className:"size-4"}),title:"Move to mailbox","aria-label":"Move to mailbox",onClick:j("move",m)}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(At,{className:H("size-4",r&&"fill-warning text-warning")}),title:x,"aria-label":"Star",onClick:j("flag",f)})]}),n.jsx("div",{className:"flex-1"}),b]}),!e&&s&&n.jsx("p",{role:"status",className:"border-b border-line bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:s})]})}const wh=(e,t)=>{const r=e==="newsletter"||e==="marketing"||t;return{framed:r,isPlain:!r}},jh=()=>`
8
+ `.trim(),S.head.prepend(A)},[h]),c.useEffect(()=>{let S=x.current;return()=>{m||Co(S.target??void 0);for(let A of S.disposables)A();S.disposables=[]}},[m]),{isPressed:u||v,pressProps:ks(g,E,{[To]:!0})}}function Da(e){return e.tagName==="A"&&e.hasAttribute("href")}function jr(e,t){const{key:s,code:r}=e,a=t,o=a.getAttribute("role");return(s==="Enter"||s===" "||s==="Spacebar"||r==="Space")&&!(a instanceof Mt(a).HTMLInputElement&&!Pl(a,s)||a instanceof Mt(a).HTMLTextAreaElement||a.isContentEditable)&&!((o==="link"||!o&&Da(a))&&s!=="Enter")}function Ut(e,t){let s=t.clientX,r=t.clientY;return{currentTarget:e,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,altKey:t.altKey,clientX:s,clientY:r,key:t.key}}function Mm(e){return e instanceof HTMLInputElement?!1:e instanceof HTMLButtonElement?e.type!=="submit"&&e.type!=="reset":!Da(e)}function Ro(e,t){return e instanceof HTMLInputElement?!Pl(e,t):Mm(e)}const Am=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function Pl(e,t){return e.type==="checkbox"||e.type==="radio"?t===" ":Am.has(e.type)}let Dm=0;const Sr=new Map;function Om(e){let[t,s]=c.useState();return Ma(()=>{if(!e)return;let r=Sr.get(e);if(r)s(r.element.id);else{let a=`react-aria-description-${Dm++}`;s(a);let o=document.createElement("div");o.id=a,o.style.display="none",o.textContent=e,document.body.appendChild(o),r={refCount:0,element:o},Sr.set(e,r)}return r.refCount++,()=>{r&&--r.refCount===0&&(r.element.remove(),Sr.delete(e))}},[e]),{"aria-describedby":e?t:void 0}}const Pm=500;function Lm(e){let{isDisabled:t,onLongPressStart:s,onLongPressEnd:r,onLongPress:a,threshold:o=Pm,accessibilityDescription:i}=e;const l=c.useRef(void 0);let{addGlobalListener:u,removeGlobalListener:f}=Ol(),{pressProps:d}=Rm({isDisabled:t,onPressStart(h){if(h.continuePropagation(),(h.pointerType==="mouse"||h.pointerType==="touch")&&(s&&s({...h,type:"longpressstart"}),l.current=setTimeout(()=>{h.target.dispatchEvent(new PointerEvent("pointercancel",{bubbles:!0})),It(h.target).activeElement!==h.target&&Us(h.target),a&&a({...h,type:"longpress"}),l.current=void 0},o),h.pointerType==="touch")){let g=p=>{p.preventDefault()},v=Mt(h.target);u(h.target,"contextmenu",g,{once:!0}),u(v,"pointerup",()=>{setTimeout(()=>{f(h.target,"contextmenu",g)},30)},{once:!0})}},onPressEnd(h){l.current&&clearTimeout(l.current),r&&(h.pointerType==="mouse"||h.pointerType==="touch")&&r({...h,type:"longpressend"})}}),m=Om(a&&!t?i:void 0);return{longPressProps:ks(d,m)}}const Ll=fe("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);const $m=fe("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);const Fm=fe("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const Xn=fe("BadgeCheck",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const _m=fe("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);const $l=fe("BellOff",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]]);const zm=fe("BookmarkPlus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"12",x2:"12",y1:"7",y2:"13",key:"1cppfj"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);const Mo=fe("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]);const ys=fe("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const Bm=fe("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);const Fl=fe("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);const _l=fe("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);const zl=fe("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);const Km=fe("Flag",[["path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z",key:"i9b6wo"}],["line",{x1:"4",x2:"4",y1:"22",y2:"15",key:"1cm3nv"}]]);const Bl=fe("Forward",[["polyline",{points:"15 17 20 12 15 7",key:"1w3sku"}],["path",{d:"M4 18v-2a4 4 0 0 1 4-4h12",key:"jmiej9"}]]);const Kl=fe("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);const Um=fe("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);const Cs=fe("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);const qm=fe("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);const Hm=fe("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const Jn=fe("Paperclip",[["path",{d:"M13.234 20.252 21 12.3",key:"1cbrk9"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486",key:"1pkts6"}]]);const Wm=fe("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);const Ul=fe("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);const ql=fe("ReplyAll",[["polyline",{points:"7 17 2 12 7 7",key:"t83bqg"}],["polyline",{points:"12 17 7 12 12 7",key:"1g4ajm"}],["path",{d:"M22 18v-2a4 4 0 0 0-4-4H7",key:"1fcyog"}]]);const Hl=fe("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);const Oa=fe("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const Ns=fe("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);const en=fe("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Vm=fe("ShieldQuestion",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const Qm=fe("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);const Ym=fe("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);const Gm=fe("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]),Xm=({address:e,showTrustedBadge:t=!1})=>{const s=t?n.jsx(Xn,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}):null;return e.displayName?n.jsxs("span",{children:[n.jsx("span",{className:"text-fg",children:e.displayName}),n.jsxs("span",{className:"text-fg-muted",children:[" ","<",e.normalizedEmail,">"]}),s]}):n.jsxs("span",{className:"text-fg",children:[e.normalizedEmail,s]})},Jm=({label:e,addresses:t,showTrustedBadge:s=!1})=>{const[r,a]=c.useState(!1);if(t.length===0)return null;const o=t.length>3,i=l=>{const u=s&&l.flags?.trusted?.value===!0;return n.jsx(Xm,{address:l,showTrustedBadge:u})};return n.jsxs("div",{className:"flex gap-2 text-sm",children:[n.jsxs("span",{className:"text-fg-muted shrink-0 w-12",children:[e,":"]}),n.jsx("div",{className:"flex-1 min-w-0",children:r?n.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((l,u)=>n.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))}):n.jsx("div",{className:"truncate",children:t.map((l,u)=>n.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))})}),o&&n.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),a(!r)},className:"shrink-0 text-fg-muted hover:text-fg transition-colors","aria-label":r?"Collapse":"Expand",children:r?n.jsx(Rt,{className:"h-4 w-4"}):n.jsx(ys,{className:"h-4 w-4"})})]})},Zm=({email:e,displayName:t,onRemove:s,className:r})=>n.jsxs("span",{className:H("inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-accent-2-soft text-sm max-w-[200px]",r),children:[n.jsx("span",{className:"truncate",children:t||e}),n.jsx("button",{type:"button",onClick:s,className:"shrink-0 p-0.5 rounded-full hover:bg-fg-muted/20 transition-colors","aria-label":`Remove ${e}`,children:n.jsx(We,{className:"size-3"})})]}),eh={unknown:{label:"Unknown sender",tone:"neutral"},wellknown:{label:"Known sender",tone:"positive"},vip:{label:"VIP",tone:"accent"}};function as({label:e,children:t,className:s}){return n.jsxs("section",{className:H("border-b border-line px-row-inset py-3",s),children:[n.jsx("h3",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),n.jsx("div",{className:"mt-2",children:t})]})}function th({sender:e}){const t=eh[e.trust],s=e.inboundCount==null?null:(e.replyCount??0)>0?`${e.inboundCount} received · you replied ${e.replyCount}×`:`${e.inboundCount} received · you've never replied`;return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(dt,{name:e.name,email:e.email,size:"md"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"truncate text-sm font-semibold text-fg",children:e.name}),n.jsx("div",{className:"truncate text-2xs text-fg-subtle",children:e.email})]})]}),n.jsx("div",{className:"mt-2 flex items-center gap-2",children:e.addressUnverified?n.jsx(lt,{tone:"danger",dot:!0,children:"Address couldn't be verified"}):n.jsx(lt,{tone:t.tone,dot:!0,children:t.label})}),n.jsxs("p",{className:"mt-2 text-xs text-fg-muted",children:["First seen ",e.firstSeenLabel,s?` · ${s}`:""]})]})}function sh({auth:e,onShowSimilar:t}){if(e.verdict==="aligned")return n.jsxs("div",{className:"flex items-start gap-2 text-xs text-fg-muted",children:[n.jsx(en,{className:"mt-0.5 size-3.5 shrink-0 text-positive"}),n.jsx("span",{children:e.summary})]});if(e.verdict==="caution")return n.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-warning/10 p-3 text-warning",children:[n.jsx(Vm,{className:"mt-0.5 size-4 shrink-0"}),n.jsx("p",{className:"text-xs leading-relaxed",children:e.summary})]});const s=e.addressUnreadable?"This sender can't be verified":"This message may be impersonating someone";return n.jsxs("div",{className:"rounded-md bg-danger-soft p-3",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(Ns,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"text-sm font-semibold text-danger",children:s}),n.jsx("p",{className:"mt-1 text-xs leading-relaxed text-fg",children:e.summary}),!e.addressUnreadable&&e.dkimDomain&&n.jsxs("p",{className:"mt-1 text-2xs text-fg-muted",children:["Sent from"," ",n.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.dkimDomain}),", claims to be"," ",n.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.fromDomain})]})]})]}),e.similarCount!=null&&e.similarCount>0&&n.jsxs(G,{variant:"secondary",size:"sm",className:"mt-2 w-full border-danger/30 text-danger hover:bg-danger-soft",onClick:t,children:[e.similarCount," similar messages"]})]})}function os({icon:e,label:t,active:s,danger:r,onClick:a}){const o=a===void 0;return n.jsxs("button",{type:"button",onClick:a,disabled:o,className:H("flex items-center gap-2 rounded-md border px-2 py-1 text-xs transition-colors",s?"border-accent-2 bg-accent-2-soft text-accent-2":"border-line text-fg-muted hover:border-line-strong hover:text-fg",r&&!s&&"text-danger hover:bg-danger-soft",o&&"cursor-not-allowed opacity-50 hover:border-line"),children:[e,t]})}const nh={sender:"matched: sender",recipient:"matched: recipient",subject:"matched: subject",attachment:"matched: attachment",body:"matched: body",entities:"matched: entities"};function Wl({data:e,onClose:t,onShowSimilar:s,actions:r,similarState:a="ready",similarLinkComponent:o,className:i,hideCloseButton:l=!1}){const{sender:u,authenticity:f,category:d,flags:m={},similar:h}=e,g=f.verdict==="mismatch";return n.jsxs("aside",{className:H("flex w-76 shrink-0 flex-col overflow-y-auto border-l border-line bg-surface",i),children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center justify-between border-b border-line px-row-inset",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"}),!l&&n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(We,{className:"size-3.5"}),onClick:t,"aria-label":"Collapse intelligence sidebar"})]}),n.jsx(as,{label:"Sender",children:n.jsx(th,{sender:u})}),n.jsx(as,{label:"Authenticity",children:n.jsx(sh,{auth:f,onShowSimilar:s})}),n.jsx(as,{label:"Category",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(lt,{tone:g?"danger":"neutral",children:d.value}),d.overridden&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"your override"}),n.jsx("button",{type:"button",className:H("ml-auto text-2xs text-accent hover:underline",!r?.onReclassify&&"cursor-not-allowed opacity-50 hover:no-underline"),disabled:!r?.onReclassify,onClick:r?.onReclassify,children:"reclassify"})]})}),n.jsx(as,{label:"Quick actions",children:n.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[n.jsx(os,{icon:n.jsx(At,{className:"size-3.5"}),label:"VIP",active:m.vip,onClick:r?.onToggleVip}),n.jsx(os,{icon:n.jsx($l,{className:"size-3.5"}),label:"Mute",active:m.muted,onClick:r?.onToggleMute}),n.jsx(os,{icon:n.jsx(_m,{className:"size-3.5"}),label:"Block",active:m.blocked,danger:!0,onClick:r?.onToggleBlock}),n.jsx(os,{icon:n.jsx(qm,{className:"size-3.5"}),label:"Unsubscribe",active:m.unsubscribed,onClick:r?.onToggleUnsubscribe}),r?.onNotSpam&&n.jsx(os,{icon:n.jsx(Um,{className:"size-3.5"}),label:"Not spam",onClick:r.onNotSpam}),r?.onMarkSpam&&n.jsx(os,{icon:n.jsx(Qm,{className:"size-3.5"}),label:"Mark spam",danger:!0,onClick:r.onMarkSpam})]})}),(a!=="ready"||h.length>0)&&n.jsx(as,{label:"Similar messages",children:a==="loading"?n.jsx("div",{className:"animate-pulse space-y-2",children:Array.from({length:3}).map((v,p)=>n.jsxs("div",{className:"space-y-1",children:[n.jsx("div",{className:"h-3 w-3/4 rounded bg-surface-sunken"}),n.jsx("div",{className:"h-2.5 w-1/2 rounded bg-surface-sunken"})]},p))}):a==="error"?n.jsx("p",{className:"text-xs text-fg-subtle",children:"Similarity search unavailable"}):n.jsx("ul",{className:"-mx-1 space-y-1",children:h.map(v=>{const p="block w-full rounded-md px-1 py-1 text-left hover:bg-surface-sunken",x=`Open message from ${v.fromName||"unknown sender"}: ${v.subject}`,b=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[n.jsx("span",{className:"truncate text-xs font-medium text-fg",children:v.fromName}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:v.timeLabel})]}),n.jsx("div",{className:"truncate text-xs text-fg-muted",children:v.subject}),n.jsx("span",{className:"mt-1 inline-block rounded-full bg-surface-sunken px-1.5 py-px text-2xs text-fg-subtle",children:nh[v.matched]})]});return n.jsx("li",{children:o?o({mailboxId:v.mailboxId,messageId:v.id,className:p,ariaLabel:x,children:b}):n.jsx("div",{className:p,children:b})},v.id)})})}),n.jsx(as,{label:"Coming soon",className:"border-b-0 opacity-70",children:n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[n.jsx(ut,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Suggested actions"}),n.jsx("div",{className:"text-2xs text-fg-subtle",children:'"Create a filter for messages like this" — on-device model'})]})]}),n.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[n.jsx(ut,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Thread summary"}),n.jsx("div",{className:"text-2xs text-fg-subtle",children:"One-paragraph digest — Bedrock"})]})]})]})})]})}const rh=[{keys:["j","k"],label:"navigate"},{keys:["m"],label:"mute"},{keys:["?"],label:"all shortcuts"}];function Vl({hints:e=rh,className:t}){return n.jsx("footer",{className:H("flex items-center gap-2 border-t border-line px-row-inset py-1 text-2xs text-fg-subtle",t),children:e.map(s=>n.jsx(ah,{hint:s},s.label))})}function ah({hint:e}){return n.jsxs("span",{className:"flex items-center gap-1",children:[e.keys.map(t=>n.jsx(ps,{children:t},t)),n.jsx("span",{children:e.label})]})}function oh(){return n.jsx("div",{className:"space-y-0",role:"status","aria-busy":"true","aria-label":"Loading messages",children:Array.from({length:8}).map((e,t)=>n.jsxs("div",{className:"animate-pulse border-b border-line px-3 py-2",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[n.jsx("div",{className:"h-4 w-32 rounded bg-surface-sunken"}),n.jsx("div",{className:"h-3 w-16 rounded bg-surface-sunken"})]}),n.jsx("div",{className:"mb-2 h-4 w-48 rounded bg-surface-sunken"}),n.jsx("div",{className:"h-3 w-full rounded bg-surface-sunken"})]},t))})}function ih({filter:e,scopeLabel:t,searchQuery:s}){const r=s?.trim();return e?n.jsxs(Ao,{children:[n.jsx("p",{className:"font-medium text-fg",children:uh(e.label,t,r)}),n.jsx("p",{className:"mt-1 text-sm text-fg-muted",children:lh[e.reach]}),n.jsx(G,{variant:"secondary",size:"sm",className:"mt-4",onClick:e.onClear,children:"Clear filter"})]}):n.jsx(Ao,{children:n.jsx("p",{className:"text-fg-muted",children:ch(r,t)})})}const lh={"whole-folder":"Every message in this folder was checked.","loaded-pages":"Only the messages loaded so far were checked."};function ch(e,t){return e?"No messages match your search":t?`No messages in ${t}`:"No messages in this mailbox"}function uh(e,t,s){return s?`No results for “${s}” in ${e}`:t?`No ${e} mail in ${t}`:`No ${e} mail`}function Ao({children:e}){return n.jsx("div",{className:"flex h-full flex-1 items-center justify-center",children:n.jsx("div",{className:"flex max-w-sm flex-col items-center justify-center p-8 text-center",children:e})})}function dh({message:e="Something went wrong loading this mailbox.",onRetry:t,onReport:s}){return n.jsx("div",{className:"flex h-full flex-1 items-center justify-center p-4",children:n.jsxs("div",{role:"alert",className:"flex max-w-sm flex-col items-center justify-center gap-3 text-center",children:[n.jsx(Gt,{className:"size-8 text-danger","aria-hidden":"true"}),n.jsxs("div",{children:[n.jsx("p",{className:"font-medium text-danger",children:"Couldn't load messages"}),n.jsx("p",{className:"mt-1 break-words text-sm text-fg-muted",children:e})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[t&&n.jsx(G,{variant:"secondary",size:"sm",onClick:t,children:"Retry"}),s&&n.jsx(G,{variant:"ghost",size:"sm",onClick:s,children:"Report a problem"})]})]})})}const Ql="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",Yl=({active:e,focused:t})=>H("relative flex h-8 w-full items-center gap-2 px-row-inset text-left",Ql,e?"bg-accent-2-soft":t?"bg-surface-sunken":"hover:bg-surface-sunken",t&&!e&&"before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-accent-2"),tn=({active:e,focused:t})=>H("relative flex w-full items-start gap-3 py-2 pl-5 pr-row-inset text-left transition-colors",Ql,e?"bg-accent-2-soft":t?"bg-surface-sunken":"hover:bg-surface-sunken",t&&!e&&"before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-accent-2");function Gl({thread:e}){const t=!e.isRead;return n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex w-4 shrink-0 items-center justify-center",children:e.suspicious?n.jsx(Ns,{className:"size-3.5 text-danger"}):e.starred?n.jsx(At,{className:"size-3 fill-warning text-warning"}):t?n.jsx("span",{className:"size-1.5 rounded-full bg-accent"}):null}),n.jsx("span",{className:H("w-36 shrink-0 truncate text-xs",t?"font-semibold text-fg":"text-fg-muted"),children:e.fromName}),n.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs",children:[n.jsx("span",{className:H(t?"font-medium text-fg":"text-fg-muted"),children:e.subject}),n.jsxs("span",{className:"text-fg-subtle",children:[" — ",e.snippet]})]}),e.hasAttachment&&n.jsx(Jn,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"w-11 shrink-0 text-right text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]})}function Hs({thread:e,badge:t}){const s=!e.isRead;return n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsxs("span",{className:"flex items-baseline justify-between gap-2",children:[n.jsxs("span",{className:H("flex min-w-0 items-center gap-1.5 truncate text-sm",s?"font-semibold text-fg":"font-medium text-fg-muted"),children:[e.trust==="vip"&&n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-accent-2"}),n.jsx("span",{className:"truncate",children:e.fromName}),e.messageCount!=null&&e.messageCount>1&&n.jsx("span",{className:"shrink-0 text-2xs font-normal text-fg-subtle",children:e.messageCount})]}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]}),n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:H("truncate text-sm",s?"text-fg":"text-fg-muted"),children:e.subject}),e.suspicious&&n.jsx(Ns,{className:"size-3.5 shrink-0 text-danger"}),e.starred&&n.jsx(At,{className:"size-3 shrink-0 fill-warning text-warning"}),e.hasAttachment&&n.jsx(Jn,{className:"size-3 shrink-0 text-fg-subtle"})]}),n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"line-clamp-1 min-w-0 flex-1 text-xs text-fg-subtle",children:e.snippet}),e.category&&e.category!=="personal"&&n.jsx(lt,{tone:Pd[e.category],className:"shrink-0",children:e.category}),e.labels?.map(r=>n.jsx(Ld,{label:r,className:"max-w-20"},r.labelId)),t]})]})}function fh({thread:e,selection:t}){if(!t)return n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"sm"});const{checked:s,alwaysVisible:r}=t;return n.jsxs("span",{className:"relative size-7 shrink-0",children:[n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"sm",className:H("absolute inset-0 transition-opacity sm:group-hover:opacity-0",(s||r)&&"opacity-0")}),n.jsx("span",{role:"button",tabIndex:-1,onClick:t.onToggle,onKeyDown:a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),a.stopPropagation(),t.onToggle(a))},className:H("absolute inset-0 size-7 items-center justify-center rounded-full border transition-opacity",r?"flex":"hidden sm:flex",s?"bg-accent border-accent text-accent-fg opacity-100":r?"border-fg-subtle/40 bg-canvas opacity-100":"border-fg-subtle/40 bg-canvas opacity-0 group-hover:opacity-100"),"aria-label":s?"Deselect message":"Select message",children:s&&n.jsx(Ys,{className:"size-3"})})]})}function Xl({thread:e,selection:t,badge:s}){const r=!e.isRead;return n.jsxs(n.Fragment,{children:[r&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx(fh,{thread:e,selection:t}),n.jsx(Hs,{thread:e,badge:s})]})}function mh({thread:e,active:t,focused:s,onClick:r}){return n.jsx("button",{type:"button",...oa,onClick:r,className:Yl({active:t,focused:s}),children:n.jsx(Gl,{thread:e})})}function hh({thread:e,active:t,focused:s,selection:r,onClick:a}){return n.jsx("button",{type:"button",...oa,onClick:a,className:H("group",tn({active:t,focused:s})),children:n.jsx(Xl,{thread:e,selection:r})})}const ph="peer relative size-5 shrink-0 cursor-pointer appearance-none rounded-md border border-line-strong bg-surface outline-none transition-colors checked:border-positive checked:bg-positive indeterminate:border-positive indeterminate:bg-positive focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface",Do="pointer-events-none absolute inset-0 m-auto size-3.5 text-accent-fg";function sn({label:e,description:t,indeterminate:s=!1,checked:r,onChange:a,className:o,...i}){const l=c.useRef(null);c.useEffect(()=>{l.current&&(l.current.indeterminate=s)},[s]);const u=n.jsxs("span",{className:"relative inline-flex",children:[n.jsx("input",{ref:l,type:"checkbox",checked:r,onChange:a,className:ph,...i}),n.jsx(Ys,{className:H(Do,"hidden peer-checked:block"),"aria-hidden":!0}),n.jsx(Hm,{className:H(Do,"hidden peer-indeterminate:block"),"aria-hidden":!0})]});return e===void 0&&t===void 0?n.jsx("span",{className:o,children:u}):n.jsxs("label",{className:H("flex min-h-11 cursor-pointer items-center gap-3 text-left",o),children:[u,n.jsxs("span",{className:"flex min-w-0 flex-col",children:[e!==void 0&&n.jsx("span",{className:"text-sm text-fg",children:e}),t!==void 0&&n.jsx("span",{className:"text-xs text-fg-subtle",children:t})]})]})}const gh={info:"bg-accent-2",success:"bg-positive",warning:"bg-warning",danger:"bg-danger"};function Pa({value:e,max:t,tone:s="info",indeterminate:r=!1,className:a}){const o=r?100:t<=0?0:Math.min(100,Math.max(0,e/t*100));return n.jsx("div",{role:"progressbar","aria-valuenow":r?void 0:e,"aria-valuemin":r?void 0:0,"aria-valuemax":r?void 0:t,className:H("h-1.5 w-full overflow-hidden rounded-full bg-surface-sunken",a),children:n.jsx("div",{className:H("h-full rounded-full transition-[width] duration-300 ease-out",gh[s],r&&"w-1/3 animate-pulse"),style:r?void 0:{width:`${o}%`}})})}const Oo=e=>e.toLocaleString();function xh({count:e,onCancel:t,onMarkRead:s,onDelete:r,moveSlot:a,isBusy:o=!1,isCounting:i=!1,selectAll:l,statusLabel:u,progress:f,notice:d}){const m=l?.checked?`All ${Oo(e)} loaded selected`:`${Oo(e)} ${e===1?"message":"messages"} selected`;return n.jsxs("header",{className:"flex shrink-0 flex-col border-b border-line bg-surface-sunken",children:[n.jsxs("div",{className:"flex h-pane-header items-center gap-2 px-row-inset",children:[n.jsx(G,{variant:"ghost",size:"touch",icon:n.jsx(We,{className:"size-4"}),onClick:t,"aria-label":"Cancel selection",className:"-ml-2 shrink-0"}),l&&n.jsx("label",{className:"-ml-1.5 flex size-11 shrink-0 cursor-pointer items-center justify-center",children:n.jsx(sn,{"aria-label":"Select all",checked:l.checked,indeterminate:l.indeterminate,onChange:l.onChange})}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-fg",role:"status","aria-live":"polite",children:u??m}),s&&!o&&n.jsx(G,{variant:"ghost",size:"touch",icon:n.jsx(Cs,{className:"size-4"}),onClick:s,"aria-label":"Mark as read",className:"shrink-0"}),a,!i&&n.jsx(G,{variant:"ghost",size:"touch",icon:o?n.jsx(nt,{className:"size-4 animate-spin"}):n.jsx(rt,{className:"size-4 text-danger"}),onClick:o?void 0:r,"aria-label":"Move selected messages to Trash","aria-busy":o||void 0,className:"ml-4 shrink-0"})]}),f&&n.jsx("div",{className:"px-row-inset pb-2",children:n.jsx(Pa,{value:f.value,max:f.max,tone:f.tone})}),d&&n.jsx(Xt,{tone:d.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-row-inset mb-2",children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.text&&n.jsx("span",{children:d.text}),d.action&&n.jsx(G,{variant:"ghost",size:"md",onClick:d.action.onClick,className:"-my-1 min-h-11 shrink-0",children:d.action.label})]})})]})}function Jl({onLongPress:e,isDisabled:t,delayMs:s=500,accessibilityDescription:r}){const{longPressProps:a}=Lm({isDisabled:t,threshold:s,accessibilityDescription:r,onLongPress:e}),o=c.useRef(""),i=c.useCallback(f=>{o.current=f.pointerType},[]),l=c.useCallback(()=>{o.current=""},[]),u=c.useCallback(f=>{const d=o.current;o.current="",(d==="touch"||d==="pen")&&f.preventDefault()},[]);return{longPressProps:ks(a,{onPointerDown:i,onPointerUp:l,onContextMenu:u})}}const ws=72,Po=10,Lo="__swipeableRowAxisCancel";function $o(e){return e==="leading"?ws:e==="trailing"?-ws:0}function bh(e){return e>=ws/2?"leading":e<=-ws/2?"trailing":"none"}function Zl({thread:e,selectionMode:t,checked:s,active:r,peek:a,onPeek:o,onToggleCheck:i,onLongPress:l,onOpen:u,onAct:f,linkComponent:d}){const m=c.useRef(null),[h,g]=c.useState(null),{longPressProps:v}=Jl({onLongPress:l,isDisabled:t,accessibilityDescription:"Select message"}),p=E=>{const S=new PointerEvent("pointercancel",{bubbles:!0});S[Lo]=!0,E.currentTarget.dispatchEvent(S)},y=ks(v,{onPointerDown:E=>{m.current={startX:E.clientX,startY:E.clientY,axis:"none",moved:!1}},onPointerMove:E=>{if(t)return;const S=m.current;if(!S)return;const A=E.clientX-S.startX,L=E.clientY-S.startY;if(S.axis==="none"){if(Math.abs(L)>Po&&Math.abs(L)>Math.abs(A)){S.axis="vertical",p(E),m.current=null;return}Math.abs(A)>Po&&(S.axis="horizontal",S.moved=!0,p(E),E.currentTarget.setPointerCapture(E.pointerId))}if(S.axis!=="horizontal")return;const T=$o(a),F=Math.max(-ws,Math.min(ws,T+A));g(F)},onPointerUp:()=>{const E=m.current;m.current=null;const S=h;if(g(null),!!E){if(E.axis==="horizontal"&&S!==null){o(bh(S));return}if(t){i();return}if(a!=="none"){o("none");return}d||u()}},onPointerCancel:E=>{E.nativeEvent[Lo]||(m.current=null,g(null))}}),I=E=>{a!=="none"&&E.preventDefault()},N=h??$o(a),k=N>0?"leading":N<0?"trailing":"none",C=H("relative touch-pan-y bg-surface","select-none [-webkit-touch-callout:none]",tn({active:s||r})),M={transform:N!==0?`translateX(${N}px)`:void 0,transition:h===null?"transform 150ms ease":"none",minHeight:44},P=!e.isRead,D=E=>E.stopPropagation(),O=t?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:H("inline-flex size-7 shrink-0 items-center justify-center rounded-full border",s?"border-accent bg-accent text-accent-fg":"border-line-strong bg-canvas"),children:s&&n.jsx(Ys,{className:"size-3.5"})}),n.jsx(Hs,{thread:e})]}):n.jsxs(n.Fragment,{children:[P&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx("button",{type:"button",role:"checkbox","aria-checked":s,"aria-label":`Select message from ${e.fromName}`,onPointerDown:D,onPointerMove:D,onPointerUp:D,onClick:E=>{E.preventDefault(),E.stopPropagation(),l()},className:"-m-2 inline-flex size-11 shrink-0 items-center justify-center rounded-full",children:n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"sm"})}),n.jsx(Hs,{thread:e})]});return n.jsxs("div",{className:"relative overflow-hidden",children:[k==="leading"&&n.jsx("button",{type:"button",onClick:()=>f("leading"),"aria-label":e.isRead?"Mark as unread":"Mark as read",className:"absolute inset-y-0 left-0 flex items-center justify-start bg-accent-2 px-6 text-accent-fg",children:e.isRead?n.jsx(ml,{className:"size-6"}):n.jsx(Cs,{className:"size-6"})}),k==="trailing"&&n.jsx("button",{type:"button",onClick:()=>f("trailing"),"aria-label":"Delete message",className:"absolute inset-y-0 right-0 flex items-center justify-end bg-danger px-6 text-canvas",children:n.jsx(rt,{className:"size-6"})}),d&&!t?d({...y,className:C,style:M,onOpenClick:I,children:O}):n.jsx("button",{type:"button",role:t?"checkbox":void 0,"aria-checked":t?s:void 0,...y,className:C,style:M,children:O})]})}function vh({sections:e,selectedThreadId:t,selectionMode:s,checkedIds:r,initialPeek:a,onToggleCheck:o,onEnterSelection:i,onOpenThread:l,onRefresh:u,refreshing:f,busy:d=!1}){const[m,h]=c.useState(()=>e.flatMap(x=>x.threads)),[g,v]=c.useState(a&&a!=="none"&&m[1]?{id:m[1].id,side:a}:null),p=(x,b)=>{h(b==="trailing"?w=>w.filter(j=>j.id!==x):w=>w.map(j=>j.id===x?{...j,isRead:!j.isRead}:j)),v(null)};return n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[f&&n.jsxs("div",{className:"flex items-center justify-center gap-2 border-b border-line py-3 text-fg-muted",children:[n.jsx(Ul,{className:"size-4 animate-spin"}),n.jsx("span",{className:"text-xs",children:"Checking for new mail…"})]}),n.jsx("div",{className:"divide-y divide-line",children:m.map(x=>n.jsx("div",{className:d?"pointer-events-none opacity-50":void 0,children:n.jsx(Zl,{thread:x,selectionMode:s,checked:r.has(x.id),active:x.id===t,peek:g?.id===x.id?g.side:"none",onPeek:b=>v(b==="none"?null:{id:x.id,side:b}),onToggleCheck:()=>o(x.id),onLongPress:()=>i(x.id),onOpen:()=>l(x.id),onAct:b=>p(x.id,b)})},x.id))}),!s&&!f&&!d&&n.jsx("button",{type:"button",onClick:u,className:"w-full border-t border-line py-2 text-center text-2xs text-fg-subtle transition-colors hover:bg-surface-sunken",children:"Pull to refresh"})]})}function ec({listTitle:e,listMeta:t,sections:s,briefFilters:r,flatList:a,listState:o="ready",searchQuery:i,listFilter:l,listScopeLabel:u,errorMessage:f,onRetry:d,onReportError:m,briefCategory:h,selectedThreadId:g,density:v="comfortable",onSelectThread:p,onSelectBriefCategory:x,onOpenNav:b,isDesktop:w,initialTouchState:j,selectionBar:y,selectionSheet:I,listBody:N,hideHeader:k=!1}){const C=v==="compact"?mh:hh,M=c.useRef(null);Kn({containerRef:M,itemSelector:ia});const P=!w&&!r&&o==="ready",D=s.flatMap(X=>X.threads),[O,E]=c.useState(j==="selection"),[S,A]=c.useState(()=>j==="selection"?new Set(D.slice(0,2).map(X=>X.id)):new Set),[L,T]=c.useState(!1),F=j==="peek-trailing"?"trailing":j==="peek-leading"?"leading":void 0,R=X=>{A(Q=>{const le=new Set(Q);return le.has(X)?le.delete(X):le.add(X),le.size===0&&E(!1),le})},$=X=>{E(!0),A(new Set([X]))},z=()=>{E(!1),A(new Set)},V=()=>{T(!0),setTimeout(()=>T(!1),1400)},ee=!y&&P&&O&&S.size>0;return n.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[y??(ee?n.jsx(xh,{count:S.size,onCancel:z,onMarkRead:z,onDelete:z}):k?null:n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[b&&n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ca,{className:"size-4"}),onClick:b,"aria-label":"Open folders",className:"-ml-1 shrink-0"}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),t&&n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:t})]})),o==="loading"?n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(oh,{})}):o==="empty"?n.jsx(ih,{filter:l,scopeLabel:u,searchQuery:i}):o==="error"?n.jsx(dh,{message:f,onRetry:d,onReport:m}):r?n.jsx(Yi,{sections:s,briefCategory:h,selectedThreadId:g,Row:C,onSelectThread:p,onSelectBriefCategory:x}):N??(P?n.jsx(vh,{sections:s,selectedThreadId:g,selectionMode:O,checkedIds:S,initialPeek:F,onToggleCheck:R,onEnterSelection:$,onOpenThread:X=>p?.(X),onRefresh:V,refreshing:L}):n.jsx("div",{ref:M,className:"flex-1 overflow-y-auto",children:s.map(X=>n.jsxs("div",{children:[!a&&X.label&&n.jsxs("div",{className:"sticky top-0 flex h-section-row items-center justify-between border-b border-line bg-surface-sunken px-row-inset",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:X.label}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:X.threads.length})]}),n.jsx("div",{className:"divide-y divide-line",children:X.threads.map(Q=>n.jsx(C,{thread:Q,active:Q.id===g,onClick:()=>p?.(Q.id)},Q.id))})]},X.id))})),w&&n.jsx(Vl,{}),I]})}function tc({triggerLabel:e,triggerIcon:t,items:s,align:r="end",touch:a=!0,className:o}){const[i,l]=c.useState(!1),u=c.useRef(null);return c.useEffect(()=>{if(!i)return;const f=m=>{u.current&&!u.current.contains(m.target)&&l(!1)},d=m=>{m.key==="Escape"&&l(!1)};return document.addEventListener("mousedown",f),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",d)}},[i]),s.length===0?null:n.jsxs("div",{ref:u,className:H("relative",o),children:[n.jsx(G,{variant:"ghost",size:"sm",icon:t??n.jsx(zl,{className:"size-5"}),onClick:()=>l(f=>!f),"aria-label":e,"aria-haspopup":"menu","aria-expanded":i,className:H(a&&"min-h-11 min-w-11 px-0")}),i&&n.jsx("div",{role:"menu",className:H("absolute top-full z-50 mt-1 flex min-w-44 flex-col rounded-md border border-line bg-surface py-1 shadow-lg",r==="end"?"right-0":"left-0"),children:s.map(f=>n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{l(!1),f.onSelect()},className:"flex min-h-11 items-center gap-3 px-4 py-2.5 text-left text-sm text-fg transition-colors hover:bg-surface-sunken",children:[f.icon&&n.jsx("span",{className:"shrink-0 text-fg-subtle",children:f.icon}),f.label]},f.key))})]})}const Ds="min-h-11 min-w-11 px-0";function sc({hasThread:e,onReply:t,onReplyAll:s,onForward:r,isStarred:a,onToggleStar:o,onDelete:i,isRead:l,onToggleRead:u,moveSlot:f,overflowItems:d=[],onUnavailable:m,unavailableHint:h,className:g}){const v=(x,b)=>()=>{if(!e){m?.(x);return}b?.()},p=u?[{key:"toggle-read",label:l?"Mark as unread":"Mark as read",icon:l?n.jsx(ml,{className:"size-4"}):n.jsx(Cs,{className:"size-4"}),onSelect:v("toggleRead",u)}]:[];return n.jsxs("div",{className:H("relative",g),children:[n.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-0.5 bg-canvas px-1",children:[n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Hl,{className:"size-5"}),onClick:v("reply",t),"aria-label":"Reply",title:"Reply",className:Ds}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(ql,{className:"size-5"}),onClick:v("replyAll",s),"aria-label":"Reply all",title:"Reply all",className:Ds}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Bl,{className:"size-5"}),onClick:v("forward",r),"aria-label":"Forward",title:"Forward",className:Ds}),n.jsx("div",{className:"flex-1"}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(At,{className:H("size-5",a&&"fill-warning text-warning")}),onClick:v("star",o),"aria-label":a?"Unstar":"Star","aria-pressed":a,title:a?"Unstar":"Star",className:Ds}),f,n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(rt,{className:"size-5"}),onClick:v("delete",i),"aria-label":"Move to Trash",title:"Move to Trash",className:Ds}),n.jsx(tc,{triggerLabel:"More actions",items:[...p,...d]})]}),!e&&h&&n.jsx("p",{role:"status",className:"bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:h})]})}function yh({open:e=!1,enabled:t=!0,onToggle:s,className:r}){return n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(la,{className:"size-4"}),title:"Intelligence","aria-label":e?"Hide intelligence sidebar":"Show intelligence sidebar","aria-pressed":e,disabled:!t,onClick:s,className:H(e&&"bg-accent-2-soft text-accent-2",r)})}function wh({hasThread:e,onUnavailable:t,unavailableHint:s,isStarred:r,showTriage:a=!0,onReply:o,onReplyAll:i,onForward:l,onDelete:u,onToggleStar:f,moveSlot:d,onMove:m,replyTitle:h="Reply (r)",replyAllTitle:g="Reply all (a)",forwardTitle:v="Forward (f)",deleteTitle:p="Move to Trash (#)",flagTitle:x="Star (s)",children:b,className:w}){const j=(y,I)=>()=>{if(!e){t?.(y);return}I?.()};return n.jsxs("div",{className:"relative",children:[n.jsxs("header",{className:H("flex h-pane-header shrink-0 items-center gap-1 border-b border-line bg-surface px-3",w),children:[n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Hl,{className:"size-4"}),title:h,"aria-label":"Reply",onClick:j("reply",o)}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(ql,{className:"size-4"}),title:g,"aria-label":"Reply all",onClick:j("replyAll",i)}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Bl,{className:"size-4"}),title:v,"aria-label":"Forward",onClick:j("forward",l)}),a&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 h-4 w-px bg-line","aria-hidden":!0}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(rt,{className:"size-4"}),title:p,"aria-label":"Move to Trash",onClick:j("delete",u)}),d??n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ia,{className:"size-4"}),title:"Move to mailbox","aria-label":"Move to mailbox",onClick:j("move",m)}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(At,{className:H("size-4",r&&"fill-warning text-warning")}),title:x,"aria-label":"Star",onClick:j("flag",f)})]}),n.jsx("div",{className:"flex-1"}),b]}),!e&&s&&n.jsx("p",{role:"status",className:"border-b border-line bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:s})]})}const jh=(e,t)=>{const r=e==="newsletter"||e==="marketing"||t;return{framed:r,isPlain:!r}},Sh=()=>`
9
9
  /* Zero the UA default body margin and clamp the document to the iframe width so
10
10
  wide author markup can't push the body (and the page) past the viewport. */
11
11
  html, body {
@@ -43,17 +43,17 @@ pre, code {
43
43
  overflow-wrap: anywhere;
44
44
  word-break: break-word;
45
45
  }
46
- `,Sh=e=>{const t=new Map;for(const s of e){if(!s.contentId||s.contentUrl.length===0)continue;const r=s.contentId.replace(/^<|>$/g,"");t.set(r,s.contentUrl)}return s=>t.get(s.replace(/^<|>$/g,""))},kh=/^(none|transparent|inherit|initial|unset)\s*$/i,Ch=e=>{const t=[],s=/<style[^>]*>([\s\S]*?)<\/style>/gi;let r;for(r=s.exec(e);r!==null;)t.push(r[1]),r=s.exec(e);return t},Nh=e=>{const t=/background(?:-color)?\s*:\s*([^;}\n]+)/gi;let s;for(s=t.exec(e);s!==null;){const r=s[1].trim();if(!kh.test(r))return!0;s=t.exec(e)}return!1},Eh=e=>{if(/\bstyle\s*=\s*["'][^"']*background/i.test(e)||/\bbgcolor\s*=/i.test(e))return!0;for(const t of Ch(e))if(Nh(t))return!0;return!1},Ih=["script","iframe","object","embed","form","input","button","textarea","select","meta","link","base"],Th=["onerror","onload","onclick","onmouseover","onmouseout","onfocus","onblur","onsubmit","onkeydown","onkeyup","formaction","xlink:href","data-bind"],Rh="data:image/svg+xml,"+encodeURIComponent(`
46
+ `,kh=e=>{const t=new Map;for(const s of e){if(!s.contentId||s.contentUrl.length===0)continue;const r=s.contentId.replace(/^<|>$/g,"");t.set(r,s.contentUrl)}return s=>t.get(s.replace(/^<|>$/g,""))},Ch=/^(none|transparent|inherit|initial|unset)\s*$/i,Nh=e=>{const t=[],s=/<style[^>]*>([\s\S]*?)<\/style>/gi;let r;for(r=s.exec(e);r!==null;)t.push(r[1]),r=s.exec(e);return t},Eh=e=>{const t=/background(?:-color)?\s*:\s*([^;}\n]+)/gi;let s;for(s=t.exec(e);s!==null;){const r=s[1].trim();if(!Ch.test(r))return!0;s=t.exec(e)}return!1},Ih=e=>{if(/\bstyle\s*=\s*["'][^"']*background/i.test(e)||/\bbgcolor\s*=/i.test(e))return!0;for(const t of Nh(e))if(Eh(t))return!0;return!1},Th=["script","iframe","object","embed","form","input","button","textarea","select","meta","link","base"],Rh=["onerror","onload","onclick","onmouseover","onmouseout","onfocus","onblur","onsubmit","onkeydown","onkeyup","formaction","xlink:href","data-bind"],Mh="data:image/svg+xml,"+encodeURIComponent(`
47
47
  <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
48
48
  <rect fill="#f0f0f0" width="100" height="100"/>
49
49
  <text x="50" y="50" text-anchor="middle" dy=".3em" fill="#999" font-size="12">
50
50
  Image blocked
51
51
  </text>
52
52
  </svg>
53
- `),Mh=e=>e.replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Ah=e=>e.replace(/@import[^;]*;/gi,"/* @import blocked */").replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Dh=(e={})=>{const t=Yi(),s={FORBID_TAGS:Ih,FORBID_ATTR:Th,ALLOW_DATA_ATTR:!1,ALLOW_UNKNOWN_PROTOCOLS:!1};return t.addHook("afterSanitizeAttributes",r=>{if(r.tagName==="IMG"){const a=r.getAttribute("src")||"";if(a.startsWith("data:"))return;if(a.startsWith("cid:")){const i=a.slice(4).replace(/^<|>$/g,""),l=e.resolveCid?.(i);l&&(r.setAttribute("src",l),r.classList.add("inline-content"));return}e.allowExternalImages||(r.setAttribute("data-blocked-src",a),r.setAttribute("src",Rh),r.setAttribute("alt","[Blocked image]"),r.classList.add("blocked-image"))}if(r.tagName==="A"){const a=r.getAttribute("href")||"";if(/^(javascript|data):/i.test(a)){r.removeAttribute("href");return}r.setAttribute("target","_blank"),r.setAttribute("rel","noopener noreferrer nofollow"),r.classList.add("external-link")}if(r.hasAttribute("style")){const a=r.getAttribute("style")||"";r.setAttribute("style",Mh(a))}}),t.addHook("uponSanitizeElement",(r,a)=>{if(a.tagName==="style"){const o=r.textContent||"";r.textContent=Ah(o)}}),r=>{const a=Eh(r),o=t.sanitize(r,s);return{html:`<style>${jh()}</style>${o}`,hasAuthorBackground:a}}},Oh='"Geist Variable", "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',Fo={light:{fg:"oklch(0.3 0.025 235)",surface:"oklch(0.975 0.012 90)",accent:"oklch(0.55 0.14 150)"},dark:{fg:"oklch(0.88 0.02 90)",surface:"oklch(0.25 0.025 220)",accent:"oklch(0.78 0.16 150)"}},Ph=/prefers-color-scheme\s*:\s*dark|color-scheme\s*:\s*[^;}"']*\bdark\b/i,_o='<meta name="viewport" content="width=device-width, initial-scale=1">',Lh=e=>{const t=e?Fo.dark:Fo.light;return`
53
+ `),Ah=e=>e.replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Dh=e=>e.replace(/@import[^;]*;/gi,"/* @import blocked */").replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Oh=(e={})=>{const t=Gi(),s={FORBID_TAGS:Th,FORBID_ATTR:Rh,ALLOW_DATA_ATTR:!1,ALLOW_UNKNOWN_PROTOCOLS:!1};return t.addHook("afterSanitizeAttributes",r=>{if(r.tagName==="IMG"){const a=r.getAttribute("src")||"";if(a.startsWith("data:"))return;if(a.startsWith("cid:")){const i=a.slice(4).replace(/^<|>$/g,""),l=e.resolveCid?.(i);l&&(r.setAttribute("src",l),r.classList.add("inline-content"));return}e.allowExternalImages||(r.setAttribute("data-blocked-src",a),r.setAttribute("src",Mh),r.setAttribute("alt","[Blocked image]"),r.classList.add("blocked-image"))}if(r.tagName==="A"){const a=r.getAttribute("href")||"";if(/^(javascript|data):/i.test(a)){r.removeAttribute("href");return}r.setAttribute("target","_blank"),r.setAttribute("rel","noopener noreferrer nofollow"),r.classList.add("external-link")}if(r.hasAttribute("style")){const a=r.getAttribute("style")||"";r.setAttribute("style",Ah(a))}}),t.addHook("uponSanitizeElement",(r,a)=>{if(a.tagName==="style"){const o=r.textContent||"";r.textContent=Dh(o)}}),r=>{const a=Ih(r),o=t.sanitize(r,s);return{html:`<style>${Sh()}</style>${o}`,hasAuthorBackground:a}}},Ph='"Geist Variable", "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',Fo={light:{fg:"oklch(0.3 0.025 235)",surface:"oklch(0.975 0.012 90)",accent:"oklch(0.55 0.14 150)"},dark:{fg:"oklch(0.88 0.02 90)",surface:"oklch(0.25 0.025 220)",accent:"oklch(0.78 0.16 150)"}},Lh=/prefers-color-scheme\s*:\s*dark|color-scheme\s*:\s*[^;}"']*\bdark\b/i,_o='<meta name="viewport" content="width=device-width, initial-scale=1">',$h=e=>{const t=e?Fo.dark:Fo.light;return`
54
54
  /* Plain-email base: UI font-stack + theme-aware colors (#424) */
55
55
  html, body {
56
- font-family: ${Oh};
56
+ font-family: ${Ph};
57
57
  font-size: 14px;
58
58
  line-height: 1.6;
59
59
  color: ${t.fg};
@@ -71,9 +71,9 @@ a, a:visited {
71
71
  color: ${t.accent} !important;
72
72
  text-decoration: underline;
73
73
  }
74
- `},$h=(e,t)=>e?t?"html,body{margin:0;color-scheme:dark light}":"html{margin:0;background-color:#ffffff;filter:invert(0.92) hue-rotate(180deg)}body{margin:0}img,picture,video,svg,canvas,[style*='background-image'],[background]{filter:invert(0.92) hue-rotate(180deg)}":"html,body{margin:0;background-color:#ffffff;color-scheme:light}",Fh=(e,t,s)=>{if(t==="plain")return`${_o}<style>${Lh(s)}</style>${e}`;const r=Ph.test(e);return`${_o}<style>${$h(s,r)}</style>${e}`},_h=5e4,zh=1e4,Bh="(max-width: 640px)",Kh=.4,Uh="allow-same-origin allow-popups allow-popups-to-escape-sandbox",zo=(e,t,s)=>Math.min(Math.ceil(Math.max(e,t)),s),qh=(e,t)=>e<=0||t<=0||e<=t?1:Math.max(Kh,t/e),Hh=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia(e);s(r.matches);const a=o=>s(o.matches);return r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[e]),t},Wh=new Set(["Enter","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"]),Vh=e=>e===" "?!1:e.length===1?!0:Wh.has(e),Bo=e=>{if(e.metaKey||e.ctrlKey||e.altKey||!Vh(e.key))return;const t=e.currentTarget??e.target,s=t?.defaultView?.parent;!s||s===t?.defaultView||s.dispatchEvent(new KeyboardEvent("keydown",{key:e.key,code:e.code,shiftKey:e.shiftKey,bubbles:!0,cancelable:!0}))},Ko=({html:e,variant:t="framed",isDark:s=!1,className:r})=>{const a=c.useRef(null),o=c.useRef(null),[i,l]=c.useState(0),[u,f]=c.useState(0),[d,m]=c.useState(0),h=Hh(Bh),g=c.useMemo(()=>Fh(e,t,s),[e,t,s]);c.useEffect(()=>{const j=a.current;if(!j)return;const y=()=>m(N=>N===j.clientWidth?N:j.clientWidth);y();const I=new ResizeObserver(y);return I.observe(j),()=>I.disconnect()},[]),c.useEffect(()=>{const j=o.current;if(!j)return;const y=()=>{const C=j.contentDocument;if(!C?.body)return;const M=C.documentElement,P=zo(C.body.scrollHeight,M?.scrollHeight??0,_h);l(O=>O===P?O:P);const D=zo(C.body.scrollWidth,M?.scrollWidth??0,zh);f(O=>O===D?O:D)};let I,N;const k=()=>{y();const C=j.contentDocument;C?.body&&(I=new ResizeObserver(y),I.observe(C.body),C.documentElement&&I.observe(C.documentElement),C.addEventListener("keydown",Bo),N=C)};return j.addEventListener("load",k),()=>{j.removeEventListener("load",k),N?.removeEventListener("keydown",Bo),I?.disconnect()}},[]);const v=h?qh(u,d):1,p=v<1,x=p?`${u}px`:h?"100%":t==="framed"&&u>0?`max(100%, ${u}px)`:u===0?"100%":`${u}px`,b=i===0?"1px":`${i}px`,w=n.jsx("iframe",{ref:o,title:"Email content",sandbox:Uh,srcDoc:g,className:p?void 0:r,scrolling:"no",style:{width:x,maxWidth:p?"none":void 0,border:"none",display:"block",height:b,overflow:"hidden",transform:p?`scale(${v})`:void 0,transformOrigin:p?"top left":void 0,colorScheme:"normal"}});return n.jsx("div",{ref:a,className:p?r:void 0,children:p?n.jsx("div",{style:{width:"100%",height:`${Math.ceil(i*v)}px`,overflow:"hidden"},children:w}):w})},Uo=()=>n.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),sc=({html:e,text:t,isDark:s=!1,category:r,allowImages:a=!1,resolveCid:o,className:i,renderBlockedNotice:l})=>{const u=c.useMemo(()=>!e||typeof document>"u"?null:Dh({allowExternalImages:a,resolveCid:o})(e),[e,a,o]),f=u?.html??null,{framed:d,isPlain:m}=wh(r,u?.hasAuthorBackground??!1),h=c.useMemo(()=>!f||a?0:(f.match(/data-blocked-src/g)||[]).length,[f,a]);return!f&&!t?n.jsx("div",{className:H("message-body",i),children:n.jsx(Uo,{})}):n.jsxs("div",{className:H("message-body",i),children:[h>0&&n.jsx("div",{className:"message-body-notice",children:l?.(h)}),f?d?n.jsx("div",{className:"w-full max-w-full overflow-x-auto",children:n.jsx(Ko,{html:f,variant:"framed",isDark:s})}):n.jsx("div",{className:"max-w-full overflow-x-auto lg:max-w-2xl",children:n.jsx(Ko,{html:f,variant:m?"plain":"framed",isDark:s})}):t?n.jsx("pre",{className:"email-text whitespace-pre-wrap text-sm leading-relaxed",children:t}):n.jsx(Uo,{})]})};function Es({message:e="Select a thread to read",icon:t,showHints:s=!0,className:r}){return n.jsxs("div",{className:H("flex flex-1 flex-col items-center justify-center text-center",r),children:[t??n.jsx(ca,{className:"size-10 text-fg-subtle"}),n.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:e}),s&&n.jsxs("p",{className:"text-2xs text-fg-subtle",children:[n.jsx(ps,{children:"j"})," / ",n.jsx(ps,{children:"k"})," to move, ",n.jsx(ps,{children:"Enter"})," to open"]})]})}function nc({message:e,onClick:t,isFocused:s,isUnread:r,trailing:a}){const o=n.jsxs(n.Fragment,{children:[n.jsx(ys,{className:"size-3.5 shrink-0 text-fg-subtle"}),n.jsxs("div",{className:"relative shrink-0",children:[n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"md"}),r&&n.jsx("span",{className:"absolute -top-0.5 -right-0.5 size-2 rounded-full border border-canvas bg-accent"})]}),n.jsx("span",{className:H("w-36 shrink-0 truncate text-sm",r?"font-semibold text-fg":"font-medium text-fg-muted"),children:e.fromName}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-fg-subtle",children:e.snippet}),a??n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.dateLabel})]}),i=H("group flex h-section-row w-full items-center gap-3 border-b border-line px-2 text-left transition-colors hover:bg-surface-sunken lg:px-4",s&&"bg-surface-sunken ring-1 ring-inset ring-accent/30");return t?n.jsx("div",{role:"button",tabIndex:0,"aria-expanded":!1,onClick:t,onKeyDown:l=>{Ld(l)&&(l.preventDefault(),t())},className:H(i,"cursor-pointer"),children:o}):n.jsx("div",{className:i,children:o})}function rc({message:e,warning:t,onHeaderClick:s,isFocused:r,senderBadge:a,trailing:o,to:i,indicators:l,actionMenu:u,actionBar:f,body:d}){const m=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[n.jsxs("span",{className:"text-sm font-semibold text-fg",children:[e.fromName,a]}),o??n.jsx("span",{className:"text-2xs text-fg-subtle",children:e.dateLabel})]}),n.jsx("div",{className:"text-xs text-fg-subtle",children:e.fromEmail}),i!==null&&n.jsx("div",{className:"text-xs text-fg-subtle",children:i??n.jsxs(n.Fragment,{children:["to ",e.toLabel]})})]});return n.jsxs("div",{className:H("px-2 py-3 lg:px-4",r&&"ring-1 ring-inset ring-accent/30"),children:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx(Rt,{className:"mt-1 size-3.5 shrink-0 text-fg-subtle"}),n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"md"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[s?n.jsx("button",{type:"button",onClick:s,className:"w-full text-left",children:m}):m,l]}),u&&n.jsx("div",{className:"shrink-0",children:u})]}),t&&n.jsxs("div",{className:"mt-3 flex items-start gap-3 rounded-md bg-danger-soft p-3",children:[n.jsx(Ns,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("div",{className:"text-sm text-fg",children:[n.jsx("span",{className:"font-semibold text-danger",children:"Caution: "}),t," ",n.jsx("button",{type:"button",className:"text-accent underline",children:"Why?"})]})]}),f&&n.jsx("div",{className:"mt-3 -mx-2 lg:-mx-4",children:f}),n.jsx("div",{className:"-mx-2 [&_.message-body-notice]:px-2 lg:mx-0 lg:[&_.message-body-notice]:px-0",children:d??n.jsx(sc,{className:"mt-3",html:e.bodyHtml,category:e.framed?"newsletter":"personal",allowImages:!0})})]})}function Qh({thread:e,onBack:t,intelligence:s,intelligenceOpen:r,onToggleIntelligence:a,actions:o,children:i,touchHandlers:l}){const[u,f]=c.useState(!1),d=a!==void 0,m=d?r??!1:u,h=!!s||d,g=()=>{if(d){a?.();return}f(p=>!p)},v=()=>{if(d){m&&a?.();return}f(!1)};return n.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Pl,{className:"size-4"}),onClick:t,"aria-label":"Back to messages",className:"-ml-1 shrink-0"}),n.jsx("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e.subject}),h&&n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(la,{className:"size-4"}),onClick:g,"aria-label":m?"Hide intelligence panel":"Show intelligence panel","aria-pressed":m,title:"Intelligence",className:H("shrink-0",m&&"bg-accent-2-soft text-accent-2")})]}),n.jsx("div",{className:"flex-1 overflow-y-auto",style:l?{touchAction:"pan-y"}:void 0,...l,children:i??e.messages.map(p=>{const x=b=>b?()=>b(p.id):void 0;return p.expanded?n.jsx(rc,{message:p,warning:e.warning,onHeaderClick:x(o?.onToggleExpand),actionBar:n.jsx(tc,{hasThread:!0,onReply:x(o?.onReply),onReplyAll:x(o?.onReplyAll),onForward:x(o?.onForward),onToggleStar:x(o?.onToggleStar),onDelete:x(o?.onDelete),onToggleRead:x(o?.onToggleRead),moveSlot:o?.moveSlot?.(p.id)})},p.id):n.jsx(nc,{message:p,onClick:x(o?.onToggleExpand)},p.id)})}),s&&!d&&n.jsx(ua,{open:m,onClose:v,title:"Intelligence",anchor:"right",className:"p-0",children:n.jsx(Hl,{data:s,onClose:v,className:"h-full w-full border-l-0"})})]})}const Yh="button:not([disabled]), a[href]",Wt="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface-sunken";function Gh({active:e,dimmed:t,indent:s}){return H("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors",Wt,s&&"pl-7",e?"bg-accent-2-soft font-medium text-accent-2":"text-fg-muted hover:bg-surface hover:text-fg",t&&"opacity-55")}function Xh({icon:e,label:t,count:s,active:r}){return n.jsxs(n.Fragment,{children:[e&&n.jsx("span",{className:H("shrink-0",r?"text-accent-2":"text-fg-subtle"),children:e}),n.jsx("span",{className:"flex-1 truncate",children:t}),s!=null&&s>0&&n.jsx("span",{className:H("text-2xs tabular-nums",r?"text-accent-2":"text-fg-subtle"),children:s})]})}function gs({icon:e,label:t,count:s,active:r,dimmed:a,indent:o,navId:i,linkComponent:l,ariaLabel:u,title:f,onClick:d}){const m=Gh({active:r,dimmed:a,indent:o}),h=n.jsx(Xh,{icon:e,label:t,count:s,active:r});return i&&l?l({navId:i,className:m,ariaLabel:u??t,title:f,onClick:d,children:h}):n.jsx("button",{type:"button",onClick:d,className:m,"aria-label":u,title:f,children:h})}const qo={inbox:0,flagged:1,drafts:2,sent:3,archive:4,all:5,junk:6,trash:7};function Jh(e){switch(e){case"inbox":return n.jsx(ca,{className:"size-4"});case"flagged":return n.jsx(At,{className:"size-4"});case"drafts":return n.jsx(Gi,{className:"size-4"});case"sent":return n.jsx(Gs,{className:"size-4"});case"archive":return n.jsx(_d,{className:"size-4"});case"all":return n.jsx(Fd,{className:"size-4"});case"junk":return n.jsx($d,{className:"size-4"});case"trash":return n.jsx(rt,{className:"size-4"})}}const Ho=e=>e.role!=null,kr=8,Wo="remit.nav.folders.open.",Vo="remit.nav.account.open.";function Qo(e,t,s){if(typeof localStorage>"u")return s;const r=localStorage.getItem(e+t);return r===null?s:r!=="0"}function Yo(e,t,s){typeof localStorage>"u"||localStorage.setItem(e+t,s?"1":"0")}function Zh({query:e,onSelect:t,onRemove:s}){return n.jsxs("div",{className:"group flex w-full items-center gap-1 rounded-md pr-1 hover:bg-surface",children:[n.jsxs("button",{type:"button",onClick:t,className:H("flex min-w-0 flex-1 items-center gap-2 px-2 py-1 text-left text-sm text-fg-muted transition-colors hover:text-fg",Wt),children:[n.jsx(Qn,{className:"size-4 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"min-w-0 flex-1 truncate",children:e})]}),s&&n.jsx("button",{type:"button",onClick:s,"aria-label":`Remove saved search: ${e}`,className:H("shrink-0 rounded-full p-1 text-fg-subtle opacity-0 transition-opacity hover:bg-surface-sunken hover:text-fg group-hover:opacity-100 focus-visible:opacity-100",Wt),children:n.jsx(We,{className:"size-3.5"})})]})}function ep({savedSearches:e,saveableQuery:t,onSelectSavedSearch:s,onRemoveSavedSearch:r,onSaveCurrentSearch:a}){return e.length===0&&!t?null:n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"px-2 pb-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Saved searches"}),t&&n.jsxs("button",{type:"button",onClick:a,className:H("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-accent transition-colors hover:bg-surface",Wt),children:[n.jsx(_m,{className:"size-4 shrink-0"}),n.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Save “",t,"”"]})]}),e.map(o=>n.jsx(Zh,{query:o,onSelect:()=>s?.(o),onRemove:r?()=>r(o):void 0},o))]})}function tp({account:e,selectedNavId:t,onSelectNav:s,linkComponent:r}){const[a,o]=c.useState(()=>Qo(Vo,e.id,!0)),[i,l]=c.useState(()=>Qo(Wo,e.id,!0)),[u,f]=c.useState(!1),d=()=>{o(w=>{const j=!w;return Yo(Vo,e.id,j),j})},m=()=>{l(w=>{const j=!w;return Yo(Wo,e.id,j),j})},h=e.mailboxes.filter(Ho).sort((w,j)=>qo[w.role]-qo[j.role]),g=e.mailboxes.filter(w=>!Ho(w)),v=u||g.length<=kr?g:g.slice(0,kr),p=g.length-v.length,x=e.status??"ready",b=x==="ready"&&h.length===0&&g.length===0;return n.jsxs("div",{className:"mt-3",children:[n.jsxs("button",{type:"button",onClick:d,"aria-expanded":a,className:H("flex w-full items-center gap-1.5 px-2 pb-1 text-left transition-colors hover:text-fg",Wt,e.muted&&"opacity-55"),children:[a?n.jsx(Rt,{className:"size-3 shrink-0 text-fg-subtle"}):n.jsx(ys,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"truncate text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),e.muted&&n.jsxs(n.Fragment,{children:[n.jsx(Ll,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:"muted"})]})]}),a&&n.jsxs(n.Fragment,{children:[x==="loading"&&n.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"Loading…"}),x==="error"&&n.jsxs("div",{role:"alert",className:"mx-2 my-1 flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-2 py-1.5 text-sm",children:[n.jsx(Gt,{className:"mt-0.5 size-4 shrink-0 text-danger","aria-hidden":"true"}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx("p",{className:"font-medium text-danger",children:"Couldn't load mailboxes"})}),e.onRetry&&n.jsx("button",{type:"button",onClick:e.onRetry,className:"shrink-0 text-sm font-medium text-accent hover:underline",children:"Retry"})]}),b&&n.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"No mailboxes"}),x==="ready"&&n.jsxs(n.Fragment,{children:[h.map(w=>n.jsx(gs,{navId:w.id,linkComponent:r,icon:Jh(w.role),label:w.name,ariaLabel:w.name,title:w.fullPath??w.name,count:w.unseen,active:t===w.id,dimmed:e.muted,onClick:()=>s?.(w.id)},w.id)),e.outboxPending!==void 0&&n.jsx(gs,{navId:"outbox",linkComponent:r,icon:n.jsx(Gs,{className:"size-4"}),label:"Outbox",ariaLabel:"Outbox",count:e.outboxPending>0?e.outboxPending:void 0,active:t==="outbox",dimmed:e.muted,onClick:()=>s?.("outbox")}),g.length>0&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{type:"button",onClick:m,"aria-expanded":i,className:H("mt-1 flex w-full items-center gap-1 px-2 py-1 text-left text-2xs font-semibold uppercase tracking-wider text-fg-subtle transition-colors hover:text-fg",Wt),children:[i?n.jsx(Rt,{className:"size-3 shrink-0"}):n.jsx(ys,{className:"size-3 shrink-0"}),n.jsx("span",{className:"flex-1",children:"Folders"}),n.jsx("span",{className:"tabular-nums opacity-70",children:g.length})]}),i&&n.jsxs(n.Fragment,{children:[v.map(w=>n.jsx(gs,{navId:w.id,linkComponent:r,icon:n.jsx(Gf,{className:"size-4"}),label:w.name,ariaLabel:w.name,title:w.fullPath??w.name,count:w.unseen,active:t===w.id,dimmed:e.muted,onClick:()=>s?.(w.id)},w.id)),(p>0||u)&&g.length>kr&&n.jsx("button",{type:"button",onClick:()=>f(w=>!w),className:H("ml-7 flex items-center px-2 py-1 text-2xs font-medium text-accent transition-colors hover:underline",Wt),children:u?"Show less":`Show all (${g.length})`})]})]})]})]})]})}function sp({accounts:e,selectedNavId:t,briefUnseen:s,onSelectNav:r,variant:a="desktop",linkComponent:o,savedSearches:i=[],saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:f,onSaveCurrentSearch:d}){const m=c.useRef(null);Kn({containerRef:m,itemSelector:Yh});const h=a==="drawer",g=n.jsxs("nav",{ref:h?m:void 0,className:h?"px-2 py-2":"flex-1 overflow-y-auto px-2 py-2","aria-label":"Mailboxes",children:[n.jsx(gs,{navId:"brief",linkComponent:o,icon:n.jsx(ut,{className:"size-4"}),label:"Daily brief",ariaLabel:"Daily brief",count:s,active:t==="brief",onClick:()=>r?.("brief")}),n.jsx(gs,{navId:"flagged",linkComponent:o,icon:n.jsx(At,{className:"size-4"}),label:"Starred",ariaLabel:"Starred",active:t==="flagged",onClick:()=>r?.("flagged")}),n.jsx(ep,{savedSearches:i,saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:f,onSaveCurrentSearch:d}),e.length===0?n.jsx("div",{className:"px-2 py-4 text-center text-sm text-fg-muted",children:"No accounts configured"}):e.map(v=>n.jsx(tp,{account:v,selectedNavId:t,onSelectNav:r,linkComponent:o},v.id))]});return h?g:n.jsxs("aside",{ref:m,className:"flex h-full w-full flex-col bg-surface-sunken",children:[g,n.jsx("div",{className:"border-t border-line px-2 py-2",children:n.jsx(gs,{navId:"settings",linkComponent:o,icon:n.jsx(Oa,{className:"size-4"}),label:"Settings",ariaLabel:"Settings",active:t==="settings",onClick:()=>r?.("settings")})})]})}function np({search:e,actions:t,className:s}){return n.jsxs("header",{className:H("flex min-h-16 w-full shrink-0 items-center gap-3 border-b border-line bg-canvas px-3 py-2",s),children:[n.jsx("div",{className:"flex min-w-0 flex-1 justify-start",children:n.jsx("div",{className:"w-full max-w-2xl",children:e})}),t&&n.jsx("div",{className:"flex shrink-0 items-center gap-1",children:t})]})}function rp({label:e,size:t="sm",onUndo:s,undoLabel:r="Undo",filtersHref:a,manageLabel:o="Manage filter",className:i}){return n.jsxs(lt,{tone:"accent",className:H(t==="md"&&"py-1 text-xs",i),children:[n.jsx(Ym,{className:H(t==="sm"?"size-3":"size-3.5","shrink-0"),"aria-hidden":!0}),n.jsx("span",{children:e}),s&&n.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),s()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:r}),a&&n.jsx("a",{href:a,onClick:l=>{l.stopPropagation()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:o})]})}const ap=({status:e})=>e==="saving"?n.jsx("span",{className:"animate-pulse text-xs text-fg-muted",children:"Saving..."}):e==="saved"?n.jsx("span",{className:"text-xs text-fg-muted",children:"Draft saved"}):e==="error"?n.jsx("span",{className:"text-xs text-danger",children:"Save failed"}):null;function op({onSend:e,onDiscard:t,sending:s,canSend:r,saveStatus:a="idle",unavailableReason:o,onUnavailable:i}){return n.jsxs("div",{className:"flex items-center justify-between border-t border-line px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(G,{variant:"primary",size:"md","aria-busy":s,title:r?void 0:o,className:"min-h-11 rounded-full px-4",icon:s?n.jsx(nt,{className:"size-4 animate-spin"}):n.jsx(Gs,{className:"size-4"}),onClick:()=>{if(!s){if(!r){o&&i?.(o);return}e()}},children:"Send"}),n.jsx(ap,{status:a})]}),n.jsx(G,{variant:"ghost",size:"md","aria-busy":s,"aria-label":"Discard",className:"min-h-11 min-w-11 px-2 hover:text-danger",icon:n.jsx(rt,{className:"size-4"}),onClick:()=>{s||t()}})]})}function ip({banner:e,header:t,children:s,quoted:r,actionBar:a}){return n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e,t,n.jsxs("div",{className:"min-h-0 flex-1 overflow-auto",children:[s,r&&n.jsx("div",{className:"px-3 pb-2",children:r})]}),a]})}function lp({key:e,shiftKey:t=!1,repeat:s=!1,caretAtStart:r,hasValue:a,chipCount:o}){const i=o-1;return e==="Escape"?a?{type:"clearQuery"}:{type:"blur"}:e==="Tab"&&t?o===0?{type:"none"}:{type:"focusChip",index:i}:e==="Backspace"||e==="ArrowLeft"?!r||o===0?{type:"none"}:s?{type:"none"}:{type:"focusChip",index:i}:{type:"none"}}function cp({key:e,repeat:t=!1,index:s,chipCount:r}){return e==="Backspace"||e==="Delete"?t?{type:"none"}:{type:"removeChip",index:s}:e==="ArrowLeft"?s===0?{type:"none"}:{type:"focusChip",index:s-1}:e==="ArrowRight"?s>=r-1?{type:"focusInput"}:{type:"focusChip",index:s+1}:e==="Enter"||e===" "?{type:"activateChip",index:s}:e==="Escape"?{type:"focusInput"}:{type:"none"}}function up(e,t){const s=t-1;return s<=0?null:e<s?e:s-1}const dp=e=>e instanceof HTMLElement?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable:!1,fp=({chips:e=[],onRemoveChip:t,onActivateChip:s,value:r,onChange:a,onClear:o,onClearQuery:i,placeholder:l="Search mail...",globalFocusKey:u=!0,showClearButton:f=!0,size:d="sm",inputId:m,chipsLabel:h="Search filters",className:g})=>{const v=c.useId(),p=m??v,x=c.useRef(null),b=c.useRef([]),w=i??o,[j,y]=c.useState(null),I=c.useRef(void 0),[N,k]=c.useState(""),C=e.length>0;c.useEffect(()=>{y(S=>S!==null&&S>=e.length?null:S)},[e.length]),c.useEffect(()=>{const S=I.current;if(S!==void 0){if(I.current=void 0,S===null){x.current?.focus();return}b.current[S]?.focus()}});const M=c.useCallback(S=>{y(S),I.current=S},[]),P=c.useCallback(S=>{const A=e[S];A&&t&&(M(up(S,e.length)),k(`${A.label} removed`),t(A.id))},[e,t,M]),D=c.useCallback(()=>{M(null),o()},[o,M]),O=c.useCallback(S=>{const A=S.currentTarget,L=lp({key:S.key,shiftKey:S.shiftKey,repeat:S.repeat,caretAtStart:A.selectionStart===0&&A.selectionEnd===0,hasValue:r.length>0,chipCount:e.length});switch(L.type){case"focusChip":S.preventDefault(),M(L.index);return;case"clearQuery":w();return;case"blur":A.blur();return;case"none":return}},[e.length,r,w,M]),E=c.useCallback(S=>A=>{const L=cp({key:A.key,repeat:A.repeat,index:S,chipCount:e.length});switch(L.type!=="none"&&A.preventDefault(),L.type){case"removeChip":P(L.index);return;case"focusChip":M(L.index);return;case"focusInput":M(null);return;case"activateChip":{const T=e[L.index];T&&s&&s(T.id);return}case"none":return}},[e,P,M,s]);return c.useEffect(()=>{if(!u)return;const S=A=>{A.key!=="/"||A.metaKey||A.ctrlKey||A.altKey||dp(A.target)||(A.preventDefault(),x.current?.focus())};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[u]),n.jsxs("label",{htmlFor:p,className:H("flex w-full items-center gap-1.5 text-sm","bg-surface-sunken/50 border border-transparent","focus-within:bg-canvas focus-within:border-line focus-within:ring-2 focus-within:ring-ring","transition-colors",d==="lg"?"rounded-xl px-4 py-2":"rounded-md px-2.5 py-1",g),children:[n.jsx(Qn,{className:H("shrink-0 text-fg-muted pointer-events-none",d==="lg"?"size-5":"size-4")}),n.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1",children:[C&&n.jsx("div",{role:"grid","aria-label":h,className:"flex min-w-0 flex-wrap items-center gap-1",children:e.map((S,A)=>n.jsx(zd,{ref:L=>{b.current[A]=L},label:S.label,tone:S.tone,focused:j===A,onFocusLabel:()=>y(A),onKeyDown:E(A),onRemove:()=>P(A),onActivate:s?()=>s(S.id):void 0},S.id))}),n.jsx("input",{ref:x,id:p,name:"q",type:"text","aria-label":"Search mail",autoComplete:"off",value:r,tabIndex:j===null?0:-1,onChange:S=>a(S.target.value),onKeyDown:O,onFocus:()=>y(null),placeholder:C?void 0:l,className:"min-w-24 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted"})]}),(r||C)&&f&&n.jsx("button",{type:"button",onClick:D,className:"shrink-0 rounded p-0.5 hover:bg-surface-raised transition-colors","aria-label":"Clear search",children:n.jsx(We,{className:H("text-fg-muted",d==="lg"?"size-5":"size-4")})}),n.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:N})]})},La=({value:e,onChange:t,onClear:s,onClearQuery:r,chips:a,onRemoveChip:o,placeholder:i="Search mail...",globalFocusKey:l=!0,showClearButton:u=!0,size:f,inputId:d,className:m})=>n.jsx(fp,{value:e,onChange:t,onClear:s,onClearQuery:r,chips:a,onRemoveChip:o,placeholder:i,globalFocusKey:l,showClearButton:u,size:f,inputId:d,className:m});function mp({title:e,unreadCount:t,isDesktop:s,onMenuClick:r,searchValue:a,onSearchChange:o,onSearchClear:i,searchOpen:l,onSearchOpenChange:u,showSearch:f=!0}){const d=`${t.toLocaleString()} unread`,m=i??(()=>o("")),h=()=>{m(),u(!1)},g=p=>n.jsx(La,{value:a,onChange:o,onClear:m,globalFocusKey:!1,showClearButton:p}),v=n.jsx(G,{variant:"ghost",icon:n.jsx(Ca,{className:"size-5"}),onClick:r,"aria-label":"Menu",className:"min-h-11 min-w-11 shrink-0 px-0"});return n.jsx("header",{className:"flex shrink-0 flex-col bg-canvas",children:n.jsx("div",{className:"flex h-12 items-center gap-2 px-row-inset",children:f?s?n.jsxs(n.Fragment,{children:[v,n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:d}),n.jsx("div",{className:"w-64 max-w-[40%] shrink-0",children:g(!0)})]}):l||a.trim().length>0?n.jsxs("div",{className:"flex flex-1 items-center gap-1",children:[n.jsx("div",{className:"flex-1",children:g(!1)}),n.jsx(G,{variant:"ghost",icon:n.jsx(We,{className:"size-5"}),onClick:h,"aria-label":"Close search",className:"min-h-11 min-w-11 shrink-0 px-0"})]}):n.jsxs(n.Fragment,{children:[v,n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:d}),n.jsx(G,{variant:"ghost",icon:n.jsx(Qn,{className:"size-5"}),onClick:()=>u(!0),"aria-label":"Search",className:"min-h-11 min-w-11 shrink-0 px-0"})]}):n.jsxs(n.Fragment,{children:[v,n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:d})]})})})}const hp=(e,t)=>e==="vip"?"vip":e==="unknown"&&t==="md"?"unknown-pill":"hidden",ac=({senderTrust:e,size:t="sm",className:s})=>{const r=hp(e,t);return r==="vip"?n.jsx(ut,{className:H("text-warning shrink-0",t==="sm"&&"size-3.5",t==="md"&&"size-4",s),"aria-label":"VIP sender","data-testid":"sender-trust-vip"}):r==="unknown-pill"?n.jsx("span",{className:H("inline-flex items-center rounded border border-dashed border-fg-subtle/40 font-medium uppercase tracking-wide text-fg-muted/80 shrink-0","px-2 py-0.5 text-xs",s),title:"First message from this sender","aria-label":"First message from this sender","data-testid":"sender-trust-unknown",children:"new"}):null};function Go(e,t){const s=t?.trim();if(!s)return e;const r=e.toLowerCase(),a=s.toLowerCase(),o=[];let i=0,l=r.indexOf(a,i),u=0;for(;l!==-1;)l>i&&o.push(e.slice(i,l)),o.push(n.jsx("mark",{className:"bg-transparent font-semibold text-fg",children:e.slice(l,l+a.length)},u++)),i=l+a.length,l=r.indexOf(a,i);return i<e.length&&o.push(e.slice(i)),o}function pp({result:e,onClick:t,query:s,showFolder:r=!0}){const a=r&&e.folder?Bd(e.folder):void 0;return n.jsxs("button",{type:"button",onClick:t,className:"flex w-full flex-col gap-0.5 border-b border-line px-row-inset py-2.5 text-left transition-colors hover:bg-surface-sunken",children:[n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:H("min-w-0 flex-1 truncate text-sm",e.unread?"font-semibold text-fg":"font-medium text-fg-muted"),children:e.sender}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.date})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:H("min-w-0 flex-1 truncate text-sm",e.unread?"text-fg":"text-fg-muted"),children:Go(e.subject,s)}),e.flagged&&n.jsx(Bm,{className:"size-3.5 shrink-0 fill-warning text-warning"})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-fg-subtle",children:Go(e.snippet,s)}),a&&n.jsx(lt,{tone:"neutral",className:"shrink-0",children:a}),e.category&&n.jsx(lt,{tone:e.category.tone??"neutral",className:"shrink-0",children:e.category.label}),e.matchedChunkLabel&&n.jsx(lt,{tone:"neutral",className:"shrink-0",children:`matched: ${e.matchedChunkLabel}`}),e.score!=null&&n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.score.toFixed(2)})]})]})}const gp=e=>e===1?"result":"results";function xp({count:e,onScopeToSpam:t}){return n.jsx(Xt,{tone:"info",variant:"soft",className:"items-center justify-between gap-3 rounded-none border-b border-line",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("p",{className:"min-w-0 text-xs text-fg-muted",children:[n.jsx("span",{className:"font-semibold text-fg tabular-nums",children:e})," ",`${gp(e)} from Spam`]}),n.jsx(G,{variant:"ghost",size:"sm",onClick:t,className:"shrink-0 text-accent",children:"Go to Spam"})]})})}const Xo=6,bp={kind:"global"},vp=e=>e.kind==="folder"&&e.role==="junk",yp=e=>e.folder?.role==="junk";function oc(e){const t=[],s=[];for(const r of e)yp(r)?s.push(r):t.push(r);return{kept:t,spam:s}}function wp({onClick:e,disabledReason:t}){const s=t!==void 0;return n.jsx("div",{className:"border-b border-line px-row-inset py-1.5",children:n.jsxs("button",{type:"button",onClick:e,disabled:s,title:t,className:H("flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs font-medium transition-colors",s?"cursor-not-allowed text-fg-subtle":"text-accent hover:bg-surface-sunken"),children:[n.jsx(Ud,{className:"size-3.5 shrink-0","aria-hidden":"true"}),n.jsx("span",{children:"Make this a filter"}),s&&n.jsx("span",{className:"ml-auto truncate text-2xs font-normal text-fg-subtle",children:t})]})})}function jp({section:e,query:t,onSelectResult:s,showFolder:r}){const[a,o]=c.useState(e.initialCollapsed??!1),[i,l]=c.useState(!1),u=e.results.length>Xo,d=!i&&u?e.results.slice(0,Xo):e.results,m=e.results.length-d.length;return n.jsxs("div",{children:[n.jsxs("button",{type:"button","aria-expanded":!a,onClick:()=>o(h=>!h),className:"sticky top-0 z-10 flex h-section-row w-full items-center gap-1.5 border-b border-line bg-surface-sunken px-row-inset text-left transition-colors hover:bg-surface",children:[n.jsx("span",{className:"flex-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:e.results.length}),n.jsx(Rt,{className:H("size-3 shrink-0 text-fg-subtle transition-transform duration-200",a?"rotate-0":"rotate-180")})]}),!a&&n.jsxs(n.Fragment,{children:[d.map(h=>n.jsx(pp,{result:h,query:t,showFolder:r,onClick:s?()=>s(h):void 0},h.id)),u&&n.jsxs("button",{type:"button",onClick:()=>l(h=>!h),className:"flex w-full items-center justify-center border-b border-line px-row-inset py-1.5 text-2xs font-medium text-accent transition-colors hover:bg-surface",children:[i?"Show less":`Show ${m} more`,!i&&n.jsx(Rt,{className:"ml-1 size-3"})]})]})]})}function ic({value:e,recentSearches:t,onPickRecent:s,sections:r,loading:a,onSelectResult:o,tokens:i,scope:l=bp,makeFilter:u}){if(!(e.trim().length>0))return t&&t.length>0?n.jsxs("div",{className:"flex flex-col",children:[n.jsx("h3",{className:"px-row-inset pb-1 pt-3 text-2xs font-semibold uppercase tracking-wide text-fg-subtle",children:"Recent searches"}),t.map(y=>n.jsxs("button",{type:"button",onClick:()=>s?.(y),className:"flex w-full items-center gap-2.5 border-b border-line px-row-inset py-2.5 text-left transition-colors hover:bg-surface-sunken",children:[n.jsx(Ta,{className:"size-4 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-fg-muted",children:y})]},y))]}):n.jsx("p",{className:"px-row-inset py-6 text-center text-sm text-fg-subtle",children:"Search across your mail by sender, subject or words in the message."});const d=i&&i.length>0&&n.jsx(Kd,{tokens:i}),m=u&&n.jsx(wp,{onClick:u.onClick,disabledReason:u.disabledReason});if(a)return n.jsxs("div",{className:"flex flex-col",children:[m,d,n.jsx("div",{className:"flex flex-col gap-3 px-row-inset py-4",children:[0,1,2,3].map(y=>n.jsxs("div",{className:"flex flex-col gap-1.5",children:[n.jsx("div",{className:"h-3 w-1/3 animate-pulse rounded bg-surface-sunken"}),n.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-surface-sunken"}),n.jsx("div",{className:"h-2.5 w-1/2 animate-pulse rounded bg-surface-sunken"})]},y))})]});const h=l.kind==="global",g=vp(l)||l.kind==="collection",v=h||l.kind==="collection",p=(r??[]).map(y=>{if(g)return{section:y,spam:[]};const{kept:I,spam:N}=oc(y.results);return{section:{...y,results:I},spam:N}}),x=p.map(y=>y.section),b=p.reduce((y,I)=>y+I.spam.length,0),w=l.kind==="global"&&b>0&&l.onScopeToSpam!==void 0?n.jsx(xp,{count:b,onScopeToSpam:l.onScopeToSpam}):void 0;return x.some(y=>y.results.length>0)?n.jsxs("div",{className:"flex flex-col",children:[m,d,w,x.filter(y=>y.results.length>0).map(y=>n.jsx(jp,{section:y,query:e,showFolder:v,onSelectResult:o},y.id))]}):n.jsxs("div",{className:"flex flex-col",children:[m,d,w,n.jsxs("div",{className:"px-row-inset py-10 text-center",children:[n.jsxs("p",{className:"text-sm font-medium text-fg",children:["No matches for “",e,"”"]}),n.jsx("p",{className:"mt-1 text-xs text-fg-subtle",children:"Try a different word, or adjust the filters above."})]})]})}function Sp({value:e,onChange:t,onClear:s,onCancel:r,filter:a,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:f,tokens:d,chips:m,onRemoveChip:h,scope:g,makeFilter:v}){const p=n.jsx(ic,{value:e,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:f,tokens:d,scope:g,makeFilter:v});return n.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx(La,{value:e,onChange:t,onClear:s,chips:m,onRemoveChip:h,globalFocusKey:!1,showClearButton:!1})}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(We,{className:"size-4"}),onClick:r,"aria-label":"Clear and close search",className:"-mr-1 shrink-0"})]}),a?n.jsx(da,{...a,children:p}):n.jsx("div",{className:"flex-1 overflow-y-auto",children:p})]})}const kp={queued:{icon:Ta,label:"Queued",className:"text-warning"},sending:{icon:nt,label:"Sending…",className:"text-accent-2",spin:!0},sent:{icon:$l,label:"Sent",className:"text-positive"},failed:{icon:Gt,label:"Failed",className:"text-danger"},blocked:{icon:fa,label:"Blocked",className:"text-warning"}};function Jo({status:e,iconOnly:t,className:s}){const r=kp[e],a=r.icon;return n.jsxs("span",{className:H("inline-flex items-center gap-1.5 text-xs font-medium",r.className,s),children:[n.jsx(a,{className:H("size-4",r.spin&&"animate-spin")}),!t&&r.label]})}const Cp=(e,t)=>t?"bg-accent-2-soft":e==="failed"?"bg-danger-soft":e==="blocked"?"bg-warning/10":"";function Np({recipients:e,subject:t,time:s,status:r,error:a,selected:o,onSelect:i,onRetry:l,retrying:u,onEdit:f,onDelete:d,deleting:m}){const h=r==="failed"||r==="blocked";return n.jsxs("div",{className:H("flex items-start gap-3 border-b border-line px-4 py-3 transition-colors hover:bg-surface-raised",Cp(r,o)),children:[n.jsxs("button",{type:"button",...oa,onClick:i,className:"flex flex-1 min-w-0 items-start gap-3 text-left",children:[n.jsx("div",{className:"mt-0.5 shrink-0",children:n.jsx(Jo,{status:r,iconOnly:!0})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"truncate text-sm font-medium",children:e}),n.jsx("span",{className:"shrink-0 text-xs text-fg-muted",children:s})]}),n.jsx("div",{className:"truncate text-sm",children:t||"No subject"}),n.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[n.jsx(Jo,{status:r}),a&&n.jsxs("span",{className:"truncate text-xs text-fg-muted",children:["— ",a]})]})]})]}),h&&n.jsx("div",{className:"shrink-0",children:n.jsx(Bf,{actions:[...r==="failed"&&l?[{label:"Retry sending",iconOnly:!0,icon:n.jsx(Xf,{className:"size-3.5"}),busy:u,onClick:l}]:[],{label:"Edit as draft",iconOnly:!0,icon:n.jsx(Gs,{className:"size-3.5"}),onClick:f}],destructive:{label:"Delete message",iconOnly:!0,icon:n.jsx(rt,{className:"size-3.5"}),busy:m,confirm:{prompt:"Delete this message?",confirmLabel:"Delete"},onClick:d}})})]})}const Ep=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia(e);s(r.matches);const a=o=>s(o.matches);return r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[e]),t},Ip=({children:e,onRefresh:t,isRefreshing:s})=>Ep("(min-width: 1024px)")?e:n.jsx(qd,{onRefresh:t,isPullable:!s,children:e}),Tp=({text:e,html:t,senderName:s,date:r})=>{const[a,o]=c.useState(!1);if(!e&&!t)return null;const i=[s,r].filter(Boolean).join(" on ");return n.jsxs("div",{className:"mt-2 px-3 pb-2",children:[n.jsxs("button",{type:"button",onClick:()=>o(!a),"aria-expanded":a,className:"flex items-center gap-1 text-xs text-fg-muted hover:text-fg transition-colors",children:[a?n.jsx(Rt,{className:"size-3"}):n.jsx(ys,{className:"size-3"}),i?`${i} wrote:`:"Show quoted text"]}),a&&n.jsx("blockquote",{className:"mt-2 pl-3 border-l-2 border-fg-subtle/30 text-sm text-fg-muted [&_a]:text-accent [&_a]:underline [&_blockquote]:pl-3 [&_blockquote]:border-l-2 [&_blockquote]:border-fg-subtle/30",children:t?n.jsx("div",{dangerouslySetInnerHTML:{__html:t}}):e.split(`
75
- `).map((l,u)=>n.jsx("p",{className:"min-h-[1.2em]",children:l},u))})]})},Rp=e=>e===1?"message":"messages";function Mp({count:e,onReview:t,onDismiss:s,actionLabel:r="Review & rescue"}){return n.jsx(Xt,{tone:"info",variant:"soft",onDismiss:s,children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("p",{className:"flex items-start gap-2 text-sm text-fg",children:[n.jsx(en,{className:"mt-0.5 size-4 shrink-0 text-positive","aria-hidden":!0}),n.jsxs("span",{children:[n.jsx("span",{className:"font-semibold text-fg",children:`${e} ${Rp(e)} here`})," ","may not be spam — they're from senders we can verify."]})]}),n.jsx(G,{variant:"primary",size:"sm",onClick:t,className:"self-start",children:r})]})})}function Ap({candidate:e,selected:t,onToggle:s,hideSender:r=!1}){const{senderName:a,senderAddress:o,subject:i,snippet:l,trustReason:u,trustSubReason:f,senderTrust:d}=e;return n.jsxs("label",{className:H("flex w-full cursor-pointer items-start gap-3 px-3 py-2.5 text-left transition-colors",r&&"pl-11",t?"bg-positive/10":"bg-surface hover:bg-surface-sunken"),children:[n.jsx(sn,{className:"mt-0.5",checked:t,onChange:s,"aria-label":`${t?"Deselect":"Select"} ${r?i:`message from ${a}`}`}),!r&&n.jsx(dt,{name:a,email:o,size:"sm"}),n.jsxs("span",{className:"min-w-0 flex-1",children:[!r&&n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-sm font-medium text-fg",children:a}),d&&n.jsx(ac,{senderTrust:d,size:"sm"}),n.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:o})]}),n.jsx("span",{className:"block truncate text-sm text-fg-muted",children:i}),n.jsx("span",{className:"block line-clamp-1 text-xs text-fg-subtle",children:l}),!r&&n.jsxs("span",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[n.jsxs(lt,{tone:"positive",children:[n.jsx(en,{className:"size-3","aria-hidden":!0}),u]}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:f})]})]})]})}const Dp=e=>{const t=new Map,s=[];for(const r of e){const a=(r.senderAddress||r.senderName).toLowerCase(),o=t.get(a);if(o){o.messages.push(r);continue}t.set(a,{key:a,senderName:r.senderName,senderAddress:r.senderAddress,trustReason:r.trustReason,trustSubReason:r.trustSubReason,senderTrust:r.senderTrust,messages:[r]}),s.push(a)}return s.map(r=>t.get(r)).sort((r,a)=>a.messages.length-r.messages.length)},Op=(e,t)=>{const s=e.messages.filter(r=>t.has(r.id)).length;return s===0?"none":s===e.messages.length?"all":"some"},Zo=e=>e===1?"message":"messages";function Pp({group:e,selected:t,onToggleGroup:s,onToggleMessage:r}){const[a,o]=c.useState(!1),i=Op(e,t),l=e.messages.length,u=a?Rt:ys;return n.jsxs("div",{className:H(i!=="none"?"bg-positive/10":"bg-surface"),children:[n.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-2.5",children:[n.jsx(sn,{className:"mt-0.5",checked:i==="all",indeterminate:i==="some",onChange:()=>s(e,i!=="all"),"aria-label":`${i==="all"?"Deselect":"Select"} all ${l} ${Zo(l)} from ${e.senderName}`}),n.jsx(dt,{name:e.senderName,email:e.senderAddress,size:"sm"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-sm font-medium text-fg",children:e.senderName}),e.senderTrust&&n.jsx(ac,{senderTrust:e.senderTrust,size:"sm"}),n.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:e.senderAddress})]}),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[n.jsxs(lt,{tone:"positive",children:[n.jsx(en,{className:"size-3","aria-hidden":!0}),e.trustReason]}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:e.trustSubReason})]})]}),n.jsxs("button",{type:"button",onClick:()=>o(f=>!f),"aria-expanded":a,className:"flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-2xs text-fg-muted transition-colors hover:bg-surface-sunken hover:text-fg",children:[`${l} ${Zo(l)}`,n.jsx(u,{className:"size-3.5","aria-hidden":!0})]})]}),a&&n.jsx("div",{className:"divide-y divide-line border-t border-line",children:e.messages.map(f=>n.jsx(Ap,{candidate:f,selected:t.has(f.id),onToggle:()=>r(f.id),hideSender:!0},f.id))})]})}const $a=e=>e===1?"message":"messages",Lp=(e,t)=>`Moves ${e===1?"this message":`these ${e} ${$a(e)}`} out of Spam to ${t} now. Nothing later.`,Qr=(e,t)=>e.find(s=>s.id===t)?.label??"Inbox";function $p(){return n.jsx(Xt,{tone:"info",variant:"soft",children:n.jsx("p",{className:"text-2xs text-fg-muted",children:"We list a message here only when we can confirm the sender is who they say — usually someone you've emailed before, write to often, or a service that consistently checks out. We never guess from words in the subject. Anything we can't confirm stays in Spam."})})}function Fp({candidates:e,selected:t,onToggle:s,onToggleGroup:r,onSelectAll:a,onSelectNone:o,onContinue:i,onCancel:l}){const[u,f]=c.useState(!1),d=t.size,m=c.useMemo(()=>Dp(e),[e]);return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("h2",{className:"flex items-center gap-2 text-sm font-semibold text-fg",children:[n.jsx(en,{className:"size-4 text-positive","aria-hidden":!0}),"Rescue from Spam"]}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(_f,{className:"size-3.5"}),onClick:()=>f(h=>!h),className:"-mr-1.5 -mt-0.5",children:"Why these?"})]}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"These look safe — from senders we can verify. Uncheck any sender that belongs in Spam, or open a sender to pick individual messages."}),u&&n.jsx("div",{className:"mt-2",children:n.jsx($p,{})})]}),n.jsxs("div",{className:"flex items-center justify-between px-row-inset pb-1.5",children:[n.jsx("span",{className:"text-2xs font-medium text-fg-muted",children:`${d} of ${e.length} selected · ${m.length} ${m.length===1?"sender":"senders"}`}),n.jsxs("span",{className:"flex gap-1",children:[n.jsx(G,{variant:"ghost",size:"sm",onClick:a,children:"Select all"}),n.jsx(G,{variant:"ghost",size:"sm",onClick:o,children:"Select none"})]})]}),n.jsx("div",{className:"min-h-0 flex-1 divide-y divide-line overflow-y-auto border-y border-line",children:m.map(h=>n.jsx(Pp,{group:h,selected:t,onToggleGroup:r,onToggleMessage:s},h.key))}),n.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[n.jsx(G,{variant:"primary",onClick:i,className:"h-11 w-full font-semibold",children:`Continue with ${d} ${$a(d)}`}),n.jsx(G,{variant:"ghost",onClick:l,className:"h-11 w-full",children:"Cancel"})]})]})}function _p({count:e,folders:t,destination:s,onPick:r,onMove:a,onBack:o}){const[i,l]=c.useState(!1);return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg",children:"Where should they go?"}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Pick a folder, then we move them out of Spam."})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-row-inset py-2",children:i?n.jsx("div",{className:"overflow-hidden rounded-xl border border-line bg-surface",children:n.jsx(Sl,{mailboxes:t,autoFocus:!0,onSelect:u=>{r(u),l(!1)},onCancel:()=>l(!1)})}):n.jsxs("div",{className:"rounded-xl border border-line bg-surface-sunken p-3",children:[n.jsx("p",{className:"text-2xs text-fg-subtle",children:"Destination"}),n.jsx("p",{className:"mt-0.5 text-sm font-medium text-fg",children:Qr(t,s)}),n.jsx(G,{variant:"ghost",size:"sm",onClick:()=>l(!0),className:"mt-2 px-0",children:"Move to a different folder"})]})}),n.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[n.jsx("p",{className:"text-2xs text-fg-subtle",children:Lp(e,Qr(t,s))}),n.jsx(G,{variant:"primary",onClick:a,className:"h-11 w-full font-semibold",children:`Move ${e} out of Spam`}),n.jsx(G,{variant:"ghost",onClick:o,className:"h-11 w-full",children:"Back"})]})]})}function zp({count:e,destinationLabel:t,onClose:s}){return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 px-row-inset py-10 text-center",children:[n.jsx(Yn,{className:"size-10 text-positive","aria-hidden":!0}),n.jsx("p",{className:"text-base font-semibold text-fg",children:`Moved ${e} ${$a(e)} out of Spam.`}),n.jsx("p",{className:"text-2xs text-fg-subtle",children:`You'll find them in ${t}.`})]}),n.jsx("div",{className:"border-t border-line bg-surface px-row-inset py-3",children:n.jsx(G,{variant:"primary",onClick:s,className:"h-11 w-full font-semibold",children:"Done"})})]})}function Bp({open:e,candidates:t,defaultDestinationId:s,availableFolders:r,onConfirmMove:a,onCancel:o}){const[i,l]=c.useState("review"),[u,f]=c.useState(()=>e?new Set(t.map(j=>j.id)):new Set),[d,m]=c.useState(s),[h,g]=c.useState(0),v=c.useRef(!1);c.useEffect(()=>{e&&!v.current&&(l("review"),f(new Set(t.map(j=>j.id))),m(s),g(0)),v.current=e},[e,t,s]);const p=u.size,x=j=>{f(y=>{const I=new Set(y);return I.has(j)?I.delete(j):I.add(j),I})},b=(j,y)=>{f(I=>{const N=new Set(I);for(const k of j.messages)y?N.add(k.id):N.delete(k.id);return N})},w=()=>{const j=Array.from(u);g(j.length),a(j,d),l("done")};return n.jsxs(hl,{open:e,onClose:o,dismissLabel:"Close rescue",children:[i==="review"&&n.jsx(Fp,{candidates:t,selected:u,onToggle:x,onToggleGroup:b,onSelectAll:()=>f(new Set(t.map(j=>j.id))),onSelectNone:()=>f(new Set),onContinue:()=>l("destination"),onCancel:o}),i==="destination"&&n.jsx(_p,{count:p,folders:r,destination:d,onPick:m,onMove:w,onBack:()=>l("review")}),i==="done"&&n.jsx(zp,{count:h,destinationLabel:Qr(r,d),onClose:o})]})}function Kp(e){return e.scopedOutFolder!==void 0||(e.droppedFacets?.length??0)>0||e.droppedSemantic===!0}function Up(e){return`Your search was limited to ${e}. This filter matches these messages in any folder — it can't be pinned to one.`}const qp=e=>e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`;function Hp(e){const t=e.length===1?"a filter condition":"filter conditions",s=e.length===1?"isn't":"aren't";return`${qp(e)} ${s} ${t}, so ${e.length===1?"it was":"they were"} left out — the filter still matches everything else you searched for.`}const Wp="The filter matches these words literally. Your search also found similar mail by meaning — a filter can't carry that, so it won't catch mail that means the same thing without these words.";function Cr({icon:e,children:t}){return n.jsxs("li",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"mt-0.5 shrink-0 text-fg-subtle","aria-hidden":"true",children:e}),n.jsx("span",{children:t})]})}function Vp({notice:e}){return Kp(e)?n.jsxs("div",{className:"rounded-md border border-line bg-surface-sunken px-3 py-2.5",children:[n.jsx("p",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"From your search"}),n.jsxs("ul",{className:"mt-1.5 space-y-1.5 text-xs text-fg-muted",children:[e.scopedOutFolder!==void 0&&n.jsx(Cr,{icon:n.jsx(Ia,{className:"size-3.5"}),children:Up(e.scopedOutFolder)}),e.droppedFacets&&e.droppedFacets.length>0&&n.jsx(Cr,{icon:n.jsx(la,{className:"size-3.5"}),children:Hp(e.droppedFacets)}),e.droppedSemantic&&n.jsx(Cr,{icon:n.jsx(ut,{className:"size-3.5"}),children:Wp})]})]}):null}const ei=e=>e.toLocaleString(),Ks=56,Qp=70,Yp=320,Gp=320,Xp="cubic-bezier(0.32, 0.9, 0.3, 1)",Jp=.5;function vn(e){return Math.sign(e)*Math.sqrt(Math.abs(e))*4}function Zp({expanded:e,delta:t,velocity:s,expandedHeight:r,teaserHeight:a,flickVelocity:o=Jp}){if(Math.abs(s)>o)return s<0;const i=(r-a)/2;return e?t<i:t<-i}function eg({count:e,mode:t="idle",onCancel:s,onDelete:r,onJunk:a,onMarkRead:o,onSelectSimilar:i,onSomethingElse:l,moveSlot:u,isBusy:f=!1,selectAll:d,statusLabel:m,progress:h,notice:g,startExpanded:v=!1}){const[p,x]=c.useState(v),b=c.useRef(null),[w,j]=c.useState(Yp),y=t==="counting"||t==="running";c.useEffect(()=>{y&&x(!0)},[y]),c.useLayoutEffect(()=>{const $=b.current;if(!$)return;const z=()=>j($.offsetHeight);z();const V=new ResizeObserver(z);return V.observe($),()=>V.disconnect()},[]);const[I,N]=c.useState(null),k=c.useRef(null),C=c.useRef(!1),M=c.useCallback($=>{y||($.currentTarget.setPointerCapture($.pointerId),k.current={startY:$.clientY,lastY:$.clientY,lastT:$.timeStamp,velocity:0},C.current=!1,N(0))},[y]),P=c.useCallback($=>{const z=k.current;if(!z)return;const V=$.timeStamp-z.lastT;V>0&&(z.velocity=($.clientY-z.lastY)/V),z.lastY=$.clientY,z.lastT=$.timeStamp;const ee=$.clientY-z.startY;Math.abs(ee)>4&&(C.current=!0);const X=w-Ks,Q=p?ee<0?vn(ee):Math.min(ee,X+vn(Math.max(0,ee-X))):ee>0?vn(ee):Math.max(ee,-X+vn(Math.min(0,ee+X)));N(Q)},[p,w]),D=c.useCallback(()=>{const $=k.current;k.current=null,$&&(N(null),x(Zp({expanded:p,delta:$.lastY-$.startY,velocity:$.velocity,expandedHeight:w,teaserHeight:Ks})))},[p,w]),O=w-Ks,E=p?0:O,S=I!==null,A=E+(I??0),L=S?"none":`transform ${Gp}ms ${Xp}`,T=d?.checked?`All ${ei(e)} loaded selected`:`${ei(e)} ${e===1?"message":"messages"} selected`,F=t==="idle"||t==="escalated",R=t==="idle";return n.jsxs("div",{ref:b,"data-selection-sheet":"",className:"absolute inset-x-0 bottom-0 z-30 flex select-none flex-col rounded-t-2xl border-t border-line bg-surface shadow-2xl shadow-black/40",style:{maxHeight:`${Qp}dvh`,minHeight:`${Ks}px`,transform:`translateY(${A}px)`,transition:L},children:[n.jsxs("div",{role:"slider","aria-label":p?"Collapse selection actions":"Expand selection actions","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":p?1:0,tabIndex:0,onPointerDown:M,onPointerMove:P,onPointerUp:D,onPointerCancel:D,onClick:()=>{if(C.current){C.current=!1;return}!S&&!y&&x($=>!$)},className:H("flex touch-none flex-col items-center pt-2",y?"":"cursor-grab active:cursor-grabbing"),children:[n.jsx("div",{className:"mb-1.5 h-1 w-10 rounded-full bg-fg-subtle/40"}),n.jsxs("div",{className:"flex w-full items-center gap-2 px-4 pb-3",children:[n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",role:"status","aria-live":"polite",children:m??T}),p?n.jsxs(n.Fragment,{children:[o&&!f&&t!=="counting"&&n.jsx(G,{variant:"ghost",size:"touch",icon:n.jsx(Cs,{className:"size-4"}),onPointerDown:$=>$.stopPropagation(),onClick:$=>{$.stopPropagation(),o()},"aria-label":"Mark as read",className:"-my-2 shrink-0"}),n.jsx(G,{variant:"ghost",size:"touch",icon:n.jsx(We,{className:"size-4"}),onPointerDown:$=>$.stopPropagation(),onClick:$=>{$.stopPropagation(),s()},"aria-label":"Cancel selection",className:"-my-2 -mr-2 shrink-0"})]}):n.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-xs text-fg-subtle",children:[n.jsx("span",{children:"Swipe up for actions"}),n.jsx(zm,{className:"size-4"})]})]})]}),n.jsxs("div",{inert:p?void 0:!0,className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-4 pb-4",children:[h&&n.jsx("div",{className:"mb-3",children:n.jsx(Pa,{value:h.value,max:h.max,tone:h.tone})}),d&&t!=="running"&&n.jsxs("label",{className:"mb-3 flex min-h-11 cursor-pointer items-center gap-3 text-sm font-medium text-fg-muted",children:[n.jsx(sn,{"aria-label":"Select all",checked:d.checked,indeterminate:d.indeterminate,onChange:d.onChange}),"Select all loaded"]}),F&&n.jsxs("div",{className:"mb-3 flex items-stretch justify-around gap-1 border-b border-line pb-3",children:[n.jsx(G,{variant:"ghost",onClick:r,icon:f?n.jsx(nt,{className:"size-5 animate-spin"}):n.jsx(rt,{className:"size-5 text-danger"}),"aria-label":"Move selected messages to Trash","aria-busy":f||void 0,className:"h-auto flex-1 flex-col gap-1 px-0 py-1.5 text-[11px]",children:"Delete"}),u&&n.jsxs("div",{className:"flex flex-1 flex-col items-center gap-1",children:[u,n.jsx("span",{"aria-hidden":"true",className:"text-[11px] text-fg-muted",children:"Move"})]}),a&&n.jsx(G,{variant:"ghost",onClick:a,icon:n.jsx(Ns,{className:"size-5"}),"aria-label":"Move selected messages to Junk",className:"h-auto flex-1 flex-col gap-1 px-0 py-1.5 text-[11px]",children:"Junk"})]}),R&&(i||l)&&n.jsxs("div",{className:"flex flex-col gap-2",children:[i&&n.jsxs(G,{variant:"primary",onClick:i,className:"h-auto flex-col items-start gap-0 px-4 py-2.5 text-left",children:[n.jsx("span",{className:"text-sm font-semibold leading-tight",children:"Select similar messages"}),n.jsx("span",{className:"text-xs opacity-80",children:"find more like these"})]}),l&&n.jsxs(G,{variant:"secondary",onClick:l,className:"h-auto flex-col items-start gap-0 px-4 py-2.5 text-left",children:[n.jsx("span",{className:"text-sm font-medium leading-tight",children:"Something else"}),n.jsx("span",{className:"text-xs text-fg-subtle",children:"just deal with these"})]})]}),g&&n.jsx(Xt,{tone:g.tone,variant:"soft",role:"status","aria-live":"polite",className:H(F||h?"mt-1":"mt-0"),children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.text&&n.jsx("span",{children:g.text}),g.action&&n.jsx(G,{variant:"ghost",size:"md",onClick:g.action.onClick,className:"-my-1 min-h-11 shrink-0",children:g.action.label})]})})]})]})}const Fa=[{id:"all",label:"All",tone:"neutral"},{id:"personal",label:"Personal",tone:"accent"},{id:"transactional",label:"Transactional",tone:"positive"},{id:"newsletter",label:"Newsletter",tone:"neutral"},{id:"marketing",label:"Marketing",tone:"warning"},{id:"social",label:"Social",tone:"warning"},{id:"automated",label:"Automated",tone:"neutral"}],lc={id:"unread",label:"Unread"},tg={id:"flagged",label:"Starred"},cc={id:"attachment",label:"Has attachment"};function sg(e){if(!(e.length<=1))return e.map(t=>({id:t.id,label:t.label,count:t.count,active:t.active}))}function ng(e=[]){return{categories:[...Fa],filters:Hd,sources:sg(e)}}function rg(){return{categories:[...Fa],filters:[lc,tg,cc]}}function ag(){return{categories:[...Fa],filters:[lc,cc]}}function Tt(e,t,{checkForDefaultPrevented:s=!0}={}){return function(a){if(e?.(a),s===!1||!a||!a.defaultPrevented)return t?.(a)}}function ti(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function og(...e){return t=>{let s=!1;const r=e.map(a=>{const o=ti(a,t);return!s&&typeof o=="function"&&(s=!0),o});if(s)return()=>{for(let a=0;a<r.length;a++){const o=r[a];typeof o=="function"?o():ti(e[a],null)}}}}function es(...e){return c.useCallback(og(...e),e)}function ig(e,t=[]){let s=[];function r(o,i){const l=c.createContext(i);l.displayName=o+"Context";const u=s.length;s=[...s,i];const f=m=>{const{scope:h,children:g,...v}=m,p=h?.[e]?.[u]||l,x=c.useMemo(()=>v,Object.values(v));return n.jsx(p.Provider,{value:x,children:g})};f.displayName=o+"Provider";function d(m,h,g={}){const{optional:v=!1}=g,p=h?.[e]?.[u]||l,x=c.useContext(p);if(x)return x;if(i!==void 0)return i;if(!v)throw new Error(`\`${m}\` must be used within \`${o}\``)}return[f,d]}const a=()=>{const o=s.map(i=>c.createContext(i));return function(l){const u=l?.[e]||o;return c.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return a.scopeName=e,[r,lg(a,...t)]}function lg(...e){const t=e[0];if(e.length===1)return t;const s=()=>{const r=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(o){const i=r.reduce((l,{useScope:u,scopeName:f})=>{const m=u(o)[`__scope${f}`];return{...l,...m}},{});return c.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return s.scopeName=t.scopeName,s}var Ws=globalThis?.document?c.useLayoutEffect:()=>{},cg=ma[" useInsertionEffect ".trim().toString()]||Ws;function ug({prop:e,defaultProp:t,onChange:s=()=>{},caller:r}){const[a,o,i]=dg({defaultProp:t,onChange:s}),l=e!==void 0,u=l?e:a;{const d=c.useRef(e!==void 0);c.useEffect(()=>{const m=d.current;m!==l&&console.warn(`${r} is changing from ${m?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=l},[l,r])}const f=c.useCallback(d=>{if(l){const m=fg(d)?d(e):d;m!==e&&i.current?.(m)}else o(d)},[l,e,o,i]);return[u,f]}function dg({defaultProp:e,onChange:t}){const[s,r]=c.useState(e),a=c.useRef(s),o=c.useRef(t);return cg(()=>{o.current=t},[t]),c.useEffect(()=>{a.current!==s&&(o.current?.(s),a.current=s)},[s,a]),[s,r,o]}function fg(e){return typeof e=="function"}function _a(e){const t=c.forwardRef((s,r)=>{let{children:a,...o}=s,i=null,l=!1;const u=[];si(a)&&typeof yn=="function"&&(a=yn(a._payload)),c.Children.forEach(a,h=>{if(xg(h)){l=!0;const g=h;let v="child"in g.props?g.props.child:g.props.children;si(v)&&typeof yn=="function"&&(v=yn(v._payload)),i=hg(g,v),u.push(i?.props?.children)}else u.push(h)}),i?i=c.cloneElement(i,void 0,u):!l&&c.Children.count(a)===1&&c.isValidElement(a)&&(i=a);const f=i?gg(i):void 0,d=es(r,f);if(!i){if(a||a===0)throw new Error(l?wg(e):yg(e));return a}const m=pg(o,i.props??{});return i.type!==c.Fragment&&(m.ref=r?d:f),c.cloneElement(i,m)});return t.displayName=`${e}.Slot`,t}var cS=_a("Slot"),mg=Symbol.for("radix.slottable"),hg=(e,t)=>{if("child"in e.props){const s=e.props.child;return c.isValidElement(s)?c.cloneElement(s,void 0,e.props.children(s.props.children)):null}return c.isValidElement(t)?t:null};function pg(e,t){const s={...t};for(const r in t){const a=e[r],o=t[r];/^on[A-Z]/.test(r)?a&&o?s[r]=(...l)=>{const u=o(...l);return a(...l),u}:a&&(s[r]=a):r==="style"?s[r]={...a,...o}:r==="className"&&(s[r]=[a,o].filter(Boolean).join(" "))}return{...e,...s}}function gg(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?e.props.ref:e.props.ref||e.ref)}function xg(e){return c.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===mg}var bg=Symbol.for("react.lazy");function si(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===bg&&"_payload"in e&&vg(e._payload)}function vg(e){return typeof e=="object"&&e!==null&&"then"in e}var yg=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,wg=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,yn=ma[" use ".trim().toString()],jg=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],bt=jg.reduce((e,t)=>{const s=_a(`Primitive.${t}`),r=c.forwardRef((a,o)=>{const{asChild:i,...l}=a,u=i?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(u,{...l,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Sg(e,t){e&&ha.flushSync(()=>e.dispatchEvent(t))}function Vs(e){const t=c.useRef(e);return c.useEffect(()=>{t.current=e}),c.useMemo(()=>((...s)=>t.current?.(...s)),[])}var kg="DismissableLayer",Yr="dismissableLayer.update",Cg="dismissableLayer.pointerDownOutside",Ng="dismissableLayer.focusOutside",ni,za=c.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),uc=c.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:l,onDismiss:u,...f}=e,d=c.useContext(za),[m,h]=c.useState(null),g=m?.ownerDocument??globalThis?.document,[,v]=c.useState({}),p=es(t,h),x=Array.from(d.layers),[b]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),w=b?x.indexOf(b):-1,j=m?x.indexOf(m):-1,y=d.layersWithOutsidePointerEventsDisabled.size>0,I=j>=w,N=c.useRef(!1),k=Mg(D=>{o?.(D),l?.(D),D.defaultPrevented||u?.()},{ownerDocument:g,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:N,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:c.useCallback(D=>{if(!(D instanceof Node))return!1;const O=[...d.branches].some(E=>E.contains(D));return I&&!O},[d.branches,I])}),C=Ag(D=>{if(r&&N.current)return;const O=D.target;[...d.branches].some(S=>S.contains(O))||(i?.(D),l?.(D),D.defaultPrevented||u?.())},g),M=m?j===x.length-1:!1,P=Vs(D=>{D.key==="Escape"&&(a?.(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))});return c.useEffect(()=>{if(M)return g.addEventListener("keydown",P,{capture:!0}),()=>g.removeEventListener("keydown",P,{capture:!0})},[g,M,P]),c.useEffect(()=>{if(m)return s&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(ni=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(m)),d.layers.add(m),ri(),()=>{s&&(d.layersWithOutsidePointerEventsDisabled.delete(m),d.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=ni))}},[m,g,s,d]),c.useEffect(()=>()=>{m&&(d.layers.delete(m),d.layersWithOutsidePointerEventsDisabled.delete(m),ri())},[m,d]),c.useEffect(()=>{const D=()=>v({});return document.addEventListener(Yr,D),()=>document.removeEventListener(Yr,D)},[]),n.jsx(bt.div,{...f,ref:p,style:{pointerEvents:y?I?"auto":"none":void 0,...e.style},onFocusCapture:Tt(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Tt(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Tt(e.onPointerDownCapture,k.onPointerDownCapture)})});uc.displayName=kg;var Eg="DismissableLayerBranch",Ig=c.forwardRef((e,t)=>{const s=c.useContext(za),r=c.useRef(null),a=es(t,r);return c.useEffect(()=>{const o=r.current;if(o)return s.branches.add(o),()=>{s.branches.delete(o)}},[s.branches]),n.jsx(bt.div,{...e,ref:a})});Ig.displayName=Eg;function Tg(){const e=c.useContext(za),[t,s]=c.useState(null);return c.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),s}var Rg=()=>!0;function Mg(e,t){const{ownerDocument:s=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:o,shouldHandlePointerDownOutside:i=Rg}=t,l=Vs(e),u=c.useRef(!1),f=c.useRef(!1),d=c.useRef(new Map),m=c.useRef(()=>{});return c.useEffect(()=>{function h(){f.current=!1,a.current=!1,d.current.clear()}function g(){return Array.from(d.current.values()).some(Boolean)}function v(j){if(!f.current)return;const y=j.target;y instanceof Node&&[...o].some(N=>N.contains(y))||d.current.set(j.type,!0),j.type==="click"&&window.setTimeout(()=>{f.current&&m.current()},0)}function p(j){f.current&&d.current.set(j.type,!1)}const x=j=>{if(j.target&&!u.current){let y=function(){s.removeEventListener("click",m.current);const N=g();h(),N||dc(Cg,l,I,{discrete:!0})};if(!i(j.target)){s.removeEventListener("click",m.current),h(),u.current=!1;return}const I={originalEvent:j};f.current=!0,a.current=r&&j.button===0,d.current.clear(),!r||j.button!==0?y():(s.removeEventListener("click",m.current),m.current=y,s.addEventListener("click",m.current,{once:!0}))}else s.removeEventListener("click",m.current),h();u.current=!1},b=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const j of b)s.addEventListener(j,v,!0),s.addEventListener(j,p);const w=window.setTimeout(()=>{s.addEventListener("pointerdown",x)},0);return()=>{window.clearTimeout(w),s.removeEventListener("pointerdown",x),s.removeEventListener("click",m.current);for(const j of b)s.removeEventListener(j,v,!0),s.removeEventListener(j,p)}},[s,l,r,a,o,i]),{onPointerDownCapture:()=>u.current=!0}}function Ag(e,t=globalThis?.document){const s=Vs(e),r=c.useRef(!1);return c.useEffect(()=>{const a=o=>{o.target&&!r.current&&dc(Ng,s,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,s]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function ri(){const e=new CustomEvent(Yr);document.dispatchEvent(e)}function dc(e,t,s,{discrete:r}){const a=s.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:s});t&&a.addEventListener(e,t,{once:!0}),r?Sg(a,o):a.dispatchEvent(o)}var wn=0,is=null;function Dg(){c.useEffect(()=>{is||(is={start:ai(),end:ai()});const{start:e,end:t}=is;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),wn++,()=>{wn===1&&(is?.start.remove(),is?.end.remove(),is=null),wn=Math.max(0,wn-1)}},[])}function ai(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Nr="focusScope.autoFocusOnMount",Er="focusScope.autoFocusOnUnmount",oi={bubbles:!1,cancelable:!0},Og="FocusScope",fc=c.forwardRef((e,t)=>{const{loop:s=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[l,u]=c.useState(null),f=Vs(a),d=Vs(o),m=c.useRef(null),h=es(t,u),g=c.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;c.useEffect(()=>{if(r){let p=function(j){if(g.paused||!l)return;const y=j.target;l.contains(y)?m.current=y:Ct(m.current,{select:!0})},x=function(j){if(g.paused||!l)return;const y=j.relatedTarget;y!==null&&(l.contains(y)||Ct(m.current,{select:!0}))},b=function(j){if(document.activeElement===document.body)for(const I of j)I.removedNodes.length>0&&Ct(l)};document.addEventListener("focusin",p),document.addEventListener("focusout",x);const w=new MutationObserver(b);return l&&w.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",x),w.disconnect()}}},[r,l,g.paused]),c.useEffect(()=>{if(l){li.add(g);const p=document.activeElement;if(!l.contains(p)){const b=new CustomEvent(Nr,oi);l.addEventListener(Nr,f),l.dispatchEvent(b),b.defaultPrevented||(Pg(zg(mc(l)),{select:!0}),document.activeElement===p&&Ct(l))}return()=>{l.removeEventListener(Nr,f),setTimeout(()=>{const b=new CustomEvent(Er,oi);l.addEventListener(Er,d),l.dispatchEvent(b),b.defaultPrevented||Ct(p??document.body,{select:!0}),l.removeEventListener(Er,d),li.remove(g)},0)}}},[l,f,d,g]);const v=c.useCallback(p=>{if(!s&&!r||g.paused)return;const x=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,b=document.activeElement;if(x&&b){const w=p.currentTarget,[j,y]=Lg(w);j&&y?!p.shiftKey&&b===y?(p.preventDefault(),s&&Ct(j,{select:!0})):p.shiftKey&&b===j&&(p.preventDefault(),s&&Ct(y,{select:!0})):b===w&&p.preventDefault()}},[s,r,g.paused]);return n.jsx(bt.div,{tabIndex:-1,...i,ref:h,onKeyDown:v})});fc.displayName=Og;function Pg(e,{select:t=!1}={}){const s=document.activeElement;for(const r of e)if(Ct(r,{select:t}),document.activeElement!==s)return}function Lg(e){const t=mc(e),s=ii(t,e),r=ii(t.reverse(),e);return[s,r]}function mc(e){const t=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)t.push(s.currentNode);return t}function ii(e,t){const s=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(s?!r.checkVisibility({checkVisibilityCSS:!0}):$g(r,{upTo:t})))return r}function $g(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Fg(e){return e instanceof HTMLInputElement&&"select"in e}function Ct(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&Fg(e)&&t&&e.select()}}var li=_g();function _g(){let e=[];return{add(t){const s=e[0];t!==s&&s?.pause(),e=ci(e,t),e.unshift(t)},remove(t){e=ci(e,t),e[0]?.resume()}}}function ci(e,t){const s=[...e],r=s.indexOf(t);return r!==-1&&s.splice(r,1),s}function zg(e){return e.filter(t=>t.tagName!=="A")}var Bg=ma[" useId ".trim().toString()]||(()=>{}),Kg=0;function Ir(e){const[t,s]=c.useState(Bg());return Ws(()=>{s(r=>r??String(Kg++))},[e]),e||(t?`radix-${t}`:"")}var Ug="Portal",hc=c.forwardRef((e,t)=>{const{container:s,...r}=e,[a,o]=c.useState(!1);Ws(()=>o(!0),[]);const i=s||a&&globalThis?.document?.body;return i?ha.createPortal(n.jsx(bt.div,{...r,ref:t}),i):null});hc.displayName=Ug;function qg(e,t){return c.useReducer((s,r)=>t[s][r]??s,e)}var Zn=e=>{const{present:t,children:s}=e,r=Hg(t),a=typeof s=="function"?s({present:r.isPresent}):c.Children.only(s),o=Wg(r.ref,Vg(a));return typeof s=="function"||r.isPresent?c.cloneElement(a,{ref:o}):null};Zn.displayName="Presence";function Hg(e){const[t,s]=c.useState(),r=c.useRef(null),a=c.useRef(e),o=c.useRef("none"),i=c.useRef(void 0),l=e?"mounted":"unmounted",[u,f]=qg(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return c.useEffect(()=>{u==="mounted"?(o.current=i.current??Os(r.current),i.current=void 0):o.current="none"},[u]),Ws(()=>{const d=r.current,m=a.current;if(m!==e){const g=o.current,v=Os(d);e?(i.current=v,f("MOUNT")):v==="none"||d?.display==="none"?f("UNMOUNT"):f(m&&g!==v?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,f]),Ws(()=>{if(t){let d;const m=t.ownerDocument.defaultView??window,h=v=>{const x=Os(r.current).includes(CSS.escape(v.animationName));if(v.target===t&&x&&(f("ANIMATION_END"),!a.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},g=v=>{v.target===t&&(o.current=Os(r.current))};return t.addEventListener("animationstart",g),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{m.clearTimeout(d),t.removeEventListener("animationstart",g),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else f("ANIMATION_END")},[t,f]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:c.useCallback(d=>{if(d){const m=getComputedStyle(d);r.current=m,i.current=Os(m)}else r.current=null;s(d)},[])}}function ui(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Wg(...e){const t=c.useRef(e);return t.current=e,c.useCallback(s=>{const r=t.current;let a=!1;const o=r.map(i=>{const l=ui(i,s);return!a&&typeof l=="function"&&(a=!0),l});if(a)return()=>{for(let i=0;i<o.length;i++){const l=o[i];typeof l=="function"?l():ui(r[i],null)}}},[])}function Os(e){return e?.animationName||"none"}function Vg(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?e.props.ref:e.props.ref||e.ref)}var Qg=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},ls=new WeakMap,jn=new WeakMap,Sn={},Tr=0,pc=function(e){return e&&(e.host||pc(e.parentNode))},Yg=function(e,t){return t.map(function(s){if(e.contains(s))return s;var r=pc(s);return r&&e.contains(r)?r:(console.error("aria-hidden",s,"in not contained inside",e,". Doing nothing"),null)}).filter(function(s){return!!s})},Gg=function(e,t,s,r){var a=Yg(t,Array.isArray(e)?e:[e]);Sn[s]||(Sn[s]=new WeakMap);var o=Sn[s],i=[],l=new Set,u=new Set(a),f=function(m){!m||l.has(m)||(l.add(m),f(m.parentNode))};a.forEach(f);var d=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(h){if(l.has(h))d(h);else try{var g=h.getAttribute(r),v=g!==null&&g!=="false",p=(ls.get(h)||0)+1,x=(o.get(h)||0)+1;ls.set(h,p),o.set(h,x),i.push(h),p===1&&v&&jn.set(h,!0),x===1&&h.setAttribute(s,"true"),v||h.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",h,b)}})};return d(t),l.clear(),Tr++,function(){i.forEach(function(m){var h=ls.get(m)-1,g=o.get(m)-1;ls.set(m,h),o.set(m,g),h||(jn.has(m)||m.removeAttribute(r),jn.delete(m)),g||m.removeAttribute(s)}),Tr--,Tr||(ls=new WeakMap,ls=new WeakMap,jn=new WeakMap,Sn={})}},Xg=function(e,t,s){s===void 0&&(s="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),a=Qg(e);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live], script"))),Gg(r,a,s,"aria-hidden")):function(){return null}},Mn="right-scroll-bar-position",An="width-before-scroll-bar",Jg="with-scroll-bars-hidden",Zg="--removed-body-scroll-bar-size";function Rr(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function ex(e,t){var s=c.useState(function(){return{value:e,callback:t,facade:{get current(){return s.value},set current(r){var a=s.value;a!==r&&(s.value=r,s.callback(r,a))}}}})[0];return s.callback=t,s.facade}var tx=typeof window<"u"?c.useLayoutEffect:c.useEffect,di=new WeakMap;function sx(e,t){var s=ex(null,function(r){return e.forEach(function(a){return Rr(a,r)})});return tx(function(){var r=di.get(s);if(r){var a=new Set(r),o=new Set(e),i=s.current;a.forEach(function(l){o.has(l)||Rr(l,null)}),o.forEach(function(l){a.has(l)||Rr(l,i)})}di.set(s,e)},[e]),s}function nx(e){return e}function rx(e,t){t===void 0&&(t=nx);var s=[],r=!1,a={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return s.length?s[s.length-1]:e},useMedium:function(o){var i=t(o,r);return s.push(i),function(){s=s.filter(function(l){return l!==i})}},assignSyncMedium:function(o){for(r=!0;s.length;){var i=s;s=[],i.forEach(o)}s={push:function(l){return o(l)},filter:function(){return s}}},assignMedium:function(o){r=!0;var i=[];if(s.length){var l=s;s=[],l.forEach(o),i=s}var u=function(){var d=i;i=[],d.forEach(o)},f=function(){return Promise.resolve().then(u)};f(),s={push:function(d){i.push(d),f()},filter:function(d){return i=i.filter(d),s}}}};return a}function ax(e){e===void 0&&(e={});var t=rx(null);return t.options=Nt({async:!0,ssr:!1},e),t}var gc=function(e){var t=e.sideCar,s=Xi(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return c.createElement(r,Nt({},s))};gc.isSideCarExport=!0;function ox(e,t){return e.useMedium(t),gc}var xc=ax(),Mr=function(){},er=c.forwardRef(function(e,t){var s=c.useRef(null),r=c.useState({onScrollCapture:Mr,onWheelCapture:Mr,onTouchMoveCapture:Mr}),a=r[0],o=r[1],i=e.forwardProps,l=e.children,u=e.className,f=e.removeScrollBar,d=e.enabled,m=e.shards,h=e.sideCar,g=e.noRelative,v=e.noIsolation,p=e.inert,x=e.allowPinchZoom,b=e.as,w=b===void 0?"div":b,j=e.gapMode,y=Xi(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),I=h,N=sx([s,t]),k=Nt(Nt({},y),a);return c.createElement(c.Fragment,null,d&&c.createElement(I,{sideCar:xc,removeScrollBar:f,shards:m,noRelative:g,noIsolation:v,inert:p,setCallbacks:o,allowPinchZoom:!!x,lockRef:s,gapMode:j}),i?c.cloneElement(c.Children.only(l),Nt(Nt({},k),{ref:N})):c.createElement(w,Nt({},k,{className:u,ref:N}),l))});er.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};er.classNames={fullWidth:An,zeroRight:Mn};var ix=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function lx(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=ix();return t&&e.setAttribute("nonce",t),e}function cx(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function ux(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var dx=function(){var e=0,t=null;return{add:function(s){e==0&&(t=lx())&&(cx(t,s),ux(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},fx=function(){var e=dx();return function(t,s){c.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},bc=function(){var e=fx(),t=function(s){var r=s.styles,a=s.dynamic;return e(r,a),null};return t},mx={left:0,top:0,right:0,gap:0},Ar=function(e){return parseInt(e||"",10)||0},hx=function(e){var t=window.getComputedStyle(document.body),s=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return[Ar(s),Ar(r),Ar(a)]},px=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return mx;var t=hx(e),s=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-s+t[2]-t[0])}},gx=bc(),xs="data-scroll-locked",xx=function(e,t,s,r){var a=e.left,o=e.top,i=e.right,l=e.gap;return s===void 0&&(s="margin"),`
76
- .`.concat(Jg,` {
74
+ `},Fh=(e,t)=>e?t?"html,body{margin:0;color-scheme:dark light}":"html{margin:0;background-color:#ffffff;filter:invert(0.92) hue-rotate(180deg)}body{margin:0}img,picture,video,svg,canvas,[style*='background-image'],[background]{filter:invert(0.92) hue-rotate(180deg)}":"html,body{margin:0;background-color:#ffffff;color-scheme:light}",_h=(e,t,s)=>{if(t==="plain")return`${_o}<style>${$h(s)}</style>${e}`;const r=Lh.test(e);return`${_o}<style>${Fh(s,r)}</style>${e}`},zh=5e4,Bh=1e4,Kh="(max-width: 640px)",Uh=.4,qh="allow-same-origin allow-popups allow-popups-to-escape-sandbox",zo=(e,t,s)=>Math.min(Math.ceil(Math.max(e,t)),s),Hh=(e,t)=>e<=0||t<=0||e<=t?1:Math.max(Uh,t/e),Wh=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia(e);s(r.matches);const a=o=>s(o.matches);return r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[e]),t},Vh=new Set(["Enter","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"]),Qh=e=>e===" "?!1:e.length===1?!0:Vh.has(e),Bo=e=>{if(e.metaKey||e.ctrlKey||e.altKey||!Qh(e.key))return;const t=e.currentTarget??e.target,s=t?.defaultView?.parent;!s||s===t?.defaultView||s.dispatchEvent(new KeyboardEvent("keydown",{key:e.key,code:e.code,shiftKey:e.shiftKey,bubbles:!0,cancelable:!0}))},Ko=({html:e,variant:t="framed",isDark:s=!1,className:r})=>{const a=c.useRef(null),o=c.useRef(null),[i,l]=c.useState(0),[u,f]=c.useState(0),[d,m]=c.useState(0),h=Wh(Kh),g=c.useMemo(()=>_h(e,t,s),[e,t,s]);c.useEffect(()=>{const j=a.current;if(!j)return;const y=()=>m(N=>N===j.clientWidth?N:j.clientWidth);y();const I=new ResizeObserver(y);return I.observe(j),()=>I.disconnect()},[]),c.useEffect(()=>{const j=o.current;if(!j)return;const y=()=>{const C=j.contentDocument;if(!C?.body)return;const M=C.documentElement,P=zo(C.body.scrollHeight,M?.scrollHeight??0,zh);l(O=>O===P?O:P);const D=zo(C.body.scrollWidth,M?.scrollWidth??0,Bh);f(O=>O===D?O:D)};let I,N;const k=()=>{y();const C=j.contentDocument;C?.body&&(I=new ResizeObserver(y),I.observe(C.body),C.documentElement&&I.observe(C.documentElement),C.addEventListener("keydown",Bo),N=C)};return j.addEventListener("load",k),()=>{j.removeEventListener("load",k),N?.removeEventListener("keydown",Bo),I?.disconnect()}},[]);const v=h?Hh(u,d):1,p=v<1,x=p?`${u}px`:h?"100%":t==="framed"&&u>0?`max(100%, ${u}px)`:u===0?"100%":`${u}px`,b=i===0?"1px":`${i}px`,w=n.jsx("iframe",{ref:o,title:"Email content",sandbox:qh,srcDoc:g,className:p?void 0:r,scrolling:"no",style:{width:x,maxWidth:p?"none":void 0,border:"none",display:"block",height:b,overflow:"hidden",transform:p?`scale(${v})`:void 0,transformOrigin:p?"top left":void 0,colorScheme:"normal"}});return n.jsx("div",{ref:a,className:p?r:void 0,children:p?n.jsx("div",{style:{width:"100%",height:`${Math.ceil(i*v)}px`,overflow:"hidden"},children:w}):w})},Uo=()=>n.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),nc=({html:e,text:t,isDark:s=!1,category:r,allowImages:a=!1,resolveCid:o,className:i,renderBlockedNotice:l})=>{const u=c.useMemo(()=>!e||typeof document>"u"?null:Oh({allowExternalImages:a,resolveCid:o})(e),[e,a,o]),f=u?.html??null,{framed:d,isPlain:m}=jh(r,u?.hasAuthorBackground??!1),h=c.useMemo(()=>!f||a?0:(f.match(/data-blocked-src/g)||[]).length,[f,a]);return!f&&!t?n.jsx("div",{className:H("message-body",i),children:n.jsx(Uo,{})}):n.jsxs("div",{className:H("message-body",i),children:[h>0&&n.jsx("div",{className:"message-body-notice",children:l?.(h)}),f?d?n.jsx("div",{className:"w-full max-w-full overflow-x-auto",children:n.jsx(Ko,{html:f,variant:"framed",isDark:s})}):n.jsx("div",{className:"max-w-full overflow-x-auto lg:max-w-2xl",children:n.jsx(Ko,{html:f,variant:m?"plain":"framed",isDark:s})}):t?n.jsx("pre",{className:"email-text whitespace-pre-wrap text-sm leading-relaxed",children:t}):n.jsx(Uo,{})]})};function Es({message:e="Select a thread to read",icon:t,showHints:s=!0,className:r}){return n.jsxs("div",{className:H("flex flex-1 flex-col items-center justify-center text-center",r),children:[t??n.jsx(ca,{className:"size-10 text-fg-subtle"}),n.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:e}),s&&n.jsxs("p",{className:"text-2xs text-fg-subtle",children:[n.jsx(ps,{children:"j"})," / ",n.jsx(ps,{children:"k"})," to move, ",n.jsx(ps,{children:"Enter"})," to open"]})]})}function rc({message:e,onClick:t,isFocused:s,isUnread:r,trailing:a}){const o=n.jsxs(n.Fragment,{children:[n.jsx(ys,{className:"size-3.5 shrink-0 text-fg-subtle"}),n.jsxs("div",{className:"relative shrink-0",children:[n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"md"}),r&&n.jsx("span",{className:"absolute -top-0.5 -right-0.5 size-2 rounded-full border border-canvas bg-accent"})]}),n.jsx("span",{className:H("w-36 shrink-0 truncate text-sm",r?"font-semibold text-fg":"font-medium text-fg-muted"),children:e.fromName}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-fg-subtle",children:e.snippet}),a??n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.dateLabel})]}),i=H("group flex h-section-row w-full items-center gap-3 border-b border-line px-2 text-left transition-colors hover:bg-surface-sunken lg:px-4",s&&"bg-surface-sunken ring-1 ring-inset ring-accent/30");return t?n.jsx("div",{role:"button",tabIndex:0,"aria-expanded":!1,onClick:t,onKeyDown:l=>{$d(l)&&(l.preventDefault(),t())},className:H(i,"cursor-pointer"),children:o}):n.jsx("div",{className:i,children:o})}function ac({message:e,warning:t,onHeaderClick:s,isFocused:r,senderBadge:a,trailing:o,to:i,indicators:l,actionMenu:u,actionBar:f,body:d}){const m=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[n.jsxs("span",{className:"text-sm font-semibold text-fg",children:[e.fromName,a]}),o??n.jsx("span",{className:"text-2xs text-fg-subtle",children:e.dateLabel})]}),n.jsx("div",{className:"text-xs text-fg-subtle",children:e.fromEmail}),i!==null&&n.jsx("div",{className:"text-xs text-fg-subtle",children:i??n.jsxs(n.Fragment,{children:["to ",e.toLabel]})})]});return n.jsxs("div",{className:H("px-2 py-3 lg:px-4",r&&"ring-1 ring-inset ring-accent/30"),children:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx(Rt,{className:"mt-1 size-3.5 shrink-0 text-fg-subtle"}),n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"md"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[s?n.jsx("button",{type:"button",onClick:s,className:"w-full text-left",children:m}):m,l]}),u&&n.jsx("div",{className:"shrink-0",children:u})]}),t&&n.jsxs("div",{className:"mt-3 flex items-start gap-3 rounded-md bg-danger-soft p-3",children:[n.jsx(Ns,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("div",{className:"text-sm text-fg",children:[n.jsx("span",{className:"font-semibold text-danger",children:"Caution: "}),t," ",n.jsx("button",{type:"button",className:"text-accent underline",children:"Why?"})]})]}),f&&n.jsx("div",{className:"mt-3 -mx-2 lg:-mx-4",children:f}),n.jsx("div",{className:"-mx-2 [&_.message-body-notice]:px-2 lg:mx-0 lg:[&_.message-body-notice]:px-0",children:d??n.jsx(nc,{className:"mt-3",html:e.bodyHtml,category:e.framed?"newsletter":"personal",allowImages:!0})})]})}function Yh({thread:e,onBack:t,intelligence:s,intelligenceOpen:r,onToggleIntelligence:a,actions:o,children:i,touchHandlers:l}){const[u,f]=c.useState(!1),d=a!==void 0,m=d?r??!1:u,h=!!s||d,g=()=>{if(d){a?.();return}f(p=>!p)},v=()=>{if(d){m&&a?.();return}f(!1)};return n.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ll,{className:"size-4"}),onClick:t,"aria-label":"Back to messages",className:"-ml-1 shrink-0"}),n.jsx("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e.subject}),h&&n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(la,{className:"size-4"}),onClick:g,"aria-label":m?"Hide intelligence panel":"Show intelligence panel","aria-pressed":m,title:"Intelligence",className:H("shrink-0",m&&"bg-accent-2-soft text-accent-2")})]}),n.jsx("div",{className:"flex-1 overflow-y-auto",style:l?{touchAction:"pan-y"}:void 0,...l,children:i??e.messages.map(p=>{const x=b=>b?()=>b(p.id):void 0;return p.expanded?n.jsx(ac,{message:p,warning:e.warning,onHeaderClick:x(o?.onToggleExpand),actionBar:n.jsx(sc,{hasThread:!0,onReply:x(o?.onReply),onReplyAll:x(o?.onReplyAll),onForward:x(o?.onForward),onToggleStar:x(o?.onToggleStar),onDelete:x(o?.onDelete),onToggleRead:x(o?.onToggleRead),moveSlot:o?.moveSlot?.(p.id)})},p.id):n.jsx(rc,{message:p,onClick:x(o?.onToggleExpand)},p.id)})}),s&&!d&&n.jsx(ua,{open:m,onClose:v,title:"Intelligence",anchor:"right",className:"p-0",children:n.jsx(Wl,{data:s,onClose:v,className:"h-full w-full border-l-0"})})]})}const Gh="button:not([disabled]), a[href]",Wt="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface-sunken";function Xh({active:e,dimmed:t,indent:s}){return H("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors",Wt,s&&"pl-7",e?"bg-accent-2-soft font-medium text-accent-2":"text-fg-muted hover:bg-surface hover:text-fg",t&&"opacity-55")}function Jh({icon:e,label:t,count:s,active:r}){return n.jsxs(n.Fragment,{children:[e&&n.jsx("span",{className:H("shrink-0",r?"text-accent-2":"text-fg-subtle"),children:e}),n.jsx("span",{className:"flex-1 truncate",children:t}),s!=null&&s>0&&n.jsx("span",{className:H("text-2xs tabular-nums",r?"text-accent-2":"text-fg-subtle"),children:s})]})}function gs({icon:e,label:t,count:s,active:r,dimmed:a,indent:o,navId:i,linkComponent:l,ariaLabel:u,title:f,onClick:d}){const m=Xh({active:r,dimmed:a,indent:o}),h=n.jsx(Jh,{icon:e,label:t,count:s,active:r});return i&&l?l({navId:i,className:m,ariaLabel:u??t,title:f,onClick:d,children:h}):n.jsx("button",{type:"button",onClick:d,className:m,"aria-label":u,title:f,children:h})}const qo={inbox:0,flagged:1,drafts:2,sent:3,archive:4,all:5,junk:6,trash:7};function Zh(e){switch(e){case"inbox":return n.jsx(ca,{className:"size-4"});case"flagged":return n.jsx(At,{className:"size-4"});case"drafts":return n.jsx(Xi,{className:"size-4"});case"sent":return n.jsx(Gs,{className:"size-4"});case"archive":return n.jsx(zd,{className:"size-4"});case"all":return n.jsx(_d,{className:"size-4"});case"junk":return n.jsx(Fd,{className:"size-4"});case"trash":return n.jsx(rt,{className:"size-4"})}}const Ho=e=>e.role!=null,kr=8,Wo="remit.nav.folders.open.",Vo="remit.nav.account.open.";function Qo(e,t,s){if(typeof localStorage>"u")return s;const r=localStorage.getItem(e+t);return r===null?s:r!=="0"}function Yo(e,t,s){typeof localStorage>"u"||localStorage.setItem(e+t,s?"1":"0")}function ep({query:e,onSelect:t,onRemove:s}){return n.jsxs("div",{className:"group flex w-full items-center gap-1 rounded-md pr-1 hover:bg-surface",children:[n.jsxs("button",{type:"button",onClick:t,className:H("flex min-w-0 flex-1 items-center gap-2 px-2 py-1 text-left text-sm text-fg-muted transition-colors hover:text-fg",Wt),children:[n.jsx(Qn,{className:"size-4 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"min-w-0 flex-1 truncate",children:e})]}),s&&n.jsx("button",{type:"button",onClick:s,"aria-label":`Remove saved search: ${e}`,className:H("shrink-0 rounded-full p-1 text-fg-subtle opacity-0 transition-opacity hover:bg-surface-sunken hover:text-fg group-hover:opacity-100 focus-visible:opacity-100",Wt),children:n.jsx(We,{className:"size-3.5"})})]})}function tp({savedSearches:e,saveableQuery:t,onSelectSavedSearch:s,onRemoveSavedSearch:r,onSaveCurrentSearch:a}){return e.length===0&&!t?null:n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"px-2 pb-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Saved searches"}),t&&n.jsxs("button",{type:"button",onClick:a,className:H("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-accent transition-colors hover:bg-surface",Wt),children:[n.jsx(zm,{className:"size-4 shrink-0"}),n.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Save “",t,"”"]})]}),e.map(o=>n.jsx(ep,{query:o,onSelect:()=>s?.(o),onRemove:r?()=>r(o):void 0},o))]})}function sp({account:e,selectedNavId:t,onSelectNav:s,linkComponent:r}){const[a,o]=c.useState(()=>Qo(Vo,e.id,!0)),[i,l]=c.useState(()=>Qo(Wo,e.id,!0)),[u,f]=c.useState(!1),d=()=>{o(w=>{const j=!w;return Yo(Vo,e.id,j),j})},m=()=>{l(w=>{const j=!w;return Yo(Wo,e.id,j),j})},h=e.mailboxes.filter(Ho).sort((w,j)=>qo[w.role]-qo[j.role]),g=e.mailboxes.filter(w=>!Ho(w)),v=u||g.length<=kr?g:g.slice(0,kr),p=g.length-v.length,x=e.status??"ready",b=x==="ready"&&h.length===0&&g.length===0;return n.jsxs("div",{className:"mt-3",children:[n.jsxs("button",{type:"button",onClick:d,"aria-expanded":a,className:H("flex w-full items-center gap-1.5 px-2 pb-1 text-left transition-colors hover:text-fg",Wt,e.muted&&"opacity-55"),children:[a?n.jsx(Rt,{className:"size-3 shrink-0 text-fg-subtle"}):n.jsx(ys,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"truncate text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),e.muted&&n.jsxs(n.Fragment,{children:[n.jsx($l,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:"muted"})]})]}),a&&n.jsxs(n.Fragment,{children:[x==="loading"&&n.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"Loading…"}),x==="error"&&n.jsxs("div",{role:"alert",className:"mx-2 my-1 flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-2 py-1.5 text-sm",children:[n.jsx(Gt,{className:"mt-0.5 size-4 shrink-0 text-danger","aria-hidden":"true"}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx("p",{className:"font-medium text-danger",children:"Couldn't load mailboxes"})}),e.onRetry&&n.jsx("button",{type:"button",onClick:e.onRetry,className:"shrink-0 text-sm font-medium text-accent hover:underline",children:"Retry"})]}),b&&n.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"No mailboxes"}),x==="ready"&&n.jsxs(n.Fragment,{children:[h.map(w=>n.jsx(gs,{navId:w.id,linkComponent:r,icon:Zh(w.role),label:w.name,ariaLabel:w.name,title:w.fullPath??w.name,count:w.unseen,active:t===w.id,dimmed:e.muted,onClick:()=>s?.(w.id)},w.id)),e.outboxPending!==void 0&&n.jsx(gs,{navId:"outbox",linkComponent:r,icon:n.jsx(Gs,{className:"size-4"}),label:"Outbox",ariaLabel:"Outbox",count:e.outboxPending>0?e.outboxPending:void 0,active:t==="outbox",dimmed:e.muted,onClick:()=>s?.("outbox")}),g.length>0&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{type:"button",onClick:m,"aria-expanded":i,className:H("mt-1 flex w-full items-center gap-1 px-2 py-1 text-left text-2xs font-semibold uppercase tracking-wider text-fg-subtle transition-colors hover:text-fg",Wt),children:[i?n.jsx(Rt,{className:"size-3 shrink-0"}):n.jsx(ys,{className:"size-3 shrink-0"}),n.jsx("span",{className:"flex-1",children:"Folders"}),n.jsx("span",{className:"tabular-nums opacity-70",children:g.length})]}),i&&n.jsxs(n.Fragment,{children:[v.map(w=>n.jsx(gs,{navId:w.id,linkComponent:r,icon:n.jsx(Xf,{className:"size-4"}),label:w.name,ariaLabel:w.name,title:w.fullPath??w.name,count:w.unseen,active:t===w.id,dimmed:e.muted,onClick:()=>s?.(w.id)},w.id)),(p>0||u)&&g.length>kr&&n.jsx("button",{type:"button",onClick:()=>f(w=>!w),className:H("ml-7 flex items-center px-2 py-1 text-2xs font-medium text-accent transition-colors hover:underline",Wt),children:u?"Show less":`Show all (${g.length})`})]})]})]})]})]})}function np({accounts:e,selectedNavId:t,briefUnseen:s,onSelectNav:r,variant:a="desktop",linkComponent:o,savedSearches:i=[],saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:f,onSaveCurrentSearch:d}){const m=c.useRef(null);Kn({containerRef:m,itemSelector:Gh});const h=a==="drawer",g=n.jsxs("nav",{ref:h?m:void 0,className:h?"px-2 py-2":"flex-1 overflow-y-auto px-2 py-2","aria-label":"Mailboxes",children:[n.jsx(gs,{navId:"brief",linkComponent:o,icon:n.jsx(ut,{className:"size-4"}),label:"Daily brief",ariaLabel:"Daily brief",count:s,active:t==="brief",onClick:()=>r?.("brief")}),n.jsx(gs,{navId:"flagged",linkComponent:o,icon:n.jsx(At,{className:"size-4"}),label:"Starred",ariaLabel:"Starred",active:t==="flagged",onClick:()=>r?.("flagged")}),n.jsx(tp,{savedSearches:i,saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:f,onSaveCurrentSearch:d}),e.length===0?n.jsx("div",{className:"px-2 py-4 text-center text-sm text-fg-muted",children:"No accounts configured"}):e.map(v=>n.jsx(sp,{account:v,selectedNavId:t,onSelectNav:r,linkComponent:o},v.id))]});return h?g:n.jsxs("aside",{ref:m,className:"flex h-full w-full flex-col bg-surface-sunken",children:[g,n.jsx("div",{className:"border-t border-line px-2 py-2",children:n.jsx(gs,{navId:"settings",linkComponent:o,icon:n.jsx(Oa,{className:"size-4"}),label:"Settings",ariaLabel:"Settings",active:t==="settings",onClick:()=>r?.("settings")})})]})}function rp({search:e,actions:t,className:s}){return n.jsxs("header",{className:H("flex min-h-16 w-full shrink-0 items-center gap-3 border-b border-line bg-canvas px-3 py-2",s),children:[n.jsx("div",{className:"flex min-w-0 flex-1 justify-start",children:n.jsx("div",{className:"w-full max-w-2xl",children:e})}),t&&n.jsx("div",{className:"flex shrink-0 items-center gap-1",children:t})]})}function ap({label:e,size:t="sm",onUndo:s,undoLabel:r="Undo",filtersHref:a,manageLabel:o="Manage filter",className:i}){return n.jsxs(lt,{tone:"accent",className:H(t==="md"&&"py-1 text-xs",i),children:[n.jsx(Gm,{className:H(t==="sm"?"size-3":"size-3.5","shrink-0"),"aria-hidden":!0}),n.jsx("span",{children:e}),s&&n.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),s()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:r}),a&&n.jsx("a",{href:a,onClick:l=>{l.stopPropagation()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:o})]})}const op=({status:e})=>e==="saving"?n.jsx("span",{className:"animate-pulse text-xs text-fg-muted",children:"Saving..."}):e==="saved"?n.jsx("span",{className:"text-xs text-fg-muted",children:"Draft saved"}):e==="error"?n.jsx("span",{className:"text-xs text-danger",children:"Save failed"}):null;function ip({onSend:e,onDiscard:t,sending:s,canSend:r,saveStatus:a="idle",unavailableReason:o,onUnavailable:i}){return n.jsxs("div",{className:"flex items-center justify-between border-t border-line px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(G,{variant:"primary",size:"md","aria-busy":s,title:r?void 0:o,className:"min-h-11 rounded-full px-4",icon:s?n.jsx(nt,{className:"size-4 animate-spin"}):n.jsx(Gs,{className:"size-4"}),onClick:()=>{if(!s){if(!r){o&&i?.(o);return}e()}},children:"Send"}),n.jsx(op,{status:a})]}),n.jsx(G,{variant:"ghost",size:"md","aria-busy":s,"aria-label":"Discard",className:"min-h-11 min-w-11 px-2 hover:text-danger",icon:n.jsx(rt,{className:"size-4"}),onClick:()=>{s||t()}})]})}function lp({banner:e,header:t,children:s,quoted:r,actionBar:a}){return n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e,t,n.jsxs("div",{className:"min-h-0 flex-1 overflow-auto",children:[s,r&&n.jsx("div",{className:"px-3 pb-2",children:r})]}),a]})}function cp({key:e,shiftKey:t=!1,repeat:s=!1,caretAtStart:r,hasValue:a,chipCount:o}){const i=o-1;return e==="Escape"?a?{type:"clearQuery"}:{type:"blur"}:e==="Tab"&&t?o===0?{type:"none"}:{type:"focusChip",index:i}:e==="Backspace"||e==="ArrowLeft"?!r||o===0?{type:"none"}:s?{type:"none"}:{type:"focusChip",index:i}:{type:"none"}}function up({key:e,repeat:t=!1,index:s,chipCount:r}){return e==="Backspace"||e==="Delete"?t?{type:"none"}:{type:"removeChip",index:s}:e==="ArrowLeft"?s===0?{type:"none"}:{type:"focusChip",index:s-1}:e==="ArrowRight"?s>=r-1?{type:"focusInput"}:{type:"focusChip",index:s+1}:e==="Enter"||e===" "?{type:"activateChip",index:s}:e==="Escape"?{type:"focusInput"}:{type:"none"}}function dp(e,t){const s=t-1;return s<=0?null:e<s?e:s-1}const fp=e=>e instanceof HTMLElement?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable:!1,mp=({chips:e=[],onRemoveChip:t,onActivateChip:s,value:r,onChange:a,onClear:o,onClearQuery:i,placeholder:l="Search mail...",globalFocusKey:u=!0,showClearButton:f=!0,size:d="sm",inputId:m,chipsLabel:h="Search filters",className:g})=>{const v=c.useId(),p=m??v,x=c.useRef(null),b=c.useRef([]),w=i??o,[j,y]=c.useState(null),I=c.useRef(void 0),[N,k]=c.useState(""),C=e.length>0;c.useEffect(()=>{y(S=>S!==null&&S>=e.length?null:S)},[e.length]),c.useEffect(()=>{const S=I.current;if(S!==void 0){if(I.current=void 0,S===null){x.current?.focus();return}b.current[S]?.focus()}});const M=c.useCallback(S=>{y(S),I.current=S},[]),P=c.useCallback(S=>{const A=e[S];A&&t&&(M(dp(S,e.length)),k(`${A.label} removed`),t(A.id))},[e,t,M]),D=c.useCallback(()=>{M(null),o()},[o,M]),O=c.useCallback(S=>{const A=S.currentTarget,L=cp({key:S.key,shiftKey:S.shiftKey,repeat:S.repeat,caretAtStart:A.selectionStart===0&&A.selectionEnd===0,hasValue:r.length>0,chipCount:e.length});switch(L.type){case"focusChip":S.preventDefault(),M(L.index);return;case"clearQuery":w();return;case"blur":A.blur();return;case"none":return}},[e.length,r,w,M]),E=c.useCallback(S=>A=>{const L=up({key:A.key,repeat:A.repeat,index:S,chipCount:e.length});switch(L.type!=="none"&&A.preventDefault(),L.type){case"removeChip":P(L.index);return;case"focusChip":M(L.index);return;case"focusInput":M(null);return;case"activateChip":{const T=e[L.index];T&&s&&s(T.id);return}case"none":return}},[e,P,M,s]);return c.useEffect(()=>{if(!u)return;const S=A=>{A.key!=="/"||A.metaKey||A.ctrlKey||A.altKey||fp(A.target)||(A.preventDefault(),x.current?.focus())};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[u]),n.jsxs("label",{htmlFor:p,className:H("flex w-full items-center gap-1.5 text-sm","bg-surface-sunken/50 border border-transparent","focus-within:bg-canvas focus-within:border-line focus-within:ring-2 focus-within:ring-ring","transition-colors",d==="lg"?"rounded-xl px-4 py-2":"rounded-md px-2.5 py-1",g),children:[n.jsx(Qn,{className:H("shrink-0 text-fg-muted pointer-events-none",d==="lg"?"size-5":"size-4")}),n.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1",children:[C&&n.jsx("div",{role:"grid","aria-label":h,className:"flex min-w-0 flex-wrap items-center gap-1",children:e.map((S,A)=>n.jsx(Bd,{ref:L=>{b.current[A]=L},label:S.label,tone:S.tone,focused:j===A,onFocusLabel:()=>y(A),onKeyDown:E(A),onRemove:()=>P(A),onActivate:s?()=>s(S.id):void 0},S.id))}),n.jsx("input",{ref:x,id:p,name:"q",type:"text","aria-label":"Search mail",autoComplete:"off",value:r,tabIndex:j===null?0:-1,onChange:S=>a(S.target.value),onKeyDown:O,onFocus:()=>y(null),placeholder:C?void 0:l,className:"min-w-24 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted"})]}),(r||C)&&f&&n.jsx("button",{type:"button",onClick:D,className:"shrink-0 rounded p-0.5 hover:bg-surface-raised transition-colors","aria-label":"Clear search",children:n.jsx(We,{className:H("text-fg-muted",d==="lg"?"size-5":"size-4")})}),n.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:N})]})},La=({value:e,onChange:t,onClear:s,onClearQuery:r,chips:a,onRemoveChip:o,placeholder:i="Search mail...",globalFocusKey:l=!0,showClearButton:u=!0,size:f,inputId:d,className:m})=>n.jsx(mp,{value:e,onChange:t,onClear:s,onClearQuery:r,chips:a,onRemoveChip:o,placeholder:i,globalFocusKey:l,showClearButton:u,size:f,inputId:d,className:m});function hp({title:e,unreadCount:t,isDesktop:s,onMenuClick:r,searchValue:a,onSearchChange:o,onSearchClear:i,searchOpen:l,onSearchOpenChange:u,showSearch:f=!0}){const d=`${t.toLocaleString()} unread`,m=i??(()=>o("")),h=()=>{m(),u(!1)},g=p=>n.jsx(La,{value:a,onChange:o,onClear:m,globalFocusKey:!1,showClearButton:p}),v=n.jsx(G,{variant:"ghost",icon:n.jsx(Ca,{className:"size-5"}),onClick:r,"aria-label":"Menu",className:"min-h-11 min-w-11 shrink-0 px-0"});return n.jsx("header",{className:"flex shrink-0 flex-col bg-canvas",children:n.jsx("div",{className:"flex h-12 items-center gap-2 px-row-inset",children:f?s?n.jsxs(n.Fragment,{children:[v,n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:d}),n.jsx("div",{className:"w-64 max-w-[40%] shrink-0",children:g(!0)})]}):l||a.trim().length>0?n.jsxs("div",{className:"flex flex-1 items-center gap-1",children:[n.jsx("div",{className:"flex-1",children:g(!1)}),n.jsx(G,{variant:"ghost",icon:n.jsx(We,{className:"size-5"}),onClick:h,"aria-label":"Close search",className:"min-h-11 min-w-11 shrink-0 px-0"})]}):n.jsxs(n.Fragment,{children:[v,n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:d}),n.jsx(G,{variant:"ghost",icon:n.jsx(Qn,{className:"size-5"}),onClick:()=>u(!0),"aria-label":"Search",className:"min-h-11 min-w-11 shrink-0 px-0"})]}):n.jsxs(n.Fragment,{children:[v,n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:d})]})})})}const pp=(e,t)=>e==="vip"?"vip":e==="unknown"&&t==="md"?"unknown-pill":"hidden",oc=({senderTrust:e,size:t="sm",className:s})=>{const r=pp(e,t);return r==="vip"?n.jsx(ut,{className:H("text-warning shrink-0",t==="sm"&&"size-3.5",t==="md"&&"size-4",s),"aria-label":"VIP sender","data-testid":"sender-trust-vip"}):r==="unknown-pill"?n.jsx("span",{className:H("inline-flex items-center rounded border border-dashed border-fg-subtle/40 font-medium uppercase tracking-wide text-fg-muted/80 shrink-0","px-2 py-0.5 text-xs",s),title:"First message from this sender","aria-label":"First message from this sender","data-testid":"sender-trust-unknown",children:"new"}):null};function Go(e,t){const s=t?.trim();if(!s)return e;const r=e.toLowerCase(),a=s.toLowerCase(),o=[];let i=0,l=r.indexOf(a,i),u=0;for(;l!==-1;)l>i&&o.push(e.slice(i,l)),o.push(n.jsx("mark",{className:"bg-transparent font-semibold text-fg",children:e.slice(l,l+a.length)},u++)),i=l+a.length,l=r.indexOf(a,i);return i<e.length&&o.push(e.slice(i)),o}function gp({result:e,onClick:t,query:s,showFolder:r=!0}){const a=r&&e.folder?Kd(e.folder):void 0;return n.jsxs("button",{type:"button",onClick:t,className:"flex w-full flex-col gap-0.5 border-b border-line px-row-inset py-2.5 text-left transition-colors hover:bg-surface-sunken",children:[n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:H("min-w-0 flex-1 truncate text-sm",e.unread?"font-semibold text-fg":"font-medium text-fg-muted"),children:e.sender}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.date})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:H("min-w-0 flex-1 truncate text-sm",e.unread?"text-fg":"text-fg-muted"),children:Go(e.subject,s)}),e.flagged&&n.jsx(Km,{className:"size-3.5 shrink-0 fill-warning text-warning"})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-fg-subtle",children:Go(e.snippet,s)}),a&&n.jsx(lt,{tone:"neutral",className:"shrink-0",children:a}),e.category&&n.jsx(lt,{tone:e.category.tone??"neutral",className:"shrink-0",children:e.category.label}),e.matchedChunkLabel&&n.jsx(lt,{tone:"neutral",className:"shrink-0",children:`matched: ${e.matchedChunkLabel}`}),e.score!=null&&n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.score.toFixed(2)})]})]})}const xp=e=>e===1?"result":"results";function bp({count:e,onScopeToSpam:t}){return n.jsx(Xt,{tone:"info",variant:"soft",className:"items-center justify-between gap-3 rounded-none border-b border-line",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("p",{className:"min-w-0 text-xs text-fg-muted",children:[n.jsx("span",{className:"font-semibold text-fg tabular-nums",children:e})," ",`${xp(e)} from Spam`]}),n.jsx(G,{variant:"ghost",size:"sm",onClick:t,className:"shrink-0 text-accent",children:"Go to Spam"})]})})}const Xo=6,vp={kind:"global"},yp=e=>e.kind==="folder"&&e.role==="junk",wp=e=>e.folder?.role==="junk";function ic(e){const t=[],s=[];for(const r of e)wp(r)?s.push(r):t.push(r);return{kept:t,spam:s}}function jp({onClick:e,disabledReason:t}){const s=t!==void 0;return n.jsx("div",{className:"border-b border-line px-row-inset py-1.5",children:n.jsxs("button",{type:"button",onClick:e,disabled:s,title:t,className:H("flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs font-medium transition-colors",s?"cursor-not-allowed text-fg-subtle":"text-accent hover:bg-surface-sunken"),children:[n.jsx(qd,{className:"size-3.5 shrink-0","aria-hidden":"true"}),n.jsx("span",{children:"Make this a filter"}),s&&n.jsx("span",{className:"ml-auto truncate text-2xs font-normal text-fg-subtle",children:t})]})})}function Sp({section:e,query:t,onSelectResult:s,showFolder:r}){const[a,o]=c.useState(e.initialCollapsed??!1),[i,l]=c.useState(!1),u=e.results.length>Xo,d=!i&&u?e.results.slice(0,Xo):e.results,m=e.results.length-d.length;return n.jsxs("div",{children:[n.jsxs("button",{type:"button","aria-expanded":!a,onClick:()=>o(h=>!h),className:"sticky top-0 z-10 flex h-section-row w-full items-center gap-1.5 border-b border-line bg-surface-sunken px-row-inset text-left transition-colors hover:bg-surface",children:[n.jsx("span",{className:"flex-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:e.results.length}),n.jsx(Rt,{className:H("size-3 shrink-0 text-fg-subtle transition-transform duration-200",a?"rotate-0":"rotate-180")})]}),!a&&n.jsxs(n.Fragment,{children:[d.map(h=>n.jsx(gp,{result:h,query:t,showFolder:r,onClick:s?()=>s(h):void 0},h.id)),u&&n.jsxs("button",{type:"button",onClick:()=>l(h=>!h),className:"flex w-full items-center justify-center border-b border-line px-row-inset py-1.5 text-2xs font-medium text-accent transition-colors hover:bg-surface",children:[i?"Show less":`Show ${m} more`,!i&&n.jsx(Rt,{className:"ml-1 size-3"})]})]})]})}function lc({value:e,recentSearches:t,onPickRecent:s,sections:r,loading:a,onSelectResult:o,tokens:i,scope:l=vp,makeFilter:u}){if(!(e.trim().length>0))return t&&t.length>0?n.jsxs("div",{className:"flex flex-col",children:[n.jsx("h3",{className:"px-row-inset pb-1 pt-3 text-2xs font-semibold uppercase tracking-wide text-fg-subtle",children:"Recent searches"}),t.map(y=>n.jsxs("button",{type:"button",onClick:()=>s?.(y),className:"flex w-full items-center gap-2.5 border-b border-line px-row-inset py-2.5 text-left transition-colors hover:bg-surface-sunken",children:[n.jsx(Ta,{className:"size-4 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-fg-muted",children:y})]},y))]}):n.jsx("p",{className:"px-row-inset py-6 text-center text-sm text-fg-subtle",children:"Search across your mail by sender, subject or words in the message."});const d=i&&i.length>0&&n.jsx(Ud,{tokens:i}),m=u&&n.jsx(jp,{onClick:u.onClick,disabledReason:u.disabledReason});if(a)return n.jsxs("div",{className:"flex flex-col",children:[m,d,n.jsx("div",{className:"flex flex-col gap-3 px-row-inset py-4",children:[0,1,2,3].map(y=>n.jsxs("div",{className:"flex flex-col gap-1.5",children:[n.jsx("div",{className:"h-3 w-1/3 animate-pulse rounded bg-surface-sunken"}),n.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-surface-sunken"}),n.jsx("div",{className:"h-2.5 w-1/2 animate-pulse rounded bg-surface-sunken"})]},y))})]});const h=l.kind==="global",g=yp(l)||l.kind==="collection",v=h||l.kind==="collection",p=(r??[]).map(y=>{if(g)return{section:y,spam:[]};const{kept:I,spam:N}=ic(y.results);return{section:{...y,results:I},spam:N}}),x=p.map(y=>y.section),b=p.reduce((y,I)=>y+I.spam.length,0),w=l.kind==="global"&&b>0&&l.onScopeToSpam!==void 0?n.jsx(bp,{count:b,onScopeToSpam:l.onScopeToSpam}):void 0;return x.some(y=>y.results.length>0)?n.jsxs("div",{className:"flex flex-col",children:[m,d,w,x.filter(y=>y.results.length>0).map(y=>n.jsx(Sp,{section:y,query:e,showFolder:v,onSelectResult:o},y.id))]}):n.jsxs("div",{className:"flex flex-col",children:[m,d,w,n.jsxs("div",{className:"px-row-inset py-10 text-center",children:[n.jsxs("p",{className:"text-sm font-medium text-fg",children:["No matches for “",e,"”"]}),n.jsx("p",{className:"mt-1 text-xs text-fg-subtle",children:"Try a different word, or adjust the filters above."})]})]})}function kp({value:e,onChange:t,onClear:s,onCancel:r,filter:a,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:f,tokens:d,chips:m,onRemoveChip:h,scope:g,makeFilter:v}){const p=n.jsx(lc,{value:e,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:f,tokens:d,scope:g,makeFilter:v});return n.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx(La,{value:e,onChange:t,onClear:s,chips:m,onRemoveChip:h,globalFocusKey:!1,showClearButton:!1})}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(We,{className:"size-4"}),onClick:r,"aria-label":"Clear and close search",className:"-mr-1 shrink-0"})]}),a?n.jsx(da,{...a,children:p}):n.jsx("div",{className:"flex-1 overflow-y-auto",children:p})]})}const Cp={queued:{icon:Ta,label:"Queued",className:"text-warning"},sending:{icon:nt,label:"Sending…",className:"text-accent-2",spin:!0},sent:{icon:Fl,label:"Sent",className:"text-positive"},failed:{icon:Gt,label:"Failed",className:"text-danger"},blocked:{icon:fa,label:"Blocked",className:"text-warning"}};function Jo({status:e,iconOnly:t,className:s}){const r=Cp[e],a=r.icon;return n.jsxs("span",{className:H("inline-flex items-center gap-1.5 text-xs font-medium",r.className,s),children:[n.jsx(a,{className:H("size-4",r.spin&&"animate-spin")}),!t&&r.label]})}const Np=(e,t)=>t?"bg-accent-2-soft":e==="failed"?"bg-danger-soft":e==="blocked"?"bg-warning/10":"";function Ep({recipients:e,subject:t,time:s,status:r,error:a,selected:o,onSelect:i,onRetry:l,retrying:u,onEdit:f,onDelete:d,deleting:m}){const h=r==="failed"||r==="blocked";return n.jsxs("div",{className:H("flex items-start gap-3 border-b border-line px-4 py-3 transition-colors hover:bg-surface-raised",Np(r,o)),children:[n.jsxs("button",{type:"button",...oa,onClick:i,className:"flex flex-1 min-w-0 items-start gap-3 text-left",children:[n.jsx("div",{className:"mt-0.5 shrink-0",children:n.jsx(Jo,{status:r,iconOnly:!0})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"truncate text-sm font-medium",children:e}),n.jsx("span",{className:"shrink-0 text-xs text-fg-muted",children:s})]}),n.jsx("div",{className:"truncate text-sm",children:t||"No subject"}),n.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[n.jsx(Jo,{status:r}),a&&n.jsxs("span",{className:"truncate text-xs text-fg-muted",children:["— ",a]})]})]})]}),h&&n.jsx("div",{className:"shrink-0",children:n.jsx(Kf,{actions:[...r==="failed"&&l?[{label:"Retry sending",iconOnly:!0,icon:n.jsx(Jf,{className:"size-3.5"}),busy:u,onClick:l}]:[],{label:"Edit as draft",iconOnly:!0,icon:n.jsx(Gs,{className:"size-3.5"}),onClick:f}],destructive:{label:"Delete message",iconOnly:!0,icon:n.jsx(rt,{className:"size-3.5"}),busy:m,confirm:{prompt:"Delete this message?",confirmLabel:"Delete"},onClick:d}})})]})}const Ip=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia(e);s(r.matches);const a=o=>s(o.matches);return r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[e]),t},Tp=({children:e,onRefresh:t,isRefreshing:s})=>Ip("(min-width: 1024px)")?e:n.jsx(Hd,{onRefresh:t,isPullable:!s,children:e}),Rp=({text:e,html:t,senderName:s,date:r})=>{const[a,o]=c.useState(!1);if(!e&&!t)return null;const i=[s,r].filter(Boolean).join(" on ");return n.jsxs("div",{className:"mt-2 px-3 pb-2",children:[n.jsxs("button",{type:"button",onClick:()=>o(!a),"aria-expanded":a,className:"flex items-center gap-1 text-xs text-fg-muted hover:text-fg transition-colors",children:[a?n.jsx(Rt,{className:"size-3"}):n.jsx(ys,{className:"size-3"}),i?`${i} wrote:`:"Show quoted text"]}),a&&n.jsx("blockquote",{className:"mt-2 pl-3 border-l-2 border-fg-subtle/30 text-sm text-fg-muted [&_a]:text-accent [&_a]:underline [&_blockquote]:pl-3 [&_blockquote]:border-l-2 [&_blockquote]:border-fg-subtle/30",children:t?n.jsx("div",{dangerouslySetInnerHTML:{__html:t}}):e.split(`
75
+ `).map((l,u)=>n.jsx("p",{className:"min-h-[1.2em]",children:l},u))})]})},Mp=e=>e===1?"message":"messages";function Ap({count:e,onReview:t,onDismiss:s,actionLabel:r="Review & rescue"}){return n.jsx(Xt,{tone:"info",variant:"soft",onDismiss:s,children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("p",{className:"flex items-start gap-2 text-sm text-fg",children:[n.jsx(en,{className:"mt-0.5 size-4 shrink-0 text-positive","aria-hidden":!0}),n.jsxs("span",{children:[n.jsx("span",{className:"font-semibold text-fg",children:`${e} ${Mp(e)} here`})," ","may not be spam — they're from senders we can verify."]})]}),n.jsx(G,{variant:"primary",size:"sm",onClick:t,className:"self-start",children:r})]})})}function Dp({candidate:e,selected:t,onToggle:s,hideSender:r=!1}){const{senderName:a,senderAddress:o,subject:i,snippet:l,trustReason:u,trustSubReason:f,senderTrust:d}=e;return n.jsxs("label",{className:H("flex w-full cursor-pointer items-start gap-3 px-3 py-2.5 text-left transition-colors",r&&"pl-11",t?"bg-positive/10":"bg-surface hover:bg-surface-sunken"),children:[n.jsx(sn,{className:"mt-0.5",checked:t,onChange:s,"aria-label":`${t?"Deselect":"Select"} ${r?i:`message from ${a}`}`}),!r&&n.jsx(dt,{name:a,email:o,size:"sm"}),n.jsxs("span",{className:"min-w-0 flex-1",children:[!r&&n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-sm font-medium text-fg",children:a}),d&&n.jsx(oc,{senderTrust:d,size:"sm"}),n.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:o})]}),n.jsx("span",{className:"block truncate text-sm text-fg-muted",children:i}),n.jsx("span",{className:"block line-clamp-1 text-xs text-fg-subtle",children:l}),!r&&n.jsxs("span",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[n.jsxs(lt,{tone:"positive",children:[n.jsx(en,{className:"size-3","aria-hidden":!0}),u]}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:f})]})]})]})}const Op=e=>{const t=new Map,s=[];for(const r of e){const a=(r.senderAddress||r.senderName).toLowerCase(),o=t.get(a);if(o){o.messages.push(r);continue}t.set(a,{key:a,senderName:r.senderName,senderAddress:r.senderAddress,trustReason:r.trustReason,trustSubReason:r.trustSubReason,senderTrust:r.senderTrust,messages:[r]}),s.push(a)}return s.map(r=>t.get(r)).sort((r,a)=>a.messages.length-r.messages.length)},Pp=(e,t)=>{const s=e.messages.filter(r=>t.has(r.id)).length;return s===0?"none":s===e.messages.length?"all":"some"},Zo=e=>e===1?"message":"messages";function Lp({group:e,selected:t,onToggleGroup:s,onToggleMessage:r}){const[a,o]=c.useState(!1),i=Pp(e,t),l=e.messages.length,u=a?Rt:ys;return n.jsxs("div",{className:H(i!=="none"?"bg-positive/10":"bg-surface"),children:[n.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-2.5",children:[n.jsx(sn,{className:"mt-0.5",checked:i==="all",indeterminate:i==="some",onChange:()=>s(e,i!=="all"),"aria-label":`${i==="all"?"Deselect":"Select"} all ${l} ${Zo(l)} from ${e.senderName}`}),n.jsx(dt,{name:e.senderName,email:e.senderAddress,size:"sm"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-sm font-medium text-fg",children:e.senderName}),e.senderTrust&&n.jsx(oc,{senderTrust:e.senderTrust,size:"sm"}),n.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:e.senderAddress})]}),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[n.jsxs(lt,{tone:"positive",children:[n.jsx(en,{className:"size-3","aria-hidden":!0}),e.trustReason]}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:e.trustSubReason})]})]}),n.jsxs("button",{type:"button",onClick:()=>o(f=>!f),"aria-expanded":a,className:"flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-2xs text-fg-muted transition-colors hover:bg-surface-sunken hover:text-fg",children:[`${l} ${Zo(l)}`,n.jsx(u,{className:"size-3.5","aria-hidden":!0})]})]}),a&&n.jsx("div",{className:"divide-y divide-line border-t border-line",children:e.messages.map(f=>n.jsx(Dp,{candidate:f,selected:t.has(f.id),onToggle:()=>r(f.id),hideSender:!0},f.id))})]})}const $a=e=>e===1?"message":"messages",$p=(e,t)=>`Moves ${e===1?"this message":`these ${e} ${$a(e)}`} out of Spam to ${t} now. Nothing later.`,Qr=(e,t)=>e.find(s=>s.id===t)?.label??"Inbox";function Fp(){return n.jsx(Xt,{tone:"info",variant:"soft",children:n.jsx("p",{className:"text-2xs text-fg-muted",children:"We list a message here only when we can confirm the sender is who they say — usually someone you've emailed before, write to often, or a service that consistently checks out. We never guess from words in the subject. Anything we can't confirm stays in Spam."})})}function _p({candidates:e,selected:t,onToggle:s,onToggleGroup:r,onSelectAll:a,onSelectNone:o,onContinue:i,onCancel:l}){const[u,f]=c.useState(!1),d=t.size,m=c.useMemo(()=>Op(e),[e]);return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("h2",{className:"flex items-center gap-2 text-sm font-semibold text-fg",children:[n.jsx(en,{className:"size-4 text-positive","aria-hidden":!0}),"Rescue from Spam"]}),n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(zf,{className:"size-3.5"}),onClick:()=>f(h=>!h),className:"-mr-1.5 -mt-0.5",children:"Why these?"})]}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"These look safe — from senders we can verify. Uncheck any sender that belongs in Spam, or open a sender to pick individual messages."}),u&&n.jsx("div",{className:"mt-2",children:n.jsx(Fp,{})})]}),n.jsxs("div",{className:"flex items-center justify-between px-row-inset pb-1.5",children:[n.jsx("span",{className:"text-2xs font-medium text-fg-muted",children:`${d} of ${e.length} selected · ${m.length} ${m.length===1?"sender":"senders"}`}),n.jsxs("span",{className:"flex gap-1",children:[n.jsx(G,{variant:"ghost",size:"sm",onClick:a,children:"Select all"}),n.jsx(G,{variant:"ghost",size:"sm",onClick:o,children:"Select none"})]})]}),n.jsx("div",{className:"min-h-0 flex-1 divide-y divide-line overflow-y-auto border-y border-line",children:m.map(h=>n.jsx(Lp,{group:h,selected:t,onToggleGroup:r,onToggleMessage:s},h.key))}),n.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[n.jsx(G,{variant:"primary",onClick:i,className:"h-11 w-full font-semibold",children:`Continue with ${d} ${$a(d)}`}),n.jsx(G,{variant:"ghost",onClick:l,className:"h-11 w-full",children:"Cancel"})]})]})}function zp({count:e,folders:t,destination:s,onPick:r,onMove:a,onBack:o}){const[i,l]=c.useState(!1);return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg",children:"Where should they go?"}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Pick a folder, then we move them out of Spam."})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-row-inset py-2",children:i?n.jsx("div",{className:"overflow-hidden rounded-xl border border-line bg-surface",children:n.jsx(kl,{mailboxes:t,autoFocus:!0,onSelect:u=>{r(u),l(!1)},onCancel:()=>l(!1)})}):n.jsxs("div",{className:"rounded-xl border border-line bg-surface-sunken p-3",children:[n.jsx("p",{className:"text-2xs text-fg-subtle",children:"Destination"}),n.jsx("p",{className:"mt-0.5 text-sm font-medium text-fg",children:Qr(t,s)}),n.jsx(G,{variant:"ghost",size:"sm",onClick:()=>l(!0),className:"mt-2 px-0",children:"Move to a different folder"})]})}),n.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[n.jsx("p",{className:"text-2xs text-fg-subtle",children:$p(e,Qr(t,s))}),n.jsx(G,{variant:"primary",onClick:a,className:"h-11 w-full font-semibold",children:`Move ${e} out of Spam`}),n.jsx(G,{variant:"ghost",onClick:o,className:"h-11 w-full",children:"Back"})]})]})}function Bp({count:e,destinationLabel:t,onClose:s}){return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 px-row-inset py-10 text-center",children:[n.jsx(Yn,{className:"size-10 text-positive","aria-hidden":!0}),n.jsx("p",{className:"text-base font-semibold text-fg",children:`Moved ${e} ${$a(e)} out of Spam.`}),n.jsx("p",{className:"text-2xs text-fg-subtle",children:`You'll find them in ${t}.`})]}),n.jsx("div",{className:"border-t border-line bg-surface px-row-inset py-3",children:n.jsx(G,{variant:"primary",onClick:s,className:"h-11 w-full font-semibold",children:"Done"})})]})}function Kp({open:e,candidates:t,defaultDestinationId:s,availableFolders:r,onConfirmMove:a,onCancel:o}){const[i,l]=c.useState("review"),[u,f]=c.useState(()=>e?new Set(t.map(j=>j.id)):new Set),[d,m]=c.useState(s),[h,g]=c.useState(0),v=c.useRef(!1);c.useEffect(()=>{e&&!v.current&&(l("review"),f(new Set(t.map(j=>j.id))),m(s),g(0)),v.current=e},[e,t,s]);const p=u.size,x=j=>{f(y=>{const I=new Set(y);return I.has(j)?I.delete(j):I.add(j),I})},b=(j,y)=>{f(I=>{const N=new Set(I);for(const k of j.messages)y?N.add(k.id):N.delete(k.id);return N})},w=()=>{const j=Array.from(u);g(j.length),a(j,d),l("done")};return n.jsxs(pl,{open:e,onClose:o,dismissLabel:"Close rescue",children:[i==="review"&&n.jsx(_p,{candidates:t,selected:u,onToggle:x,onToggleGroup:b,onSelectAll:()=>f(new Set(t.map(j=>j.id))),onSelectNone:()=>f(new Set),onContinue:()=>l("destination"),onCancel:o}),i==="destination"&&n.jsx(zp,{count:p,folders:r,destination:d,onPick:m,onMove:w,onBack:()=>l("review")}),i==="done"&&n.jsx(Bp,{count:h,destinationLabel:Qr(r,d),onClose:o})]})}function Up(e){return e.scopedOutFolder!==void 0||(e.droppedFacets?.length??0)>0||e.droppedSemantic===!0}function qp(e){return`Your search was limited to ${e}. This filter matches these messages in any folder — it can't be pinned to one.`}const Hp=e=>e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`;function Wp(e){const t=e.length===1?"a filter condition":"filter conditions",s=e.length===1?"isn't":"aren't";return`${Hp(e)} ${s} ${t}, so ${e.length===1?"it was":"they were"} left out — the filter still matches everything else you searched for.`}const Vp="The filter matches these words literally. Your search also found similar mail by meaning — a filter can't carry that, so it won't catch mail that means the same thing without these words.";function Cr({icon:e,children:t}){return n.jsxs("li",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"mt-0.5 shrink-0 text-fg-subtle","aria-hidden":"true",children:e}),n.jsx("span",{children:t})]})}function Qp({notice:e}){return Up(e)?n.jsxs("div",{className:"rounded-md border border-line bg-surface-sunken px-3 py-2.5",children:[n.jsx("p",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"From your search"}),n.jsxs("ul",{className:"mt-1.5 space-y-1.5 text-xs text-fg-muted",children:[e.scopedOutFolder!==void 0&&n.jsx(Cr,{icon:n.jsx(Ia,{className:"size-3.5"}),children:qp(e.scopedOutFolder)}),e.droppedFacets&&e.droppedFacets.length>0&&n.jsx(Cr,{icon:n.jsx(la,{className:"size-3.5"}),children:Wp(e.droppedFacets)}),e.droppedSemantic&&n.jsx(Cr,{icon:n.jsx(ut,{className:"size-3.5"}),children:Vp})]})]}):null}const ei=e=>e.toLocaleString(),Ks=56,Yp=70,Gp=320,Xp=320,Jp="cubic-bezier(0.32, 0.9, 0.3, 1)",Zp=.5;function vn(e){return Math.sign(e)*Math.sqrt(Math.abs(e))*4}function eg({expanded:e,delta:t,velocity:s,expandedHeight:r,teaserHeight:a,flickVelocity:o=Zp}){if(Math.abs(s)>o)return s<0;const i=(r-a)/2;return e?t<i:t<-i}function tg({count:e,mode:t="idle",onCancel:s,onDelete:r,onJunk:a,onMarkRead:o,onSelectSimilar:i,onSomethingElse:l,moveSlot:u,isBusy:f=!1,selectAll:d,statusLabel:m,progress:h,notice:g,startExpanded:v=!1}){const[p,x]=c.useState(v),b=c.useRef(null),[w,j]=c.useState(Gp),y=t==="counting"||t==="running";c.useEffect(()=>{y&&x(!0)},[y]),c.useLayoutEffect(()=>{const $=b.current;if(!$)return;const z=()=>j($.offsetHeight);z();const V=new ResizeObserver(z);return V.observe($),()=>V.disconnect()},[]);const[I,N]=c.useState(null),k=c.useRef(null),C=c.useRef(!1),M=c.useCallback($=>{y||($.currentTarget.setPointerCapture($.pointerId),k.current={startY:$.clientY,lastY:$.clientY,lastT:$.timeStamp,velocity:0},C.current=!1,N(0))},[y]),P=c.useCallback($=>{const z=k.current;if(!z)return;const V=$.timeStamp-z.lastT;V>0&&(z.velocity=($.clientY-z.lastY)/V),z.lastY=$.clientY,z.lastT=$.timeStamp;const ee=$.clientY-z.startY;Math.abs(ee)>4&&(C.current=!0);const X=w-Ks,Q=p?ee<0?vn(ee):Math.min(ee,X+vn(Math.max(0,ee-X))):ee>0?vn(ee):Math.max(ee,-X+vn(Math.min(0,ee+X)));N(Q)},[p,w]),D=c.useCallback(()=>{const $=k.current;k.current=null,$&&(N(null),x(eg({expanded:p,delta:$.lastY-$.startY,velocity:$.velocity,expandedHeight:w,teaserHeight:Ks})))},[p,w]),O=w-Ks,E=p?0:O,S=I!==null,A=E+(I??0),L=S?"none":`transform ${Xp}ms ${Jp}`,T=d?.checked?`All ${ei(e)} loaded selected`:`${ei(e)} ${e===1?"message":"messages"} selected`,F=t==="idle"||t==="escalated",R=t==="idle";return n.jsxs("div",{ref:b,"data-selection-sheet":"",className:"absolute inset-x-0 bottom-0 z-30 flex select-none flex-col rounded-t-2xl border-t border-line bg-surface shadow-2xl shadow-black/40",style:{maxHeight:`${Yp}dvh`,minHeight:`${Ks}px`,transform:`translateY(${A}px)`,transition:L},children:[n.jsxs("div",{role:"slider","aria-label":p?"Collapse selection actions":"Expand selection actions","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":p?1:0,tabIndex:0,onPointerDown:M,onPointerMove:P,onPointerUp:D,onPointerCancel:D,onClick:()=>{if(C.current){C.current=!1;return}!S&&!y&&x($=>!$)},className:H("flex touch-none flex-col items-center pt-2",y?"":"cursor-grab active:cursor-grabbing"),children:[n.jsx("div",{className:"mb-1.5 h-1 w-10 rounded-full bg-fg-subtle/40"}),n.jsxs("div",{className:"flex w-full items-center gap-2 px-4 pb-3",children:[n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",role:"status","aria-live":"polite",children:m??T}),p?n.jsxs(n.Fragment,{children:[o&&!f&&t!=="counting"&&n.jsx(G,{variant:"ghost",size:"touch",icon:n.jsx(Cs,{className:"size-4"}),onPointerDown:$=>$.stopPropagation(),onClick:$=>{$.stopPropagation(),o()},"aria-label":"Mark as read",className:"-my-2 shrink-0"}),n.jsx(G,{variant:"ghost",size:"touch",icon:n.jsx(We,{className:"size-4"}),onPointerDown:$=>$.stopPropagation(),onClick:$=>{$.stopPropagation(),s()},"aria-label":"Cancel selection",className:"-my-2 -mr-2 shrink-0"})]}):n.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-xs text-fg-subtle",children:[n.jsx("span",{children:"Swipe up for actions"}),n.jsx(Bm,{className:"size-4"})]})]})]}),n.jsxs("div",{inert:p?void 0:!0,className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-4 pb-4",children:[h&&n.jsx("div",{className:"mb-3",children:n.jsx(Pa,{value:h.value,max:h.max,tone:h.tone})}),d&&t!=="running"&&n.jsxs("label",{className:"mb-3 flex min-h-11 cursor-pointer items-center gap-3 text-sm font-medium text-fg-muted",children:[n.jsx(sn,{"aria-label":"Select all",checked:d.checked,indeterminate:d.indeterminate,onChange:d.onChange}),"Select all loaded"]}),F&&n.jsxs("div",{className:"mb-3 flex items-stretch justify-around gap-1 border-b border-line pb-3",children:[n.jsx(G,{variant:"ghost",onClick:r,icon:f?n.jsx(nt,{className:"size-5 animate-spin"}):n.jsx(rt,{className:"size-5 text-danger"}),"aria-label":"Move selected messages to Trash","aria-busy":f||void 0,className:"h-auto flex-1 flex-col gap-1 px-0 py-1.5 text-[11px]",children:"Delete"}),u&&n.jsxs("div",{className:"flex flex-1 flex-col items-center gap-1",children:[u,n.jsx("span",{"aria-hidden":"true",className:"text-[11px] text-fg-muted",children:"Move"})]}),a&&n.jsx(G,{variant:"ghost",onClick:a,icon:n.jsx(Ns,{className:"size-5"}),"aria-label":"Move selected messages to Junk",className:"h-auto flex-1 flex-col gap-1 px-0 py-1.5 text-[11px]",children:"Junk"})]}),R&&(i||l)&&n.jsxs("div",{className:"flex flex-col gap-2",children:[i&&n.jsxs(G,{variant:"primary",onClick:i,className:"h-auto flex-col items-start gap-0 px-4 py-2.5 text-left",children:[n.jsx("span",{className:"text-sm font-semibold leading-tight",children:"Select similar messages"}),n.jsx("span",{className:"text-xs opacity-80",children:"find more like these"})]}),l&&n.jsxs(G,{variant:"secondary",onClick:l,className:"h-auto flex-col items-start gap-0 px-4 py-2.5 text-left",children:[n.jsx("span",{className:"text-sm font-medium leading-tight",children:"Something else"}),n.jsx("span",{className:"text-xs text-fg-subtle",children:"just deal with these"})]})]}),g&&n.jsx(Xt,{tone:g.tone,variant:"soft",role:"status","aria-live":"polite",className:H(F||h?"mt-1":"mt-0"),children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.text&&n.jsx("span",{children:g.text}),g.action&&n.jsx(G,{variant:"ghost",size:"md",onClick:g.action.onClick,className:"-my-1 min-h-11 shrink-0",children:g.action.label})]})})]})]})}const Fa=[{id:"all",label:"All",tone:"neutral"},{id:"personal",label:"Personal",tone:"accent"},{id:"transactional",label:"Transactional",tone:"positive"},{id:"newsletter",label:"Newsletter",tone:"neutral"},{id:"marketing",label:"Marketing",tone:"warning"},{id:"social",label:"Social",tone:"warning"},{id:"automated",label:"Automated",tone:"neutral"}],cc={id:"unread",label:"Unread"},sg={id:"flagged",label:"Starred"},uc={id:"attachment",label:"Has attachment"};function ng(e){if(!(e.length<=1))return e.map(t=>({id:t.id,label:t.label,count:t.count,active:t.active}))}function rg(e=[]){return{categories:[...Fa],filters:Wd,sources:ng(e)}}function ag(){return{categories:[...Fa],filters:[cc,sg,uc]}}function og(){return{categories:[...Fa],filters:[cc,uc]}}function Tt(e,t,{checkForDefaultPrevented:s=!0}={}){return function(a){if(e?.(a),s===!1||!a||!a.defaultPrevented)return t?.(a)}}function ti(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ig(...e){return t=>{let s=!1;const r=e.map(a=>{const o=ti(a,t);return!s&&typeof o=="function"&&(s=!0),o});if(s)return()=>{for(let a=0;a<r.length;a++){const o=r[a];typeof o=="function"?o():ti(e[a],null)}}}}function es(...e){return c.useCallback(ig(...e),e)}function lg(e,t=[]){let s=[];function r(o,i){const l=c.createContext(i);l.displayName=o+"Context";const u=s.length;s=[...s,i];const f=m=>{const{scope:h,children:g,...v}=m,p=h?.[e]?.[u]||l,x=c.useMemo(()=>v,Object.values(v));return n.jsx(p.Provider,{value:x,children:g})};f.displayName=o+"Provider";function d(m,h,g={}){const{optional:v=!1}=g,p=h?.[e]?.[u]||l,x=c.useContext(p);if(x)return x;if(i!==void 0)return i;if(!v)throw new Error(`\`${m}\` must be used within \`${o}\``)}return[f,d]}const a=()=>{const o=s.map(i=>c.createContext(i));return function(l){const u=l?.[e]||o;return c.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return a.scopeName=e,[r,cg(a,...t)]}function cg(...e){const t=e[0];if(e.length===1)return t;const s=()=>{const r=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(o){const i=r.reduce((l,{useScope:u,scopeName:f})=>{const m=u(o)[`__scope${f}`];return{...l,...m}},{});return c.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return s.scopeName=t.scopeName,s}var Ws=globalThis?.document?c.useLayoutEffect:()=>{},ug=ma[" useInsertionEffect ".trim().toString()]||Ws;function dg({prop:e,defaultProp:t,onChange:s=()=>{},caller:r}){const[a,o,i]=fg({defaultProp:t,onChange:s}),l=e!==void 0,u=l?e:a;{const d=c.useRef(e!==void 0);c.useEffect(()=>{const m=d.current;m!==l&&console.warn(`${r} is changing from ${m?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=l},[l,r])}const f=c.useCallback(d=>{if(l){const m=mg(d)?d(e):d;m!==e&&i.current?.(m)}else o(d)},[l,e,o,i]);return[u,f]}function fg({defaultProp:e,onChange:t}){const[s,r]=c.useState(e),a=c.useRef(s),o=c.useRef(t);return ug(()=>{o.current=t},[t]),c.useEffect(()=>{a.current!==s&&(o.current?.(s),a.current=s)},[s,a]),[s,r,o]}function mg(e){return typeof e=="function"}function _a(e){const t=c.forwardRef((s,r)=>{let{children:a,...o}=s,i=null,l=!1;const u=[];si(a)&&typeof yn=="function"&&(a=yn(a._payload)),c.Children.forEach(a,h=>{if(bg(h)){l=!0;const g=h;let v="child"in g.props?g.props.child:g.props.children;si(v)&&typeof yn=="function"&&(v=yn(v._payload)),i=pg(g,v),u.push(i?.props?.children)}else u.push(h)}),i?i=c.cloneElement(i,void 0,u):!l&&c.Children.count(a)===1&&c.isValidElement(a)&&(i=a);const f=i?xg(i):void 0,d=es(r,f);if(!i){if(a||a===0)throw new Error(l?jg(e):wg(e));return a}const m=gg(o,i.props??{});return i.type!==c.Fragment&&(m.ref=r?d:f),c.cloneElement(i,m)});return t.displayName=`${e}.Slot`,t}var uS=_a("Slot"),hg=Symbol.for("radix.slottable"),pg=(e,t)=>{if("child"in e.props){const s=e.props.child;return c.isValidElement(s)?c.cloneElement(s,void 0,e.props.children(s.props.children)):null}return c.isValidElement(t)?t:null};function gg(e,t){const s={...t};for(const r in t){const a=e[r],o=t[r];/^on[A-Z]/.test(r)?a&&o?s[r]=(...l)=>{const u=o(...l);return a(...l),u}:a&&(s[r]=a):r==="style"?s[r]={...a,...o}:r==="className"&&(s[r]=[a,o].filter(Boolean).join(" "))}return{...e,...s}}function xg(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?e.props.ref:e.props.ref||e.ref)}function bg(e){return c.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===hg}var vg=Symbol.for("react.lazy");function si(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===vg&&"_payload"in e&&yg(e._payload)}function yg(e){return typeof e=="object"&&e!==null&&"then"in e}var wg=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,jg=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,yn=ma[" use ".trim().toString()],Sg=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],bt=Sg.reduce((e,t)=>{const s=_a(`Primitive.${t}`),r=c.forwardRef((a,o)=>{const{asChild:i,...l}=a,u=i?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(u,{...l,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function kg(e,t){e&&ha.flushSync(()=>e.dispatchEvent(t))}function Vs(e){const t=c.useRef(e);return c.useEffect(()=>{t.current=e}),c.useMemo(()=>((...s)=>t.current?.(...s)),[])}var Cg="DismissableLayer",Yr="dismissableLayer.update",Ng="dismissableLayer.pointerDownOutside",Eg="dismissableLayer.focusOutside",ni,za=c.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),dc=c.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:l,onDismiss:u,...f}=e,d=c.useContext(za),[m,h]=c.useState(null),g=m?.ownerDocument??globalThis?.document,[,v]=c.useState({}),p=es(t,h),x=Array.from(d.layers),[b]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),w=b?x.indexOf(b):-1,j=m?x.indexOf(m):-1,y=d.layersWithOutsidePointerEventsDisabled.size>0,I=j>=w,N=c.useRef(!1),k=Ag(D=>{o?.(D),l?.(D),D.defaultPrevented||u?.()},{ownerDocument:g,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:N,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:c.useCallback(D=>{if(!(D instanceof Node))return!1;const O=[...d.branches].some(E=>E.contains(D));return I&&!O},[d.branches,I])}),C=Dg(D=>{if(r&&N.current)return;const O=D.target;[...d.branches].some(S=>S.contains(O))||(i?.(D),l?.(D),D.defaultPrevented||u?.())},g),M=m?j===x.length-1:!1,P=Vs(D=>{D.key==="Escape"&&(a?.(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))});return c.useEffect(()=>{if(M)return g.addEventListener("keydown",P,{capture:!0}),()=>g.removeEventListener("keydown",P,{capture:!0})},[g,M,P]),c.useEffect(()=>{if(m)return s&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(ni=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(m)),d.layers.add(m),ri(),()=>{s&&(d.layersWithOutsidePointerEventsDisabled.delete(m),d.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=ni))}},[m,g,s,d]),c.useEffect(()=>()=>{m&&(d.layers.delete(m),d.layersWithOutsidePointerEventsDisabled.delete(m),ri())},[m,d]),c.useEffect(()=>{const D=()=>v({});return document.addEventListener(Yr,D),()=>document.removeEventListener(Yr,D)},[]),n.jsx(bt.div,{...f,ref:p,style:{pointerEvents:y?I?"auto":"none":void 0,...e.style},onFocusCapture:Tt(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Tt(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Tt(e.onPointerDownCapture,k.onPointerDownCapture)})});dc.displayName=Cg;var Ig="DismissableLayerBranch",Tg=c.forwardRef((e,t)=>{const s=c.useContext(za),r=c.useRef(null),a=es(t,r);return c.useEffect(()=>{const o=r.current;if(o)return s.branches.add(o),()=>{s.branches.delete(o)}},[s.branches]),n.jsx(bt.div,{...e,ref:a})});Tg.displayName=Ig;function Rg(){const e=c.useContext(za),[t,s]=c.useState(null);return c.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),s}var Mg=()=>!0;function Ag(e,t){const{ownerDocument:s=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:o,shouldHandlePointerDownOutside:i=Mg}=t,l=Vs(e),u=c.useRef(!1),f=c.useRef(!1),d=c.useRef(new Map),m=c.useRef(()=>{});return c.useEffect(()=>{function h(){f.current=!1,a.current=!1,d.current.clear()}function g(){return Array.from(d.current.values()).some(Boolean)}function v(j){if(!f.current)return;const y=j.target;y instanceof Node&&[...o].some(N=>N.contains(y))||d.current.set(j.type,!0),j.type==="click"&&window.setTimeout(()=>{f.current&&m.current()},0)}function p(j){f.current&&d.current.set(j.type,!1)}const x=j=>{if(j.target&&!u.current){let y=function(){s.removeEventListener("click",m.current);const N=g();h(),N||fc(Ng,l,I,{discrete:!0})};if(!i(j.target)){s.removeEventListener("click",m.current),h(),u.current=!1;return}const I={originalEvent:j};f.current=!0,a.current=r&&j.button===0,d.current.clear(),!r||j.button!==0?y():(s.removeEventListener("click",m.current),m.current=y,s.addEventListener("click",m.current,{once:!0}))}else s.removeEventListener("click",m.current),h();u.current=!1},b=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const j of b)s.addEventListener(j,v,!0),s.addEventListener(j,p);const w=window.setTimeout(()=>{s.addEventListener("pointerdown",x)},0);return()=>{window.clearTimeout(w),s.removeEventListener("pointerdown",x),s.removeEventListener("click",m.current);for(const j of b)s.removeEventListener(j,v,!0),s.removeEventListener(j,p)}},[s,l,r,a,o,i]),{onPointerDownCapture:()=>u.current=!0}}function Dg(e,t=globalThis?.document){const s=Vs(e),r=c.useRef(!1);return c.useEffect(()=>{const a=o=>{o.target&&!r.current&&fc(Eg,s,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,s]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function ri(){const e=new CustomEvent(Yr);document.dispatchEvent(e)}function fc(e,t,s,{discrete:r}){const a=s.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:s});t&&a.addEventListener(e,t,{once:!0}),r?kg(a,o):a.dispatchEvent(o)}var wn=0,is=null;function Og(){c.useEffect(()=>{is||(is={start:ai(),end:ai()});const{start:e,end:t}=is;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),wn++,()=>{wn===1&&(is?.start.remove(),is?.end.remove(),is=null),wn=Math.max(0,wn-1)}},[])}function ai(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Nr="focusScope.autoFocusOnMount",Er="focusScope.autoFocusOnUnmount",oi={bubbles:!1,cancelable:!0},Pg="FocusScope",mc=c.forwardRef((e,t)=>{const{loop:s=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[l,u]=c.useState(null),f=Vs(a),d=Vs(o),m=c.useRef(null),h=es(t,u),g=c.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;c.useEffect(()=>{if(r){let p=function(j){if(g.paused||!l)return;const y=j.target;l.contains(y)?m.current=y:Ct(m.current,{select:!0})},x=function(j){if(g.paused||!l)return;const y=j.relatedTarget;y!==null&&(l.contains(y)||Ct(m.current,{select:!0}))},b=function(j){if(document.activeElement===document.body)for(const I of j)I.removedNodes.length>0&&Ct(l)};document.addEventListener("focusin",p),document.addEventListener("focusout",x);const w=new MutationObserver(b);return l&&w.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",x),w.disconnect()}}},[r,l,g.paused]),c.useEffect(()=>{if(l){li.add(g);const p=document.activeElement;if(!l.contains(p)){const b=new CustomEvent(Nr,oi);l.addEventListener(Nr,f),l.dispatchEvent(b),b.defaultPrevented||(Lg(Bg(hc(l)),{select:!0}),document.activeElement===p&&Ct(l))}return()=>{l.removeEventListener(Nr,f),setTimeout(()=>{const b=new CustomEvent(Er,oi);l.addEventListener(Er,d),l.dispatchEvent(b),b.defaultPrevented||Ct(p??document.body,{select:!0}),l.removeEventListener(Er,d),li.remove(g)},0)}}},[l,f,d,g]);const v=c.useCallback(p=>{if(!s&&!r||g.paused)return;const x=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,b=document.activeElement;if(x&&b){const w=p.currentTarget,[j,y]=$g(w);j&&y?!p.shiftKey&&b===y?(p.preventDefault(),s&&Ct(j,{select:!0})):p.shiftKey&&b===j&&(p.preventDefault(),s&&Ct(y,{select:!0})):b===w&&p.preventDefault()}},[s,r,g.paused]);return n.jsx(bt.div,{tabIndex:-1,...i,ref:h,onKeyDown:v})});mc.displayName=Pg;function Lg(e,{select:t=!1}={}){const s=document.activeElement;for(const r of e)if(Ct(r,{select:t}),document.activeElement!==s)return}function $g(e){const t=hc(e),s=ii(t,e),r=ii(t.reverse(),e);return[s,r]}function hc(e){const t=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)t.push(s.currentNode);return t}function ii(e,t){const s=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(s?!r.checkVisibility({checkVisibilityCSS:!0}):Fg(r,{upTo:t})))return r}function Fg(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function _g(e){return e instanceof HTMLInputElement&&"select"in e}function Ct(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&_g(e)&&t&&e.select()}}var li=zg();function zg(){let e=[];return{add(t){const s=e[0];t!==s&&s?.pause(),e=ci(e,t),e.unshift(t)},remove(t){e=ci(e,t),e[0]?.resume()}}}function ci(e,t){const s=[...e],r=s.indexOf(t);return r!==-1&&s.splice(r,1),s}function Bg(e){return e.filter(t=>t.tagName!=="A")}var Kg=ma[" useId ".trim().toString()]||(()=>{}),Ug=0;function Ir(e){const[t,s]=c.useState(Kg());return Ws(()=>{s(r=>r??String(Ug++))},[e]),e||(t?`radix-${t}`:"")}var qg="Portal",pc=c.forwardRef((e,t)=>{const{container:s,...r}=e,[a,o]=c.useState(!1);Ws(()=>o(!0),[]);const i=s||a&&globalThis?.document?.body;return i?ha.createPortal(n.jsx(bt.div,{...r,ref:t}),i):null});pc.displayName=qg;function Hg(e,t){return c.useReducer((s,r)=>t[s][r]??s,e)}var Zn=e=>{const{present:t,children:s}=e,r=Wg(t),a=typeof s=="function"?s({present:r.isPresent}):c.Children.only(s),o=Vg(r.ref,Qg(a));return typeof s=="function"||r.isPresent?c.cloneElement(a,{ref:o}):null};Zn.displayName="Presence";function Wg(e){const[t,s]=c.useState(),r=c.useRef(null),a=c.useRef(e),o=c.useRef("none"),i=c.useRef(void 0),l=e?"mounted":"unmounted",[u,f]=Hg(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return c.useEffect(()=>{u==="mounted"?(o.current=i.current??Os(r.current),i.current=void 0):o.current="none"},[u]),Ws(()=>{const d=r.current,m=a.current;if(m!==e){const g=o.current,v=Os(d);e?(i.current=v,f("MOUNT")):v==="none"||d?.display==="none"?f("UNMOUNT"):f(m&&g!==v?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,f]),Ws(()=>{if(t){let d;const m=t.ownerDocument.defaultView??window,h=v=>{const x=Os(r.current).includes(CSS.escape(v.animationName));if(v.target===t&&x&&(f("ANIMATION_END"),!a.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},g=v=>{v.target===t&&(o.current=Os(r.current))};return t.addEventListener("animationstart",g),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{m.clearTimeout(d),t.removeEventListener("animationstart",g),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else f("ANIMATION_END")},[t,f]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:c.useCallback(d=>{if(d){const m=getComputedStyle(d);r.current=m,i.current=Os(m)}else r.current=null;s(d)},[])}}function ui(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Vg(...e){const t=c.useRef(e);return t.current=e,c.useCallback(s=>{const r=t.current;let a=!1;const o=r.map(i=>{const l=ui(i,s);return!a&&typeof l=="function"&&(a=!0),l});if(a)return()=>{for(let i=0;i<o.length;i++){const l=o[i];typeof l=="function"?l():ui(r[i],null)}}},[])}function Os(e){return e?.animationName||"none"}function Qg(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?e.props.ref:e.props.ref||e.ref)}var Yg=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},ls=new WeakMap,jn=new WeakMap,Sn={},Tr=0,gc=function(e){return e&&(e.host||gc(e.parentNode))},Gg=function(e,t){return t.map(function(s){if(e.contains(s))return s;var r=gc(s);return r&&e.contains(r)?r:(console.error("aria-hidden",s,"in not contained inside",e,". Doing nothing"),null)}).filter(function(s){return!!s})},Xg=function(e,t,s,r){var a=Gg(t,Array.isArray(e)?e:[e]);Sn[s]||(Sn[s]=new WeakMap);var o=Sn[s],i=[],l=new Set,u=new Set(a),f=function(m){!m||l.has(m)||(l.add(m),f(m.parentNode))};a.forEach(f);var d=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(h){if(l.has(h))d(h);else try{var g=h.getAttribute(r),v=g!==null&&g!=="false",p=(ls.get(h)||0)+1,x=(o.get(h)||0)+1;ls.set(h,p),o.set(h,x),i.push(h),p===1&&v&&jn.set(h,!0),x===1&&h.setAttribute(s,"true"),v||h.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",h,b)}})};return d(t),l.clear(),Tr++,function(){i.forEach(function(m){var h=ls.get(m)-1,g=o.get(m)-1;ls.set(m,h),o.set(m,g),h||(jn.has(m)||m.removeAttribute(r),jn.delete(m)),g||m.removeAttribute(s)}),Tr--,Tr||(ls=new WeakMap,ls=new WeakMap,jn=new WeakMap,Sn={})}},Jg=function(e,t,s){s===void 0&&(s="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),a=Yg(e);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live], script"))),Xg(r,a,s,"aria-hidden")):function(){return null}},Mn="right-scroll-bar-position",An="width-before-scroll-bar",Zg="with-scroll-bars-hidden",ex="--removed-body-scroll-bar-size";function Rr(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function tx(e,t){var s=c.useState(function(){return{value:e,callback:t,facade:{get current(){return s.value},set current(r){var a=s.value;a!==r&&(s.value=r,s.callback(r,a))}}}})[0];return s.callback=t,s.facade}var sx=typeof window<"u"?c.useLayoutEffect:c.useEffect,di=new WeakMap;function nx(e,t){var s=tx(null,function(r){return e.forEach(function(a){return Rr(a,r)})});return sx(function(){var r=di.get(s);if(r){var a=new Set(r),o=new Set(e),i=s.current;a.forEach(function(l){o.has(l)||Rr(l,null)}),o.forEach(function(l){a.has(l)||Rr(l,i)})}di.set(s,e)},[e]),s}function rx(e){return e}function ax(e,t){t===void 0&&(t=rx);var s=[],r=!1,a={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return s.length?s[s.length-1]:e},useMedium:function(o){var i=t(o,r);return s.push(i),function(){s=s.filter(function(l){return l!==i})}},assignSyncMedium:function(o){for(r=!0;s.length;){var i=s;s=[],i.forEach(o)}s={push:function(l){return o(l)},filter:function(){return s}}},assignMedium:function(o){r=!0;var i=[];if(s.length){var l=s;s=[],l.forEach(o),i=s}var u=function(){var d=i;i=[],d.forEach(o)},f=function(){return Promise.resolve().then(u)};f(),s={push:function(d){i.push(d),f()},filter:function(d){return i=i.filter(d),s}}}};return a}function ox(e){e===void 0&&(e={});var t=ax(null);return t.options=Nt({async:!0,ssr:!1},e),t}var xc=function(e){var t=e.sideCar,s=Ji(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return c.createElement(r,Nt({},s))};xc.isSideCarExport=!0;function ix(e,t){return e.useMedium(t),xc}var bc=ox(),Mr=function(){},er=c.forwardRef(function(e,t){var s=c.useRef(null),r=c.useState({onScrollCapture:Mr,onWheelCapture:Mr,onTouchMoveCapture:Mr}),a=r[0],o=r[1],i=e.forwardProps,l=e.children,u=e.className,f=e.removeScrollBar,d=e.enabled,m=e.shards,h=e.sideCar,g=e.noRelative,v=e.noIsolation,p=e.inert,x=e.allowPinchZoom,b=e.as,w=b===void 0?"div":b,j=e.gapMode,y=Ji(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),I=h,N=nx([s,t]),k=Nt(Nt({},y),a);return c.createElement(c.Fragment,null,d&&c.createElement(I,{sideCar:bc,removeScrollBar:f,shards:m,noRelative:g,noIsolation:v,inert:p,setCallbacks:o,allowPinchZoom:!!x,lockRef:s,gapMode:j}),i?c.cloneElement(c.Children.only(l),Nt(Nt({},k),{ref:N})):c.createElement(w,Nt({},k,{className:u,ref:N}),l))});er.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};er.classNames={fullWidth:An,zeroRight:Mn};var lx=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function cx(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=lx();return t&&e.setAttribute("nonce",t),e}function ux(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function dx(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var fx=function(){var e=0,t=null;return{add:function(s){e==0&&(t=cx())&&(ux(t,s),dx(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},mx=function(){var e=fx();return function(t,s){c.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},vc=function(){var e=mx(),t=function(s){var r=s.styles,a=s.dynamic;return e(r,a),null};return t},hx={left:0,top:0,right:0,gap:0},Ar=function(e){return parseInt(e||"",10)||0},px=function(e){var t=window.getComputedStyle(document.body),s=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return[Ar(s),Ar(r),Ar(a)]},gx=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return hx;var t=px(e),s=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-s+t[2]-t[0])}},xx=vc(),xs="data-scroll-locked",bx=function(e,t,s,r){var a=e.left,o=e.top,i=e.right,l=e.gap;return s===void 0&&(s="margin"),`
76
+ .`.concat(Zg,` {
77
77
  overflow: hidden `).concat(r,`;
78
78
  padding-right: `).concat(l,"px ").concat(r,`;
79
79
  }
@@ -107,12 +107,12 @@ a, a:visited {
107
107
  }
108
108
 
109
109
  body[`).concat(xs,`] {
110
- `).concat(Zg,": ").concat(l,`px;
110
+ `).concat(ex,": ").concat(l,`px;
111
111
  }
112
- `)},fi=function(){var e=parseInt(document.body.getAttribute(xs)||"0",10);return isFinite(e)?e:0},bx=function(){c.useEffect(function(){return document.body.setAttribute(xs,(fi()+1).toString()),function(){var e=fi()-1;e<=0?document.body.removeAttribute(xs):document.body.setAttribute(xs,e.toString())}},[])},vx=function(e){var t=e.noRelative,s=e.noImportant,r=e.gapMode,a=r===void 0?"margin":r;bx();var o=c.useMemo(function(){return px(a)},[a]);return c.createElement(gx,{styles:xx(o,!t,a,s?"":"!important")})},Gr=!1;if(typeof window<"u")try{var kn=Object.defineProperty({},"passive",{get:function(){return Gr=!0,!0}});window.addEventListener("test",kn,kn),window.removeEventListener("test",kn,kn)}catch{Gr=!1}var cs=Gr?{passive:!1}:!1,yx=function(e){return e.tagName==="TEXTAREA"},vc=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!yx(e)&&s[t]==="visible")},wx=function(e){return vc(e,"overflowY")},jx=function(e){return vc(e,"overflowX")},mi=function(e,t){var s=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=yc(e,r);if(a){var o=wc(e,r),i=o[1],l=o[2];if(i>l)return!0}r=r.parentNode}while(r&&r!==s.body);return!1},Sx=function(e){var t=e.scrollTop,s=e.scrollHeight,r=e.clientHeight;return[t,s,r]},kx=function(e){var t=e.scrollLeft,s=e.scrollWidth,r=e.clientWidth;return[t,s,r]},yc=function(e,t){return e==="v"?wx(t):jx(t)},wc=function(e,t){return e==="v"?Sx(t):kx(t)},Cx=function(e,t){return e==="h"&&t==="rtl"?-1:1},Nx=function(e,t,s,r,a){var o=Cx(e,window.getComputedStyle(t).direction),i=o*r,l=s.target,u=t.contains(l),f=!1,d=i>0,m=0,h=0;do{if(!l)break;var g=wc(e,l),v=g[0],p=g[1],x=g[2],b=p-x-o*v;(v||b)&&yc(e,l)&&(m+=b,h+=v);var w=l.parentNode;l=w&&w.nodeType===Node.DOCUMENT_FRAGMENT_NODE?w.host:w}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(d&&Math.abs(m)<1||!d&&Math.abs(h)<1)&&(f=!0),f},Cn=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},hi=function(e){return[e.deltaX,e.deltaY]},pi=function(e){return e&&"current"in e?e.current:e},Ex=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Ix=function(e){return`
112
+ `)},fi=function(){var e=parseInt(document.body.getAttribute(xs)||"0",10);return isFinite(e)?e:0},vx=function(){c.useEffect(function(){return document.body.setAttribute(xs,(fi()+1).toString()),function(){var e=fi()-1;e<=0?document.body.removeAttribute(xs):document.body.setAttribute(xs,e.toString())}},[])},yx=function(e){var t=e.noRelative,s=e.noImportant,r=e.gapMode,a=r===void 0?"margin":r;vx();var o=c.useMemo(function(){return gx(a)},[a]);return c.createElement(xx,{styles:bx(o,!t,a,s?"":"!important")})},Gr=!1;if(typeof window<"u")try{var kn=Object.defineProperty({},"passive",{get:function(){return Gr=!0,!0}});window.addEventListener("test",kn,kn),window.removeEventListener("test",kn,kn)}catch{Gr=!1}var cs=Gr?{passive:!1}:!1,wx=function(e){return e.tagName==="TEXTAREA"},yc=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!wx(e)&&s[t]==="visible")},jx=function(e){return yc(e,"overflowY")},Sx=function(e){return yc(e,"overflowX")},mi=function(e,t){var s=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=wc(e,r);if(a){var o=jc(e,r),i=o[1],l=o[2];if(i>l)return!0}r=r.parentNode}while(r&&r!==s.body);return!1},kx=function(e){var t=e.scrollTop,s=e.scrollHeight,r=e.clientHeight;return[t,s,r]},Cx=function(e){var t=e.scrollLeft,s=e.scrollWidth,r=e.clientWidth;return[t,s,r]},wc=function(e,t){return e==="v"?jx(t):Sx(t)},jc=function(e,t){return e==="v"?kx(t):Cx(t)},Nx=function(e,t){return e==="h"&&t==="rtl"?-1:1},Ex=function(e,t,s,r,a){var o=Nx(e,window.getComputedStyle(t).direction),i=o*r,l=s.target,u=t.contains(l),f=!1,d=i>0,m=0,h=0;do{if(!l)break;var g=jc(e,l),v=g[0],p=g[1],x=g[2],b=p-x-o*v;(v||b)&&wc(e,l)&&(m+=b,h+=v);var w=l.parentNode;l=w&&w.nodeType===Node.DOCUMENT_FRAGMENT_NODE?w.host:w}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(d&&Math.abs(m)<1||!d&&Math.abs(h)<1)&&(f=!0),f},Cn=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},hi=function(e){return[e.deltaX,e.deltaY]},pi=function(e){return e&&"current"in e?e.current:e},Ix=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Tx=function(e){return`
113
113
  .block-interactivity-`.concat(e,` {pointer-events: none;}
114
114
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
115
- `)},Tx=0,us=[];function Rx(e){var t=c.useRef([]),s=c.useRef([0,0]),r=c.useRef(),a=c.useState(Tx++)[0],o=c.useState(bc)[0],i=c.useRef(e);c.useEffect(function(){i.current=e},[e]),c.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=Wd([e.lockRef.current],(e.shards||[]).map(pi),!0).filter(Boolean);return p.forEach(function(x){return x.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=c.useCallback(function(p,x){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var b=Cn(p),w=s.current,j="deltaX"in p?p.deltaX:w[0]-b[0],y="deltaY"in p?p.deltaY:w[1]-b[1],I,N=p.target,k=Math.abs(j)>Math.abs(y)?"h":"v";if("touches"in p&&k==="h"&&N.type==="range")return!1;var C=window.getSelection(),M=C&&C.anchorNode,P=M?M===N||M.contains(N):!1;if(P)return!1;var D=mi(k,N);if(!D)return!0;if(D?I=k:(I=k==="v"?"h":"v",D=mi(k,N)),!D)return!1;if(!r.current&&"changedTouches"in p&&(j||y)&&(r.current=I),!I)return!0;var O=r.current||I;return Nx(O,x,p,O==="h"?j:y)},[]),u=c.useCallback(function(p){var x=p;if(!(!us.length||us[us.length-1]!==o)){var b="deltaY"in x?hi(x):Cn(x),w=t.current.filter(function(I){return I.name===x.type&&(I.target===x.target||x.target===I.shadowParent)&&Ex(I.delta,b)})[0];if(w&&w.should){x.cancelable&&x.preventDefault();return}if(!w){var j=(i.current.shards||[]).map(pi).filter(Boolean).filter(function(I){return I.contains(x.target)}),y=j.length>0?l(x,j[0]):!i.current.noIsolation;y&&x.cancelable&&x.preventDefault()}}},[]),f=c.useCallback(function(p,x,b,w){var j={name:p,delta:x,target:b,should:w,shadowParent:Mx(b)};t.current.push(j),setTimeout(function(){t.current=t.current.filter(function(y){return y!==j})},1)},[]),d=c.useCallback(function(p){s.current=Cn(p),r.current=void 0},[]),m=c.useCallback(function(p){f(p.type,hi(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){f(p.type,Cn(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return us.push(o),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:h}),document.addEventListener("wheel",u,cs),document.addEventListener("touchmove",u,cs),document.addEventListener("touchstart",d,cs),function(){us=us.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,cs),document.removeEventListener("touchmove",u,cs),document.removeEventListener("touchstart",d,cs)}},[]);var g=e.removeScrollBar,v=e.inert;return c.createElement(c.Fragment,null,v?c.createElement(o,{styles:Ix(a)}):null,g?c.createElement(vx,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Mx(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Ax=ox(xc,Rx);var jc=c.forwardRef(function(e,t){return c.createElement(er,Nt({},e,{ref:t,sideCar:Ax}))});jc.classNames=er.classNames;var Dx=class extends pa{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,r=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:l}=r,u=s.fetchMeta?.fetchMore?.direction,f=i&&u==="forward",d=a&&u==="forward",m=i&&u==="backward",h=a&&u==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Qd(t,s.data),hasPreviousPage:Vd(t,s.data),isFetchNextPageError:f,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:h,isRefetchError:l&&!f&&!m,isRefetching:o&&!d&&!h}}};function gi(e,t){const s=new Set(t);return e.filter(r=>!s.has(r))}function Ox(e,t,s){const r=e.slice(0);return r[t]=s,r}var Px=class extends Yd{#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,Br.batch(()=>{const s=this.#t,r=this.#f(this.#a);r.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=r.map(d=>d.observer),o=a.map(d=>d.getCurrentResult()),i=s.length!==a.length,l=a.some((d,m)=>d!==s[m]),u=i||l,f=u?!0:o.some((d,m)=>{const h=this.#e[m];return!h||!Gd(d,h)});!u&&!f||(u&&(this.#c=r,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(gi(s,a).forEach(d=>{d.destroy()}),gi(a,s).forEach(d=>{d.subscribe(m=>{this.#m(d,m)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const s=this.#f(e),r=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[r,o=>this.#d(o??r,t,a),()=>this.#u(r,s)]}#u(e,t){return t.map((s,r)=>{const a=e[r];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const r=this.#l,a=s!==void 0&&r!==void 0&&(r.length!==s.length||s.some((o,i)=>o!==r[i]));return(!this.#n||this.#e!==this.#i||a||t!==this.#o)&&(this.#o=t,this.#i=this.#e,s!==void 0&&(this.#l=s),this.#n=Xd(this.#n,t(e))),this.#n}return e}#p(){return this.#r?.combine!==void 0&&this.#t.some((e,t)=>e.options.suspense&&this.#e[t]?.data===void 0)}#f(e){const t=new Map;this.#t.forEach(r=>{const a=r.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(r):t.set(a,[r])});const s=[];return e.forEach(r=>{const a=this.#s.defaultQueryOptions(r),i=t.get(a.queryHash)?.shift()??new pa(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=Ox(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,r=t?s:this.#d(e,this.#r?.combine);(t||s!==r)&&Br.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function Ft({queries:e,...t},s){const r=ye(),a=Jd(),o=Zd(),i=c.useMemo(()=>e.map(p=>{const x=r.defaultQueryOptions(p);return x._optimisticResults=a?"isRestoring":"optimistic",x}),[e,r,a]);i.forEach(p=>{ef(p);const x=r.getQueryCache().get(p.queryHash);tf(p,o,x)}),sf(o);const[l]=c.useState(()=>new Px(r,i,t)),[u,f,d]=l.getOptimisticResult(i,t.combine),m=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>m?l.subscribe(Br.batchCalls(p)):nf,[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const g=u.some((p,x)=>vo(i[x],p))?u.flatMap((p,x)=>{const b=i[x];if(b&&vo(b,p)){const w=new pa(r,b);return rf(b,w,o)}return[]}):[];if(g.length>0)throw Promise.all(g);const v=u.find((p,x)=>{const b=i[x];return b&&af({result:p,errorResetBoundary:o,throwOnError:b.throwOnError,query:r.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(v?.error)throw v.error;return f(d())}function Sc(e,t){return of(e,Dx)}function Lx(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const s=!!(e.condition??!0),r=e.blockerFn;return{shouldBlockFn:async()=>s&&r!==void 0?await r():s,enableBeforeUnload:s,withResolver:r===void 0}}function $x(e,t){const{shouldBlockFn:s,enableBeforeUnload:r=!0,disabled:a=!1,withResolver:o=!1}=Lx(e),i=ga(),{history:l}=i,[u,f]=c.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return c.useEffect(()=>{const d=async m=>{function h(b){const w=i.parseLocation(b),j=i.getMatchedRoutes(w.pathname);return j.foundRoute===void 0?{routeId:"__notFound__",fullPath:w.pathname,pathname:w.pathname,params:j.routeParams,search:i.options.parseSearch(b.search)}:{routeId:j.foundRoute.id,fullPath:j.foundRoute.fullPath,pathname:w.pathname,params:j.routeParams,search:i.options.parseSearch(b.search)}}const g=h(m.currentLocation),v=h(m.nextLocation);if(g.routeId==="__notFound__"&&v.routeId!=="__notFound__")return!1;const p=await s({action:m.action,current:g,next:v});if(!o)return p;if(!p)return!1;const x=await new Promise(b=>{f({status:"blocked",current:g,next:v,action:m.action,proceed:()=>b(!1),reset:()=>b(!0)})});return f({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),x};return a?void 0:l.block({blockerFn:d,enableBeforeUnload:r})},[s,r,a,o,l,i]),u}function gt(e){const t=ga({warn:e?.router===void 0}),s=e?.router||t;return Ji(s.stores.__store,Zi(e,s))}function tr(e){const t=ga();return Ji(t.stores.location,Zi(e,t))}const Fx=new Set(["outbox","flagged"]),_x=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!Fx.has(s)};function zx(e){const t=Ft({queries:e.map(s=>({..._e({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,r]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Xs(r.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function kc(e){const{openCompose:t}=Dt(),s=Oe(),r=tr(),a=zx(e);return c.useCallback(()=>{if(_x(r.pathname)){c.startTransition(()=>{t({mode:"new"})});return}a&&(c.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,r.pathname,a])}const Bx=e=>e.startsWith("/mail")||e.startsWith("/settings"),Kx=({accounts:e})=>{const{state:t}=Dt(),s=tr(),r=kc(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!Bx(s.pathname)||t.isOpen||o?null:n.jsx("button",{type:"button",onClick:r,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:n.jsx(Hm,{className:"size-6"})})},Cc=({trigger:e,children:t,align:s="right"})=>{const[r,a]=c.useState(!1),o=c.useRef(null),i=c.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),l=c.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return c.useEffect(()=>(r&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",l)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",l)}),[r,i,l]),n.jsxs("div",{ref:o,className:"relative",children:[n.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!r)},className:be("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),r&&n.jsx("div",{className:be("absolute z-50 mt-1 min-w-[180px] py-1","bg-surface border border-line rounded-md shadow-lg",s==="right"?"right-0":"left-0"),children:t})]})},hs=({onClick:e,disabled:t,destructive:s,children:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:be("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:r}),Xr=()=>n.jsx("div",{className:"my-1 h-px bg-line"}),Nc=({children:e})=>{const{Account:t}=xa();return n.jsx(t,{children:e})},Ux=({email:e,onSignOut:t})=>{const s=Oe(),r=e??"Account";return n.jsxs(Cc,{trigger:n.jsx(dt,{name:r,email:e??void 0,size:"sm"}),align:"right",children:[e&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),n.jsx(Xr,{})]}),n.jsxs(hs,{onClick:()=>s({to:"/settings/accounts"}),children:[n.jsx(Oa,{className:"size-4"}),"Settings"]}),n.jsx(Xr,{}),n.jsxs(hs,{onClick:t,children:[n.jsx(Bl,{className:"size-4"}),"Sign out"]})]})},qx=()=>n.jsx(Nc,{children:({email:e,signOut:t})=>n.jsx(Ux,{email:e,onSignOut:t})}),xi=()=>{const e=ba(),t=va(e);window.open(t,"_blank","noopener,noreferrer")};function Ec({variant:e="icon"}){return e==="drawer"?n.jsxs("button",{type:"button",onClick:xi,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(Mo,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]}):n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Mo,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:xi})}const Ic="/mail/",Ba="/mail/$mailboxId",Tc="/mail/outbox",Rc="/mail/flagged";function Ka(e){return e.some(t=>t.routeId===Ic)}function nn(e){return e.some(t=>t.routeId===Rc)}function sr(e){return e.some(t=>t.routeId===Tc)}function Mc(e){return e.some(t=>t.routeId===Ba)}function Hx(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Ba}:${t}`:nn(e)?Rc:sr(e)?Tc:Ka(e)?Ic:""}const Dn="search-scope";function Wx(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function Ac(e){return nn(e)||sr(e)||Mc(e)}function Dc(e){return e.find(t=>t.routeId===Ba)?.params?.mailboxId}function Vx(e){const t=Dc(e.matches);return t||(Ac(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function Qx(e,t){return Ka(e)?{kind:"global"}:nn(e)?{kind:"scoped",chip:{id:Dn,label:"is:starred"}}:sr(e)?{kind:"scoped",chip:{id:Dn,label:"in:outbox"}}:Mc(e)?t?{kind:"scoped",chip:{id:Dn,label:Wx(t)}}:{kind:"pending"}:{kind:"global"}}function Yx(e,t,s){return t.kind==="global"?{kind:"global"}:nn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const Oc=({accounts:e})=>{const t=ya({strict:!1}),s=tr(),r=t.mailboxId,{t:a}=Un("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=Ft({queries:e.map(l=>({..._e({path:{accountId:l.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!r)return null;for(let l=0;l<e.length;l++){const u=i[l]?.data?.items;if(!u)continue;const f=u.find(m=>m.mailboxId===r);if(!f)continue;const d=Xs(e[l].folderAppointments);return bs(f,d.get(r),o)}return null},Gx=({accounts:e})=>{const s=ya({strict:!1}).mailboxId,r=Ft({queries:e.map(a=>({..._e({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of r){const o=a.data?.items;if(!o)continue;const i=o.find(l=>l.mailboxId===s);if(i)return i.unseenCount}return null};function Pc(e){const t=Oe(),{searchInput:s}=Ce(),r=Oc({accounts:e}),a=gt({select:l=>l.matches}),o=Qx(a,r),i=c.useCallback(l=>{l===Dn&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const Lc=[{title:"Navigation",hints:[{action:"focusNext",keys:["j"],description:"Focus next message"},{action:"focusPrevious",keys:["k"],description:"Focus previous message"},{action:"focusNext",keys:["↓"],description:"Focus next message"},{action:"focusPrevious",keys:["↑"],description:"Focus previous message"},{action:"focusFirst",keys:["Home"],description:"Focus first"},{action:"focusLast",keys:["End"],description:"Focus last"},{action:"openFocused",keys:["Enter"],description:"Open focused thread"},{action:"back",keys:["Esc"],description:"Back / close overlay"}]},{title:"Selection",hints:[{action:"toggleSelect",keys:["x"],description:"Toggle select"},{action:"toggleSelect",keys:["Space"],description:"Toggle select"},{action:"extendSelectDown",keys:["Shift","j"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","k"],description:"Extend selection up"},{action:"extendSelectDown",keys:["Shift","↓"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","↑"],description:"Extend selection up"},{action:"selectAll",keys:["⌘","A"],description:"Select all"}]},{title:"Actions",hints:[{action:"reply",keys:["r"],description:"Reply"},{action:"replyAll",keys:["a"],description:"Reply all"},{action:"forward",keys:["f"],description:"Forward"},{action:"delete",keys:["#"],description:"Delete"},{action:"toggleStar",keys:["s"],description:"Star / unstar"},{action:"toggleRead",keys:["u"],description:"Toggle read / unread"}]},{title:"Sender",hints:[{action:"muteSender",keys:["m"],description:"Mute sender"},{action:"blockSender",keys:["b"],description:"Block sender"},{action:"vipSender",keys:["v"],description:"VIP sender"},{action:"markJunk",keys:["!"],description:"Mark junk"}]},{title:"Go to",hints:[{action:"goBrief",keys:["g","b"],description:"Daily brief"},{action:"goInbox",keys:["g","i"],description:"Inbox"},{action:"goSent",keys:["g","s"],description:"Sent"},{action:"goFlagged",keys:["g","f"],description:"Starred"},{action:"goSettings",keys:["g",","],description:"Settings"}]},{title:"View & global",hints:[{action:"toggleIntelligence",keys:["i"],description:"Toggle intelligence"},{action:"toggleDensity",keys:["d"],description:"Toggle density"},{action:"focusSearch",keys:["/"],description:"Focus search"},{action:"compose",keys:["c"],description:"Compose"},{action:"compose",keys:["⌘","N"],description:"Compose"},{action:"help",keys:["?"],description:"Shortcut help"}]}];function Xx(e){for(const t of Lc){const s=t.hints.find(r=>r.action===e);if(s)return s.keys}}function fs(e){const t=Xx(e);return!t||t.length===0?"":t.length===1?`(${t[0]})`:t[0]==="g"?`(${t.join(" then ")})`:`(${t.join("")})`}const Jx={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function Zx({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:r,onSearchClearQuery:a}=Ce(),o=kc(e),{scope:i,clearScope:l}=Pc(e),u=i.kind==="scoped"?[{id:i.chip.id,label:i.chip.label,tone:"scope"}]:void 0,f=Jx[i.kind];return n.jsx(np,{search:n.jsx(La,{value:t,onChange:s,onClear:r,onClearQuery:a,chips:u,onRemoveChip:l,placeholder:f,size:"lg"}),actions:n.jsxs(n.Fragment,{children:[n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Qm,{className:"size-4"}),title:`Compose ${fs("compose")}`,"aria-label":"Compose",onClick:o}),n.jsx(Ec,{}),n.jsx(qx,{})]})})}const Ua=({isOpen:e,onClose:t,children:s,ariaLabel:r="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=c.useRef(null),l=c.useRef(null);if(c.useEffect(()=>{if(!e)return;l.current=document.activeElement;const f=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",f),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const m=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",f),document.body.style.overflow=m,l.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return n.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":r,children:[n.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),n.jsxs("div",{ref:i,className:be("absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[n.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:n.jsx(We,{className:"size-5"})})}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},eb=e=>{const t=e.filter(a=>!a.isMultipart&&a.disposition!=="attachment"&&a.mediaType==="TEXT"&&a.contentUrl.length>0),s=t.find(a=>a.mediaSubtype.toUpperCase()==="HTML");if(s)return{kind:"html",contentUrl:s.contentUrl};const r=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return r?{kind:"text",contentUrl:r.contentUrl}:null},Jr={all:["messages"],detail:e=>[...Jr.all,"detail",e],body:e=>[...Jr.detail(e),"body"]};class Ht extends Error{reason;status;retryAfterSeconds;constructor(t,s,r,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=r,this.retryAfterSeconds=a}}const tb=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},sb=8,nb="x-remit-403-reason",rb=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},ab=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,ob=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},ib=async(e,t,s=async()=>null)=>{const r={},a=await s();a&&(r.Authorization=`Bearer ${a}`);const o=await lf(e,{headers:r});if(o.status===202)throw new Ht("not-ready","Message body is still syncing",202,tb(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(nb),f=rb(o.status,u);throw new Ht(f,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(ob(t,i))throw new Ht("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(ab(l,i))throw new Ht("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},lb=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),$c=({messageId:e,bodyParts:t,enabled:s=!0})=>{const r=t?eb(t):null,a=Js(),{getToken:o}=xa(),i=c.useRef(null),l=ye(),u=c.useRef(!1),f=c.useRef(null),d=e&&r?`${e}:${r.contentUrl}`:null;f.current!==d&&(f.current=d,u.current=!1);const m=de({queryKey:e?[...Jr.body(e),r?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!r)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const v=u.current;return u.current=!1,lb({fetchContent:(p,x)=>ib(p,x,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:el({path:{messageId:e}})})},{contentUrl:r.contentUrl,kind:r.kind,isRetryAfterNotReady:v})},enabled:s&&!!e&&!!r,staleTime:300*1e3,gcTime:1800*1e3,retry:(v,p)=>p instanceof Ht&&p.reason==="not-ready"?v<sb:v<1,retryDelay:(v,p)=>p instanceof Ht&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=m.isLoading&&!!r;c.useEffect(()=>{h&&(i.current=performance.now())},[h]),c.useEffect(()=>{m.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[m.isSuccess,a]);const g=m.data&&r?{kind:r.kind,body:m.data}:void 0;return{picked:r,data:g,isLoading:h,isError:m.isError,error:m.error,refetch:m.refetch}},cb=({outboxMessageId:e,onDraftCreated:t})=>{const[s,r]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=ye(),u=ve(tl()),f=ve(cf()),d=c.useCallback(async v=>{if(r("saving"),o(null),e){const x=await f.mutateAsync({path:{outboxMessageId:e},body:{toAddresses:v.toAddresses,ccAddresses:v.ccAddresses,bccAddresses:v.bccAddresses,subject:v.subject,textBody:v.textBody,htmlBody:v.htmlBody,inReplyTo:v.inReplyTo,references:v.references}});return r("saved"),x}const p=await u.mutateAsync({body:{...v,sendImmediately:!1}});return t(p.outboxMessageId),r("saved"),l.invalidateQueries({queryKey:qn().queryKey}),p},[e,u,f,t,l]),m=c.useCallback(v=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{d(v).catch(p=>{o(p),r("error")})},2e3)},[d]),h=c.useCallback(v=>(i.current&&clearTimeout(i.current),d(v)),[d]),g=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:m,saveImmediately:h,cancelAutoSave:g}},Fc=e=>"text"in e&&!("children"in e),_c=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),ub=e=>{let t=_c(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},zc=e=>{const t=e.children.map(s=>Fc(s)?ub(s):zc(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${_c(s)}">${t}</a>`}default:return`<p>${t}</p>`}},bi=e=>e.map(zc).join(""),Bc=e=>Fc(e)?e.text:e.children.map(Bc).join(""),Zr=e=>e.map(Bc).join(`
116
- `),db=e=>e.displayName?`${e.displayName} <${e.normalizedEmail}>`:e.normalizedEmail,vi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),fb=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const r=s[1].trim(),a=s[2].trim();if(vi(a))return{email:a,displayName:r}}if(vi(t))return{email:t}},Dr=({label:e,addresses:t,onChange:s,placeholder:r})=>{const[a,o]=c.useState(""),[i,l]=c.useState(-1),[u,f]=c.useState(!1),d=c.useRef(null),m=c.useRef(null),h=ml(a,200),{data:g}=de({...sl({query:{q:h,limit:8}}),enabled:h.length>=2}),v=g?.items??[],p=new Set(t.map(k=>k.email.toLowerCase())),x=v.filter(k=>!p.has(k.normalizedEmail.toLowerCase()));c.useEffect(()=>{l(-1),f(x.length>0&&a.length>=2)},[x.length,a.length]);const b=c.useCallback(k=>{p.has(k.email.toLowerCase())||(s([...t,k]),o(""),f(!1))},[t,p,s]),w=c.useCallback(k=>{s(t.filter((C,M)=>M!==k))},[t,s]),j=c.useCallback(k=>{b({email:k.normalizedEmail,displayName:k.displayName}),d.current?.focus()},[b]),y=c.useCallback(()=>{const k=fb(a);k&&b(k)},[a,b]),I=c.useCallback(k=>{if(k.key==="Backspace"&&a===""&&t.length>0){w(t.length-1);return}if(k.key==="Enter"||k.key==="Tab"||k.key===","){if(i>=0&&x[i]){k.preventDefault(),j(x[i]);return}a.trim()&&(k.preventDefault(),y());return}if(k.key==="ArrowDown"&&u){k.preventDefault(),l(C=>C<x.length-1?C+1:0);return}if(k.key==="ArrowUp"&&u){k.preventDefault(),l(C=>C>0?C-1:x.length-1);return}k.key==="Escape"&&(f(!1),l(-1))},[a,t.length,i,x,u,w,j,y]),N=c.useCallback(()=>{setTimeout(()=>{y(),f(!1)},150)},[y]);return n.jsxs("div",{className:"relative",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),n.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>d.current?.focus(),onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&d.current?.focus()},children:[t.map((k,C)=>n.jsx(Jm,{email:k.email,displayName:k.displayName,onRemove:()=>w(C)},k.email)),n.jsx("input",{ref:d,id:`address-field-${e}`,type:"text",value:a,onChange:k=>o(k.target.value),onKeyDown:I,onBlur:N,placeholder:t.length===0?r:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5"})]})]}),u&&x.length>0&&n.jsx("ul",{ref:m,className:"absolute left-12 right-0 mt-1 bg-surface border border-line rounded-md shadow-lg z-50 max-h-[200px] overflow-auto",children:x.map((k,C)=>n.jsx("li",{className:be("px-3 py-2 text-sm cursor-pointer transition-colors",C===i&&"bg-accent-2-soft"),onMouseDown:M=>{M.preventDefault(),j(k)},onMouseEnter:()=>l(C),children:db(k)},k.addressId))})]})},mb=({accountId:e})=>{const t=Oe();return n.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[n.jsx(fa,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),n.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",n.jsx(Lm,{className:"size-3","aria-hidden":"true"})]})]})]})},yi=150,hb=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>yi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,r=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>yi})};return r(),s.addEventListener("resize",r),()=>s.removeEventListener("resize",r)},[]),e},pb=({selectedAccountId:e,onSelect:t})=>{const{data:s}=de({...xt(),staleTime:1/0}),r=s?.accounts??[];if(c.useEffect(()=>{!e&&r.length===1&&r[0]&&t(r[0])},[e,r,t]),r.length<=1){const a=r[0];return a?n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=r.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:r.map(a=>n.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},gb=({value:e,onChange:t})=>n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),n.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),xb=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],bb=["href"],vb=e=>Yi.sanitize(e,{ALLOWED_TAGS:xb,ALLOWED_ATTR:bb}),yb=c.lazy(()=>df(()=>import("./ComposeBody-C_pJkiQs.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}))),wb=()=>n.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[n.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),n.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),Kc=[{type:"p",children:[{text:""}]}],jb=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],Sb=e=>e?[...jb,{type:"p",children:[{text:e}]}]:Kc,kb=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",Cb=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",Nb=(e,t,s)=>{const{envelope:r}=e,o=(r.replyTo.length>0?r.replyTo:r.from).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(f=>f.email.toLowerCase())),u=[...r.to,...r.cc].filter(f=>f.normalizedEmail.toLowerCase()!==i&&!l.has(f.normalizedEmail.toLowerCase())).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));return{to:o,cc:u}},Eb=e=>{const t=e.envelope.messageIdValue,r=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!r.includes(t)&&r.push(t),{inReplyTo:t,references:r}},Ib=(e,t,s,r,a)=>e.length===0&&t.length===0&&s.length===0&&r.trim()===""&&Zr(a).trim()==="",Tb=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:r,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:f,showBcc:d,setShowBcc:m,subject:h,setSubject:g})=>{const v=Ot(),{isKeyboardOpen:p}=hb();if(!v&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(w=>w.displayName??w.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.push(h),n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[n.jsx("span",{className:"truncate text-xs text-fg-muted",children:b.length>0?b.join(" · "):"…"}),n.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return n.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[n.jsx(pb,{selectedAccountId:e,onSelect:t}),n.jsx(Dr,{label:"To",addresses:s,onChange:r,placeholder:"Recipients"}),u?n.jsx(Dr,{label:"Cc",addresses:a,onChange:o}):n.jsxs("div",{className:"flex gap-2 pl-14",children:[n.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&n.jsx("div",{className:"pl-14",children:n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&n.jsx(Dr,{label:"Bcc",addresses:i,onChange:l}),n.jsx(gb,{value:h,onChange:g})]})},qa=({mode:e,account:t,sourceMessage:s,onClose:r,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Dt(),{pushError:u}=Ve(),{outboxMessageId:f}=o,[d,m]=c.useState([]),[h,g]=c.useState([]),[v,p]=c.useState([]),[x,b]=c.useState(""),[w,j]=c.useState(!1),[y,I]=c.useState(!1),[N,k]=c.useState(t?.accountId),[C,M]=c.useState(!1),P=c.useRef(f);c.useEffect(()=>{P.current!==f&&(P.current=f,f&&(m([]),g([]),p([]),b(""),j(!1),I(!1),E(Kc),M(!1)))},[f]);const{signature:D}=Kf(N),[O,E]=c.useState(()=>Sb(D.plainText)),{data:S}=de({...uf({path:{outboxMessageId:f??""}}),enabled:!!f&&!C});c.useEffect(()=>{!S||C||(m(S.toAddresses.map(J=>({email:J,displayName:void 0}))),S.ccAddresses&&S.ccAddresses.length>0&&(g(S.ccAddresses.map(J=>({email:J,displayName:void 0}))),j(!0)),S.bccAddresses&&S.bccAddresses.length>0&&(p(S.bccAddresses.map(J=>({email:J,displayName:void 0}))),I(!0)),S.subject&&b(S.subject),S.textBody&&E([{type:"p",children:[{text:S.textBody}]}]),k(S.accountId),M(!0))},[S,C]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:J,cc:ae}=Nb(s,e,t?.email);m(J),g(ae),ae.length>0&&j(!0),b(kb(s.envelope.subject))}e==="forward"&&b(Cb(s.envelope.subject))}},[e,s,t?.email]);const A=e==="reply"||e==="reply_all"||e==="forward",{data:L}=$c({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:A&&!!s}),T=L?.kind==="text"?L.body:"",F=L?.kind==="html"?vb(L.body):void 0,R=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:$,saveError:z,saveDraft:V,cancelAutoSave:ee}=cb({outboxMessageId:f,onDraftCreated:i});c.useEffect(()=>{z&&u({title:"Couldn't save draft",detail:st(z)??"Saving the draft failed.",error:z})},[z,u]);const X=ve(tl()),Q=ve(nl()),le=ve({...Hn(),onError:J=>{u(Vt("Couldn't discard draft","The draft wasn't discarded.",J))}}),{data:ue}=de({...xt(),staleTime:1/0}),te=ue?.accounts.find(J=>J.accountId===N),K=te?zf(te):!1,U=X.isPending||Q.isPending,re=d.length>0&&!!N&&!K;c.useEffect(()=>{if(!N||f&&!C||Ib(d,h,v,x,O))return;const J=Zr(O),ae=bi(O);V({accountId:N,toAddresses:d.map(ce=>ce.email),ccAddresses:h.length>0?h.map(ce=>ce.email):void 0,bccAddresses:v.length>0?v.map(ce=>ce.email):void 0,subject:x||void 0,textBody:J||void 0,htmlBody:ae||void 0})},[N,f,C,d,h,v,x,O,V]);const Ie=c.useCallback(async()=>{if(!N||d.length===0)return;ee();const J=s&&(e==="reply"||e==="reply_all")?Eb(s):{};let ae=f,ce=!1;if(!ae){const Fe=Zr(O),pe=bi(O),ge=await X.mutateAsync({body:{accountId:N,toAddresses:d.map(Se=>Se.email),ccAddresses:h.length>0?h.map(Se=>Se.email):void 0,bccAddresses:v.length>0?v.map(Se=>Se.email):void 0,subject:x||void 0,textBody:Fe||void 0,htmlBody:pe||void 0,sendImmediately:!0,...J}}).catch(Se=>(u({title:"Couldn't send message",detail:st(Se)??"Saving the draft failed.",error:Se}),null));if(ge===null)return;ae=ge.outboxMessageId,ce=!0,i(ae)}await Q.mutateAsync({path:{outboxMessageId:ae}}).catch(Fe=>(u({title:"Couldn't send message",detail:st(Fe)??(ce?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:Fe}),null))!==null&&(l(ae),r())},[N,d,h,v,x,O,e,s,f,X,Q,ee,l,i,u,r]),je=c.useCallback(()=>{ee(),f&&le.mutate({path:{outboxMessageId:f}}),r()},[ee,f,le,r]),W=c.useCallback(J=>{k(J.accountId),a?.(J)},[a]);return n.jsx(ip,{banner:te&&K?n.jsx(mb,{accountId:te.accountId}):void 0,header:n.jsx(Tb,{selectedAccountId:N,onAccountChange:W,toAddresses:d,setToAddresses:m,ccAddresses:h,setCcAddresses:g,bccAddresses:v,setBccAddresses:p,showCc:w,setShowCc:j,showBcc:y,setShowBcc:I,subject:x,setSubject:b}),quoted:T||F?n.jsx(Tp,{text:T,html:F,senderName:R}):void 0,actionBar:n.jsx(op,{onSend:Ie,onDiscard:je,sending:U,canSend:re,saveStatus:$,unavailableReason:K?"SMTP not configured":void 0,onUnavailable:J=>u({title:"Can't send yet",detail:J})}),children:n.jsx(c.Suspense,{fallback:n.jsx(wb,{}),children:n.jsx(yb,{value:O,onChange:E,onSubmit:Ie,autoFocus:e==="new"})})})},wi=({mode:e,account:t,sourceMessage:s,onClose:r})=>n.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:n.jsx(qa,{mode:e,account:t,sourceMessage:s,onClose:r})}),Uc=({message:e,icon:t})=>n.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&n.jsx("div",{className:"mb-4 text-fg-muted",children:t}),n.jsx("p",{className:"text-fg-muted",children:e})]}),Ha=({enabled:e=!0,bindings:t,capture:s=!1})=>{const r=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const f=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(f&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",r,s),()=>window.removeEventListener("keydown",r,s)},[e,r,s])},qc=e=>{const{data:t,isLoading:s}=de({...xt(),staleTime:1/0}),r=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=Ft({queries:r.map(l=>({..._e({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<r.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return r[l]}},[e,r,a]),isLoading:o}},Rb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),Mb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Hc=(e,t)=>e===void 0?e:Rb(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:Mb(e)?{...e,items:t(e.items)}:e,vt=e=>{const t=[];for(const s of new Set(e))t.push(wa({path:{mailboxId:s}})),t.push(rl({path:{mailboxId:s}}));return t.push(al()),t},rn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),an=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,r])=>({queryKey:s,data:r})),on=(e,t,s)=>{const r=a=>Hc(a,s);for(const a of t)e.setQueriesData({queryKey:a},r)},ln=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},yt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Ab=3e3,Db=(e,t,s)=>{if(e.length===0)return()=>{};const r=setTimeout(()=>s(e),t);return()=>clearTimeout(r)},nr=(e,t,s)=>{const r=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(r.get(o)??s);return[...a]},$n=(e,t,s)=>e.map(r=>t.has(r.messageId)?{...r,isRead:s}:r),Ob=(e,t,s,r)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!r.has(a.messageId)).map(a=>a.messageId),Pb=({messages:e,expandedIds:t,threadId:s,mailboxId:r,accountId:a})=>{const o=ye(),{pushError:i}=Ve(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:f}=ve({...Wn(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),v=h.body.isRead??!0,p=Zt({path:{threadId:s}}),x=vt(nr(g,e,r));await Promise.all([o.cancelQueries({queryKey:p}),rn(o,x)]);const b=o.getQueriesData({queryKey:p}).filter(j=>j[1]!==void 0).map(([j,y])=>({queryKey:j,data:y})),w=an(o,x);return o.setQueriesData({queryKey:p},j=>j&&{...j,items:$n(j.items,g,v)}),on(o,x,j=>$n(j,g,v)),{threadMessagesPrefix:p,listPrefixes:x,previousThreadMessages:b,previousThreadsList:w}},onSuccess:(h,g)=>{const v=g.body.messageIds??[];for(const p of v)l.current.add(p),u.current.delete(p)},onError:(h,g,v)=>{const p=g.body.messageIds??[];for(const b of p)u.current.delete(b);if(v){for(const b of v.previousThreadMessages)o.setQueryData(b.queryKey,b.data);ln(o,v.previousThreadsList)}const x=g.body.isRead??!0;i({title:x?"Couldn't mark as read":"Couldn't mark as unread",detail:st(h),error:h})},onSettled:(h,g,v,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),yt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:Jt({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(v=>!l.current.has(v)&&!u.current.has(v));if(g.length!==0){for(const v of g)u.current.add(v);f({body:{messageIds:g,isRead:!0}})}},[f]),m=c.useMemo(()=>Ob(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Db(m,Ab,d),[m,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},rr=e=>{const{mailboxId:t,accountId:s,messages:r}=e,a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...Wn(),onError:(f,d)=>{const m=d.body.isRead??!0;o({title:m?"Couldn't mark as read":"Couldn't mark as unread",detail:st(f),error:f})},onSettled:(f,d,m)=>{yt(a,vt(nr(m.body.messageIds??[],r??[],t))),s&&a.invalidateQueries({queryKey:Jt({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,isRead:d}})},[i]),isPending:l}},Lb=60,$b=1.5,Fb=(e,t,s)=>{const r=Math.abs(e),a=Math.abs(t);return r<s?{direction:null}:r<a*$b?{direction:null}:{direction:e<0?"left":"right"}},_b=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Lb})=>{const r=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){r.current=null;return}r.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const f=r.current;if(r.current=null,!f)return;const{direction:d}=Fb(u.clientX-f.x,u.clientY-f.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{r.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},zb=(e,t,s)=>t?.find(r=>r.messageId===e)?.mailboxId??s,ji=(e,t,s)=>e.map(r=>r.messageId===t?{...r,hasStars:s}:r),Wa=({threadId:e,mailboxId:t,messages:s})=>{const r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i,variables:l}=ve({...ff(),onMutate:async f=>{const d=f.path.messageId,m=f.body.isStarred??!1,h=Zt({path:{threadId:e}}),g=vt([zb(d,s,t)]);await Promise.all([r.cancelQueries({queryKey:h}),rn(r,g)]);const v=r.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})),p=an(r,g);return r.setQueriesData({queryKey:h},x=>Hc(x,b=>ji(b,d,m))),on(r,g,x=>ji(x,d,m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)r.setQueryData(g.queryKey,g.data);ln(r,m.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:st(f),error:f})},onSettled:(f,d,m,h)=>{h&&(r.invalidateQueries({queryKey:h.threadMessagesPrefix}),yt(r,h.listPrefixes))}});return{toggleStar:(f,d)=>{o({path:{messageId:f},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function cn(e){return e===void 0?"uncategorized":e}const Bb={inbox:"Inbox",junk:"Junk"},Va=e=>e.destinationMailboxId!==void 0,Kb=(e,t)=>{if(Va(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${Bb[s]??"another folder"} by Remit`},Ub=(e,t)=>{if(e===jo.MoveToInbox)return t.inboxMailboxId;if(e===jo.MoveToJunk)return t.junkMailboxId},qb=(e,t,s)=>{if(!e||!t)return!1;const r=Va(e)?e.destinationMailboxId:Ub(e.action,s);return r!==void 0&&r===t},Hb=(e,t)=>{if(e){if(Va(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},ar=(e,t)=>{const{data:s,isLoading:r}=de({...xt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:r}},Wb=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Vb=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},Qa=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},or=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Junk");return{junkMailboxId:t,isLoading:s}},Wc=e=>{const{data:t}=de({...xt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Si=(e,t)=>e.filter(s=>!t.has(s.messageId)),Qt=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...mf(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),m=t?Zt({path:{threadId:t}}):[],h=vt([e,f.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:m})]:[],rn(a,h)]);const g=t?a.getQueriesData({queryKey:m}).filter(p=>p[1]!==void 0).map(([p,x])=>({queryKey:p,data:x})):[],v=an(a,h);return t&&a.setQueriesData({queryKey:m},p=>p&&{...p,items:Si(p.items,d)}),on(a,h,p=>Si(p,d)),r?.(Array.from(d)),{threadMessagesPrefix:m,listPrefixes:h,previousThreadMessages:g,previousThreadsList:v}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)a.setQueryData(g.queryKey,g.data);ln(a,m.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:st(f),error:f})},onSettled:(f,d,m,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),yt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:Jt({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,destinationMailboxId:d}})},[i]),isPending:l}},Qb=({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a})=>{const{inboxMailboxId:o}=Qa(e),{junkMailboxId:i}=or(e),{moveMessages:l,isPending:u}=Qt({mailboxId:r,threadId:s,accountId:e}),{data:f}=de({..._e({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},m=qb(a,r,d),h=Hb(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!m||!a)return{show:!1,label:"",isUndoing:!1};const v=a.fromMailboxId?f?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>Vn(p.fullPath))[0]:void 0;return{show:!0,label:Kb(a,v),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function Vc({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a,size:o="sm"}){const i=Qb({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a});return i.show?n.jsx(rp,{label:i.label,size:o,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:o==="md"?i.filtersHref:void 0}):null}const ki=(e,t)=>e.filter(s=>!t.has(s.messageId)),Yb=e=>e.filter(t=>t.isDeleted!==!0),Yt=({mailboxId:e,threadId:t,accountId:s,messages:r,onAfterOptimisticRemove:a})=>{const o=ye(),{pushError:i}=Ve(),{mutate:l,isPending:u}=ve({...hf(),onMutate:async d=>{const m=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],g=vt(nr(m,r??[],e));await Promise.all([o.cancelQueries({queryKey:h}),rn(o,g)]);const v=t?o.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})):[],p=an(o,g);return t&&o.setQueriesData({queryKey:h},x=>x&&{...x,items:ki(x.items,m)}),on(o,g,x=>ki(x,m)),a?.(Array.from(m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(d,m,h)=>{if(h){for(const v of h.previousThreadMessages)o.setQueryData(v.queryKey,v.data);ln(o,h.previousThreadsList)}const g=m.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:st(d),error:d})},onSettled:(d,m,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),yt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:Jt({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&l({body:{messageIds:d}})},[l]),isPending:u}},Qc=(e,t=Date.now())=>({value:e,setAt:t}),Gb=(e,t,s,r)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Qc(!0,r):delete a.trusted,{...e,flags:a}},Xb=(e,t,s,r)=>{const a=o=>o.map(i=>Gb(i,t,s,r));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},Ya=({messageId:e})=>{const t=ye(),{pushError:s}=Ve(),{mutate:r,isPending:a,error:o,reset:i}=ve({...ol(),onMutate:async u=>{const f=u.path.addressId,m=u.body.flags?.trusted?.value===!0,h=el({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,p])=>({queryKey:v,data:p}));return t.setQueriesData({queryKey:h},v=>v&&Xb(v,f,m)),{describePrefix:h,previous:g}},onError:(u,f,d)=>{if(d)for(const m of d.previous)t.setQueryData(m.queryKey,m.data);s(Vt("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,f,d,m)=>{m&&t.invalidateQueries({queryKey:m.describePrefix})}});return{toggleTrusted:(u,f)=>{r({path:{addressId:u},body:{flags:{trusted:Qc(!f)}}})},isPending:a,error:o,reset:i}};var ir="Dialog",[Yc]=ig(ir),[Jb,at]=Yc(ir),Gc=e=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[f,d]=ug({prop:r,defaultProp:a??!1,onChange:o,caller:ir});return n.jsx(Jb,{scope:t,triggerRef:l,contentRef:u,contentId:Ir(),titleId:Ir(),descriptionId:Ir(),open:f,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),modal:i,children:s})};Gc.displayName=ir;var Xc="DialogTrigger",Zb=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(Xc,s),o=es(t,a.triggerRef);return n.jsx(bt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Xa(a.open),...r,ref:o,onClick:Tt(e.onClick,a.onOpenToggle)})});Zb.displayName=Xc;var Ga="DialogPortal",[ev,Jc]=Yc(Ga,{forceMount:void 0}),Zc=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,o=at(Ga,t);return n.jsx(ev,{scope:t,forceMount:s,children:c.Children.map(r,i=>n.jsx(Zn,{present:s||o.open,children:n.jsx(hc,{asChild:!0,container:a,children:i})}))})};Zc.displayName=Ga;var Fn="DialogOverlay",eu=c.forwardRef((e,t)=>{const s=Jc(Fn,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=at(Fn,e.__scopeDialog);return o.modal?n.jsx(Zn,{present:r||o.open,children:n.jsx(sv,{...a,ref:t})}):null});eu.displayName=Fn;var tv=_a("DialogOverlay.RemoveScroll"),sv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(Fn,s),o=Tg(),i=es(t,o);return n.jsx(jc,{as:tv,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(bt.div,{"data-state":Xa(a.open),...r,ref:i,style:{pointerEvents:"auto",...r.style}})})}),js="DialogContent",tu=c.forwardRef((e,t)=>{const s=Jc(js,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=at(js,e.__scopeDialog);return n.jsx(Zn,{present:r||o.open,children:o.modal?n.jsx(nv,{...a,ref:t}):n.jsx(rv,{...a,ref:t})})});tu.displayName=js;var nv=c.forwardRef((e,t)=>{const s=at(js,e.__scopeDialog),r=c.useRef(null),a=es(t,s.contentRef,r);return c.useEffect(()=>{const o=r.current;if(o)return Xg(o)},[]),n.jsx(su,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Tt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Tt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Tt(e.onFocusOutside,o=>o.preventDefault())})}),rv=c.forwardRef((e,t)=>{const s=at(js,e.__scopeDialog),r=c.useRef(!1),a=c.useRef(!1);return n.jsx(su,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||s.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),su=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=at(js,s);return Dg(),n.jsx(n.Fragment,{children:n.jsx(fc,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:o,children:n.jsx(uc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Xa(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),nu="DialogTitle",ru=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(nu,s);return n.jsx(bt.h2,{id:a.titleId,...r,ref:t})});ru.displayName=nu;var au="DialogDescription",av=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(au,s);return n.jsx(bt.p,{id:a.descriptionId,...r,ref:t})});av.displayName=au;var ou="DialogClose",ov=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(ou,s);return n.jsx(bt.button,{type:"button",...r,ref:t,onClick:Tt(e.onClick,()=>a.onOpenChange(!1))})});ov.displayName=ou;function Xa(e){return e?"open":"closed"}function iv(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 iu=q.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}),un=()=>{const e=q.useContext(iu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};iv(`[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(
115
+ `)},Rx=0,us=[];function Mx(e){var t=c.useRef([]),s=c.useRef([0,0]),r=c.useRef(),a=c.useState(Rx++)[0],o=c.useState(vc)[0],i=c.useRef(e);c.useEffect(function(){i.current=e},[e]),c.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=Vd([e.lockRef.current],(e.shards||[]).map(pi),!0).filter(Boolean);return p.forEach(function(x){return x.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=c.useCallback(function(p,x){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var b=Cn(p),w=s.current,j="deltaX"in p?p.deltaX:w[0]-b[0],y="deltaY"in p?p.deltaY:w[1]-b[1],I,N=p.target,k=Math.abs(j)>Math.abs(y)?"h":"v";if("touches"in p&&k==="h"&&N.type==="range")return!1;var C=window.getSelection(),M=C&&C.anchorNode,P=M?M===N||M.contains(N):!1;if(P)return!1;var D=mi(k,N);if(!D)return!0;if(D?I=k:(I=k==="v"?"h":"v",D=mi(k,N)),!D)return!1;if(!r.current&&"changedTouches"in p&&(j||y)&&(r.current=I),!I)return!0;var O=r.current||I;return Ex(O,x,p,O==="h"?j:y)},[]),u=c.useCallback(function(p){var x=p;if(!(!us.length||us[us.length-1]!==o)){var b="deltaY"in x?hi(x):Cn(x),w=t.current.filter(function(I){return I.name===x.type&&(I.target===x.target||x.target===I.shadowParent)&&Ix(I.delta,b)})[0];if(w&&w.should){x.cancelable&&x.preventDefault();return}if(!w){var j=(i.current.shards||[]).map(pi).filter(Boolean).filter(function(I){return I.contains(x.target)}),y=j.length>0?l(x,j[0]):!i.current.noIsolation;y&&x.cancelable&&x.preventDefault()}}},[]),f=c.useCallback(function(p,x,b,w){var j={name:p,delta:x,target:b,should:w,shadowParent:Ax(b)};t.current.push(j),setTimeout(function(){t.current=t.current.filter(function(y){return y!==j})},1)},[]),d=c.useCallback(function(p){s.current=Cn(p),r.current=void 0},[]),m=c.useCallback(function(p){f(p.type,hi(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){f(p.type,Cn(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return us.push(o),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:h}),document.addEventListener("wheel",u,cs),document.addEventListener("touchmove",u,cs),document.addEventListener("touchstart",d,cs),function(){us=us.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,cs),document.removeEventListener("touchmove",u,cs),document.removeEventListener("touchstart",d,cs)}},[]);var g=e.removeScrollBar,v=e.inert;return c.createElement(c.Fragment,null,v?c.createElement(o,{styles:Tx(a)}):null,g?c.createElement(yx,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Ax(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Dx=ix(bc,Mx);var Sc=c.forwardRef(function(e,t){return c.createElement(er,Nt({},e,{ref:t,sideCar:Dx}))});Sc.classNames=er.classNames;var Ox=class extends pa{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,r=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:l}=r,u=s.fetchMeta?.fetchMore?.direction,f=i&&u==="forward",d=a&&u==="forward",m=i&&u==="backward",h=a&&u==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Yd(t,s.data),hasPreviousPage:Qd(t,s.data),isFetchNextPageError:f,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:h,isRefetchError:l&&!f&&!m,isRefetching:o&&!d&&!h}}};function gi(e,t){const s=new Set(t);return e.filter(r=>!s.has(r))}function Px(e,t,s){const r=e.slice(0);return r[t]=s,r}var Lx=class extends Gd{#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,Br.batch(()=>{const s=this.#t,r=this.#f(this.#a);r.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=r.map(d=>d.observer),o=a.map(d=>d.getCurrentResult()),i=s.length!==a.length,l=a.some((d,m)=>d!==s[m]),u=i||l,f=u?!0:o.some((d,m)=>{const h=this.#e[m];return!h||!Xd(d,h)});!u&&!f||(u&&(this.#c=r,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(gi(s,a).forEach(d=>{d.destroy()}),gi(a,s).forEach(d=>{d.subscribe(m=>{this.#m(d,m)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const s=this.#f(e),r=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[r,o=>this.#d(o??r,t,a),()=>this.#u(r,s)]}#u(e,t){return t.map((s,r)=>{const a=e[r];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const r=this.#l,a=s!==void 0&&r!==void 0&&(r.length!==s.length||s.some((o,i)=>o!==r[i]));return(!this.#n||this.#e!==this.#i||a||t!==this.#o)&&(this.#o=t,this.#i=this.#e,s!==void 0&&(this.#l=s),this.#n=Jd(this.#n,t(e))),this.#n}return e}#p(){return this.#r?.combine!==void 0&&this.#t.some((e,t)=>e.options.suspense&&this.#e[t]?.data===void 0)}#f(e){const t=new Map;this.#t.forEach(r=>{const a=r.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(r):t.set(a,[r])});const s=[];return e.forEach(r=>{const a=this.#s.defaultQueryOptions(r),i=t.get(a.queryHash)?.shift()??new pa(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=Px(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,r=t?s:this.#d(e,this.#r?.combine);(t||s!==r)&&Br.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function Ft({queries:e,...t},s){const r=ye(),a=Zd(),o=ef(),i=c.useMemo(()=>e.map(p=>{const x=r.defaultQueryOptions(p);return x._optimisticResults=a?"isRestoring":"optimistic",x}),[e,r,a]);i.forEach(p=>{tf(p);const x=r.getQueryCache().get(p.queryHash);sf(p,o,x)}),nf(o);const[l]=c.useState(()=>new Lx(r,i,t)),[u,f,d]=l.getOptimisticResult(i,t.combine),m=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>m?l.subscribe(Br.batchCalls(p)):rf,[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const g=u.some((p,x)=>vo(i[x],p))?u.flatMap((p,x)=>{const b=i[x];if(b&&vo(b,p)){const w=new pa(r,b);return af(b,w,o)}return[]}):[];if(g.length>0)throw Promise.all(g);const v=u.find((p,x)=>{const b=i[x];return b&&of({result:p,errorResetBoundary:o,throwOnError:b.throwOnError,query:r.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(v?.error)throw v.error;return f(d())}function kc(e,t){return lf(e,Ox)}function $x(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const s=!!(e.condition??!0),r=e.blockerFn;return{shouldBlockFn:async()=>s&&r!==void 0?await r():s,enableBeforeUnload:s,withResolver:r===void 0}}function Fx(e,t){const{shouldBlockFn:s,enableBeforeUnload:r=!0,disabled:a=!1,withResolver:o=!1}=$x(e),i=ga(),{history:l}=i,[u,f]=c.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return c.useEffect(()=>{const d=async m=>{function h(b){const w=i.parseLocation(b),j=i.getMatchedRoutes(w.pathname);return j.foundRoute===void 0?{routeId:"__notFound__",fullPath:w.pathname,pathname:w.pathname,params:j.routeParams,search:i.options.parseSearch(b.search)}:{routeId:j.foundRoute.id,fullPath:j.foundRoute.fullPath,pathname:w.pathname,params:j.routeParams,search:i.options.parseSearch(b.search)}}const g=h(m.currentLocation),v=h(m.nextLocation);if(g.routeId==="__notFound__"&&v.routeId!=="__notFound__")return!1;const p=await s({action:m.action,current:g,next:v});if(!o)return p;if(!p)return!1;const x=await new Promise(b=>{f({status:"blocked",current:g,next:v,action:m.action,proceed:()=>b(!1),reset:()=>b(!0)})});return f({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),x};return a?void 0:l.block({blockerFn:d,enableBeforeUnload:r})},[s,r,a,o,l,i]),u}function gt(e){const t=ga({warn:e?.router===void 0}),s=e?.router||t;return Zi(s.stores.__store,el(e,s))}function tr(e){const t=ga();return Zi(t.stores.location,el(e,t))}const _x=new Set(["outbox","flagged"]),zx=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!_x.has(s)};function Bx(e){const t=Ft({queries:e.map(s=>({..._e({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,r]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Xs(r.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function Cc(e){const{openCompose:t}=Dt(),s=Oe(),r=tr(),a=Bx(e);return c.useCallback(()=>{if(zx(r.pathname)){c.startTransition(()=>{t({mode:"new"})});return}a&&(c.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,r.pathname,a])}const Kx=e=>e.startsWith("/mail")||e.startsWith("/settings"),Ux=({accounts:e})=>{const{state:t}=Dt(),s=tr(),r=Cc(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!Kx(s.pathname)||t.isOpen||o?null:n.jsx("button",{type:"button",onClick:r,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:n.jsx(Wm,{className:"size-6"})})},Nc=({trigger:e,children:t,align:s="right"})=>{const[r,a]=c.useState(!1),o=c.useRef(null),i=c.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),l=c.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return c.useEffect(()=>(r&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",l)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",l)}),[r,i,l]),n.jsxs("div",{ref:o,className:"relative",children:[n.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!r)},className:be("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),r&&n.jsx("div",{className:be("absolute z-50 mt-1 min-w-[180px] py-1","bg-surface border border-line rounded-md shadow-lg",s==="right"?"right-0":"left-0"),children:t})]})},hs=({onClick:e,disabled:t,destructive:s,children:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:be("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:r}),Xr=()=>n.jsx("div",{className:"my-1 h-px bg-line"}),Ec=({children:e})=>{const{Account:t}=xa();return n.jsx(t,{children:e})},qx=({email:e,onSignOut:t})=>{const s=Oe(),r=e??"Account";return n.jsxs(Nc,{trigger:n.jsx(dt,{name:r,email:e??void 0,size:"sm"}),align:"right",children:[e&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),n.jsx(Xr,{})]}),n.jsxs(hs,{onClick:()=>s({to:"/settings/accounts"}),children:[n.jsx(Oa,{className:"size-4"}),"Settings"]}),n.jsx(Xr,{}),n.jsxs(hs,{onClick:t,children:[n.jsx(Kl,{className:"size-4"}),"Sign out"]})]})},Hx=()=>n.jsx(Ec,{children:({email:e,signOut:t})=>n.jsx(qx,{email:e,onSignOut:t})}),xi=()=>{const e=ba(),t=va(e);window.open(t,"_blank","noopener,noreferrer")};function Ic({variant:e="icon"}){return e==="drawer"?n.jsxs("button",{type:"button",onClick:xi,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(Mo,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]}):n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Mo,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:xi})}const Tc="/mail/",Ba="/mail/$mailboxId",Rc="/mail/outbox",Mc="/mail/flagged";function Ka(e){return e.some(t=>t.routeId===Tc)}function nn(e){return e.some(t=>t.routeId===Mc)}function sr(e){return e.some(t=>t.routeId===Rc)}function Ac(e){return e.some(t=>t.routeId===Ba)}function Wx(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Ba}:${t}`:nn(e)?Mc:sr(e)?Rc:Ka(e)?Tc:""}const Dn="search-scope";function Vx(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function Dc(e){return nn(e)||sr(e)||Ac(e)}function Oc(e){return e.find(t=>t.routeId===Ba)?.params?.mailboxId}function Qx(e){const t=Oc(e.matches);return t||(Dc(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function Yx(e,t){return Ka(e)?{kind:"global"}:nn(e)?{kind:"scoped",chip:{id:Dn,label:"is:starred"}}:sr(e)?{kind:"scoped",chip:{id:Dn,label:"in:outbox"}}:Ac(e)?t?{kind:"scoped",chip:{id:Dn,label:Vx(t)}}:{kind:"pending"}:{kind:"global"}}function Gx(e,t,s){return t.kind==="global"?{kind:"global"}:nn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const Pc=({accounts:e})=>{const t=ya({strict:!1}),s=tr(),r=t.mailboxId,{t:a}=Un("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=Ft({queries:e.map(l=>({..._e({path:{accountId:l.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!r)return null;for(let l=0;l<e.length;l++){const u=i[l]?.data?.items;if(!u)continue;const f=u.find(m=>m.mailboxId===r);if(!f)continue;const d=Xs(e[l].folderAppointments);return bs(f,d.get(r),o)}return null},Xx=({accounts:e})=>{const s=ya({strict:!1}).mailboxId,r=Ft({queries:e.map(a=>({..._e({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of r){const o=a.data?.items;if(!o)continue;const i=o.find(l=>l.mailboxId===s);if(i)return i.unseenCount}return null};function Lc(e){const t=Oe(),{searchInput:s}=Ce(),r=Pc({accounts:e}),a=gt({select:l=>l.matches}),o=Yx(a,r),i=c.useCallback(l=>{l===Dn&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const $c=[{title:"Navigation",hints:[{action:"focusNext",keys:["j"],description:"Focus next message"},{action:"focusPrevious",keys:["k"],description:"Focus previous message"},{action:"focusNext",keys:["↓"],description:"Focus next message"},{action:"focusPrevious",keys:["↑"],description:"Focus previous message"},{action:"focusFirst",keys:["Home"],description:"Focus first"},{action:"focusLast",keys:["End"],description:"Focus last"},{action:"openFocused",keys:["Enter"],description:"Open focused thread"},{action:"back",keys:["Esc"],description:"Back / close overlay"}]},{title:"Selection",hints:[{action:"toggleSelect",keys:["x"],description:"Toggle select"},{action:"toggleSelect",keys:["Space"],description:"Toggle select"},{action:"extendSelectDown",keys:["Shift","j"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","k"],description:"Extend selection up"},{action:"extendSelectDown",keys:["Shift","↓"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","↑"],description:"Extend selection up"},{action:"selectAll",keys:["⌘","A"],description:"Select all"}]},{title:"Actions",hints:[{action:"reply",keys:["r"],description:"Reply"},{action:"replyAll",keys:["a"],description:"Reply all"},{action:"forward",keys:["f"],description:"Forward"},{action:"delete",keys:["#"],description:"Delete"},{action:"toggleStar",keys:["s"],description:"Star / unstar"},{action:"toggleRead",keys:["u"],description:"Toggle read / unread"}]},{title:"Sender",hints:[{action:"muteSender",keys:["m"],description:"Mute sender"},{action:"blockSender",keys:["b"],description:"Block sender"},{action:"vipSender",keys:["v"],description:"VIP sender"},{action:"markJunk",keys:["!"],description:"Mark junk"}]},{title:"Go to",hints:[{action:"goBrief",keys:["g","b"],description:"Daily brief"},{action:"goInbox",keys:["g","i"],description:"Inbox"},{action:"goSent",keys:["g","s"],description:"Sent"},{action:"goFlagged",keys:["g","f"],description:"Starred"},{action:"goSettings",keys:["g",","],description:"Settings"}]},{title:"View & global",hints:[{action:"toggleIntelligence",keys:["i"],description:"Toggle intelligence"},{action:"toggleDensity",keys:["d"],description:"Toggle density"},{action:"focusSearch",keys:["/"],description:"Focus search"},{action:"compose",keys:["c"],description:"Compose"},{action:"compose",keys:["⌘","N"],description:"Compose"},{action:"help",keys:["?"],description:"Shortcut help"}]}];function Jx(e){for(const t of $c){const s=t.hints.find(r=>r.action===e);if(s)return s.keys}}function fs(e){const t=Jx(e);return!t||t.length===0?"":t.length===1?`(${t[0]})`:t[0]==="g"?`(${t.join(" then ")})`:`(${t.join("")})`}const Zx={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function eb({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:r,onSearchClearQuery:a}=Ce(),o=Cc(e),{scope:i,clearScope:l}=Lc(e),u=i.kind==="scoped"?[{id:i.chip.id,label:i.chip.label,tone:"scope"}]:void 0,f=Zx[i.kind];return n.jsx(rp,{search:n.jsx(La,{value:t,onChange:s,onClear:r,onClearQuery:a,chips:u,onRemoveChip:l,placeholder:f,size:"lg"}),actions:n.jsxs(n.Fragment,{children:[n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ym,{className:"size-4"}),title:`Compose ${fs("compose")}`,"aria-label":"Compose",onClick:o}),n.jsx(Ic,{}),n.jsx(Hx,{})]})})}const Ua=({isOpen:e,onClose:t,children:s,ariaLabel:r="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=c.useRef(null),l=c.useRef(null);if(c.useEffect(()=>{if(!e)return;l.current=document.activeElement;const f=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",f),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const m=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",f),document.body.style.overflow=m,l.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return n.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":r,children:[n.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),n.jsxs("div",{ref:i,className:be("absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[n.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:n.jsx(We,{className:"size-5"})})}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},tb=e=>{const t=e.filter(a=>!a.isMultipart&&a.disposition!=="attachment"&&a.mediaType==="TEXT"&&a.contentUrl.length>0),s=t.find(a=>a.mediaSubtype.toUpperCase()==="HTML");if(s)return{kind:"html",contentUrl:s.contentUrl};const r=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return r?{kind:"text",contentUrl:r.contentUrl}:null},Jr={all:["messages"],detail:e=>[...Jr.all,"detail",e],body:e=>[...Jr.detail(e),"body"]};class Ht extends Error{reason;status;retryAfterSeconds;constructor(t,s,r,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=r,this.retryAfterSeconds=a}}const sb=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},nb=8,rb="x-remit-403-reason",ab=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},ob=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,ib=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},lb=async(e,t,s=async()=>null)=>{const r={},a=await s();a&&(r.Authorization=`Bearer ${a}`);const o=await cf(e,{headers:r});if(o.status===202)throw new Ht("not-ready","Message body is still syncing",202,sb(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(rb),f=ab(o.status,u);throw new Ht(f,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(ib(t,i))throw new Ht("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(ob(l,i))throw new Ht("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},cb=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),Fc=({messageId:e,bodyParts:t,enabled:s=!0})=>{const r=t?tb(t):null,a=Js(),{getToken:o}=xa(),i=c.useRef(null),l=ye(),u=c.useRef(!1),f=c.useRef(null),d=e&&r?`${e}:${r.contentUrl}`:null;f.current!==d&&(f.current=d,u.current=!1);const m=de({queryKey:e?[...Jr.body(e),r?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!r)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const v=u.current;return u.current=!1,cb({fetchContent:(p,x)=>lb(p,x,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:tl({path:{messageId:e}})})},{contentUrl:r.contentUrl,kind:r.kind,isRetryAfterNotReady:v})},enabled:s&&!!e&&!!r,staleTime:300*1e3,gcTime:1800*1e3,retry:(v,p)=>p instanceof Ht&&p.reason==="not-ready"?v<nb:v<1,retryDelay:(v,p)=>p instanceof Ht&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=m.isLoading&&!!r;c.useEffect(()=>{h&&(i.current=performance.now())},[h]),c.useEffect(()=>{m.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[m.isSuccess,a]);const g=m.data&&r?{kind:r.kind,body:m.data}:void 0;return{picked:r,data:g,isLoading:h,isError:m.isError,error:m.error,refetch:m.refetch}},ub=({outboxMessageId:e,onDraftCreated:t})=>{const[s,r]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=ye(),u=ve(sl()),f=ve(uf()),d=c.useCallback(async v=>{if(r("saving"),o(null),e){const x=await f.mutateAsync({path:{outboxMessageId:e},body:{toAddresses:v.toAddresses,ccAddresses:v.ccAddresses,bccAddresses:v.bccAddresses,subject:v.subject,textBody:v.textBody,htmlBody:v.htmlBody,inReplyTo:v.inReplyTo,references:v.references}});return r("saved"),x}const p=await u.mutateAsync({body:{...v,sendImmediately:!1}});return t(p.outboxMessageId),r("saved"),l.invalidateQueries({queryKey:qn().queryKey}),p},[e,u,f,t,l]),m=c.useCallback(v=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{d(v).catch(p=>{o(p),r("error")})},2e3)},[d]),h=c.useCallback(v=>(i.current&&clearTimeout(i.current),d(v)),[d]),g=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:m,saveImmediately:h,cancelAutoSave:g}},_c=e=>"text"in e&&!("children"in e),zc=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),db=e=>{let t=zc(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},Bc=e=>{const t=e.children.map(s=>_c(s)?db(s):Bc(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${zc(s)}">${t}</a>`}default:return`<p>${t}</p>`}},bi=e=>e.map(Bc).join(""),Kc=e=>_c(e)?e.text:e.children.map(Kc).join(""),Zr=e=>e.map(Kc).join(`
116
+ `),fb=e=>e.displayName?`${e.displayName} <${e.normalizedEmail}>`:e.normalizedEmail,vi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),mb=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const r=s[1].trim(),a=s[2].trim();if(vi(a))return{email:a,displayName:r}}if(vi(t))return{email:t}},Dr=({label:e,addresses:t,onChange:s,placeholder:r})=>{const[a,o]=c.useState(""),[i,l]=c.useState(-1),[u,f]=c.useState(!1),d=c.useRef(null),m=c.useRef(null),h=hl(a,200),{data:g}=de({...nl({query:{q:h,limit:8}}),enabled:h.length>=2}),v=g?.items??[],p=new Set(t.map(k=>k.email.toLowerCase())),x=v.filter(k=>!p.has(k.normalizedEmail.toLowerCase()));c.useEffect(()=>{l(-1),f(x.length>0&&a.length>=2)},[x.length,a.length]);const b=c.useCallback(k=>{p.has(k.email.toLowerCase())||(s([...t,k]),o(""),f(!1))},[t,p,s]),w=c.useCallback(k=>{s(t.filter((C,M)=>M!==k))},[t,s]),j=c.useCallback(k=>{b({email:k.normalizedEmail,displayName:k.displayName}),d.current?.focus()},[b]),y=c.useCallback(()=>{const k=mb(a);k&&b(k)},[a,b]),I=c.useCallback(k=>{if(k.key==="Backspace"&&a===""&&t.length>0){w(t.length-1);return}if(k.key==="Enter"||k.key==="Tab"||k.key===","){if(i>=0&&x[i]){k.preventDefault(),j(x[i]);return}a.trim()&&(k.preventDefault(),y());return}if(k.key==="ArrowDown"&&u){k.preventDefault(),l(C=>C<x.length-1?C+1:0);return}if(k.key==="ArrowUp"&&u){k.preventDefault(),l(C=>C>0?C-1:x.length-1);return}k.key==="Escape"&&(f(!1),l(-1))},[a,t.length,i,x,u,w,j,y]),N=c.useCallback(()=>{setTimeout(()=>{y(),f(!1)},150)},[y]);return n.jsxs("div",{className:"relative",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),n.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>d.current?.focus(),onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&d.current?.focus()},children:[t.map((k,C)=>n.jsx(Zm,{email:k.email,displayName:k.displayName,onRemove:()=>w(C)},k.email)),n.jsx("input",{ref:d,id:`address-field-${e}`,type:"text",value:a,onChange:k=>o(k.target.value),onKeyDown:I,onBlur:N,placeholder:t.length===0?r:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5"})]})]}),u&&x.length>0&&n.jsx("ul",{ref:m,className:"absolute left-12 right-0 mt-1 bg-surface border border-line rounded-md shadow-lg z-50 max-h-[200px] overflow-auto",children:x.map((k,C)=>n.jsx("li",{className:be("px-3 py-2 text-sm cursor-pointer transition-colors",C===i&&"bg-accent-2-soft"),onMouseDown:M=>{M.preventDefault(),j(k)},onMouseEnter:()=>l(C),children:fb(k)},k.addressId))})]})},hb=({accountId:e})=>{const t=Oe();return n.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[n.jsx(fa,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),n.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",n.jsx($m,{className:"size-3","aria-hidden":"true"})]})]})]})},yi=150,pb=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>yi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,r=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>yi})};return r(),s.addEventListener("resize",r),()=>s.removeEventListener("resize",r)},[]),e},gb=({selectedAccountId:e,onSelect:t})=>{const{data:s}=de({...xt(),staleTime:1/0}),r=s?.accounts??[];if(c.useEffect(()=>{!e&&r.length===1&&r[0]&&t(r[0])},[e,r,t]),r.length<=1){const a=r[0];return a?n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=r.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:r.map(a=>n.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},xb=({value:e,onChange:t})=>n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),n.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),bb=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],vb=["href"],yb=e=>Gi.sanitize(e,{ALLOWED_TAGS:bb,ALLOWED_ATTR:vb}),wb=c.lazy(()=>ff(()=>import("./ComposeBody-CTtNTugV.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}))),jb=()=>n.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[n.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),n.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),Uc=[{type:"p",children:[{text:""}]}],Sb=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],kb=e=>e?[...Sb,{type:"p",children:[{text:e}]}]:Uc,Cb=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",Nb=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",Eb=(e,t,s)=>{const{envelope:r}=e,o=(r.replyTo.length>0?r.replyTo:r.from).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(f=>f.email.toLowerCase())),u=[...r.to,...r.cc].filter(f=>f.normalizedEmail.toLowerCase()!==i&&!l.has(f.normalizedEmail.toLowerCase())).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));return{to:o,cc:u}},Ib=e=>{const t=e.envelope.messageIdValue,r=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!r.includes(t)&&r.push(t),{inReplyTo:t,references:r}},Tb=(e,t,s,r,a)=>e.length===0&&t.length===0&&s.length===0&&r.trim()===""&&Zr(a).trim()==="",Rb=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:r,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:f,showBcc:d,setShowBcc:m,subject:h,setSubject:g})=>{const v=Ot(),{isKeyboardOpen:p}=pb();if(!v&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(w=>w.displayName??w.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.push(h),n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[n.jsx("span",{className:"truncate text-xs text-fg-muted",children:b.length>0?b.join(" · "):"…"}),n.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return n.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[n.jsx(gb,{selectedAccountId:e,onSelect:t}),n.jsx(Dr,{label:"To",addresses:s,onChange:r,placeholder:"Recipients"}),u?n.jsx(Dr,{label:"Cc",addresses:a,onChange:o}):n.jsxs("div",{className:"flex gap-2 pl-14",children:[n.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&n.jsx("div",{className:"pl-14",children:n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&n.jsx(Dr,{label:"Bcc",addresses:i,onChange:l}),n.jsx(xb,{value:h,onChange:g})]})},qa=({mode:e,account:t,sourceMessage:s,onClose:r,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Dt(),{pushError:u}=Ve(),{outboxMessageId:f}=o,[d,m]=c.useState([]),[h,g]=c.useState([]),[v,p]=c.useState([]),[x,b]=c.useState(""),[w,j]=c.useState(!1),[y,I]=c.useState(!1),[N,k]=c.useState(t?.accountId),[C,M]=c.useState(!1),P=c.useRef(f);c.useEffect(()=>{P.current!==f&&(P.current=f,f&&(m([]),g([]),p([]),b(""),j(!1),I(!1),E(Uc),M(!1)))},[f]);const{signature:D}=Uf(N),[O,E]=c.useState(()=>kb(D.plainText)),{data:S}=de({...df({path:{outboxMessageId:f??""}}),enabled:!!f&&!C});c.useEffect(()=>{!S||C||(m(S.toAddresses.map(J=>({email:J,displayName:void 0}))),S.ccAddresses&&S.ccAddresses.length>0&&(g(S.ccAddresses.map(J=>({email:J,displayName:void 0}))),j(!0)),S.bccAddresses&&S.bccAddresses.length>0&&(p(S.bccAddresses.map(J=>({email:J,displayName:void 0}))),I(!0)),S.subject&&b(S.subject),S.textBody&&E([{type:"p",children:[{text:S.textBody}]}]),k(S.accountId),M(!0))},[S,C]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:J,cc:ae}=Eb(s,e,t?.email);m(J),g(ae),ae.length>0&&j(!0),b(Cb(s.envelope.subject))}e==="forward"&&b(Nb(s.envelope.subject))}},[e,s,t?.email]);const A=e==="reply"||e==="reply_all"||e==="forward",{data:L}=Fc({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:A&&!!s}),T=L?.kind==="text"?L.body:"",F=L?.kind==="html"?yb(L.body):void 0,R=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:$,saveError:z,saveDraft:V,cancelAutoSave:ee}=ub({outboxMessageId:f,onDraftCreated:i});c.useEffect(()=>{z&&u({title:"Couldn't save draft",detail:st(z)??"Saving the draft failed.",error:z})},[z,u]);const X=ve(sl()),Q=ve(rl()),le=ve({...Hn(),onError:J=>{u(Vt("Couldn't discard draft","The draft wasn't discarded.",J))}}),{data:ue}=de({...xt(),staleTime:1/0}),te=ue?.accounts.find(J=>J.accountId===N),K=te?Bf(te):!1,U=X.isPending||Q.isPending,re=d.length>0&&!!N&&!K;c.useEffect(()=>{if(!N||f&&!C||Tb(d,h,v,x,O))return;const J=Zr(O),ae=bi(O);V({accountId:N,toAddresses:d.map(ce=>ce.email),ccAddresses:h.length>0?h.map(ce=>ce.email):void 0,bccAddresses:v.length>0?v.map(ce=>ce.email):void 0,subject:x||void 0,textBody:J||void 0,htmlBody:ae||void 0})},[N,f,C,d,h,v,x,O,V]);const Ie=c.useCallback(async()=>{if(!N||d.length===0)return;ee();const J=s&&(e==="reply"||e==="reply_all")?Ib(s):{};let ae=f,ce=!1;if(!ae){const Fe=Zr(O),pe=bi(O),ge=await X.mutateAsync({body:{accountId:N,toAddresses:d.map(Se=>Se.email),ccAddresses:h.length>0?h.map(Se=>Se.email):void 0,bccAddresses:v.length>0?v.map(Se=>Se.email):void 0,subject:x||void 0,textBody:Fe||void 0,htmlBody:pe||void 0,sendImmediately:!0,...J}}).catch(Se=>(u({title:"Couldn't send message",detail:st(Se)??"Saving the draft failed.",error:Se}),null));if(ge===null)return;ae=ge.outboxMessageId,ce=!0,i(ae)}await Q.mutateAsync({path:{outboxMessageId:ae}}).catch(Fe=>(u({title:"Couldn't send message",detail:st(Fe)??(ce?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:Fe}),null))!==null&&(l(ae),r())},[N,d,h,v,x,O,e,s,f,X,Q,ee,l,i,u,r]),je=c.useCallback(()=>{ee(),f&&le.mutate({path:{outboxMessageId:f}}),r()},[ee,f,le,r]),W=c.useCallback(J=>{k(J.accountId),a?.(J)},[a]);return n.jsx(lp,{banner:te&&K?n.jsx(hb,{accountId:te.accountId}):void 0,header:n.jsx(Rb,{selectedAccountId:N,onAccountChange:W,toAddresses:d,setToAddresses:m,ccAddresses:h,setCcAddresses:g,bccAddresses:v,setBccAddresses:p,showCc:w,setShowCc:j,showBcc:y,setShowBcc:I,subject:x,setSubject:b}),quoted:T||F?n.jsx(Rp,{text:T,html:F,senderName:R}):void 0,actionBar:n.jsx(ip,{onSend:Ie,onDiscard:je,sending:U,canSend:re,saveStatus:$,unavailableReason:K?"SMTP not configured":void 0,onUnavailable:J=>u({title:"Can't send yet",detail:J})}),children:n.jsx(c.Suspense,{fallback:n.jsx(jb,{}),children:n.jsx(wb,{value:O,onChange:E,onSubmit:Ie,autoFocus:e==="new"})})})},wi=({mode:e,account:t,sourceMessage:s,onClose:r})=>n.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:n.jsx(qa,{mode:e,account:t,sourceMessage:s,onClose:r})}),qc=({message:e,icon:t})=>n.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&n.jsx("div",{className:"mb-4 text-fg-muted",children:t}),n.jsx("p",{className:"text-fg-muted",children:e})]}),Ha=({enabled:e=!0,bindings:t,capture:s=!1})=>{const r=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const f=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(f&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",r,s),()=>window.removeEventListener("keydown",r,s)},[e,r,s])},Hc=e=>{const{data:t,isLoading:s}=de({...xt(),staleTime:1/0}),r=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=Ft({queries:r.map(l=>({..._e({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<r.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return r[l]}},[e,r,a]),isLoading:o}},Mb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),Ab=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Wc=(e,t)=>e===void 0?e:Mb(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:Ab(e)?{...e,items:t(e.items)}:e,vt=e=>{const t=[];for(const s of new Set(e))t.push(wa({path:{mailboxId:s}})),t.push(al({path:{mailboxId:s}}));return t.push(ol()),t},rn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),an=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,r])=>({queryKey:s,data:r})),on=(e,t,s)=>{const r=a=>Wc(a,s);for(const a of t)e.setQueriesData({queryKey:a},r)},ln=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},yt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Db=3e3,Ob=(e,t,s)=>{if(e.length===0)return()=>{};const r=setTimeout(()=>s(e),t);return()=>clearTimeout(r)},nr=(e,t,s)=>{const r=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(r.get(o)??s);return[...a]},$n=(e,t,s)=>e.map(r=>t.has(r.messageId)?{...r,isRead:s}:r),Pb=(e,t,s,r)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!r.has(a.messageId)).map(a=>a.messageId),Lb=({messages:e,expandedIds:t,threadId:s,mailboxId:r,accountId:a})=>{const o=ye(),{pushError:i}=Ve(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:f}=ve({...Wn(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),v=h.body.isRead??!0,p=Zt({path:{threadId:s}}),x=vt(nr(g,e,r));await Promise.all([o.cancelQueries({queryKey:p}),rn(o,x)]);const b=o.getQueriesData({queryKey:p}).filter(j=>j[1]!==void 0).map(([j,y])=>({queryKey:j,data:y})),w=an(o,x);return o.setQueriesData({queryKey:p},j=>j&&{...j,items:$n(j.items,g,v)}),on(o,x,j=>$n(j,g,v)),{threadMessagesPrefix:p,listPrefixes:x,previousThreadMessages:b,previousThreadsList:w}},onSuccess:(h,g)=>{const v=g.body.messageIds??[];for(const p of v)l.current.add(p),u.current.delete(p)},onError:(h,g,v)=>{const p=g.body.messageIds??[];for(const b of p)u.current.delete(b);if(v){for(const b of v.previousThreadMessages)o.setQueryData(b.queryKey,b.data);ln(o,v.previousThreadsList)}const x=g.body.isRead??!0;i({title:x?"Couldn't mark as read":"Couldn't mark as unread",detail:st(h),error:h})},onSettled:(h,g,v,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),yt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:Jt({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(v=>!l.current.has(v)&&!u.current.has(v));if(g.length!==0){for(const v of g)u.current.add(v);f({body:{messageIds:g,isRead:!0}})}},[f]),m=c.useMemo(()=>Pb(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Ob(m,Db,d),[m,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},rr=e=>{const{mailboxId:t,accountId:s,messages:r}=e,a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...Wn(),onError:(f,d)=>{const m=d.body.isRead??!0;o({title:m?"Couldn't mark as read":"Couldn't mark as unread",detail:st(f),error:f})},onSettled:(f,d,m)=>{yt(a,vt(nr(m.body.messageIds??[],r??[],t))),s&&a.invalidateQueries({queryKey:Jt({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,isRead:d}})},[i]),isPending:l}},$b=60,Fb=1.5,_b=(e,t,s)=>{const r=Math.abs(e),a=Math.abs(t);return r<s?{direction:null}:r<a*Fb?{direction:null}:{direction:e<0?"left":"right"}},zb=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=$b})=>{const r=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){r.current=null;return}r.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const f=r.current;if(r.current=null,!f)return;const{direction:d}=_b(u.clientX-f.x,u.clientY-f.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{r.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},Bb=(e,t,s)=>t?.find(r=>r.messageId===e)?.mailboxId??s,ji=(e,t,s)=>e.map(r=>r.messageId===t?{...r,hasStars:s}:r),Wa=({threadId:e,mailboxId:t,messages:s})=>{const r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i,variables:l}=ve({...mf(),onMutate:async f=>{const d=f.path.messageId,m=f.body.isStarred??!1,h=Zt({path:{threadId:e}}),g=vt([Bb(d,s,t)]);await Promise.all([r.cancelQueries({queryKey:h}),rn(r,g)]);const v=r.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})),p=an(r,g);return r.setQueriesData({queryKey:h},x=>Wc(x,b=>ji(b,d,m))),on(r,g,x=>ji(x,d,m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)r.setQueryData(g.queryKey,g.data);ln(r,m.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:st(f),error:f})},onSettled:(f,d,m,h)=>{h&&(r.invalidateQueries({queryKey:h.threadMessagesPrefix}),yt(r,h.listPrefixes))}});return{toggleStar:(f,d)=>{o({path:{messageId:f},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function cn(e){return e===void 0?"uncategorized":e}const Kb={inbox:"Inbox",junk:"Junk"},Va=e=>e.destinationMailboxId!==void 0,Ub=(e,t)=>{if(Va(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${Kb[s]??"another folder"} by Remit`},qb=(e,t)=>{if(e===jo.MoveToInbox)return t.inboxMailboxId;if(e===jo.MoveToJunk)return t.junkMailboxId},Hb=(e,t,s)=>{if(!e||!t)return!1;const r=Va(e)?e.destinationMailboxId:qb(e.action,s);return r!==void 0&&r===t},Wb=(e,t)=>{if(e){if(Va(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},ar=(e,t)=>{const{data:s,isLoading:r}=de({...xt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:r}},Vb=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Qb=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},Qa=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},or=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Junk");return{junkMailboxId:t,isLoading:s}},Vc=e=>{const{data:t}=de({...xt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Si=(e,t)=>e.filter(s=>!t.has(s.messageId)),Qt=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...hf(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),m=t?Zt({path:{threadId:t}}):[],h=vt([e,f.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:m})]:[],rn(a,h)]);const g=t?a.getQueriesData({queryKey:m}).filter(p=>p[1]!==void 0).map(([p,x])=>({queryKey:p,data:x})):[],v=an(a,h);return t&&a.setQueriesData({queryKey:m},p=>p&&{...p,items:Si(p.items,d)}),on(a,h,p=>Si(p,d)),r?.(Array.from(d)),{threadMessagesPrefix:m,listPrefixes:h,previousThreadMessages:g,previousThreadsList:v}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)a.setQueryData(g.queryKey,g.data);ln(a,m.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:st(f),error:f})},onSettled:(f,d,m,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),yt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:Jt({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,destinationMailboxId:d}})},[i]),isPending:l}},Yb=({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a})=>{const{inboxMailboxId:o}=Qa(e),{junkMailboxId:i}=or(e),{moveMessages:l,isPending:u}=Qt({mailboxId:r,threadId:s,accountId:e}),{data:f}=de({..._e({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},m=Hb(a,r,d),h=Wb(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!m||!a)return{show:!1,label:"",isUndoing:!1};const v=a.fromMailboxId?f?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>Vn(p.fullPath))[0]:void 0;return{show:!0,label:Ub(a,v),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function Qc({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a,size:o="sm"}){const i=Yb({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a});return i.show?n.jsx(ap,{label:i.label,size:o,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:o==="md"?i.filtersHref:void 0}):null}const ki=(e,t)=>e.filter(s=>!t.has(s.messageId)),Gb=e=>e.filter(t=>t.isDeleted!==!0),Yt=({mailboxId:e,threadId:t,accountId:s,messages:r,onAfterOptimisticRemove:a})=>{const o=ye(),{pushError:i}=Ve(),{mutate:l,isPending:u}=ve({...pf(),onMutate:async d=>{const m=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],g=vt(nr(m,r??[],e));await Promise.all([o.cancelQueries({queryKey:h}),rn(o,g)]);const v=t?o.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})):[],p=an(o,g);return t&&o.setQueriesData({queryKey:h},x=>x&&{...x,items:ki(x.items,m)}),on(o,g,x=>ki(x,m)),a?.(Array.from(m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(d,m,h)=>{if(h){for(const v of h.previousThreadMessages)o.setQueryData(v.queryKey,v.data);ln(o,h.previousThreadsList)}const g=m.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:st(d),error:d})},onSettled:(d,m,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),yt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:Jt({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&l({body:{messageIds:d}})},[l]),isPending:u}},Yc=(e,t=Date.now())=>({value:e,setAt:t}),Xb=(e,t,s,r)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Yc(!0,r):delete a.trusted,{...e,flags:a}},Jb=(e,t,s,r)=>{const a=o=>o.map(i=>Xb(i,t,s,r));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},Ya=({messageId:e})=>{const t=ye(),{pushError:s}=Ve(),{mutate:r,isPending:a,error:o,reset:i}=ve({...il(),onMutate:async u=>{const f=u.path.addressId,m=u.body.flags?.trusted?.value===!0,h=tl({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,p])=>({queryKey:v,data:p}));return t.setQueriesData({queryKey:h},v=>v&&Jb(v,f,m)),{describePrefix:h,previous:g}},onError:(u,f,d)=>{if(d)for(const m of d.previous)t.setQueryData(m.queryKey,m.data);s(Vt("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,f,d,m)=>{m&&t.invalidateQueries({queryKey:m.describePrefix})}});return{toggleTrusted:(u,f)=>{r({path:{addressId:u},body:{flags:{trusted:Yc(!f)}}})},isPending:a,error:o,reset:i}};var ir="Dialog",[Gc]=lg(ir),[Zb,at]=Gc(ir),Xc=e=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[f,d]=dg({prop:r,defaultProp:a??!1,onChange:o,caller:ir});return n.jsx(Zb,{scope:t,triggerRef:l,contentRef:u,contentId:Ir(),titleId:Ir(),descriptionId:Ir(),open:f,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),modal:i,children:s})};Xc.displayName=ir;var Jc="DialogTrigger",ev=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(Jc,s),o=es(t,a.triggerRef);return n.jsx(bt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Xa(a.open),...r,ref:o,onClick:Tt(e.onClick,a.onOpenToggle)})});ev.displayName=Jc;var Ga="DialogPortal",[tv,Zc]=Gc(Ga,{forceMount:void 0}),eu=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,o=at(Ga,t);return n.jsx(tv,{scope:t,forceMount:s,children:c.Children.map(r,i=>n.jsx(Zn,{present:s||o.open,children:n.jsx(pc,{asChild:!0,container:a,children:i})}))})};eu.displayName=Ga;var Fn="DialogOverlay",tu=c.forwardRef((e,t)=>{const s=Zc(Fn,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=at(Fn,e.__scopeDialog);return o.modal?n.jsx(Zn,{present:r||o.open,children:n.jsx(nv,{...a,ref:t})}):null});tu.displayName=Fn;var sv=_a("DialogOverlay.RemoveScroll"),nv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(Fn,s),o=Rg(),i=es(t,o);return n.jsx(Sc,{as:sv,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(bt.div,{"data-state":Xa(a.open),...r,ref:i,style:{pointerEvents:"auto",...r.style}})})}),js="DialogContent",su=c.forwardRef((e,t)=>{const s=Zc(js,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=at(js,e.__scopeDialog);return n.jsx(Zn,{present:r||o.open,children:o.modal?n.jsx(rv,{...a,ref:t}):n.jsx(av,{...a,ref:t})})});su.displayName=js;var rv=c.forwardRef((e,t)=>{const s=at(js,e.__scopeDialog),r=c.useRef(null),a=es(t,s.contentRef,r);return c.useEffect(()=>{const o=r.current;if(o)return Jg(o)},[]),n.jsx(nu,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Tt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Tt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Tt(e.onFocusOutside,o=>o.preventDefault())})}),av=c.forwardRef((e,t)=>{const s=at(js,e.__scopeDialog),r=c.useRef(!1),a=c.useRef(!1);return n.jsx(nu,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||s.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),nu=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=at(js,s);return Og(),n.jsx(n.Fragment,{children:n.jsx(mc,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:o,children:n.jsx(dc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Xa(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),ru="DialogTitle",au=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(ru,s);return n.jsx(bt.h2,{id:a.titleId,...r,ref:t})});au.displayName=ru;var ou="DialogDescription",ov=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(ou,s);return n.jsx(bt.p,{id:a.descriptionId,...r,ref:t})});ov.displayName=ou;var iu="DialogClose",iv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(iu,s);return n.jsx(bt.button,{type:"button",...r,ref:t,onClick:Tt(e.onClick,()=>a.onOpenChange(!1))})});iv.displayName=iu;function Xa(e){return e?"open":"closed"}function lv(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 lu=q.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}),un=()=>{const e=q.useContext(lu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};lv(`[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
- ){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 lv(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function cv(){return Ja(/^Mac/)}function uv(){return Ja(/^iPhone/)}function Ci(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function dv(){return Ja(/^iPad/)||cv()&&navigator.maxTouchPoints>1}function lu(){return uv()||dv()}function Ja(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const fv=24,mv=typeof window<"u"?c.useLayoutEffect:c.useEffect;function Ni(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const Or=typeof document<"u"&&window.visualViewport;function Ei(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function cu(e){for(Ei(e)&&(e=e.parentElement);e&&!Ei(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const hv=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Nn=0,Pr;function pv(e={}){let{isDisabled:t}=e;mv(()=>{if(!t)return Nn++,Nn===1&&lu()&&(Pr=gv()),()=>{Nn--,Nn===0&&Pr?.()}},[t])}function gv(){let e,t=0,s=m=>{e=cu(m.target),!(e===document.documentElement&&e===document.body)&&(t=m.changedTouches[0].pageY)},r=m=>{if(!e||e===document.documentElement||e===document.body){m.preventDefault();return}let h=m.changedTouches[0].pageY,g=e.scrollTop,v=e.scrollHeight-e.clientHeight;v!==0&&((g<=0&&h>t||g>=v&&h<t)&&m.preventDefault(),t=h)},a=m=>{let h=m.target;ea(h)&&h!==document.activeElement&&(m.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=m=>{let h=m.target;ea(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",Or&&(Or.height<window.innerHeight?requestAnimationFrame(()=>{Ii(h)}):Or.addEventListener("resize",()=>Ii(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,f=Ni(xv(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=Ni(Ps(document,"touchstart",s,{passive:!1,capture:!0}),Ps(document,"touchmove",r,{passive:!1,capture:!0}),Ps(document,"touchend",a,{passive:!1,capture:!0}),Ps(document,"focus",o,!0),Ps(window,"scroll",i));return()=>{f(),d(),window.scrollTo(l,u)}}function xv(e,t,s){let r=e.style[t];return e.style[t]=s,()=>{e.style[t]=r}}function Ps(e,t,s,r){return e.addEventListener(t,s,r),()=>{e.removeEventListener(t,s,r)}}function Ii(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=cu(e);if(s!==document.documentElement&&s!==document.body&&s!==e){let r=s.getBoundingClientRect().top,a=e.getBoundingClientRect().top,o=e.getBoundingClientRect().bottom;const i=s.getBoundingClientRect().bottom+fv;o>i&&(s.scrollTop+=a-r)}e=s.parentElement}}function ea(e){return e instanceof HTMLInputElement&&!hv.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function bv(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function vv(...e){return t=>e.forEach(s=>bv(s,t))}function uu(...e){return c.useCallback(vv(...e),e)}const du=new WeakMap;function Ee(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let r={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}r[a]=e.style[a],e.style[a]=o}),!s&&du.set(e,r)}function yv(e,t){if(!e||!(e instanceof HTMLElement))return;let s=du.get(e);s&&(e.style[t]=s[t])}const ke=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function En(e,t){if(!e)return null;const s=window.getComputedStyle(e),r=s.transform||s.webkitTransform||s.mozTransform;let a=r.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[ke(t)?13:12]):(a=r.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[ke(t)?5:4]):null)}function wv(e){return 8*(Math.log(e+1)-2)}function Lr(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function jv(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const xe={DURATION:.5,EASE:[.32,.72,0,1]},fu=.4,Sv=.25,kv=100,mu=8,qt=16,ta=26,$r="vaul-dragging";function hu(e){const t=q.useRef(e);return q.useEffect(()=>{t.current=e}),q.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function Cv({defaultProp:e,onChange:t}){const s=q.useState(e),[r]=s,a=q.useRef(r),o=hu(t);return q.useEffect(()=>{a.current!==r&&(o(r),a.current=r)},[r,a,o]),s}function pu({prop:e,defaultProp:t,onChange:s=()=>{}}){const[r,a]=Cv({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:r,l=hu(s),u=q.useCallback(f=>{if(o){const m=typeof f=="function"?f(e):f;m!==e&&l(m)}else a(f)},[o,e,a,l]);return[i,u]}function Nv({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:r,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:f}){const[d,m]=pu({prop:e,defaultProp:s?.[0],onChange:t}),[h,g]=q.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);q.useEffect(()=>{function k(){g({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]);const v=q.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=q.useMemo(()=>{var k;return(k=s?.findIndex(C=>C===d))!=null?k:null},[s,d]),x=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,b=q.useMemo(()=>{const k=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var C;return(C=s?.map(M=>{const P=typeof M=="string";let D=0;if(P&&(D=parseInt(M,10)),ke(l)){const E=P?D:h?M*k.height:0;return h?l==="bottom"?k.height-E:-k.height+E:E}const O=P?D:h?M*k.width:0;return h?l==="right"?k.width-O:-k.width+O:O}))!=null?C:[]},[s,h,u]),w=q.useMemo(()=>p!==null?b?.[p]:null,[b,p]),j=q.useCallback(k=>{var C;const M=(C=b?.findIndex(P=>P===k))!=null?C:null;i(M),Ee(r.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(l)?`translate3d(0, ${k}px, 0)`:`translate3d(${k}px, 0, 0)`}),b&&M!==b.length-1&&o!==void 0&&M!==o&&M<o?Ee(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"0"}):Ee(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"1"}),m(s?.[Math.max(M,0)])},[r.current,s,b,o,a,m]);q.useEffect(()=>{if(d||e){var k;const C=(k=s?.findIndex(M=>M===e||M===d))!=null?k:-1;b&&C!==-1&&typeof b[C]=="number"&&j(b[C])}},[d,e,s,b,j]);function y({draggedDistance:k,closeDrawer:C,velocity:M,dismissible:P}){if(o===void 0)return;const D=l==="bottom"||l==="right"?(w??0)-k:(w??0)+k,O=p===o-1,E=p===0,S=k>0;if(O&&Ee(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`}),!f&&M>2&&!S){P?C():j(b[0]);return}if(!f&&M>2&&S&&b&&s){j(b[s.length-1]);return}const A=b?.reduce((T,F)=>typeof T!="number"||typeof F!="number"?T:Math.abs(F-D)<Math.abs(T-D)?F:T),L=ke(l)?window.innerHeight:window.innerWidth;if(M>fu&&Math.abs(k)<L*.4){const T=S?1:-1;if(T>0&&v&&s){j(b[s.length-1]);return}if(E&&T<0&&P&&C(),p===null)return;j(b[p+T]);return}j(A)}function I({draggedDistance:k}){if(w===null)return;const C=l==="bottom"||l==="right"?w-k:w+k;(l==="bottom"||l==="right")&&C<b[b.length-1]||(l==="top"||l==="left")&&C>b[b.length-1]||Ee(r.current,{transform:ke(l)?`translate3d(0, ${C}px, 0)`:`translate3d(${C}px, 0, 0)`})}function N(k,C){if(!s||typeof p!="number"||!b||o===void 0)return null;const M=p===o-1;if(p>=o&&C)return 0;if(M&&!C)return 1;if(!x&&!M)return null;const D=M?p+1:p-1,O=M?b[D]-b[D-1]:b[D+1]-b[D],E=k/Math.abs(O);return M?1-E:E}return{isLastSnapPoint:v,activeSnapPoint:d,shouldFade:x,getPercentageDragged:N,setActiveSnapPoint:m,activeSnapPointIndex:p,onRelease:y,onDrag:I,snapPointsOffset:b}}const Ev=()=>()=>{};function Iv(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:r,noBodyStyles:a}=un(),o=q.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-ta)/window.innerWidth}q.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;jv(r&&!a?Lr(document.body,{background:"black"}):Ev,Lr(u,{transformOrigin:ke(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${xe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${xe.EASE.join(",")})`}));const f=Lr(u,{borderRadius:`${mu}px`,overflow:"hidden",...ke(e)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{f(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},xe.DURATION*1e3)}}},[t,s,i])}let Ls=null;function Tv({isOpen:e,modal:t,nested:s,hasBeenOpened:r,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=q.useState(()=>typeof window<"u"?window.location.href:""),u=q.useRef(0),f=q.useCallback(()=>{if(Ci()&&Ls===null&&e&&!o){Ls={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:m,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-m}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const g=h-window.innerHeight;g&&u.current>=h&&(document.body.style.top=`${-(u.current+g)}px`)}),300)}},[e]),d=q.useCallback(()=>{if(Ci()&&Ls!==null&&!o){const m=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Ls),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,m)}),Ls=null}},[i]);return q.useEffect(()=>{function m(){u.current=window.scrollY}return m(),window.addEventListener("scroll",m),()=>{window.removeEventListener("scroll",m)}},[]),q.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),q.useEffect(()=>{s||!r||(e?(!window.matchMedia("(display-mode: standalone)").matches&&f(),t||window.setTimeout(()=>{d()},500)):d())},[e,r,i,t,s,f,d]),{restorePositionSetting:d}}function Rv({open:e,onOpenChange:t,children:s,onDrag:r,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=Sv,scrollLockTimeout:f=kv,dismissible:d=!0,handleOnly:m=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:g,setActiveSnapPoint:v,fixed:p,modal:x=!0,onClose:b,nested:w,noBodyStyles:j=!1,direction:y="bottom",defaultOpen:I=!1,disablePreventScroll:N=!0,snapToSequentialPoint:k=!1,preventScrollRestoration:C=!1,repositionInputs:M=!0,onAnimationEnd:P,container:D,autoFocus:O=!1}){var E,S;const[A=!1,L]=pu({defaultProp:I,prop:e,onChange:Z=>{t?.(Z),!Z&&!w&&Be(),setTimeout(()=>{P?.(Z)},xe.DURATION*1e3),Z&&!x&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),Z||(document.body.style.pointerEvents="auto")}}),[T,F]=q.useState(!1),[R,$]=q.useState(!1),[z,V]=q.useState(!1),ee=q.useRef(null),X=q.useRef(null),Q=q.useRef(null),le=q.useRef(null),ue=q.useRef(null),te=q.useRef(!1),K=q.useRef(null),U=q.useRef(0),re=q.useRef(!1),Ie=q.useRef(!I),je=q.useRef(0),W=q.useRef(null),J=q.useRef(((E=W.current)==null?void 0:E.getBoundingClientRect().height)||0),ae=q.useRef(((S=W.current)==null?void 0:S.getBoundingClientRect().width)||0),ce=q.useRef(0),B=q.useCallback(Z=>{o&&Z===Qe.length-1&&(X.current=new Date)},[]),{activeSnapPoint:Fe,activeSnapPointIndex:pe,setActiveSnapPoint:ge,onRelease:Se,snapPointsOffset:Qe,onDrag:ts,shouldFade:ze,getPercentageDragged:Ze}=Nv({snapPoints:o,activeSnapPointProp:g,setActiveSnapPointProp:v,drawerRef:W,fadeFromIndex:h,overlayRef:ee,onSnapPointChange:B,direction:y,container:D,snapToSequentialPoint:k});pv({isDisabled:!A||R||!x||z||!T||!M||!N});const{restorePositionSetting:Be}=Tv({isOpen:A,modal:x,nested:w??!1,hasBeenOpened:T,preventScrollRestoration:C,noBodyStyles:j});function Ke(){return(window.innerWidth-ta)/window.innerWidth}function ft(Z){var ie,ne;!d&&!o||W.current&&!W.current.contains(Z.target)||(J.current=((ie=W.current)==null?void 0:ie.getBoundingClientRect().height)||0,ae.current=((ne=W.current)==null?void 0:ne.getBoundingClientRect().width)||0,$(!0),Q.current=new Date,lu()&&window.addEventListener("touchend",()=>te.current=!1,{once:!0}),Z.target.setPointerCapture(Z.pointerId),U.current=ke(y)?Z.pageY:Z.pageX)}function Te(Z,ie){var ne;let oe=Z;const he=(ne=window.getSelection())==null?void 0:ne.toString(),me=W.current?En(W.current,y):null,we=new Date;if(oe.tagName==="SELECT"||oe.hasAttribute("data-vaul-no-drag")||oe.closest("[data-vaul-no-drag]"))return!1;if(y==="right"||y==="left")return!0;if(X.current&&we.getTime()-X.current.getTime()<500)return!1;if(me!==null&&(y==="bottom"?me>0:me<0))return!0;if(he&&he.length>0)return!1;if(ue.current&&we.getTime()-ue.current.getTime()<f&&me===0||ie)return ue.current=we,!1;for(;oe;){if(oe.scrollHeight>oe.clientHeight){if(oe.scrollTop!==0)return ue.current=new Date,!1;if(oe.getAttribute("role")==="dialog")return!0}oe=oe.parentNode}return!0}function ss(Z){if(W.current&&R){const ie=y==="bottom"||y==="right"?1:-1,ne=(U.current-(ke(y)?Z.pageY:Z.pageX))*ie,oe=ne>0,he=o&&!d&&!oe;if(he&&pe===0)return;const me=Math.abs(ne),we=document.querySelector("[data-vaul-drawer-wrapper]"),Pe=y==="bottom"||y==="top"?J.current:ae.current;let Ae=me/Pe;const He=Ze(me,oe);if(He!==null&&(Ae=He),he&&Ae>=1||!te.current&&!Te(Z.target,oe))return;if(W.current.classList.add($r),te.current=!0,Ee(W.current,{transition:"none"}),Ee(ee.current,{transition:"none"}),o&&ts({draggedDistance:ne}),oe&&!o){const Re=wv(ne),Ye=Math.min(Re*-1,0)*ie;Ee(W.current,{transform:ke(y)?`translate3d(0, ${Ye}px, 0)`:`translate3d(${Ye}px, 0, 0)`});return}const De=1-Ae;if((ze||h&&pe===h-1)&&(r?.(Z,Ae),Ee(ee.current,{opacity:`${De}`,transition:"none"},!0)),we&&ee.current&&i){const Re=Math.min(Ke()+Ae*(1-Ke()),1),Ye=8-Ae*8,Ge=Math.max(0,14-Ae*14);Ee(we,{borderRadius:`${Ye}px`,transform:ke(y)?`scale(${Re}) translate3d(0, ${Ge}px, 0)`:`scale(${Re}) translate3d(${Ge}px, 0, 0)`,transition:"none"},!0)}if(!o){const Re=me*ie;Ee(W.current,{transform:ke(y)?`translate3d(0, ${Re}px, 0)`:`translate3d(${Re}px, 0, 0)`})}}}q.useEffect(()=>{window.requestAnimationFrame(()=>{Ie.current=!0})},[]),q.useEffect(()=>{var Z;function ie(){if(!W.current||!M)return;const ne=document.activeElement;if(ea(ne)||re.current){var oe;const he=((oe=window.visualViewport)==null?void 0:oe.height)||0,me=window.innerHeight;let we=me-he;const Pe=W.current.getBoundingClientRect().height||0,Ae=Pe>me*.8;ce.current||(ce.current=Pe);const He=W.current.getBoundingClientRect().top;if(Math.abs(je.current-we)>60&&(re.current=!re.current),o&&o.length>0&&Qe&&pe){const De=Qe[pe]||0;we+=De}if(je.current=we,Pe>he||re.current){const De=W.current.getBoundingClientRect().height;let Re=De;De>he&&(Re=he-(Ae?He:ta)),p?W.current.style.height=`${De-Math.max(we,0)}px`:W.current.style.height=`${Math.max(Re,he-He)}px`}else lv()||(W.current.style.height=`${ce.current}px`);o&&o.length>0&&!re.current?W.current.style.bottom="0px":W.current.style.bottom=`${Math.max(we,0)}px`}}return(Z=window.visualViewport)==null||Z.addEventListener("resize",ie),()=>{var ne;return(ne=window.visualViewport)==null?void 0:ne.removeEventListener("resize",ie)}},[pe,o,Qe]);function Ue(Z){Ne(),b?.(),Z||L(!1),setTimeout(()=>{o&&ge(o[0])},xe.DURATION*1e3)}function _t(){if(!W.current)return;const Z=document.querySelector("[data-vaul-drawer-wrapper]"),ie=En(W.current,y);Ee(W.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`}),Ee(ee.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"1"}),i&&ie&&ie>0&&A&&Ee(Z,{borderRadius:`${mu}px`,overflow:"hidden",...ke(y)?{transform:`scale(${Ke()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${Ke()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${xe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${xe.EASE.join(",")})`},!0)}function Ne(){!R||!W.current||(W.current.classList.remove($r),te.current=!1,$(!1),le.current=new Date)}function qe(Z){if(!R||!W.current)return;W.current.classList.remove($r),te.current=!1,$(!1),le.current=new Date;const ie=En(W.current,y);if(!Z||!Te(Z.target,!1)||!ie||Number.isNaN(ie)||Q.current===null)return;const ne=le.current.getTime()-Q.current.getTime(),oe=U.current-(ke(y)?Z.pageY:Z.pageX),he=Math.abs(oe)/ne;if(he>.05&&(V(!0),setTimeout(()=>{V(!1)},200)),o){Se({draggedDistance:oe*(y==="bottom"||y==="right"?1:-1),closeDrawer:Ue,velocity:he,dismissible:d}),a?.(Z,!0);return}if(y==="bottom"||y==="right"?oe>0:oe<0){_t(),a?.(Z,!0);return}if(he>fu){Ue(),a?.(Z,!1);return}var me;const we=Math.min((me=W.current.getBoundingClientRect().height)!=null?me:0,window.innerHeight);var Pe;const Ae=Math.min((Pe=W.current.getBoundingClientRect().width)!=null?Pe:0,window.innerWidth),He=y==="left"||y==="right";if(Math.abs(ie)>=(He?Ae:we)*u){Ue(),a?.(Z,!1);return}a?.(Z,!0),_t()}q.useEffect(()=>(A&&(Ee(document.documentElement,{scrollBehavior:"auto"}),X.current=new Date),()=>{yv(document.documentElement,"scrollBehavior")}),[A]);function mt(Z){const ie=Z?(window.innerWidth-qt)/window.innerWidth:1,ne=Z?-qt:0;K.current&&window.clearTimeout(K.current),Ee(W.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(y)?`scale(${ie}) translate3d(0, ${ne}px, 0)`:`scale(${ie}) translate3d(${ne}px, 0, 0)`}),!Z&&W.current&&(K.current=setTimeout(()=>{const oe=En(W.current,y);Ee(W.current,{transition:"none",transform:ke(y)?`translate3d(0, ${oe}px, 0)`:`translate3d(${oe}px, 0, 0)`})},500))}function ns(Z,ie){if(ie<0)return;const ne=(window.innerWidth-qt)/window.innerWidth,oe=ne+ie*(1-ne),he=-qt+ie*qt;Ee(W.current,{transform:ke(y)?`scale(${oe}) translate3d(0, ${he}px, 0)`:`scale(${oe}) translate3d(${he}px, 0, 0)`,transition:"none"})}function zt(Z,ie){const ne=ke(y)?window.innerHeight:window.innerWidth,oe=ie?(ne-qt)/ne:1,he=ie?-qt:0;ie&&Ee(W.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(y)?`scale(${oe}) translate3d(0, ${he}px, 0)`:`scale(${oe}) translate3d(${he}px, 0, 0)`})}return q.useEffect(()=>{x||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[x]),q.createElement(Gc,{defaultOpen:I,onOpenChange:Z=>{!d&&!Z||(Z?F(!0):Ue(!0),L(Z))},open:A},q.createElement(iu.Provider,{value:{activeSnapPoint:Fe,snapPoints:o,setActiveSnapPoint:ge,drawerRef:W,overlayRef:ee,onOpenChange:t,onPress:ft,onRelease:qe,onDrag:ss,dismissible:d,shouldAnimate:Ie,handleOnly:m,isOpen:A,isDragging:R,shouldFade:ze,closeDrawer:Ue,onNestedDrag:ns,onNestedOpenChange:mt,onNestedRelease:zt,keyboardIsOpen:re,modal:x,snapPointsOffset:Qe,activeSnapPointIndex:pe,direction:y,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:j,container:D,autoFocus:O}},s))}const gu=q.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:r,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=un(),f=uu(t,s),d=r&&r.length>0;if(!l)return null;const m=q.useCallback(h=>a(h),[a]);return q.createElement(eu,{onMouseUp:m,ref:f,"data-vaul-overlay":"","data-vaul-snap-points":i&&d?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});gu.displayName="Drawer.Overlay";const xu=q.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...r},a){const{drawerRef:o,onPress:i,onRelease:l,onDrag:u,keyboardIsOpen:f,snapPointsOffset:d,activeSnapPointIndex:m,modal:h,isOpen:g,direction:v,snapPoints:p,container:x,handleOnly:b,shouldAnimate:w,autoFocus:j}=un(),[y,I]=q.useState(!1),N=uu(a,o),k=q.useRef(null),C=q.useRef(null),M=q.useRef(!1),P=p&&p.length>0;Iv();const D=(E,S,A=0)=>{if(M.current)return!0;const L=Math.abs(E.y),T=Math.abs(E.x),F=T>L,R=["bottom","right"].includes(S)?1:-1;if(S==="left"||S==="right"){if(!(E.x*R<0)&&T>=0&&T<=A)return F}else if(!(E.y*R<0)&&L>=0&&L<=A)return!F;return M.current=!0,!0};q.useEffect(()=>{P&&window.requestAnimationFrame(()=>{I(!0)})},[]);function O(E){k.current=null,M.current=!1,l(E)}return q.createElement(tu,{"data-vaul-drawer-direction":v,"data-vaul-drawer":"","data-vaul-delayed-snap-points":y?"true":"false","data-vaul-snap-points":g&&P?"true":"false","data-vaul-custom-container":x?"true":"false","data-vaul-animate":w?.current?"true":"false",...r,ref:N,style:d&&d.length>0?{"--snap-point-height":`${d[m??0]}px`,...t}:t,onPointerDown:E=>{b||(r.onPointerDown==null||r.onPointerDown.call(r,E),k.current={x:E.pageX,y:E.pageY},i(E))},onOpenAutoFocus:E=>{s?.(E),j||E.preventDefault()},onPointerDownOutside:E=>{if(e?.(E),!h||E.defaultPrevented){E.preventDefault();return}f.current&&(f.current=!1)},onFocusOutside:E=>{if(!h){E.preventDefault();return}},onPointerMove:E=>{if(C.current=E,b||(r.onPointerMove==null||r.onPointerMove.call(r,E),!k.current))return;const S=E.pageY-k.current.y,A=E.pageX-k.current.x,L=E.pointerType==="touch"?10:2;D({x:A,y:S},v,L)?u(E):(Math.abs(A)>L||Math.abs(S)>L)&&(k.current=null)},onPointerUp:E=>{r.onPointerUp==null||r.onPointerUp.call(r,E),k.current=null,M.current=!1,l(E)},onPointerOut:E=>{r.onPointerOut==null||r.onPointerOut.call(r,E),O(C.current)},onContextMenu:E=>{r.onContextMenu==null||r.onContextMenu.call(r,E),C.current&&O(C.current)}})});xu.displayName="Drawer.Content";const Mv=250,Av=120,bu=q.forwardRef(function({preventCycle:e=!1,children:t,...s},r){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:l,setActiveSnapPoint:u,dismissible:f,handleOnly:d,isOpen:m,onPress:h,onDrag:g}=un(),v=q.useRef(null),p=q.useRef(!1);function x(){if(p.current){j();return}window.setTimeout(()=>{b()},Av)}function b(){if(o||e||p.current){j();return}if(j(),!i||i.length===0){f||a();return}if(l===i[i.length-1]&&f){a();return}const I=i.findIndex(k=>k===l);if(I===-1)return;const N=i[I+1];u(N)}function w(){v.current=window.setTimeout(()=>{p.current=!0},Mv)}function j(){v.current&&window.clearTimeout(v.current),p.current=!1}return q.createElement("div",{onClick:x,onPointerCancel:j,onPointerDown:y=>{d&&h(y),w()},onPointerMove:y=>{d&&g(y)},ref:r,"data-vaul-drawer-visible":m?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},q.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});bu.displayName="Drawer.Handle";function Dv(e){const t=un(),{container:s=t.container,...r}=e;return q.createElement(Zc,{container:s,...r})}const Je={Root:Rv,Content:xu,Overlay:gu,Portal:Dv,Handle:bu,Title:ru},vu="inline-flex items-center justify-center transition-colors",Ov=be(vu,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Pv=be(vu,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),dn=({accountId:e,currentMailboxId:t,onMove:s,disabled:r=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),f=Ot(),d=c.useRef(null),m=i??"Move to folder",h=c.useId(),{t:g}=Un("mail",{useSuspense:!1}),v=c.useCallback((O,E)=>g(O,{defaultValue:E}),[g]),{data:p,isLoading:x,isError:b,error:w,refetch:j}=de({..._e({path:{accountId:e}}),staleTime:1/0,enabled:l}),y=Wc(e),{createFolder:I}=jl(e),N=c.useMemo(()=>{const O=Zs(p?.items??[],y),E=Xs(y);return O.map(S=>({id:S.mailboxId,label:bs(S,E.get(S.mailboxId),v),searchValue:S.fullPath,isCurrent:S.mailboxId===t}))},[p?.items,y,t,v]),k=c.useCallback(O=>{u(!1),s(O)},[s]),C=c.useCallback(async(O,E)=>{const S=await I(O,E);return{id:S.id,label:S.label}},[I]);c.useEffect(()=>{if(!l||!f)return;const O=S=>{d.current&&!d.current.contains(S.target)&&u(!1)},E=S=>{S.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",O),document.addEventListener("keydown",E),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("keydown",E)}},[l,f]);const M=r||!!a,P=n.jsxs("button",{type:"button",onClick:O=>{O.stopPropagation(),!M&&u(E=>!E)},"aria-label":m,"aria-haspopup":f?"listbox":"dialog","aria-expanded":l,"aria-controls":l?h:void 0,title:a,className:o==="icon-only"?Ov:Pv,children:[n.jsx(Ia,{className:"size-4"}),o==="compact"&&n.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),D=x?n.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):b?n.jsx("div",{className:"p-3",children:n.jsx(Pt,{variant:"inline",title:"Couldn't load folders",error:w,onRetry:()=>j()})}):n.jsx(Sl,{mailboxes:N,onSelect:k,onCreateFolder:C,onCancel:()=>u(!1),autoFocus:!f,labels:{createLabel:O=>`Create "${O}"`,searchPlaceholder:g("move_picker_placeholder",{defaultValue:"Move to…"}),searchAriaLabel:g("move_picker_filter_label",{defaultValue:"Filter folders"}),optionLabel:O=>`Move to ${O}`,currentSuffix:"(current folder)",currentTag:"current",emptyMessage:O=>`No folders match "${O}"`}});return f?n.jsxs("div",{ref:d,className:"relative inline-block",children:[P,l&&n.jsx("div",{id:h,className:be("absolute right-0 mt-1 z-50 w-72 max-h-96 flex flex-col","bg-surface border border-line rounded-md shadow-lg"),children:D})]}):n.jsxs(n.Fragment,{children:[P,n.jsx(Je.Root,{open:l,onOpenChange:u,children:n.jsxs(Je.Portal,{children:[n.jsx(Je.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Je.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{maxHeight:"85dvh"},id:h,children:[n.jsx(Je.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),n.jsx(Je.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),n.jsx("div",{className:"flex-1 overflow-hidden",children:D})]})]})})]})},Lv=({messageId:e,threadId:t,mailboxId:s,isRead:r,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const f=ye(),d=Oe(),{pushError:m}=Ve(),{selectedMessageId:h}=vs({strict:!1}),{mutate:g,isPending:v}=ve({...Wn(),onMutate:async A=>{const L=A.body.isRead??!0,T=new Set(A.body.messageIds??[]),F=Zt({path:{threadId:t}}),R=vt([s]);await Promise.all([f.cancelQueries({queryKey:F}),rn(f,R)]);const $=f.getQueriesData({queryKey:F}).filter(V=>V[1]!==void 0).map(([V,ee])=>({queryKey:V,data:ee})),z=an(f,R);return f.setQueriesData({queryKey:F},V=>V&&{...V,items:$n(V.items,T,L)}),on(f,R,V=>$n(V,T,L)),{threadMessagesPrefix:F,listPrefixes:R,previousThreadMessages:$,previousThreadsList:z}},onError:(A,L,T)=>{if(T){for(const R of T.previousThreadMessages)f.setQueryData(R.queryKey,R.data);ln(f,T.previousThreadsList)}const F=L.body.isRead??!0;m({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:st(A),error:A})},onSettled:(A,L,T,F)=>{F&&(f.invalidateQueries({queryKey:F.threadMessagesPrefix}),yt(f,F.listPrefixes))}}),p=c.useCallback(A=>{h&&A.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:L=>({...L,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:x,isPending:b}=Yt({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:w,isPending:j}=Qt({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:y,isPending:I,error:N,reset:k}=Ya({messageId:e}),C=()=>{g({body:{messageIds:[e],isRead:!1}})},M=()=>{x([e])},P=()=>{o&&y(o,i)},D=v||b||j||I,O=D||!o,E=c.useCallback(A=>{w([e],A)},[w,e]),S=o?void 0:"Sender has no parseable address";return n.jsxs("div",{className:"flex flex-col items-end gap-1",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[a&&n.jsx(dn,{accountId:a,currentMailboxId:s,onMove:E,disabled:D,label:"Move this message"}),n.jsxs(Cc,{trigger:n.jsx(_l,{className:"size-4"}),children:[n.jsxs(hs,{onClick:P,disabled:O,children:[i?n.jsx(Xn,{className:"size-4 text-positive"}):n.jsx(Ys,{className:"size-4 opacity-0"}),n.jsx("span",{title:S,children:"Trusted sender"})]}),r&&n.jsxs(hs,{onClick:C,disabled:D,children:[n.jsx(Cs,{className:"size-4"}),"Mark as unread"]}),u&&n.jsxs(hs,{onClick:u,children:[n.jsx(Fl,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),n.jsx(Xr,{}),n.jsxs(hs,{onClick:M,disabled:D,destructive:!0,children:[n.jsx(rt,{className:"size-4"}),"Delete"]})]})]}),N&&n.jsx("div",{className:"w-64",children:n.jsx(Pt,{variant:"inline",title:"Couldn't update trust",error:N,onRetry:()=>{k(),P()}})})]})},$v=()=>{const[e,t]=c.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return c.useEffect(()=>{const s=document.documentElement,r=new MutationObserver(()=>{t(s.classList.contains("dark"))});return r.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>r.disconnect()},[]),e},Fv=({blockedImageCount:e,canAlwaysTrust:t,isTrustPending:s,onLoadOnce:r,onAlwaysTrust:a})=>n.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-md bg-surface-sunken/50 px-3 py-2 text-sm",children:[n.jsxs("span",{className:"text-fg-muted",children:[e," image",e>1?"s":""," blocked for privacy"]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:r,className:"text-accent hover:underline",children:"Load once"}),t&&n.jsx("button",{type:"button",onClick:a,"aria-busy":s,className:"text-accent hover:underline aria-busy:opacity-50",children:s?"Trusting…":"Always trust"})]})]}),_v=(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}}},zv=e=>e instanceof Ht?e.reason:"generic",Bv=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",Kv=({error:e,onRetry:t})=>{const s=zv(e),r=Bv(e),{title:a,detail:o}=_v(s,r),[i,l]=c.useState(!1),{Account:u}=xa();return i?null:n.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[n.jsx(Gt,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"font-medium text-danger",children:a}),n.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&n.jsx(u,{children:({signOut:f})=>n.jsx("button",{type:"button",onClick:()=>f(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&n.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),n.jsx("button",{type:"button",onClick:()=>l(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:n.jsx(We,{className:"size-4","aria-hidden":"true"})})]})]})},Uv=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),Ti=()=>n.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),yu=({bodyParts:e,html:t,text:s,isTrusted:r=!1,messageId:a,fromAddressId:o,category:i,className:l})=>{const[u,f]=c.useState(!1),d=r||u,m=$v(),{toggleTrusted:h,isPending:g}=Ya({messageId:a??""}),v=!!e&&e.length>0,{picked:p,data:x,isLoading:b,isError:w,error:j,refetch:y}=$c({messageId:a,bodyParts:e,enabled:v}),I=c.useMemo(()=>Sh(e??[]),[e]),N=v&&x?.kind==="html"?x.body:t,k=v&&x?.kind==="text"?x.body:s;if(v){if(b)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Uv,{})});if(w)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Kv,{error:j,onRetry:()=>y()})});if(!p)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Ti,{})})}else if(!t&&!s)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Ti,{})});const C=!!(o&&a),M=()=>{!o||g||(f(!0),h(o,!1))};return n.jsx(sc,{className:l,html:N,text:k,isDark:m,category:i,allowImages:d,resolveCid:I,renderBlockedNotice:P=>n.jsx(Fv,{blockedImageCount:P,canAlwaysTrust:C,isTrustPending:g,onLoadOnce:()=>f(!0),onAlwaysTrust:M})})},qv=({messageId:e,threadId:t,mailboxId:s,accountId:r,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:l,isTrusted:u,showRaw:f,onToggleRaw:d,onReply:m,onReplyAll:h,onForward:g})=>{const v=ye(),{deleteMessages:p}=Yt({mailboxId:s,threadId:t}),{moveMessages:x}=Qt({mailboxId:s,threadId:t,accountId:r}),{toggleTrusted:b}=Ya({messageId:e}),{mutate:w}=ve({...Wn(),onSettled:()=>{v.invalidateQueries({queryKey:Zt({path:{threadId:t}})}),yt(v,vt([s]))}}),j=c.useCallback(k=>{x([e],k)},[x,e]),y=c.useCallback(()=>{p([e])},[p,e]),I=c.useCallback(()=>{w({body:{messageIds:[e],isRead:!a}})},[w,e,a]),N=[];return l&&N.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?n.jsx(Xn,{className:"size-4 text-positive"}):n.jsx(Ys,{className:"size-4"}),onSelect:()=>b(l,u)}),d&&N.push({key:"raw",label:f?"Show formatted":"Show raw email",icon:n.jsx(Fl,{className:"size-4"}),onSelect:d}),n.jsx(tc,{hasThread:!0,onReply:m,onReplyAll:h,onForward:g,isStarred:o,onToggleStar:i,onDelete:y,isRead:a,onToggleRead:I,overflowItems:N,moveSlot:r?n.jsx(dn,{accountId:r,currentMailboxId:s,onMove:j,label:"Move this message"}):void 0})},Hv=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading raw email",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"})]}),Wv=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:r,isError:a,error:o,refetch:i}=de({...pf({path:{messageId:e}}),enabled:t});if(r)return n.jsx("div",{className:"message-body",children:n.jsx(Hv,{})});if(a)return n.jsx("div",{className:"message-body",children:n.jsx(Pt,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const l=s?.raw??"";return l===""?n.jsx("div",{className:"message-body",children:n.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):n.jsx("div",{className:"message-body",children:n.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:l})})},Vv=()=>n.jsx(Xn,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),wu=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),ju=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:be("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":be("text-fg-subtle hover:text-warning",r&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:n.jsx(At,{className:be("size-3.5",e&&"fill-current")})}),Qv=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:r,isStarPending:a})=>{const o=yl(e.sentDate,"datetime"),i=wu(e,o);return n.jsx(nc,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:n.jsxs(n.Fragment,{children:[e.hasAttachment&&n.jsx(Jn,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx(ju,{isStarred:e.hasStars,onToggleStar:r,isStarPending:a,hoverReveal:!0}),n.jsx("span",{"data-testid":"message-date",className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:o})]})})},Yv=({threadMessage:e,messageData:t,isLoading:s,isError:r,error:a,onRetry:o,isFocused:i,onToggle:l,onToggleStar:u,isStarPending:f,accountId:d,showRaw:m,onToggleRaw:h,mobile:g,onReply:v,onReplyAll:p,onForward:x})=>{const b=yl(e.sentDate,"long"),w=!e.isRead,j=t?.envelope.from[0]?.flags?.trusted?.value===!0,y=t?.envelope.from[0]?.addressId,I=wu(e,b),N=e.autoMoved?n.jsx(Vc,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"md"}):null;return n.jsx(rc,{message:I,isFocused:g?!1:i,onHeaderClick:l,senderBadge:j?n.jsx(Vv,{}):void 0,trailing:n.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:b}),to:t?n.jsx(Xm,{label:"To",addresses:t.envelope.to}):null,indicators:N||!g?n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[N,!g&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n.jsx(ju,{isStarred:e.hasStars,onToggleStar:u,isStarPending:f}),e.hasAttachment&&n.jsx("span",{className:"text-fg-subtle p-0.5",children:n.jsx(Jn,{className:"size-3.5"})})]}),w&&n.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:g?void 0:n.jsx(Lv,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:y,isTrusted:j,showRaw:m,onToggleRaw:h}),actionBar:g?n.jsx(qv,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:y,isTrusted:j,showRaw:m,onToggleRaw:h,onReply:v,onReplyAll:p,onForward:x}):void 0,body:s?n.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):r&&gf(a)?n.jsx("div",{className:"mt-3",children:n.jsx(Uc,{message:"This message has been deleted"})}):r?n.jsx("div",{className:"mt-3",children:n.jsx(Pt,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):m?n.jsx("div",{className:"mt-3",children:n.jsx(Wv,{messageId:e.messageId})}):n.jsx("div",{className:"mt-3",children:n.jsx(yu,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:j,category:cn(e.category)})})})},Gv=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,mobile:l,onReply:u,onReplyAll:f,onForward:d})=>{const[m,h]=c.useState(!1),{data:g,isLoading:v,isError:p,error:x,refetch:b}=de({...ja({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?n.jsx(Yv,{threadMessage:e,messageData:g,isLoading:v,isError:p,error:x,onRetry:()=>b(),isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,showRaw:m,onToggleRaw:()=>h(w=>!w),mobile:l,onReply:u,onReplyAll:f,onForward:d}):n.jsx(Qv,{threadMessage:e,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o})},Xv=()=>n.jsxs("div",{className:"animate-pulse p-4",children:[n.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),n.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>n.jsxs("div",{className:"flex gap-3 py-3",children:[n.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function Ri({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?n.jsxs("div",{className:"flex items-start gap-2 rounded-none border-b border-danger/20 bg-danger-soft px-5 py-2.5 text-sm",children:[n.jsx(Ns,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",n.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&n.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const Is=({threadId:e,mailboxId:t,subject:s,selectedMessageId:r,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:l,onComposeClose:u,onSwipeNext:f,onSwipePrevious:d,mobileIntelligenceOpen:m})=>{const h=Ot(),{handlers:g}=_b({onSwipeLeft:f,onSwipeRight:d}),{accountId:v}=qc(t),{data:p,isLoading:x,isError:b,error:w,refetch:j}=de({...xf({path:{threadId:e}})}),y=c.useMemo(()=>p?.items??[],[p?.items]),I=y[y.length-1],N=c.useRef(new Map),[k,C]=c.useState(new Set),[M,P]=c.useState(null),[D,O]=c.useState(0);c.useEffect(()=>{if(y.length>0&&e!==M){P(e);const J=new Set([y[y.length-1].threadMessageId]);if(r){const ae=y.find(ce=>ce.messageId===r);ae&&J.add(ae.threadMessageId)}C(J),O(y.length-1)}},[e,y,M,r]);const E=c.useCallback(J=>{C(ae=>{const ce=new Set(ae);return ce.has(J)?ce.delete(J):ce.add(J),ce})},[]),S=c.useCallback(J=>{const ae=y[J];if(!ae)return;N.current.get(ae.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[y]),A=c.useCallback(()=>{if(y.length===0)return;const J=Math.min(D+1,y.length-1);O(J),S(J)},[y.length,D,S]),L=c.useCallback(()=>{if(y.length===0)return;const J=Math.max(D-1,0);O(J),S(J)},[y.length,D,S]),T=c.useCallback(()=>{const J=y[D];J&&E(J.threadMessageId)},[y,D,E]),{data:F}=de({...xt(),staleTime:1/0}),R=F?.accounts?.[0],$=!!R?.smtpHost;Pb({messages:y,expandedIds:k,threadId:e,mailboxId:t,accountId:R?.accountId});const{toggleStar:z,isPending:V,pendingMessageId:ee}=Wa({threadId:e,mailboxId:t,messages:y}),[X,Q]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(Q(l),u?.())},[l,u]);const{data:le}=de({...ja({path:{messageId:I?.messageId??""}}),enabled:!!I&&X!==null}),ue=c.useCallback(()=>{Q("reply")},[]),te=c.useCallback(()=>{Q("reply_all")},[]),K=c.useCallback(()=>{Q("forward")},[]),U=c.useCallback(()=>{Q(null),u?.()},[u]);if(Ha({enabled:!x&&y.length>0&&X===null,bindings:[{key:"j",handler:A,preventDefault:!0},{key:"ArrowDown",handler:A,preventDefault:!0},{key:"k",handler:L,preventDefault:!0},{key:"ArrowUp",handler:L,preventDefault:!0},{key:"Enter",handler:T,preventDefault:!0},{key:"o",handler:T,preventDefault:!0},...$?[{key:"r",handler:ue,preventDefault:!0},{key:"R",handler:te,noModifiers:!1,preventDefault:!0},{key:"f",handler:K,preventDefault:!0}]:[]]}),x)return n.jsx(Xv,{});if(b)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(Pt,{title:"Couldn't load this conversation",error:w,onRetry:()=>j()})});if(y.length===0)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(Uc,{message:"No messages in this thread"})});const re=s||y[0]?.subject||"(No subject)",Ie=y.length,je=J=>n.jsx("div",{children:y.map((ae,ce)=>n.jsx("div",{ref:B=>{B&&N.current.set(ae.threadMessageId,B)},children:n.jsx(Gv,{threadMessage:ae,isExpanded:k.has(ae.threadMessageId),isFocused:ce===D,onToggle:()=>E(ae.threadMessageId),onToggleStar:()=>z(ae.messageId,ae.hasStars),isStarPending:V&&ee===ae.messageId,accountId:v,mobile:J,onReply:J&&$?ue:void 0,onReplyAll:J&&$?te:void 0,onForward:J&&$?K:void 0})},ae.threadMessageId))}),W=n.jsxs("header",{className:"border-b border-line px-5 pt-5 pb-3",children:[n.jsx("h1",{className:"max-w-2xl text-lg font-semibold leading-snug text-fg",children:re}),n.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Ie," ",Ie===1?"message":"messages"]})]});return h?n.jsxs("article",{className:"h-full flex flex-col",children:[W,a?.dkimMismatch&&n.jsx(Ri,{authenticity:a,onOpenIntelligence:o}),n.jsx("div",{className:"flex-1 overflow-auto",children:je(!1)}),X!==null&&n.jsx(wi,{mode:X,account:R,sourceMessage:le,onClose:U})]}):n.jsxs(Qh,{thread:{subject:re,messages:[]},onBack:i??(()=>{}),intelligenceOpen:m,onToggleIntelligence:o,touchHandlers:g,children:[a?.dkimMismatch&&n.jsx(Ri,{authenticity:a,onOpenIntelligence:o}),je(!0),X!==null&&n.jsx(wi,{mode:X,account:R,sourceMessage:le,onClose:U})]})};function Ts(){const{mailboxNameIndex:e,accountNameIndex:t}=Ce();return{...gt({select:r=>Ac(r.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Za=e=>e.trim().toLocaleLowerCase(),Jv=/^\d{4}-\d{2}-\d{2}$/;function Mi(e,t,s){if(!Jv.test(s))return;const r=Date.parse(`${s}T00:00:00Z`);if(!Number.isNaN(r))return{type:e,raw:t,value:s,epochSeconds:Math.floor(r/1e3)}}function Zv(e,t){const s=e.toLowerCase();if(s.startsWith("from:")&&e.length>5)return{type:"from",raw:e,value:e.slice(5)};if(s==="has:attachment")return{type:"hasAttachment",raw:e};if(s==="is:unread")return{type:"isUnread",raw:e};if(s.startsWith("before:")&&e.length>7)return Mi("before",e,e.slice(7));if(s.startsWith("after:")&&e.length>6)return Mi("after",e,e.slice(6));if(s.startsWith("in:")&&e.length>3){const r=e.slice(3),a=t.mailboxesByName?.get(r.toLowerCase());return a?{type:"in",raw:e,value:r,mailboxId:a}:void 0}if(s.startsWith("account:")&&e.length>8){const r=e.slice(8),a=t.accountsByName?.get(r.toLowerCase());return a?{type:"account",raw:e,value:r,accountId:a}:void 0}}function Rs(e,t={}){const s=e.split(/\s+/).filter(o=>o.length>0),r=[],a=[];for(const o of s){const i=Zv(o,t);i?r.push(i):a.push(o)}return{freeText:a.join(" "),tokens:r}}function ey(e,t){return e.split(/\s+/).filter(s=>s.length>0&&s!==t.raw).join(" ")}function Su(e){switch(e.type){case"from":return`From: ${e.value}`;case"hasAttachment":return"Has attachment";case"isUnread":return"Unread";case"before":return`Before ${e.value}`;case"after":return`After ${e.value}`;case"in":return`In: ${e.value}`;case"account":return`Account: ${e.value}`}}const ty=20,sy=new Set(Object.values(it)),ny=e=>e!==void 0&&sy.has(e)?e:void 0;function ku({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Ce(),r=Ts(),a=gt({select:w=>w.matches}),o=Za(s),{freeText:i,tokens:l}=Rs(o,r),u=i.length>0,f=ny(t),d=l.some(w=>w.type==="hasAttachment")?!0:void 0,m=l.some(w=>w.type==="isUnread")?!1:void 0,h=l.find(w=>w.type==="after"),g=l.find(w=>w.type==="before"),v=l.find(w=>w.type==="in"),p=Vx({matches:a,callerMailboxId:e,inTokenMailboxId:v?.mailboxId}),{data:x,isLoading:b}=de({...il({query:{query:i,mailboxId:p,limit:ty,...f!==void 0?{category:f}:{},...d!==void 0?{hasAttachment:d}:{},...m!==void 0?{isRead:m}:{},...h?{sentDateFrom:h.epochSeconds}:{},...g?{sentDateTo:g.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:x?.items??[],isLoading:u&&b}}const ry=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),ay=e=>[...e].sort(ry);function sa(e){const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId??e.accountConfigId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:cn(e.category),suspicious:t}}function oy(e,t){const s=new Set,r=[];for(const a of[...e,...t])s.has(a.id)||(s.add(a.id),r.push(a));return r.sort((a,o)=>(o.sentDate??0)-(a.sentDate??0))}const Ai=[{id:"personal",label:"Personal",category:it.personal},{id:"transactional",label:"Transactional",category:it.transactional},{id:"newsletter",label:"Newsletter",category:it.newsletter},{id:"marketing",label:"Marketing",category:it.marketing},{id:"social",label:"Social",category:it.social},{id:"automated",label:"Automated",category:it.automated},{id:"uncategorized",label:"Unclassified",category:it.uncategorized}];function iy(e){const t=new Map(Ai.map(r=>[r.category,[]]));for(const r of e){const a=r.category??it.uncategorized;(t.get(a)??t.get(it.uncategorized))?.push(r)}const s=[];for(const r of Ai){const a=t.get(r.category);a&&a.length>0&&s.push({id:r.id,label:r.label,threads:a})}return s}function Cu(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Nu(e,t){return t.every(s=>{switch(s.type){case"from":{const r=s.value.toLowerCase();return e.fromEmail.toLowerCase().includes(r)||e.fromName.toLowerCase().includes(r)}case"hasAttachment":return e.hasAttachment===!0;case"isUnread":return!e.isRead;case"after":return e.sentDate!=null&&e.sentDate>=s.epochSeconds*1e3;case"before":return e.sentDate!=null&&e.sentDate<s.epochSeconds*1e3;case"in":return e.mailboxId===s.mailboxId;case"account":return e.accountId===s.accountId;default:return!1}})}const ly={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function cy(e){return ly[e]??e}function uy(e,t){const{folder:s}=Sa(t,[e.mailboxId]);return{id:e.messageId,sender:e.fromName??e.fromEmail??"Unknown",subject:e.subject??"(No subject)",snippet:e.snippet??"",date:Lt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Eu(e,t){const{folder:s}=Sa(t,e.mailboxId?[e.mailboxId]:[]);return{id:e.id,sender:e.fromName,subject:e.subject,snippet:e.snippet,date:e.timeLabel,unread:!e.isRead,flagged:e.starred===!0,...e.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function dy(e,t){const{mailboxId:s,folder:r}=Sa(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?Lt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:cy(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...r?{folder:r}:{}}}function Iu(e,t,s){const r=new Set(t),a=[];for(const o of[...e].sort((i,l)=>l.score-i.score))r.has(o.threadId)||(r.add(o.threadId),a.push(dy(o,s)));return a}const fy=768,my=1024,Tu=e=>e!=="desktop",lr=()=>{const e=wo(`(min-width: ${fy}px)`);return wo(`(min-width: ${my}px)`)?"desktop":e?"tablet":"phone"},hy=new Set(["hasAttachment","isUnread","before","after"]),Ru=(e,{searchHadSemanticReach:t})=>{const s=[],r=[];let a,o;for(const u of e.tokens){if(u.type==="from"){s.push({field:"From",value:u.value});continue}if(u.type==="in"){a={mailboxId:u.mailboxId,label:u.value};continue}if(u.type==="account"){o=u.accountId;continue}hy.has(u.type)&&r.push({type:u.type,label:Su(u)})}const i=e.freeText.trim(),l=i.length>0;return l&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:r,targetAccountId:o,keptTerms:l,droppedSemantic:l&&t}},py=e=>e.clauses.length>0,Mu=(e,{scope:t="standing",moveMailboxId:s}={})=>({clauses:e.clauses.map((r,a)=>({id:`search-${a}`,field:r.field,value:r.value})),matchOperator:e.matchOperator,moveMailboxId:s,scope:t,name:""}),Au="remit.recentSearches",gy=5;function na(){try{const e=localStorage.getItem(Au);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Di(e){const t=e.trim();if(!t)return na();const s=[t,...na().filter(r=>r!==t)].slice(0,gy);try{localStorage.setItem(Au,JSON.stringify(s))}catch{return s}return s}const xy=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function by(e){const{spam:t}=oc([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let r;for(const[a,o]of s)(!r||o>r.count)&&(r={mailboxId:a,count:o});return r}const vy=(e,t)=>{const s=ve(ll()),{mutate:r,reset:a}=s,o=c.useCallback(()=>{e&&(a(),r({path:{accountId:e},body:qr({matchOperator:t.matchOperator,literalClauses:t.literalClauses})}))},[e,t.matchOperator,t.literalClauses,r,a]);return c.useEffect(()=>{o()},[o]),{seedCount:s.data?.matchedCount,isPending:s.isPending||s.data===void 0,isError:s.isError,error:s.error,retry:o}},Du=({initialRule:e,widenAnchorCount:t=1})=>{const[s,r]=c.useState(e),[a,o]=c.useState(),i=c.useRef(0);return{rule:s,setRule:N=>r(N),handlers:{clauseEdit:a,onStartAddClause:()=>o({mode:"add",draft:{field:Na[0],value:""}}),onStartEditClause:N=>{const k=s.clauses.find(C=>C.id===N);k&&o({mode:"edit",clauseId:N,draft:{field:k.field,value:k.value}})},onRemoveClause:N=>r(k=>({...k,clauses:k.clauses.filter(C=>C.id!==N)})),onChangeDraftField:N=>o(k=>k&&{...k,draft:{...k.draft,field:N}}),onChangeDraftValue:N=>o(k=>k&&{...k,draft:{...k.draft,value:N}}),onSubmitClause:()=>{if(!a)return;const N=a.draft.field,k=Uf(N,a.draft.value);k!==""&&(r(C=>a.mode==="edit"&&a.clauseId?{...C,clauses:C.clauses.map(M=>M.id===a.clauseId?{id:M.id,field:N,value:k}:M)}:(i.current+=1,{...C,clauses:[...C.clauses,{id:`clause-${i.current}`,field:N,value:k}]})),o(void 0))},onCancelClause:()=>o(void 0),onAddWiden:()=>r(N=>({...N,widen:{anchorCount:Math.max(t,1)}})),onRemoveWiden:()=>r(N=>({...N,widen:void 0})),onChangeMatchOperator:N=>r(k=>({...k,matchOperator:N})),onChangeMove:N=>r(k=>({...k,moveMailboxId:N||void 0})),onChangeLabel:N=>r(k=>({...k,labelId:N||void 0})),onChangeScope:N=>r(k=>({...k,scope:N})),onChangeName:N=>r(k=>({...k,name:N})),onChangeUntil:N=>r(k=>({...k,until:N}))}}};function Ou({progress:e,isDone:t,runningLabel:s,onClose:r}){const a=e.state==="Failed";return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[t?a?n.jsx("span",{className:"text-sm font-semibold text-danger",children:"Organize failed"}):n.jsx(Yn,{className:"size-8 text-positive"}):n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),!t&&n.jsx("p",{className:"text-sm font-medium text-fg",children:s}),t&&!a&&n.jsxs("div",{className:"text-sm text-fg",children:[n.jsx("p",{className:"font-medium",children:"Done"}),n.jsxs("p",{className:"mt-1 text-xs text-fg-muted",children:[e.appliedCount," of ",e.matchedCount," moved",e.failedCount>0?` · ${e.failedCount} failed`:"","."]})]}),t&&a&&n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:e.errorMessage||"Something went wrong. Please try again."}),t&&n.jsx(G,{variant:"primary",onClick:r,className:"mt-2",children:"Done"})]})}function ra(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Saving rule…"})]})}function Pu({onClose:e}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(Yn,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Filter saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"You can see it, and when it expires, under Settings › Filters."}),n.jsx(G,{variant:"primary",onClick:e,className:"mt-2",children:"Done"})]})}function yy({onRetry:e,onClose:t}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(Yn,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Rule saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"New mail follows it automatically. Moving the mail already in your mailbox didn't run — try again?"}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(G,{variant:"primary",onClick:e,children:"Move existing mail"}),n.jsx(G,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function Lu({onRetry:e,onClose:t}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't save the rule"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(G,{variant:"primary",onClick:e,children:"Try again"}),n.jsx(G,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function wy({accountId:e,conversion:t,seedCount:s,onClose:r}){const[a]=c.useState(()=>Mu(t)),{rule:o,handlers:i}=Du({initialRule:a}),{data:l}=de({..._e({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),u=c.useMemo(()=>Zs(l?.items??[]).map(g=>({id:g.mailboxId,label:Vn(g.fullPath)})),[l?.items]),f=pl(e,Ea(o),s),d=gl(e),m=xl(e),h=()=>{const g=bl(o);if(o.scope==="once"){d.start(g);return}m.createFilter(g,o.scope==="standing"?"standing":"temporary",(o.name??"").trim())};return d.isStarting||d.isRunning||d.isDone?n.jsx(Ou,{progress:d.progress,isDone:d.isDone,runningLabel:"Organizing your mail…",onClose:r}):m.isPending?n.jsx(ra,{}):m.isSuccess?n.jsx(Pu,{onClose:r}):m.isError?n.jsx(Lu,{onRetry:m.reset,onClose:r}):n.jsx(cl,{rule:o,folders:u,preview:f,notice:n.jsx(Vp,{notice:{scopedOutFolder:t.scopedOut?.label,droppedFacets:t.droppedFacets.map(g=>g.label),droppedSemantic:t.droppedSemantic}}),semanticAvailable:!1,clauseFields:Na,...i,onCommit:h,onCancel:r})}function jy({open:e,accountId:t,parsed:s,searchHadSemanticReach:r,onClose:a}){const o=c.useMemo(()=>Ru(s,{searchHadSemanticReach:r}),[s,r]),i=c.useMemo(()=>Ea(Mu(o)),[o]),{seedCount:l,isPending:u,isError:f,retry:d}=vy(e?t:void 0,i);return e?n.jsx(ua,{open:e,onClose:a,title:"Filter rule",children:f?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't build the filter"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(G,{variant:"primary",onClick:d,children:"Try again"}),n.jsx(G,{variant:"ghost",onClick:a,children:"Not now"})]})]}):u||l===void 0?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Turning your search into a filter…"})]}):n.jsx(wy,{accountId:t,conversion:o,seedCount:l,onClose:a})}):null}function $u({title:e,unreadCount:t,children:s,footer:r,searchFilter:a,searchResults:o,searchLoading:i,relatedResults:l,relatedLoading:u,onSelectSearchResult:f,searchResultsLabel:d="Top matches",relatedResultsLabel:m="Related",searchResultsInBody:h=!1}){const{accounts:g,resultFolderIndex:v,searchQuery:p,searchInput:x,onSearchChange:b,onSearchClear:w,searchViewKey:j}=Ce(),y=Ts(),I=Oe(),N=Ss(),k=lr(),[C,M]=c.useState(!1),[P,D]=c.useState(na),[O,E]=c.useState(!1),S=c.useRef(j);c.useEffect(()=>{S.current!==j&&(S.current=j,M(!1))},[j]);const A=x.trim().length>0,{mailboxesByName:L,accountsByName:T}=y,F=c.useMemo(()=>Rs(x,{mailboxesByName:L,accountsByName:T}),[x,L,T]),R=F.tokens.map(pe=>({label:Su(pe),onRemove:()=>b(ey(x,pe))})),$=o??[],z=l??[],V=A?[{id:"top",label:d,results:$},{id:"related",label:m,results:z}]:[],X=!($.length+z.length>0)&&(i===!0||u===!0),{scope:Q}=Pc(g),le=gt({select:pe=>pe.matches}),ue=Dc(le),te=Yx(le,Q,ue?v.get(ue)?.role:void 0),K=te.kind==="global"?by([...$,...z]):void 0,U=K?{kind:"global",onScopeToSpam:()=>I({to:"/mail/$mailboxId",params:{mailboxId:K.mailboxId},search:{q:p||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:te,Ie=F.tokens.find(pe=>pe.type==="account")?.accountId??g[0]?.accountId,je=z.length>0,W=A&&Ie?{onClick:()=>E(!0),disabledReason:py(Ru(F,{searchHadSemanticReach:je}))?void 0:"Add a sender or words to filter on"}:void 0,J=O&&Ie?n.jsx(jy,{open:O,accountId:Ie,parsed:F,searchHadSemanticReach:je,onClose:()=>E(!1)}):null;if(k==="phone"&&C){const pe=ge=>{D(Di(x)),M(!1),f?.(ge)};return n.jsxs(n.Fragment,{children:[n.jsx(Sp,{value:x,onChange:b,onClear:w,onCancel:()=>{M(!1),w()},filter:a,recentSearches:P,onPickRecent:b,makeFilter:W,sections:V,loading:X,onSelectResult:pe,tokens:R,scope:U}),J]})}const ae=xy({tier:k,hasLiveInput:A,hasCommittedQuery:p.trim().length>0,bodyRendersCommittedResults:h}),ce=pe=>{D(Di(x)),f?.(pe)},B=n.jsx(ic,{value:x,sections:V,loading:X,onSelectResult:ce,tokens:R,scope:U,makeFilter:W}),Fe=ae?a?n.jsx(da,{...a,children:B}):n.jsx("div",{className:"h-full overflow-y-auto",children:B}):s;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsx(mp,{title:e,unreadCount:t,isDesktop:!1,showSearch:Tu(k),onMenuClick:()=>N?.openNav(),searchValue:x,onSearchChange:b,onSearchClear:w,searchOpen:C,onSearchOpenChange:M}),n.jsx("div",{className:"min-h-0 flex-1",children:Fe}),r,J]})}const Sy=(e,t,s)=>{const r=e.indexOf(s);if(r===-1)return[];const a=t===void 0?-1:e.indexOf(t);if(a===-1)return[s];const o=Math.min(a,r),i=Math.max(a,r);return e.slice(o,i+1)},ky=(e,t,s,r)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:r,Cy=(e,t)=>{const s=new Set(t),r=new Set;for(const a of e)s.has(a)&&r.add(a);return r},Fu=(e,t,s)=>{if(e.length===0)return;const r=t===void 0?-1:e.indexOf(t);if(r===-1)return s>0?e[0]:e[e.length-1];const a=Math.min(Math.max(r+s,0),e.length-1);return e[a]},_u=e=>{const[t,s]=c.useState(new Set),[r,a]=c.useState(void 0),o=c.useCallback(p=>t.has(p),[t]),i=c.useCallback(p=>{a(p),s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},[]),l=c.useCallback(p=>{a(p),s(x=>{if(x.has(p))return x;const b=new Set(x);return b.add(p),b})},[]),u=c.useCallback(p=>{s(x=>{if(!x.has(p))return x;const b=new Set(x);return b.delete(p),b})},[]),f=c.useCallback(p=>{s(new Set(p))},[]),d=c.useCallback(()=>{a(void 0),s(new Set)},[]),m=c.useCallback(p=>{s(x=>p.every(w=>x.has(w))?new Set:new Set(p))},[]),h=c.useCallback(p=>{a(p)},[]),g=c.useCallback(p=>{s(x=>{if(x.size===0)return x;const b=Cy(x,p);return b.size===x.size?x:b})},[]),v=c.useCallback((p,x,b)=>{const w=ky(p,r,b,x);s(j=>{const y=Sy(p,w,x);if(y.length===0)return j;const I=new Set(j);for(const N of y)I.add(N);return I}),a(w)},[r]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:l,deselect:u,selectAll:f,clearSelection:d,toggleAll:m,selectRange:v,setAnchor:h,anchorId:r,intersectWith:g}},zu=(e,t)=>!t&&e>0,Ny=(e,t)=>e==="BACK"&&t,Ey=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:r})=>{const[a,o]=c.useState(s),i=_u(),{selectedCount:l,toggle:u,clearSelection:f,selectRange:d,setAnchor:m,selectAll:h}=i,g=zu(l,t),v=c.useRef(null),p=c.useRef(!1),x=c.useCallback(()=>{r?.(),f()},[f,r]),b=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),w=c.useCallback(E=>{if(E<0||E>=e.length)return;const S=e[E];if(g){u(S);return}v.current=S,p.current=!1,o(S)},[e,g,u]),j=c.useCallback(()=>{e.length!==0&&w(b<0?0:Math.min(b+1,e.length-1))},[e.length,b,w]),y=c.useCallback(()=>{e.length!==0&&w(b<=0?0:b-1)},[e.length,b,w]),I=c.useCallback(()=>w(0),[w]),N=c.useCallback(()=>w(e.length-1),[w,e.length]),k=c.useCallback(()=>{a&&u(a)},[a,u]),C=c.useCallback((E,S)=>S.shiftKey?(d(e,E,a),!0):S.metaKey||S.ctrlKey?(u(E),!0):(x(),m(E),!1),[e,a,d,u,x,m]),M=c.useCallback(E=>{const S=Fu(e,a,E);S!==void 0&&(d(e,S),v.current=S,p.current=!1,o(S))},[e,a,d]),P=c.useCallback(()=>M(-1),[M]),D=c.useCallback(()=>M(1),[M]),O=c.useCallback(()=>{e.length>0&&h(e)},[e,h]);return{focusedMessageId:a,setFocusedMessageId:o,focusIndex:b,pendingDomFocusRef:v,cursorMovedByPointerRef:p,selection:i,isMultiSelectMode:g,exitSelection:x,moveFocusToIndex:w,focusNext:j,focusPrevious:y,focusFirst:I,focusLast:N,toggleFocusedSelection:k,extendRangeUp:P,extendRangeDown:D,selectAllLoaded:O,handleRowSelect:C}};function Bu(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Iy=e=>{const{mailboxId:t,messages:s}=e,r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i}=ve({...bf(),onError:(u,f)=>{a({title:f.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:st(u),error:u})},onSettled:(u,f,d)=>{yt(r,vt(nr(d.body.messageIds??[],s??[],t)))}});return{applyLabel:c.useCallback((u,f,d)=>{u.length!==0&&o({body:{messageIds:u,labelId:f,action:d}})},[o]),isPending:i}};function Ty({accountId:e,mailboxId:t,messageIds:s}){const{labels:r}=kl(e),{applyLabel:a}=Iy({mailboxId:t}),o=c.useMemo(()=>r.map(i=>({key:i.labelId,label:i.name,icon:n.jsx("span",{className:`size-2.5 rounded-full ${vf(i.color)?yo[i.color]:yo.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[r,s,a]);return o.length===0?null:n.jsx(ec,{triggerLabel:"Apply label to selected messages",triggerIcon:n.jsx(yf,{className:"size-4"}),items:o})}const Ku=({selectedCount:e,onDelete:t,onClearSelection:s,onMarkAsRead:r,onMove:a,onOrganize:o,isDeleting:i=!1,isMoving:l=!1,accountId:u,currentMailboxId:f,selectedMessageIds:d,moveDisabledHint:m,selectAll:h,statusLabel:g,isCounting:v=!1,progress:p,notice:x})=>{if(e===0)return null;const b=p!==void 0,w=i||l||b,j=!b&&!v,y=!!a&&!!u&&!!f,I=!!u&&!!f&&!!d?.length,N=!!o&&!!u&&!!f&&!m&&!g,k=h?.checked?`All ${e} loaded selected`:`${e} ${e===1?"message":"messages"} selected`;return n.jsxs("div",{className:"sticky top-0 z-10 flex flex-col bg-surface-sunken border-b border-line",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:s,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded hover:bg-surface-raised transition-colors","aria-label":"Clear selection",children:n.jsx(We,{className:"size-4 text-fg-muted"})}),h&&n.jsx("label",{className:"flex size-11 shrink-0 cursor-pointer items-center justify-center",children:n.jsx(sn,{"aria-label":"Select all",checked:h.checked,indeterminate:h.indeterminate,onChange:h.onChange})}),n.jsx("span",{className:"text-sm font-medium",children:g??k}),m&&!x&&n.jsx("span",{className:"text-xs text-fg-muted",role:"status","aria-live":"polite",children:m})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[N&&o&&n.jsxs("button",{type:"button",onClick:w?void 0:o,className:"min-h-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Organize similar messages",children:[n.jsx(ut,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:"Organize"})]}),j&&r&&n.jsx("button",{type:"button",onClick:w?void 0:r,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Mark as read","aria-busy":w,children:n.jsx(Cs,{className:"size-4"})}),j&&y&&a&&u&&f&&n.jsx(dn,{accountId:u,currentMailboxId:f,onMove:w?()=>{}:a,disabledHint:m,variant:"icon-only",label:"Move selected messages"}),j&&I&&u&&f&&d&&n.jsx(Ty,{accountId:u,mailboxId:f,messageIds:d}),j&&n.jsxs("button",{type:"button",onClick:w?void 0:t,className:be("min-h-11 min-w-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors","bg-danger text-canvas hover:bg-danger/90"),"aria-label":"Delete selected messages","aria-busy":i,children:[i?n.jsx(nt,{className:"size-4 animate-spin"}):n.jsx(rt,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:i?"Deleting...":"Delete"})]})]})]}),p&&n.jsx("div",{className:"px-3 pb-2",children:n.jsx(Pa,{value:p.value,max:p.max,tone:p.tone})}),x&&n.jsx(Xt,{tone:x.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-3 mb-2",children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[x.text&&n.jsx("span",{children:x.text}),x.action&&n.jsx("button",{type:"button",onClick:x.action.onClick,className:"-my-1 min-h-11 shrink-0 inline-flex items-center px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised",children:x.action.label})]})})]})},eo=c.createContext(null),Ry=e=>{const t=c.useContext(eo);return t?t.rowInteraction(e):null},My=()=>{const e=c.useContext(eo);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},Ay="[data-message-id]",Dy=e=>Array.from(e.querySelectorAll(Ay)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),Oy=(e,t)=>e.length===t.length&&e.every((s,r)=>s===t[r]),Py=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const r=e.current;if(!r)return;const a=()=>{const i=Dy(r);s(l=>Oy(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(r,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function Uu({selectedMessageId:e,onOpen:t,onDeleteMessages:s,isDeleting:r=!1,commandsRef:a,onTriageContextChange:o,children:i}){const l=Ot(),u=c.useRef(null),f=Py(u),d=Ey({orderedIds:f,isDesktop:l,initialFocusedId:e}),{focusedMessageId:m,setFocusedMessageId:h,pendingDomFocusRef:g,cursorMovedByPointerRef:v,selection:p,isMultiSelectMode:x,exitSelection:b,handleRowSelect:w}=d,{selectedIds:j,selectedCount:y,isSelected:I,toggle:N,select:k}=p,{intersectWith:C}=p;c.useEffect(()=>{C(f)},[C,f]),c.useEffect(()=>{const Q=g.current;Q!==null&&(g.current=null,u.current?.querySelector(`[data-message-id="${Q}"]`)?.focus())});const M=c.useCallback(Q=>{v.current=!0,h(Q)},[v,h]),P=c.useCallback(Q=>{l||k(Q)},[l,k]),D=c.useCallback(()=>{m&&t(m)},[m,t]),[O,E]=c.useState(null),S=c.useCallback(Q=>!s||Q.length===0?!1:(E(Q),!0),[s]),A=c.useCallback(()=>{S(Array.from(j))},[S,j]),L=c.useCallback(()=>O!==null?!0:y>0?S(Array.from(j)):m?S([m]):!1,[O,y,j,m,S]),T=c.useCallback(()=>{O!==null&&(s?.(O),E(null),b())},[O,s,b]),F=c.useCallback(()=>E(null),[]),R=c.useCallback(()=>y===0?!1:(b(),!0),[y,b]),$=f.length>0;c.useEffect(()=>{if(a){if(!$){a.current=null;return}return a.current={focusNext:d.focusNext,focusPrevious:d.focusPrevious,focusFirst:d.focusFirst,focusLast:d.focusLast,openFocused:D,toggleSelect:d.toggleFocusedSelection,extendSelectDown:d.extendRangeDown,extendSelectUp:d.extendRangeUp,selectAll:d.selectAllLoaded,clearSelection:R,requestDelete:L,toggleDensity:()=>{}},()=>{a.current=null}}},[a,$,d.focusNext,d.focusPrevious,d.focusFirst,d.focusLast,d.toggleFocusedSelection,d.extendRangeDown,d.extendRangeUp,d.selectAllLoaded,D,R,L]);const z=c.useMemo(()=>Array.from(j),[j]),V=O!==null;c.useEffect(()=>{o?.({focusedMessageId:m,selectedIds:z,orderedIds:f,hasList:$,blocksKeyboard:V})},[o,m,z,f,$,V]);const ee=Bu(f,m),X=c.useMemo(()=>({selectedIds:j,selectedCount:y,exitSelection:b,requestDeleteSelection:A,rowInteraction:Q=>({focused:Q===m,isTabStop:Q===ee,isDesktop:l,onFocusRow:M,selection:{isChecked:I(Q),onToggleCheck:N,onRowSelect:w,isMultiSelectMode:x,onLongPress:P}})}),[j,y,b,A,m,ee,l,M,I,N,w,x,P]);return n.jsxs(eo.Provider,{value:X,children:[n.jsx("div",{ref:u,className:"contents",children:i}),n.jsx(Ra,{isOpen:V,title:wl(O?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:r,onConfirm:T,onCancel:F})]})}function qu({onMarkAsRead:e,isDeleting:t}){const{selectedIds:s,selectedCount:r,exitSelection:a,requestDeleteSelection:o}=My(),i=c.useCallback(()=>{e?.(Array.from(s)),a()},[e,s,a]);return n.jsx(Ku,{selectedCount:r,onDelete:o,onClearSelection:a,onMarkAsRead:e?i:void 0,isDeleting:t})}const Ly=({thread:e,active:t=!1,focused:s,isTabStop:r,density:a="comfortable",isDesktop:o,badge:i,selection:l,inListbox:u=!1,linkMailboxId:f,onClick:d,onFocusRow:m})=>{const h=ye(),g=e.id,v=Ry(g),p=s??v?.focused??!1,x=r??v?.isTabStop??!1,b=l??v?.selection,w=m??v?.onFocusRow,j=o??v?.isDesktop??!0,y=b?.isChecked??!1,I=b?.isMultiSelectMode??!1,N=b?.onToggleCheck,k=b?.onRowSelect,C=b?.onLongPress,M=c.useCallback(R=>{R.preventDefault(),R.stopPropagation(),N?.(g)},[N,g]),P=c.useCallback(R=>{if(!j){if(I){R.preventDefault(),R.stopPropagation(),N?.(g);return}d?.();return}const $={shiftKey:R.shiftKey,metaKey:R.metaKey,ctrlKey:R.ctrlKey};if(k?.(g,$)){R.preventDefault(),R.stopPropagation(),$.shiftKey&&window.getSelection()?.removeAllRanges();return}d?.()},[j,I,N,k,d,g]),D=c.useCallback(R=>{j&&R.shiftKey&&R.preventDefault()},[j]),O=c.useCallback(()=>{C?.(g)},[C,g]),{longPressProps:E}=Xl({onLongPress:O,delayMs:500,accessibilityDescription:y?"Deselect message":"Select message"}),S=c.useCallback(()=>{h.prefetchQuery(ja({path:{messageId:g}}))},[h,g]),A=c.useCallback(()=>{S(),w?.(g)},[S,w,g]),L=ks({"data-list-row":"","data-message-row":!0,"data-message-id":g,...u?{role:"option","aria-selected":y}:{},tabIndex:x?0:-1,onClick:P,onMouseDown:D,onMouseEnter:S,onFocus:A},j||!b?{}:E),T=be(a==="compact"?Ql({active:t,focused:p}):be("group",tn({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",y&&"bg-accent-soft",!j&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?n.jsx(Yl,{thread:e}):n.jsx(Gl,{thread:e,badge:i,selection:b?{checked:y,alwaysVisible:I,onToggle:M}:void 0});return f===void 0?n.jsx("button",{type:"button",...L,className:T,children:F}):n.jsx(pt,{to:"/mail/$mailboxId",params:{mailboxId:f},search:R=>({...R,selectedMessageId:g}),...L,className:T,children:F})},to=c.memo(Ly),$y=200,Fy={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0,contacts:e=>e.trust==="vip"||e.trust==="wellknown",today:e=>e.sentDate!=null&&new Date(e.sentDate).toDateString()===new Date().toDateString()},Oi=()=>n.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>n.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[n.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsxs("div",{className:"flex justify-between gap-2",children:[n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),_y=({accountEmail:e})=>{const t=Oe();return n.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[n.jsx(Gt,{className:"size-3.5 shrink-0"}),n.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),n.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})};function zy({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:r,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i,onMarkMessagesRead:l}){const{searchQuery:u,resultFolderIndex:f}=Ce(),d=Ts(),m=Ot(),h=c.useMemo(()=>ay(e.filter(K=>!K.muted?.value)),[e]),[g,v]=c.useState("all"),[p,x]=c.useState("all"),[b,w]=c.useState(new Set),[j,y]=c.useState(!1),I=c.useCallback(K=>{w(U=>{const re=new Set(U);return re.has(K)?re.delete(K):re.add(K),re})},[]),{data:N,isLoading:k,isError:C,refetch:M}=de({...Kr(),staleTime:6e4}),P=Ft({queries:h.map(K=>({..._e({path:{accountId:K.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),D=c.useMemo(()=>{const K=new Map;for(let U=0;U<h.length;U++){const re=h[U].accountId,je=(P[U]?.data?.items??[]).reduce((W,J)=>W+(J.unseenCount??0),0);K.set(re,je)}return K},[h,P]),O=c.useMemo(()=>h.filter((K,U)=>{const re=P[U];return re?.isError?!Ur(re.error):!1}),[h,P]),{freeText:E,tokens:S}=Rs(u.trim().toLowerCase(),d),{data:A,isFetching:L}=de({...Kr({query:{query:E,limit:$y}}),enabled:E.length>0,staleTime:3e4}),T=c.useMemo(()=>{const K=(N?.items??[]).map(sa);return(E?oy(K.filter(re=>Cu(re,E)),(A?.items??[]).map(sa)):K).filter(re=>(g==="all"||re.accountId===g)&&Nu(re,S))},[N,A,g,E,S]),F=c.useMemo(()=>iy(T),[T]),R=c.useMemo(()=>h.length<=1?[]:[{id:"all",label:"All",active:g==="all"},...h.map(K=>({id:K.accountId,label:K.email.split("@")[0]??K.email,count:D.get(K.accountId),active:g===K.accountId}))],[h,D,g]),$=c.useMemo(()=>e.filter(K=>K.muted?.value).length,[e]),z=c.useMemo(()=>Array.from(D.values()).reduce((K,U)=>K+U,0),[D]),V=c.useMemo(()=>{const K=Array.from(b).map(U=>Fy[U]).filter(U=>U!=null);return T.filter(U=>(p==="all"||U.category===p)&&K.every(re=>re(U))).map(U=>Eu(U,f))},[T,p,b,f]),{hits:ee,isLoading:X}=ku(),Q=c.useMemo(()=>{const K=new Map;for(const re of N?.items??[])K.set(re.messageId,re.threadId);const U=V.map(re=>K.get(re.id)).filter(re=>re!=null);return Iu(ee,U,f)},[ee,V,N,f]),le=c.useMemo(()=>{const K=ng(R.map(U=>({id:U.id,label:U.label,count:U.count,active:U.active})));return{categories:K.categories,filters:K.filters,sources:K.sources,sourcesNote:$>0?`+${$} muted`:void 0,selectedCategory:p,activeFilters:b,expanded:j,onExpandedChange:y,onSelectCategory:U=>x(U),onSelectSource:v,onToggleFilter:I,onClear:()=>{x("all"),v("all"),w(new Set)}}},[R,$,p,b,j,I]),ue=F.length===0&&g==="all"&&E.length===0,te=k?n.jsxs("div",{className:"h-full overflow-y-auto",children:[n.jsx(Oi,{}),n.jsx(Oi,{})]}):C?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[n.jsx(Gt,{className:"size-8 text-danger"}),n.jsx("p",{children:"Couldn't load your messages"}),n.jsxs("button",{type:"button",onClick:()=>M(),className:"flex items-center gap-1 text-accent underline text-xs",children:[n.jsx(Kl,{className:"size-3.5"}),"Try again"]})]}):ue?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[n.jsx(ut,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"You're caught up"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Nothing needs attention."})]}):n.jsx(Uu,{selectedMessageId:t,onOpen:K=>s?.(K),onDeleteMessages:i,commandsRef:a,onTriageContextChange:o,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[i?n.jsx(qu,{onMarkAsRead:l}):null,n.jsx("div",{className:"min-h-0 flex-1",children:n.jsx(Qi,{sections:F,Row:to,manageFocus:!1,briefCategory:p,onSelectBriefCategory:x,sources:R,sourcesNote:$>0?`+${$} muted`:void 0,onSelectSource:v,selectedThreadId:t,onSelectThread:s})})]})});return n.jsx($u,{title:"Daily brief",unreadCount:z,footer:m?n.jsx(Wl,{}):void 0,searchFilter:le,searchResults:V,searchLoading:k||L,relatedResults:Q,relatedLoading:X,onSelectSearchResult:r,children:n.jsxs("div",{className:"flex h-full flex-col",children:[O.map(K=>n.jsx(_y,{accountEmail:K.email,accountId:K.accountId},K.accountId)),n.jsx("div",{className:"min-h-0 flex-1",children:te})]})})}const By=10,Hu=e=>({q:e?.toLowerCase()??"",limit:By}),Ky=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(r=>r.normalizedEmail===s)};function Uy(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Pn(t,{month:"short",year:"numeric"})}function Wu(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const qy="We can't verify the sender of this email, which could mean it's from an insecure source.",Hy="We couldn't read this sender's address, so we can't confirm who really sent this message.";function Wy(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?Uy(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Wu(e.fromEmail)}}function Vy(e){return e?.flags?{vip:e.flags.vip?.value===!0,muted:e.flags.muted?.value===!0,blocked:e.flags.blocked?.value===!0,unsubscribed:e.flags.unsubscribed?.value===!0}:{}}function Qy(e,t){const s=t>0?t:void 0;if(Wu(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:Hy,similarCount:s};const r=e.authenticity;if(!r)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:qy};if(!r.dkimMismatch)return{verdict:"aligned",fromDomain:r.fromDomain,dkimDomain:r.dkimDomain,summary:r.dkimDomain?`We verified this message was really sent by ${r.fromDomain}.`:"Nothing looks unusual about this sender."};const a=r.fromDomain,o=r.dkimDomain,i=e.fromName&&e.fromName!==e.fromEmail?e.fromName:void 0,l=i?`The display name claims "${i}", but this message was actually sent from ${o??"another sender"} — not ${a}. Real senders use their own address.`:`This message claims to be from ${a}, but it was actually sent from ${o??"a different sender"}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:l,similarCount:s}}function Vu(e,t){const s=e?.fromEmail??null,r=e?.subject??"",{data:a,error:o}=de({...sl({query:Hu(s??void 0)}),enabled:!!s,staleTime:3e4}),i=Ky(a?.items,s??void 0),l=[r,s].filter(Boolean).join(" "),{data:u,isLoading:f,error:d}=de({...il({query:{query:l,limit:5}}),enabled:!!(e&&l.length>3),staleTime:6e4,retry:1});return{data:c.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(b=>b.messageId!==e.messageId).map(b=>({id:b.messageId,mailboxId:t!=null&&b.mailboxIds.includes(t)?t:b.mailboxIds[0]??"",fromName:b.fromName??"",subject:b.subject??"(No subject)",timeLabel:b.sentDate!=null?Lt(b.sentDate*1e3):"",matched:b.matchedChunkType})),g=Wy(e,i),v=Qy(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},x=Vy(i);return{sender:g,authenticity:v,category:p,flags:x,similar:h}},[e,i,u,t]),isSimilarLoading:f,similarError:d,similarErrorIsFatal:Ur(d),addressErrorIsFatal:Ur(o),addressId:i?.addressId,address:i}}function Yy(e,t){const s={...e??{}};for(const[r,a]of Object.entries(t))a==null?delete s[r]:s[r]={...a,setAt:a.setAt??Date.now()};return s}function Qu({addressId:e,senderEmail:t}){const s=ye(),{pushError:r}=Ve(),a=wf({query:Hu(t)}),{mutate:o,isPending:i}=ve({...ol(),onMutate:async u=>{const f=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,m=>m&&{...m,items:m.items.map(h=>h.addressId===u.path.addressId?{...h,flags:Yy(h.flags,f)}:h)}),{previous:d}},onError:(u,f,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),r({title:"Couldn't update sender preference",detail:st(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){ul(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 Gy=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Yu=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function Xy(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function Jy(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function Zy(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Gu(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const e0=["personal","newsletter","marketing","automated","transactional","social"],t0=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:r}=e;return t?s&&t===s?r?"notSpam":null:s?"markSpam":null:null},s0=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:r}=e;return t&&!s?"error":r?"loading":"ready"};function n0(){return n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(ut,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"h-8 rounded bg-surface"})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>n.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function r0({isOpen:e,current:t,onSelect:s,onCancel:r}){return e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:r,children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),n.jsx("div",{className:"mt-4 flex flex-col gap-1",children:e0.map(a=>n.jsxs("button",{type:"button",onClick:()=>s(a),className:`flex min-h-11 items-center justify-between rounded px-3 text-left text-sm capitalize transition-colors hover:bg-surface-raised ${a===t?"font-semibold text-accent":"text-fg"}`,children:[a,a===t&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"current"})]},a))}),n.jsx("div",{className:"mt-6 flex justify-end",children:n.jsx("button",{type:"button",onClick:r,className:"inline-flex min-h-11 items-center justify-center rounded border border-line px-4 text-sm font-medium transition-colors hover:bg-surface-raised",children:"Cancel"})})]})]}):null}function a0({thread:e,onClose:t,mailboxId:s,accountId:r,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:f}=Vu(e,s),[d,m]=c.useState(!1),[h,g]=c.useState(!1),v=e.fromEmail??void 0,{updateFlags:p,isPending:x}=Qu({addressId:i,senderEmail:v}),{junkMailboxId:b}=or(r),{inboxMailboxId:w}=Qa(r),{moveMessages:j}=Qt({mailboxId:s??"",threadId:e.threadId,accountId:r}),y=Js(),I=t0({mailboxId:s,junkMailboxId:b,inboxMailboxId:w}),N=c.useCallback(()=>{w&&j([e.messageId],w)},[w,j,e.messageId]),k=c.useCallback(()=>{b&&(Gu(y,{count:1,senderTrust:e.senderTrust,wasRescuable:Yu(e)}),j([e.messageId],b))},[b,j,e,y]),C=c.useCallback(()=>{},[]),M=c.useCallback(()=>{const R=o?.flags?.vip!==!0;p({vip:{value:R}})},[o?.flags?.vip,p]),P=c.useCallback(()=>{const R=o?.flags?.muted!==!0;p({muted:{value:R}})},[o?.flags?.muted,p]),D=c.useCallback(()=>{o?.flags?.blocked===!0?p({blocked:{value:!1}}):m(!0)},[o?.flags?.blocked,p]),O=c.useCallback(()=>{m(!1),p({blocked:{value:!0}})},[p]),E=c.useCallback(()=>{const R=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:R}})},[o?.flags?.unsubscribed,p]),S=c.useCallback(R=>{g(!1),p({category:{value:R}})},[p]),A=i!==void 0,L={onToggleVip:A?M:void 0,onToggleMute:A?P:void 0,onToggleBlock:A?D:void 0,onToggleUnsubscribe:A?E:void 0,onReclassify:A?()=>g(!0):void 0,onNotSpam:I==="notSpam"?N:void 0,onMarkSpam:I==="markSpam"?k:void 0},T=({mailboxId:R,messageId:$,className:z,ariaLabel:V,children:ee})=>n.jsx(pt,{to:"/mail/$mailboxId",params:{mailboxId:R},search:X=>({...X,selectedMessageId:$}),className:z,"aria-label":V,children:ee});if(!o)return n.jsx(n0,{});const F=s0({similarError:u,similarErrorIsFatal:f,isSimilarLoading:l});return n.jsxs(n.Fragment,{children:[n.jsx(Hl,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:C,actions:L,similarState:F,similarLinkComponent:T,className:"border-l-0 h-full w-full"}),n.jsx(Ra,{isOpen:d,title:"Block this sender?",description:`Messages from ${v??"this sender"} will never load images and will be flagged. You can undo this in Settings → Senders.`,confirmLabel:"Block sender",destructive:!0,isBusy:x,onConfirm:O,onCancel:()=>m(!1)}),n.jsx(r0,{isOpen:h,current:o.category.value,onSelect:S,onCancel:()=>g(!1)})]})}const Ms=({onClose:e,thread:t,mailboxId:s,accountId:r,hideCloseButton:a})=>t?n.jsx(a0,{thread:t,onClose:e,mailboxId:s,accountId:r,hideCloseButton:a}):n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(ut,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[n.jsx(ut,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),Fr="Open a message first",so=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:r,onReply:a,onReplyAll:o,onForward:i,onDelete:l,canDelete:u,onToggleStar:f,isStarred:d,moveContext:m})=>{const[h,g]=c.useState(null),v=u??e,p=x=>()=>g(x);return n.jsx(yh,{hasThread:e,isStarred:d,onUnavailable:x=>g(Fr),unavailableHint:h,replyTitle:`Reply ${fs("reply")}`,replyAllTitle:`Reply all ${fs("replyAll")}`,forwardTitle:`Forward ${fs("forward")}`,deleteTitle:`Move to Trash ${fs("delete")}`,flagTitle:`Star ${fs("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:v?l:p(Fr),onToggleStar:f,onMove:p(Fr),moveSlot:m?n.jsx(dn,{accountId:m.accountId,currentMailboxId:m.currentMailboxId,onMove:m.onMove,label:"Move to mailbox"}):void 0,children:n.jsx(vh,{open:t,enabled:s,onToggle:r})})},Xu=()=>{const e=ye();return c.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])},Qs=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=t??e?.mailboxId,o=s??e?.accountConfigId,i=Xu(),{deleteMessages:l}=Yt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{moveMessages:u}=Qt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{toggleStar:f}=Wa({threadId:e?.threadId??"",mailboxId:a??""}),d=c.useCallback(()=>{e&&l(i(e))},[e,i,l]),m=c.useCallback(x=>{e&&u(i(e),x)},[e,i,u]),h=c.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[g,v]=c.useState(null),p=c.useCallback(()=>v(null),[]);return{mailboxId:a,accountId:o,isStarred:e?.hasStars,deleteThread:d,moveThread:m,toggleStar:h,composeRequest:g,requestCompose:v,clearComposeRequest:p}},$s={action:null,nextPrefix:null,preventDefault:!1},o0={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},i0={j:{action:"focusNext"},k:{action:"focusPrevious"},arrowdown:{action:"focusNext"},arrowup:{action:"focusPrevious"},home:{action:"focusFirst"},end:{action:"focusLast"},enter:{action:"openFocused"}," ":{action:"toggleSelect"},delete:{action:"delete"},backspace:{action:"delete"},u:{action:"toggleRead"},x:{action:"toggleSelect"},r:{action:"reply"},a:{action:"replyAll"},f:{action:"forward"},"#":{action:"delete"},s:{action:"toggleStar"},m:{action:"muteSender"},b:{action:"blockSender"},v:{action:"vipSender"},"!":{action:"markJunk"},i:{action:"toggleIntelligence"},d:{action:"toggleDensity"},"/":{action:"focusSearch"},c:{action:"compose"},"?":{action:"help"}};function l0(e,t){const s=e.key.toLowerCase(),r=e.metaKey||e.ctrlKey;if(e.inEditable)return{...$s,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...$s,nextPrefix:t==="g"?null:t};if(r&&s==="n")return{action:"compose",nextPrefix:null,preventDefault:!0};if(r&&s==="a")return{action:"selectAll",nextPrefix:null,preventDefault:!0};if(r)return{...$s,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=o0[s===","?",":s]??null;return{action:i,nextPrefix:null,preventDefault:i!==null}}if(s==="g"&&!e.shiftKey)return{action:null,nextPrefix:"g",preventDefault:!0};if(e.shiftKey){const o=s==="j"||s==="arrowdown";if(o||(s==="k"||s==="arrowup"))return{action:o?"extendSelectDown":"extendSelectUp",nextPrefix:null,preventDefault:!0}}const a=i0[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?$s:{action:a.action,nextPrefix:null,preventDefault:!0}}return $s}function c0(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const u0="data-message-row",d0='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function f0(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(d0);return t?!t.hasAttribute(u0):!1}function m0({handlers:e,enabled:t=!0,sequenceTimeoutMs:s=1e3}){const r=c.useRef(e);r.current=e;const a=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{if(!t)return;const i=()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},l=u=>{const f=l0({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:c0(u.target),onControl:f0(u.target)},a.current);if(i(),a.current=f.nextPrefix,f.nextPrefix!==null&&(o.current=setTimeout(()=>{a.current=null,o.current=null},s)),f.action===null)return;const d=r.current[f.action];d&&(f.preventDefault&&u.preventDefault(),d())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l),i(),a.current=null}},[t,s])}const Pi=(e,t,s)=>{if(!t)return null;const r=e.indexOf(t);if(r===-1)return null;const a=s==="next"?r+1:r-1;return a<0||a>=e.length?null:e[a]},no=()=>{const[e,t]=c.useState(void 0),[s,r]=c.useState([]),[a,o]=c.useState([]),i=c.useRef(null),[l,u]=c.useState(!1),[f,d]=c.useState(!1),m=c.useCallback(h=>{t(h.focusedMessageId),r(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:m,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:l,blocksKeyboard:f}},ro=({context:e,orderedIds:t,selectedMessageId:s,enabled:r=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:l,blocksKeyboard:u}=e,f=c.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return m0({enabled:r&&!u,handlers:{...l?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:f,...o}}),{goBack:f,nextMessageId:Pi(t,s,"next")??void 0,previousMessageId:Pi(t,s,"previous")??void 0}};function h0(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function Ju(e,t){if(e)return h0(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const Zu=c.createContext(null);function cr(){const e=c.useContext(Zu);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function p0({selectedMessageId:e,children:t}){const s=Oe(),{searchInput:r}=Ce(),{selectedThreadId:a,selectedMailboxId:o}=vs({strict:!1}),{data:i}=de({...Kr(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(P=>P.messageId===e)},[i,e]),u=c.useMemo(()=>Ju(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),f=c.useCallback(P=>{s({to:"/mail",search:D=>({...D,selectedMessageId:P,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),d=c.useCallback(P=>{s({to:"/mail",search:D=>({...D,q:r||void 0,selectedMessageId:P.id,selectedThreadId:P.threadId,selectedMailboxId:P.mailboxId})})},[s,r]),m=c.useCallback(P=>{e&&P.includes(e)&&s({to:"/mail",search:D=>({...D,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=Qs({thread:l,onAfterOptimisticRemove:m}),g=c.useCallback(()=>{s({to:"/mail",search:P=>({...P,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),v=no(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:x}=Yt({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:m}),{toggleReadFor:b}=rr({mailboxId:l?.mailboxId??"",messages:p}),w=c.useCallback(P=>b(P,!0),[b]),j=v.focusedMessageId,I=c.useMemo(()=>i?.items.find(P=>P.messageId===j),[i,j])??l,N=Qs({thread:I}),{nextMessageId:k,previousMessageId:C}=ro({context:v,orderedIds:v.orderedIds,selectedMessageId:e,onClose:g,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{v.listCommandsRef.current?.requestDelete()||N.deleteThread()},toggleStar:N.toggleStar,toggleRead:()=>{const P=v.selectedIds.length>0?v.selectedIds:I?[I.messageId]:[];P.length!==0&&b(P,!(I?.isRead??!1))},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),M={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:f,onSelectSearchResult:d,onCloseThread:g,actions:h,triage:v,onDeleteMessages:x,onMarkMessagesRead:w,nextMessageId:k,previousMessageId:C};return n.jsx(Zu.Provider,{value:M,children:t})}function ed(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:r,onDeleteMessages:a,onMarkMessagesRead:o}=cr(),{accounts:i}=Ce();return n.jsx(zy,{accounts:i,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:r.listCommandsRef,onTriageContextChange:r.onTriageContextChange,onDeleteMessages:a,onMarkMessagesRead:o})}function g0(){const{conversation:e,actions:t}=cr(),{intelligenceOpen:s,onToggleIntelligence:r}=Ce(),a=Ss()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(so,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Es,{})})]})}function x0(){const{selectedThread:e}=cr(),{onToggleIntelligence:t}=Ce();return n.jsx(Ms,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function b0(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:r,nextMessageId:a,previousMessageId:o}=cr(),{intelligenceOpen:i,onToggleIntelligence:l}=Ce();return t?n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:r,onOpenIntelligence:l,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:i}),n.jsx(Ua,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:l,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(ed,{})})}const Fs=Object.assign(p0,{List:ed,Reading:g0,Intelligence:x0,Phone:b0}),v0=()=>al({query:{starred:!0,order:"desc"}});function td(){const{data:e,isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=Sc({queryKey:v0(),queryFn:async({pageParam:f})=>{const{data:d}=await jf({query:{starred:!0,order:"desc",continuationToken:f},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:f=>f.continuationToken,staleTime:6e4});return{threads:c.useMemo(()=>(e?.pages??[]).flatMap(f=>f.items??[]),[e]),isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}}const y0=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function sd({title:e,unreadCount:t,preset:s,selectedCategory:r,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:l,onClearFilters:u,children:f,footer:d,searchResults:m,searchLoading:h,relatedResults:g,relatedLoading:v,onSelectSearchResult:p,searchResultsLabel:x,relatedResultsLabel:b,searchResultsInBody:w}){const[j,y]=c.useState(!1),I={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:r,activeFilters:a,expanded:j,onExpandedChange:y,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return n.jsx($u,{title:e,unreadCount:t,footer:d,searchFilter:I,searchResults:m,searchLoading:h,relatedResults:g,relatedLoading:v,onSelectSearchResult:p,searchResultsLabel:x,relatedResultsLabel:b,searchResultsInBody:w,children:n.jsx(da,{...I,children:f})})}const w0={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function j0({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:r,onDeleteMessages:a,onMarkMessagesRead:o}){const{searchQuery:i,resultFolderIndex:l}=Ce(),u=Ts(),f=Ot(),[d,m]=c.useState("all"),[h,g]=c.useState(new Set),v=c.useCallback(T=>{g(F=>{const R=new Set(F);return R.has(T)?R.delete(T):R.add(T),R})},[]),p=c.useCallback(()=>{m("all"),g(new Set)},[]),{threads:x,isLoading:b,isError:w,error:j,refetch:y,fetchNextPage:I,hasNextPage:N,isFetchingNextPage:k}=td(),{freeText:C,tokens:M}=Rs(i.trim().toLowerCase(),u),P=c.useMemo(()=>{const T=Array.from(h).map(F=>w0[F]).filter(F=>F!=null);return y0(x).map(sa).filter(F=>(d==="all"||F.category===d)&&T.every(R=>R(F))&&(!C||Cu(F,C))&&Nu(F,M))},[x,d,h,C,M]),D=c.useMemo(()=>ag(),[]),O=c.useMemo(()=>P.map(T=>Eu(T,l)),[P,l]),E=c.useMemo(()=>P.filter(T=>!T.isRead).length,[P]),S=b?"loading":w?"error":P.length===0?"empty":"ready",A=c.useCallback(()=>{const T=va(ba());window.open(T,"_blank","noopener,noreferrer")},[]),L=n.jsx(Uu,{selectedMessageId:e,onOpen:T=>t?.(T),onDeleteMessages:a,commandsRef:s,onTriageContextChange:r,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a?n.jsx(qu,{onMarkAsRead:o}):null,n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.jsx("div",{className:"divide-y divide-line",children:P.map(T=>n.jsx(to,{thread:T,active:T.id===e,onClick:()=>t?.(T.id)},T.id))}),N?n.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>I(),disabled:k,children:k?"Loading…":"Load more"}):null]})]})});return n.jsx(sd,{title:"Starred",unreadCount:E,preset:D,selectedCategory:d,activeFilters:h,onSelectCategory:m,onToggleFilter:v,onClearFilters:p,searchResults:O,searchLoading:b,onSelectSearchResult:T=>t?.(T.id),children:n.jsx(Zl,{listTitle:"Starred",sections:[{id:"flagged",threads:P}],flatList:!0,hideHeader:!0,listState:S,searchQuery:C?i:void 0,errorMessage:w?vl(j):void 0,onRetry:()=>y(),onReportError:A,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:f,listBody:S==="ready"?L:void 0})})}const nd=c.createContext(null);function ur(){const e=c.useContext(nd);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function S0({selectedMessageId:e,children:t}){const s=Oe(),{threads:r}=td(),a=c.useMemo(()=>{if(e)return r.find(y=>y.messageId===e)},[r,e]),o=c.useCallback(y=>{s({to:"/mail/flagged",search:I=>({...I,selectedMessageId:y})})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:y=>({...y,selectedMessageId:void 0})})},[s]),l=c.useCallback(y=>{e&&y.includes(e)&&i()},[e,i]),u=Qs({thread:a,onAfterOptimisticRemove:l}),f=no(),{deleteMessages:d}=Yt({mailboxId:a?.mailboxId??"",messages:r,onAfterOptimisticRemove:l}),{toggleReadFor:m}=rr({mailboxId:a?.mailboxId??"",messages:r}),h=c.useCallback(y=>m(y,!0),[m]),g=f.focusedMessageId,p=c.useMemo(()=>r.find(y=>y.messageId===g),[r,g])??a,x=Qs({thread:p}),{nextMessageId:b,previousMessageId:w}=ro({context:f,orderedIds:f.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{f.listCommandsRef.current?.requestDelete()||x.deleteThread()},toggleStar:x.toggleStar,toggleRead:()=>{const y=f.selectedIds.length>0?f.selectedIds:p?[p.messageId]:[];y.length!==0&&m(y,!(p?.isRead??!1))},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),j={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:f,onDeleteMessages:d,onMarkMessagesRead:h,nextMessageId:b,previousMessageId:w};return n.jsx(nd.Provider,{value:j,children:t})}function rd(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:r,onMarkMessagesRead:a}=ur();return n.jsx(j0,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:r,onMarkMessagesRead:a})}function k0(){const{selectedThread:e,actions:t}=ur(),{intelligenceOpen:s,onToggleIntelligence:r}=Ce(),a=Ss()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(so,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Es,{})})]})}function C0(){const{selectedThread:e}=ur(),{onToggleIntelligence:t}=Ce();return n.jsx(Ms,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function N0(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:r,previousMessageId:a}=ur(),{intelligenceOpen:o,onToggleIntelligence:i}=Ce();return e?n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:i,onSwipeNext:r?()=>s(r):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:o}),n.jsx(Ua,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:i,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(rd,{})})}const _s=Object.assign(S0,{List:rd,Reading:k0,Intelligence:C0,Phone:N0}),E0={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},I0=()=>{const e=c.useRef(!1);return c.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector("[data-slate-editor]")?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},T0=()=>{const{state:e,closeCompose:t}=Dt(),s=I0(),[r,a]=c.useState(!1),{isError:o,error:i,refetch:l}=de({...xt(),staleTime:1/0}),u=c.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),f=c.useCallback(()=>{a(!1),t()},[t]),d=c.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const m=E0[e.mode]??"New Message";return n.jsxs(Je.Root,{open:e.isOpen,onOpenChange:u,children:[n.jsxs(Je.Portal,{children:[n.jsx(Je.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Je.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[n.jsx(Je.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),n.jsx(Je.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:m}),o?n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(Pt,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):n.jsx("div",{className:"flex-1 overflow-hidden",children:n.jsx(qa,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),r&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50",children:n.jsxs("div",{className:"mx-4 w-full max-w-sm rounded-xl bg-canvas p-6 shadow-xl",children:[n.jsx("h3",{className:"text-lg font-semibold",children:"Discard draft?"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Your message has unsaved content. Are you sure you want to discard it?"}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:d,className:"rounded-md px-4 py-2 text-sm font-medium hover:bg-surface-raised transition-colors",children:"Keep editing"}),n.jsx("button",{type:"button",onClick:f,className:"rounded-md bg-danger px-4 py-2 text-sm font-medium text-canvas hover:bg-danger/90 transition-colors",children:"Discard"})]})]})})]})},R0={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},ad=()=>{const{state:e,closeCompose:t}=Dt(),s=Ot(),{isError:r,error:a,refetch:o}=de({...xt(),staleTime:1/0});if(!s)return n.jsx(T0,{});if(!e.isOpen)return null;const i=R0[e.mode]??"New Message",l=n.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[n.jsx("div",{className:"flex items-center gap-2 min-w-0",children:n.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:n.jsx(We,{className:"size-5"})})]});return r?n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[l,n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(Pt,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[l,n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:n.jsx(qa,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function M0(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:Lt(e.updatedAt),isRead:!0}}function A0(e){return{id:e.messageId,accountId:e.accountConfigId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function D0({outboxMessages:e,accountId:t,imapThreads:s}){const r=e.filter(i=>i.status==="draft"&&i.accountId===t).map(M0),a=s.map(A0),o=[];return r.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:r}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function ao(){const e=Ss();return!e||e.showNavPane?null:n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ca,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const O0=({label:e,count:t})=>n.jsxs("div",{className:"sticky top-0 z-10 flex items-baseline justify-between border-b border-line bg-surface-sunken px-row-inset py-1",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:t})]}),P0=({row:e,isSelected:t,onOpen:s,onDelete:r,isDeleting:a})=>n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:H("group",tn({active:t})),children:[n.jsx(Gi,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),n.jsx(Hs,{thread:e}),n.jsx("div",{className:"flex items-center gap-1 shrink-0",children:n.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),r(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:n.jsx(rt,{className:"size-3.5"})})})]}),L0=({row:e,isSelected:t,onOpen:s})=>{const r=!e.isRead;return n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:H("group",tn({active:t})),children:[r&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"sm"}),n.jsx(Hs,{thread:e})]})};function $0({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:r,title:a,unreadCount:o}){const{openCompose:i,state:l}=Dt(),u=Oe(),f=ye(),{data:d}=de(qn()),m=c.useMemo(()=>D0({outboxMessages:d?.items??[],accountId:t,imapThreads:r}),[d?.items,t,r]),h=ve({...Hn(),onSuccess:()=>{f.invalidateQueries({queryKey:ka()})}}),g=b=>{h.mutate({path:{outboxMessageId:b}})},v=b=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:b})},p=b=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:b}})},x=m.length===0;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(ao,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:a}),(o??0)>0&&n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:[o," unread"]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:x?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[n.jsx(ca,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):m.map(b=>n.jsxs("div",{children:[b.label&&n.jsx(O0,{label:b.label,count:b.threads.length}),n.jsx("div",{className:"divide-y divide-line",children:b.threads.map(w=>b.id==="remit-drafts"?n.jsx(P0,{row:w,isSelected:l.isOpen&&w.id===l.outboxMessageId,onOpen:v,onDelete:g,isDeleting:h.isPending},w.id):n.jsx(L0,{row:w,isSelected:w.id===s,onOpen:p},w.id))})]},b.id))})]})}function F0(e,t,s){const r=new Array(e);return new Proxy(r,{get(a,o,i){if(typeof o=="string"){const l=o.charCodeAt(0);if(l>=48&&l<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let f=a[u];if(!f){const d=t[u*2];f=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return f}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function ds(e,t,s){let r=s.initialDeps??[],a,o=!0;function i(){const l=e();return(l.length!==r.length||l.some((f,d)=>r[d]!==f))&&(r=l,a=t(...l),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=l=>{r=l},i}function Li(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _0=(e,t)=>Math.abs(e-t)<1.01,z0=(e,t,s)=>{let r;return function(...a){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,a),s)}};let zs;const _r=()=>{if(zs!==void 0)return zs;if(typeof navigator>"u")return zs=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zs=!0;const e=navigator.maxTouchPoints;return zs=navigator.platform==="MacIntel"&&e!==void 0&&e>0},$i=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},B0=e=>e,K0=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,a=new Array(r);for(let o=0;o<r;o++)a[o]=t+o;return a},U0=(e,t)=>{const s=e.scrollElement;if(!s)return;const r=e.targetWindow;if(!r)return;const a=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(a($i(s)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u?.borderBoxSize){const f=u.borderBoxSize[0];if(f){a({width:f.inlineSize,height:f.blockSize});return}}a($i(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},_n={passive:!0},q0=typeof window>"u"?!0:"onscrollend"in window,H0=(e,t,s)=>{const r=e.scrollElement;if(!r)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&q0;let i=0;const l=o?null:z0(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=m=>()=>{i=s(r),l?.(),t(i,m)},f=u(!0),d=u(!1);return r.addEventListener("scroll",f,_n),o&&r.addEventListener("scrollend",d,_n),()=>{r.removeEventListener("scroll",f),o&&r.removeEventListener("scrollend",d)}},W0=(e,t)=>H0(e,t,s=>{const{horizontal:r,isRtl:a}=e.options;return r?s.scrollLeft*(a&&-1||1):s.scrollTop}),V0=(e,t,s)=>{if(s.options.useCachedMeasurements){const r=s.indexFromElement(e),a=s.options.getItemKey(r);return s.itemSizeCache.get(a)??s.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[s.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=s.indexFromElement(e),a=s.options.getItemKey(r),o=s.itemSizeCache.get(a);if(o!==void 0)return o}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},Q0=(e,{adjustments:t=0,behavior:s},r)=>{var a,o;(o=(a=r.scrollElement)==null?void 0:a.scrollTo)==null||o.call(a,{[r.options.horizontal?"left":"top"]:e+t,behavior:s})},Y0=Q0;class G0{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,r,a;return((a=(r=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:r.now)==null?void 0:a.call(r))??Date.now()},this.observer=(()=>{let s=null;const r=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const l=o.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[f,d]of this.elementsCache)if(d===l){this.elementsCache.delete(f);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=r())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=r())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=r())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var r,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:B0,rangeExtractor:K0,onChange:()=>{},measureElement:V0,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in s){const g=s[h];g!==void 0&&(o[h]=g)}const i=this.options;let l=null,u=null,f=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,g=o.count,v=this.getMeasurements(),p=h>0?((r=v[0])==null?void 0:r.key)??i.getItemKey(0):null,x=h>0?((a=v[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(g!==h||h>0&&g>0&&(o.getItemKey(0)!==p||o.getItemKey(g-1)!==x)){f=!0;const j=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??v[0]:null;j&&(l=[j.key,this.getScrollOffset()-j.start]);const y=o.followOnAppend===!0?"auto":o.followOnAppend||null;y&&g>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(g-1)!==x)&&(u=y)}}this.options=o,f&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,m=0;if(l&&this.scrollOffset!==null){const[h,g]=l,v=this.getMeasurements(),{count:p,getItemKey:x}=this.options;let b=0;for(;b<p&&x(b)!==h;)b++;if(b<p){const w=v[b];if(w){const j=w.start+g;j!==this.scrollOffset&&(m=j-this.scrollOffset,this.scrollOffset=j,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,u,m])},this.notify=s=>{var r,a;(a=(r=this.options).onChange)==null||a.call(r,this,s)},this.maybeNotify=ds(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===o?this.scrollDirection:l<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!_r()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,_n),o.addEventListener("touchend",l,_n),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,l,u]=a;o!==null&&!l&&(_r()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),r=this.getMaxScrollOffset();if(s<0||s>r)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=ds(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,r,a,o,i,l,u,f)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f}),{key:!1}),this.getMeasurements=ds(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f},d)=>{const m=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const b of this.laneAssignments.keys())b>=s&&this.laneAssignments.delete(b);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(b=>{this.itemSizeCache.set(b.key,b.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),l===1){const b=s*2;let w=this._flatMeasurements;if(!w||w.length<b){const I=new Float64Array(b);w&&h>0&&I.set(w.subarray(0,h*2)),w=I,this._flatMeasurements=w}let j;if(h===0)j=r+a;else{const I=h-1;j=w[I*2]+w[I*2+1]+f}for(let I=h;I<s;I++){const N=o(I),k=m.get(N),C=typeof k=="number"?k:this.options.estimateSize(I);w[I*2]=j,w[I*2+1]=C,j+=C+f}const y=F0(s,w,o);return this.measurementsCache=y,y}const g=this.measurementsCache.slice(0,h),v=new Array(l).fill(void 0),p=new Float64Array(l);let x=0;for(let b=0;b<h;b++){const w=g[b];w&&(v[w.lane]===void 0&&x++,v[w.lane]=b,p[w.lane]=w.end)}for(let b=h;b<s;b++){const w=o(b),j=this.laneAssignments.get(b);let y,I;const N=u==="estimate"||m.has(w);if(j!==void 0&&this.options.lanes>1){y=j;const P=v[y],D=P!==void 0?g[P]:void 0;I=D?D.end+f:r+a}else if(x===l){let P=0,D=p[0],O=v[0];for(let E=1;E<l;E++){const S=p[E];(S<D||S===D&&v[E]<O)&&(P=E,D=S,O=v[E])}y=P,I=D+f,N&&this.laneAssignments.set(b,y)}else y=b%this.options.lanes,I=r+a,N&&this.laneAssignments.set(b,y);const k=m.get(w),C=typeof k=="number"?k:this.options.estimateSize(b),M=I+C;g[b]={index:b,start:I,size:C,end:M,key:w,lane:y},v[y]===void 0&&x++,v[y]=b,p[y]=M}return this.measurementsCache=g,g},{key:!1,debug:()=>this.options.debug}),this.calculateRange=ds(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,r,a,o)=>s.length===0||r===0?(this.range=null,null):(this.range=J0(s,r,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ds(()=>{let s=null,r=null;const a=this.calculateRange();return a&&(s=a.startIndex,r=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,r]},(s,r,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:r,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const r=this.options.indexAttribute,a=s.getAttribute(r);return a?parseInt(a,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),l=Math.min(this.options.count-1,a+o);return s>=i&&s<=l}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const r=this.indexFromElement(s),a=this.options.getItemKey(r),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,r)=>{var a,o;if(s<0||s>=this.options.count)return;let i,l,u;const f=this._flatMeasurements;if(this.options.lanes===1&&f!==null)u=this.options.getItemKey(s),l=f[s*2],i=f[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,l=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,m=r-d;if(m!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,g=h?this.getTotalSize():0,v=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:l,size:i,end:l+i,lane:0},m,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,r),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-g):v&&this.applyScrollAdjustment(m),this.notify(!1)}},this.getVirtualItems=ds(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,r)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const l=s[o],u=r[l];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const r=this.getMeasurements();if(r.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=od(0,r.length-1,o?l=>a[l*2]:l=>Li(r[l]).start,s);return Li(r[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,r,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=s>=i+o?"end":"start"),r==="center"?s+=(a-o)/2:r==="end"&&(s-=o);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,r="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(r==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)r="end";else if(i.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,i.size),r]},this.scrollToOffset=(s,{align:r="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,r),i=this.now();this.scrollState={index:null,align:r,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:r="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,r);if(!o)return;const[i,l]=o,u=this.now();this.scrollState={index:s,align:l,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:r="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const r=this.getMeasurements();let a;if(r.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=r[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&o.some(l=>l===null);){const l=r[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}a=Math.max(...o.filter(l=>l!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const r=this.getMeasurements();for(const a of r)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:r,behavior:a})=>{this._intendedScrollOffset=s+(r??0),this.options.scrollToFn(s,{behavior:a,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&(_r()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=r?r[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&_0(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),f=this.scrollState.behavior==="smooth"&&u>l;this.scrollState.lastTargetOffset=a,f||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:f?"smooth":"auto"})}this.scheduleScrollReconcile()}}const od=(e,t,s,r)=>{for(;e<=t;){const a=(e+t)/2|0,o=s(a);if(o<r)e=a+1;else if(o>r)t=a-1;else return a}return e>0?e-1:0};function X0(e,t,s){let r=0;for(;r<=t;){const a=(r+t)/2|0,o=e[a*2];if(o<s)r=a+1;else if(o>s)t=a-1;else return a}return r>0?r-1:0}function J0(e,t,s,r,a){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&a!==null){const f=X0(a,o,s);let d=f;const m=s+t;for(;d<o&&a[d*2]+a[d*2+1]<m;)d++;return{startIndex:f,endIndex:d}}let l=od(0,o,f=>e[f].start,s),u=l;if(r===1)for(;u<o&&e[u].end<s+t;)u++;else if(r>1){const f=Array(r).fill(0);for(;u<o&&f.some(m=>m<s+t);){const m=e[u];f[m.lane]=m.end,u++}const d=Array(r).fill(s+t);for(;l>=0&&d.some(m=>m>=s);){const m=e[l];d[m.lane]=m.start,l--}l=Math.max(0,l-l%r),u=Math.min(o,u+(r-1-u%r))}return{startIndex:l,endIndex:u}}const zr=typeof document<"u"?c.useLayoutEffect:c.useEffect;function Z0({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...r}){const a=c.useReducer(f=>f+1,0)[1],o=c.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=f=>{const d=o.current;if(!d.enabled||!d.container)return;const m=f.getTotalSize();if(m!==d.lastSize){d.lastSize=m;const b=f.options.horizontal?"width":"height";d.container.style[b]=`${m}px`}const h=!!f.options.horizontal,g=d.mode==="transform",v=h?"left":"top",p=f.options.scrollMargin,x=f.getVirtualItems();for(const b of x){const w=b.start-p,j=f.elementsCache.get(b.key);j&&d.lastPositions.get(j)!==w&&(d.lastPositions.set(j,w),g?j.style.transform=h?`translate3d(${w}px, 0, 0)`:`translate3d(0, ${w}px, 0)`:j.style[v]=`${w}px`)}},l={...r,onChange:(f,d)=>{var m;const h=o.current;let g=!0;if(h.enabled){i(f);const v=f.range,p=h.prevRange;g=!p||p.isScrolling!==f.isScrolling||p.startIndex!==v?.startIndex||p.endIndex!==v?.endIndex,g&&(h.prevRange=v?{startIndex:v.startIndex,endIndex:v.endIndex,isScrolling:f.isScrolling}:null)}g&&(e&&d?ha.flushSync(a):a()),(m=r.onChange)==null||m.call(r,f,d)}},[u]=c.useState(()=>{const f=new G0(l);return Object.assign(f,{containerRef:d=>{const m=o.current;if(m.container=d,m.lastSize=null,d&&m.enabled){const h=f.getTotalSize();m.lastSize=h;const g=f.options.horizontal?"width":"height";d.style[g]=`${h}px`}}})});return u.setOptions(l),zr(()=>u._didMount(),[]),zr(()=>u._willUpdate()),zr(()=>{i(u)}),u}function ew(e){return Z0({observeElementRect:U0,observeElementOffset:W0,scrollToFn:Y0,...e})}const tw={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},id={delete:"moved to Trash",move:"moved",markRead:"marked as read"},ld={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},sw={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},nw={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},rw=(e,t,s)=>tw[e](ct(t),ct(s)),Fi=(e,t)=>`${ct(t)} ${id[e]}. Your mail server is still catching up.`,aw=(e,t,s)=>`${ct(t)} ${id[e]}. ${ct(s)} ${ld[e]}.`,ow=(e,t)=>t>0?`Stopped after ${ct(t)} — some messages ${ld[e]}`:sw[e],iw=e=>nw[e],lw=e=>e==="delete"?"danger":"info",cd=100,zn=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),cw=(e,t=cd)=>{if(e.length===0)return[];const s=[];for(let r=0;r<e.length;r+=t)s.push(e.slice(r,r+t));return s},uw=async(e,t,s,r)=>{const a=cw(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(r())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const f=a[u],d=await zn(t(f));if(!d.ok)return l.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:l,cancelled:!1,error:d.error};i+=f.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},dw=async(e,t,s,r,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await zn(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const f=u.value;if(f.ids.length>0){const d=await zn(s(f.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=f.ids.length,r({done:o,total:t})}l=f.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},fw=e=>({done:e.done,total:Math.max(e.total,e.done)}),mw=async(e,t,s)=>{let r=0,a;do{if(s())return{total:r,cancelled:!0};const o=await zn(e(a));if(!o.ok)return{total:r,cancelled:!1,error:o.error};const i=o.value;r+=i.ids.length,t(r),a=i.continuationToken}while(a);return{total:r,cancelled:!1}},hw=e=>e.failedIds.length>0?{exit:!1,retryIds:e.failedIds}:e.cancelled||e.error?{exit:!1,retryIds:[]}:{exit:!0,retryIds:[]},pw=100,gw=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],xw=({mailboxId:e,accountId:t,enabled:s,predicateKey:r,searchQuery:a})=>{const[o,i]=c.useState({kind:"idle"}),[l,u]=c.useState(void 0),[f,d]=c.useState(void 0),m=c.useRef(!1),h=ye(),{pushError:g}=Ve();c.useEffect(()=>{m.current=!0,i({kind:"idle"})},[s,r]);const v=c.useRef(a);v.current=a;const p=c.useCallback(async N=>{const{data:k}=await dl({path:{mailboxId:e},query:{...v.current,continuationToken:N,limit:pw},throwOnError:!0});return{ids:(k.items??[]).map(C=>C.messageId),continuationToken:k.continuationToken}},[e]),x=c.useCallback(N=>async k=>{if(N.kind==="move"){const{data:M}=await Sf({body:{messageIds:k,destinationMailboxId:N.destinationMailboxId},throwOnError:!0});return M}if(N.kind==="markRead"){const{data:M}=await kf({body:{messageIds:k,isRead:!0},throwOnError:!0});return M}const{data:C}=await Cf({body:{messageIds:k},throwOnError:!0});return C},[]),b=c.useCallback(N=>{yt(h,vt(gw(N,e))),t&&h.invalidateQueries({queryKey:Jt({path:{accountId:t}})})},[h,e,t]),w=c.useCallback(()=>{m.current=!1,i({kind:"counting",countSoFar:0}),mw(p,N=>i({kind:"counting",countSoFar:N}),()=>m.current).then(N=>{if(N.error){g(Vt("Couldn't count matching messages","The count didn't finish.",N.error)),i({kind:"idle"});return}if(N.cancelled){i({kind:"idle"});return}i({kind:"escalated",total:N.total})})},[p,g]),j=c.useCallback(()=>{m.current=!0},[]),y=c.useCallback(()=>{m.current=!0,i({kind:"idle"})},[]),I=c.useCallback(async(N,k)=>{m.current=!1,u(N);const C=D=>d(fw(D)),M=x(N),P=k!==void 0?await uw(k,M,C,()=>m.current):await dw(p,o.kind==="escalated"?o.total:0,M,C,()=>m.current);return u(void 0),d(void 0),i({kind:"idle"}),P.error&&g(Vt(ow(N.kind,P.done),iw(N.kind),P.error)),P.done>0&&b(N),P},[x,p,o,g,b]);return{phase:o,escalate:w,stop:j,clear:y,isRunning:l!==void 0,runningAction:l,progress:f,runAction:I}},ud=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",bw=e=>`Select all ${ud(e)}`,vw=(e,t)=>`All ${ct(t)} ${ud(e)} selected`,yw=e=>e.isRunning?"running":e.isCounting?"counting":e.isEscalated?"escalated":"idle",ww=2,jw=(e,t,s=!1)=>e>=ww||t!=="idle"||s,dd=(e,t,s)=>{const r=ve(ll()),{mutate:a,reset:o}=r,[i,l]=c.useState(!1),u=c.useMemo(()=>qf(s),[s]),f=c.useCallback(()=>{!e||!t||(l(!1),a({path:{accountId:e},body:qr({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=c.useCallback(()=>{l(!1),o()},[o]),m=r.data,h=m?.semanticUnavailable===!0&&!i&&u.length>0;c.useEffect(()=>{!h||!e||(l(!0),a({path:{accountId:e},body:qr(Hf(u))}))},[h,e,u,a]);const g=i||(m?.semanticUnavailable??!1),v=r.isPending||h,p=i?{matchOperator:"Or",literalClauses:Wf(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:f,reset:d,matchedCount:v?void 0:m?.matchedCount,messageIds:v?void 0:m?.messageIds,semanticUnavailable:g,senderFallback:i,senders:u,matchPredicate:p,isPending:v,isError:r.isError,error:r.error}},Sw=({entry:e,hasSeed:t,previewStatus:s,matchedCount:r})=>{if(e==="something-else"&&!t)return{kind:"something-else"};if(s==="error")return{kind:"error"};if(s!=="success")return{kind:"widening"};const a=r??0;return{kind:"organize",matchedCount:a,fallback:a===0}};function fd({accountId:e,selectedMessageIds:t,seedCount:s,semanticUnavailable:r=!1,senders:a=[],seedMailboxId:o,seedScope:i,onClose:l}){const u=t[0],f=r&&a.length>0,[d]=c.useState(()=>Vf({anchorMessageId:u,semanticUnavailable:r,senders:a,selectionCount:t.length,seedMailboxId:o,seedScope:i})),{rule:m,handlers:h}=Du({initialRule:d,widenAnchorCount:t.length}),{data:g}=de({..._e({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),v=c.useMemo(()=>Zs(g?.items??[]).map(O=>({id:O.mailboxId,label:Vn(O.fullPath)})),[g?.items]),{labels:p}=kl(e),x=c.useMemo(()=>p.map(O=>({id:O.labelId,name:O.name,color:O.color})),[p]),{createLabel:b}=Jf(e),w=async O=>{const E=await b(O);return{id:E.labelId,name:E.name,color:E.color}},j=pl(e,Ea(m,u),s),y=gl(e),I=xl(e),{createFolder:N}=jl(e),[k,C]=c.useState(),M=c.useRef(!1),P=()=>{const O=bl(m,u);if(m.scope==="once"){y.start(O);return}M.current=!1,C(Qf(O)?O:void 0),I.createFilter(O,m.scope==="standing"?"standing":"temporary",(m.name??"").trim())};c.useEffect(()=>{!k||M.current||!I.isSuccess||(M.current=!0,y.start(k))},[k,I.isSuccess,y.start]);const D=()=>{k&&y.start(k)};return y.isStarting||y.isRunning||y.isDone?n.jsx(Ou,{progress:y.progress,isDone:y.isDone,runningLabel:f?"Organizing mail from these senders…":"Organizing similar mail…",onClose:l}):I.isSuccess&&y.isError?n.jsx(yy,{onRetry:D,onClose:l}):I.isPending?n.jsx(ra,{}):I.isSuccess?k?n.jsx(ra,{}):n.jsx(Pu,{onClose:l}):I.isError?n.jsx(Lu,{onRetry:I.reset,onClose:l}):n.jsx(cl,{rule:m,folders:v,labels:x,preview:j,semanticAvailable:!r,clauseFields:Na,...h,onCreateFolder:N,onCreateLabel:w,onCommit:P,onCancel:l})}const _i=(e,t)=>e.find(s=>s.label.toLowerCase()===t),kw=(e,t)=>{const s=[],r=_i(e,"inbox");r&&s.push({id:"keep-inbox",label:"Always keep in Inbox",seed:{moveMailboxId:r.id,scope:"standing"}});const a=_i(e,"archive");a&&s.push({id:"file-archive",label:"File in Archive",seed:{moveMailboxId:a.id}});const o=t?e.find(i=>i.id===t):void 0;return o&&s.push({id:"move-junk",label:`Move to ${o.label}`,seed:{moveMailboxId:o.id}}),s},Cw=(e,t)=>{const s=e.toLowerCase(),r=t.find(o=>s.includes(o.label.toLowerCase())),a=/\b(always|keep|future|from now)\b/.test(s);return{moveMailboxId:r?.id,scope:a?"standing":void 0}};function Nw({folderOptions:e,junkMailboxId:t,onSeed:s}){const[r,a]=c.useState(""),o=c.useMemo(()=>kw(e,t),[e,t]),i=()=>{const l=r.trim();l&&s(Cw(l,e))};return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"border-b border-line px-5 py-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg",children:"What should Remit do?"}),n.jsx("p",{className:"mt-0.5 text-xs text-fg-muted",children:"Pick a shortcut or say it in your own words."})]}),n.jsx("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto px-5 py-4",children:o.map(l=>n.jsx(G,{variant:"secondary",onClick:()=>s(l.seed),className:"h-12 w-full justify-start px-4",children:l.label},l.id))}),n.jsxs("div",{className:"flex items-center gap-2 border-t border-line px-5 py-3",children:[n.jsx(Nf,{value:r,onChange:l=>a(l.target.value),onKeyDown:l=>l.key==="Enter"&&i(),placeholder:"Tell Remit what to do…","aria-label":"Tell Remit what to do",className:"flex-1"}),n.jsx(G,{variant:"primary","aria-label":"Send",onClick:i,disabled:!r.trim(),icon:n.jsx($m,{className:"size-4"}),className:"size-9 shrink-0 px-0"})]})]})}const Ew=e=>e?.scope==="standing"?"standing":void 0,Iw=(e,t,s)=>e?"error":t?"pending":s!==void 0?"success":"idle";function Tw({entry:e,accountId:t,selectedMessageIds:s,selectedSenders:r,junkMailboxId:a,onClose:o}){const i=s[0],[l,u]=c.useState(),{preview:f,matchedCount:d,semanticUnavailable:m,senders:h,isPending:g,isError:v,error:p}=dd(t,i,r);c.useEffect(()=>{f()},[f]);const{data:x}=de({..._e({path:{accountId:t}}),staleTime:Number.POSITIVE_INFINITY}),b=c.useMemo(()=>Zs(x?.items??[]).map(j=>({id:j.mailboxId,label:Vn(j.fullPath)})),[x?.items]),w=Sw({entry:e,hasSeed:l!==void 0,previewStatus:Iw(v,g,d),matchedCount:d});return n.jsxs(hl,{open:!0,onClose:o,dismissLabel:"Dismiss organize",children:[w.kind==="something-else"&&n.jsx(Nw,{folderOptions:b,junkMailboxId:a,onSeed:u}),w.kind==="widening"&&n.jsx(Rw,{}),w.kind==="error"&&n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:p instanceof Error?p.message:"Please try again."}),n.jsx(G,{variant:"ghost",onClick:o,className:"mt-2",children:"Close"})]}),w.kind==="organize"&&n.jsx(fd,{accountId:t,selectedMessageIds:s,seedCount:w.matchedCount,seedScope:Ew(l),seedMailboxId:l?.moveMailboxId,semanticUnavailable:m,senders:h,onClose:o})]})}function Rw(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]})}function Mw({open:e,accountId:t,selectedMessageIds:s,selectedSenders:r,onClose:a}){const o=s[0],{preview:i,reset:l,matchedCount:u,semanticUnavailable:f,senders:d,isPending:m,isError:h,error:g}=dd(t,o,r);c.useEffect(()=>{e&&i()},[e,i]);const v=()=>{l(),a()};return e?n.jsx(ua,{open:e,onClose:v,title:"Filter rule",children:m||u===void 0?h?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:g instanceof Error?g.message:"Please try again."}),n.jsx(G,{variant:"ghost",onClick:v,className:"mt-2",children:"Close"})]}):n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]}):n.jsx(fd,{accountId:t,selectedMessageIds:s,seedCount:u,semanticUnavailable:f,senders:d,onClose:v})}):null}const Aw=(e,t)=>({id:e.messageId,accountId:e.accountConfigId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:cn(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),Dw=({thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,messageCount:d,isMultiSelectMode:m,onLongPress:h,isDesktop:g,density:v})=>n.jsx(to,{thread:Aw(e,d),linkMailboxId:t,inListbox:!0,active:r,focused:a,isTabStop:o,density:v,isDesktop:g,onFocusRow:i,selection:{isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:m,onLongPress:h},badge:e.autoMoved?n.jsx(Vc,{accountId:s,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"sm"}):void 0}),Ow=c.memo(Dw),Pw=e=>{const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountConfigId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:cn(e.category),suspicious:t}},Lw=({thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:d,onLongPress:m,isDesktop:h,onDelete:g,onToggleRead:v,density:p})=>{const[x,b]=c.useState("none"),w=c.useCallback(I=>{navigator.vibrate?.(10),I==="trailing"?g(e.messageId):v(e.messageId,e.isRead),b("none")},[g,v,e.messageId,e.isRead]),j=c.useCallback(()=>{m(e.messageId)},[m,e.messageId]),y=c.useCallback(()=>{u(e.messageId)},[u,e.messageId]);return h||d?n.jsx(Ow,{thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:d,onLongPress:m,isDesktop:h,density:p}):n.jsx(Jl,{thread:Pw(e),selectionMode:!1,checked:!1,active:r,peek:x,onPeek:b,onToggleCheck:y,onLongPress:j,onOpen:()=>{},onAct:w,linkComponent:({onOpenClick:I,children:N,...k})=>n.jsx(pt,{...k,to:"/mail/$mailboxId",params:{mailboxId:t},search:C=>({...C,selectedMessageId:e.messageId}),"data-message-row":!0,onClick:I,children:N})})},$w=72,Fw=32,_w=5,md="remit:list-density",zw={kind:"delete"},zi={kind:"markRead"},Bw=()=>{try{const e=localStorage.getItem(md);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},Kw=({query:e,count:t})=>n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[n.jsx(Qn,{className:"size-4 text-fg-muted"}),n.jsxs("span",{className:"text-sm text-fg-muted",children:[t," ",t===1?"result":"results"," for “",e,"”"]})]}),Uw=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:r,isError:a=!1,error:o,onRetry:i,searchQuery:l,searchPredicate:u,onDeleteMessages:f,onMoveMessages:d,isDeleting:m=!1,isMoving:h=!1,onLoadMore:g,hasMore:v=!1,isLoadingMore:p=!1,accountId:x,listTitle:b,listMeta:w,onTriageContextChange:j,commandsRef:y,hideHeader:I=!1})=>{const N=c.useRef(null),k=Oe(),C=Ot(),[M,P]=c.useState(!1),[D,O]=c.useState(null),E=!!l?.trim(),[S,A]=c.useState(s),[L,T]=c.useState(Bw),F=c.useCallback(()=>{T(_=>{const se=_==="comfortable"?"compact":"comfortable";try{localStorage.setItem(md,se)}catch{}return se})},[]),{toggleReadFor:R}=rr({mailboxId:e}),{junkMailboxId:$}=or(x),{selectedIds:z,selectedCount:V,hasSelection:ee,isSelected:X,toggle:Q,select:le,clearSelection:ue,selectRange:te,setAnchor:K,selectAll:U,toggleAll:re,intersectWith:Ie}=_u(),je=zu(V,C);c.useEffect(()=>{V===0&&O(null)},[V]);const[W,J]=c.useState(null),ae=E&&!!u,ce=`${e}|${JSON.stringify(u??{})}`,B=xw({mailboxId:e,accountId:x,enabled:ae,predicateKey:ce,searchQuery:u??{}}),Fe=B.phase.kind,pe=B.clear,ge=c.useCallback(()=>{Fe==="escalated"&&pe(),ue()},[ue,pe,Fe]),[Se,Qe]=c.useState(null),[ts,ze]=c.useState(null),Ze=c.useRef(null),Be=c.useRef(!1),Ke=c.useRef(null),ft=!r&&t.length>0,Te=W!==null,ss=c.useCallback((_,se)=>{const{exit:St,retryIds:Xe}=hw(se);if(St){ze(Fi(_.kind,se.done)),Qe(null),ge();return}if(Xe.length>0){Qe({action:_,succeeded:se.done}),U(Xe);return}Qe(null)},[ge,U]),Ue=ew({count:t.length,getScrollElement:()=>N.current,estimateSize:()=>L==="compact"?Fw:$w,overscan:_w}),_t=s?t.findIndex(_=>_.messageId===s):-1,Ne=S?t.findIndex(_=>_.messageId===S):-1,qe=c.useCallback(_=>{if(_<0||_>=t.length)return;const se=t[_];if(je){Q(se.messageId);return}Ze.current=se.messageId,Be.current=!1,A(se.messageId)},[t,je,Q]),mt=c.useCallback(()=>{if(t.length===0)return;const _=Ne<0?0:Math.min(Ne+1,t.length-1);qe(_)},[t.length,Ne,qe]),ns=c.useCallback(()=>{if(t.length===0)return;const _=Ne<=0?0:Ne-1;qe(_)},[t.length,Ne,qe]),zt=c.useCallback(()=>qe(0),[qe]),Z=c.useCallback(()=>qe(t.length-1),[qe,t.length]),ie=c.useCallback(()=>{S&&Q(S)},[S,Q]),ne=c.useMemo(()=>t.map(_=>_.messageId),[t]),oe=c.useMemo(()=>{const _=[];for(const se of t)z.has(se.messageId)&&se.fromEmail&&_.push(se.fromEmail);return _},[t,z]),he=c.useCallback((_,se)=>se.shiftKey?(te(ne,_,S),!0):se.metaKey||se.ctrlKey?(Q(_),!0):(ge(),K(_),!1),[ne,S,te,Q,ge,K]),me=c.useCallback(_=>{!f||_.length===0||(Ke.current=S??null,J({source:"ids",ids:_}))},[f,S]),we=c.useCallback(()=>{B.phase.kind==="escalated"&&(Ke.current=S??null,J({source:"predicate",total:B.phase.total}))},[B.phase,S]),Pe=c.useCallback(_=>{const se=Fu(ne,S,_);se!==void 0&&(te(ne,se),Ze.current=se,Be.current=!1,A(se))},[ne,S,te]),Ae=c.useCallback(()=>Pe(-1),[Pe]),He=c.useCallback(()=>Pe(1),[Pe]),De=c.useCallback(()=>{ne.length>0&&U(ne)},[ne,U]),Re=c.useCallback(()=>W!==null?!0:f?V>0?(me(Array.from(z)),!0):S?(me([S]),!0):!1:!1,[W,f,V,z,S,me]),Ye=c.useCallback(()=>{S&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:_=>({..._,selectedMessageId:S})})},[S,k,e]),Ge=c.useCallback(()=>{V>0&&me(Array.from(z))},[me,V,z]),et=c.useCallback(async(_,se)=>{const St=await B.runAction(_,se);ss(_,St)},[B,ss]),Bt=c.useCallback(async _=>{J(null),Ke.current=null,await et(zw,_)},[et]),fr=c.useCallback(()=>{if(!W)return;if(W.source==="predicate"){Bt(void 0);return}const{ids:_}=W;if(_.length===0){J(null);return}if(_.length>cd){Bt(_);return}const se=new Set(_),St=t.findIndex($e=>se.has($e.messageId));let Xe;for(let $e=St+1;$e<t.length;$e++)if(!se.has(t[$e].messageId)){Xe=t[$e].messageId;break}if(Xe===void 0){for(let $e=St-1;$e>=0;$e--)if(!se.has(t[$e].messageId)){Xe=t[$e].messageId;break}}f?.(_),ge(),Ke.current=null,J(null),Xe!==void 0&&(Ze.current=Xe,Be.current=!1,A(Xe),C&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:$e=>({...$e,selectedMessageId:Xe}),replace:!0})),C||ze(Fi("delete",_.length))},[W,t,f,ge,k,e,C,Bt]),wt=c.useCallback(()=>{const _=Ke.current;Ke.current=null,J(null),_!==null&&(Ze.current=_,Be.current=!1,A(_))},[]),fn=c.useCallback(()=>{if(B.phase.kind==="escalated"){et(zi);return}V!==0&&et(zi,Array.from(z))},[B.phase,et,V,z]),rs=c.useCallback(_=>{if(B.phase.kind==="escalated"){et({kind:"move",destinationMailboxId:_});return}!d||V===0||(d(Array.from(z),_),ge())},[B.phase,et,d,V,z,ge]),mr=c.useCallback(()=>{$&&rs($)},[$,rs]),Kt=c.useMemo(()=>{if(V===0)return;const _=new Set;for(const se of t)z.has(se.messageId)&&_.add(se.accountConfigId);if(_.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[V,z,t]),hr=c.useCallback(_=>{f?.([_])},[f]),pr=c.useCallback((_,se)=>{R([_],!se)},[R]),gr=c.useCallback(_=>{C||le(_)},[C,le]),jt=c.useCallback(()=>{if(B.phase.kind==="escalated"){we();return}Ge()},[B.phase,we,Ge]),As=c.useCallback(()=>{if(B.isRunning||B.phase.kind==="counting"){B.stop();return}ge()},[B,ge]),mn=c.useCallback(()=>{B.clear()},[B]),xr=c.useCallback(()=>{if(!Se)return;const _=Array.from(z);if(Se.action.kind==="delete"){Bt(_);return}et(Se.action,_)},[Se,Bt,et,z]);c.useEffect(()=>{if(Be.current||!C&&s)return;const _=Ne>=0?Ne:_t;_>=0&&Ue.scrollToIndex(_,{align:"auto"})},[Ne,_t,Ue,C,s]),c.useEffect(()=>{s&&(Be.current=!1,A(s))},[s]),c.useEffect(()=>{S&&(t.some(_=>_.messageId===S)||A(t[0]?.messageId))},[t,S]),c.useEffect(()=>{j?.({focusedMessageId:S,selectedIds:Array.from(z),hasList:ft,blocksKeyboard:Te})},[S,z,ft,Te,j]);const hn=c.useRef(j);hn.current=j,c.useEffect(()=>()=>hn.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{B.phase.kind!=="idle"||B.isRunning||Ie(t.map(_=>_.messageId))},[t,Ie,B.phase,B.isRunning]);const pn=c.useRef(e);c.useEffect(()=>{pn.current!==e&&(pn.current=e,ge())},[e,ge]),$x({shouldBlockFn:({action:_})=>Ny(_,ee)?(ge(),!0):!1,enableBeforeUnload:!1,disabled:!ee}),c.useEffect(()=>{const _=N.current;if(!_||!v||!g)return;const se=()=>{if(p)return;const{scrollTop:St,scrollHeight:Xe,clientHeight:$e}=_;St+$e>=Xe-200&&g()};return _.addEventListener("scroll",se,{passive:!0}),se(),()=>_.removeEventListener("scroll",se)},[v,p,g]),c.useEffect(()=>{const _=Ze.current;if(!_)return;const se=N.current?.querySelector(`[data-message-id="${_}"]`);se&&(Ze.current=null,se.focus({preventScroll:!0}))}),c.useEffect(()=>{if(y){if(!ft){y.current=null;return}return y.current={focusNext:mt,focusPrevious:ns,focusFirst:zt,focusLast:Z,openFocused:Ye,toggleSelect:ie,extendSelectDown:He,extendSelectUp:Ae,selectAll:De,clearSelection:()=>ee?(ge(),!0):!1,requestDelete:Re,toggleDensity:F},()=>{y.current=null}}},[y,ft,mt,ns,zt,Z,Ye,ie,He,Ae,De,ee,ge,Re,F]);const gn=r?"loading":a?"error":t.length===0?"empty":"ready",br=a?vl(o):void 0,Y=c.useCallback(()=>{const _=va(ba());window.open(_,"_blank","noopener,noreferrer")},[]),tt=[{id:"inbox",threads:[]}],Le=ne.length>0&&ne.every(_=>z.has(_)),kd=ae&&v&&Le&&!m&&!h&&B.phase.kind==="idle"&&!B.isRunning,Cd=m||h||B.isRunning,vr=B.phase.kind==="escalated"?B.phase.total:V,lo=B.runningAction?rw(B.runningAction.kind,B.progress?.done??0,B.progress?.total??0):B.phase.kind==="counting"?B.phase.countSoFar>=5e3?`Counting… ${ct(B.phase.countSoFar)} so far. This is a big result set.`:`Counting… ${ct(B.phase.countSoFar)} so far`:B.phase.kind==="escalated"?vw(u??{},B.phase.total):void 0,co=B.phase.kind!=="escalated"&&ne.length>0?{checked:Le,indeterminate:V>0&&!Le,onChange:()=>re(ne)}:void 0,uo=B.runningAction&&B.progress?{value:B.progress.done,max:B.progress.total,tone:lw(B.runningAction.kind)}:void 0,fo=B.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:B.stop}}:B.phase.kind==="escalated"&&!B.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:mn}}:kd?{tone:"info",text:"",action:{label:bw(u??{}),onClick:B.escalate}}:Se!==null&&V>0?{tone:"danger",text:aw(Se.action.kind,Se.succeeded,V),action:{label:`Retry ${ct(V)}`,onClick:xr}}:void 0,mo=fo??(Kt?{tone:"warning",text:Kt}:void 0),ho=yw({isRunning:B.isRunning,isCounting:B.phase.kind==="counting",isEscalated:B.phase.kind==="escalated"}),po=!C&&je&&jw(vr,ho,mo!==void 0),Nd=(d||B.phase.kind==="escalated")&&x&&e?n.jsx(dn,{accountId:x,currentMailboxId:e,onMove:m||h?()=>{}:rs,disabledHint:Kt,label:"Move selected messages"}):void 0,go=D&&x&&!C&&V>0?n.jsx(Tw,{entry:D,accountId:x,selectedMessageIds:Array.from(z),selectedSenders:oe,junkMailboxId:$,onClose:()=>{O(null),ge()}}):void 0,xo=po?n.jsx(eg,{count:vr,mode:ho,onCancel:As,onDelete:jt,onJunk:$&&$!==e&&!Kt?mr:void 0,onMarkRead:fn,onSelectSimilar:x?()=>O("select-similar"):void 0,onSomethingElse:x?()=>O("something-else"):void 0,moveSlot:Nd,isBusy:Cd,selectAll:co,statusLabel:lo,progress:uo,notice:mo}):void 0,Ed=xo||go?n.jsxs(n.Fragment,{children:[xo,go]}):void 0,Id=ee&&C?n.jsx(Ku,{selectedCount:vr,onDelete:jt,onClearSelection:As,onMarkAsRead:fn,onMove:d?rs:void 0,onOrganize:()=>P(!0),isDeleting:m,isMoving:h,accountId:x,currentMailboxId:e,selectedMessageIds:Array.from(z),moveDisabledHint:Kt,selectAll:ae?co:void 0,statusLabel:lo,isCounting:B.phase.kind==="counting",progress:uo,notice:fo}):void 0,Td=Bu(ne,S),Rd=c.useCallback(_=>{Be.current=!0,A(_)},[]),Md=n.jsxs(n.Fragment,{children:[E&&l&&n.jsx(Kw,{query:l,count:t.length}),n.jsxs("div",{ref:N,role:"listbox","aria-multiselectable":!0,"aria-label":b,className:"flex-1 overflow-y-auto",style:po?{paddingBottom:Ks}:void 0,children:[n.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${Ue.getTotalSize()}px`},children:Ue.getVirtualItems().map(_=>{const se=t[_.index];return n.jsx("div",{role:"presentation","data-index":_.index,ref:Ue.measureElement,className:be("absolute left-0 top-0 w-full border-b border-line",B.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${_.start}px)`},children:n.jsx(Lw,{thread:se,mailboxId:e,accountId:x,isSelected:s===se.messageId,isFocused:S===se.messageId,isTabStop:Td===se.messageId,onFocusRow:Rd,isChecked:X(se.messageId),onToggleCheck:Q,onRowSelect:he,isMultiSelectMode:je,onLongPress:gr,isDesktop:C,onDelete:hr,onToggleRead:pr,density:L})},_.key)})}),p&&n.jsx("div",{className:"flex justify-center py-4",children:n.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-fg-muted border-t-transparent"})})]})]}),Ad=W?W.source==="ids"?W.ids.length:W.total:0,bo=W?.source==="predicate";return n.jsxs(n.Fragment,{children:[ts&&!C&&n.jsx(Xt,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>ze(null),children:ts}),n.jsx(Zl,{listTitle:b,listMeta:w,sections:tt,flatList:!0,listState:gn,searchQuery:E?l:void 0,errorMessage:br,onRetry:i,onReportError:Y,density:L,selectedThreadId:s,onSelectThread:_=>k({to:"/mail/$mailboxId",params:{mailboxId:e},search:se=>({...se,selectedMessageId:_})}),onSelectBriefCategory:()=>{},isDesktop:C,hideHeader:I,selectionBar:Id,selectionSheet:Ed,listBody:gn==="ready"?Md:void 0}),n.jsx(Ra,{isOpen:W!==null,title:wl(Ad,bo),description:bo?"This count is a snapshot — new mail arriving during the delete won't be included. You can restore what's deleted from Trash later.":"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:m,onConfirm:fr,onCancel:wt}),M&&x&&n.jsx(Mw,{open:M,accountId:x,selectedMessageIds:Array.from(z),selectedSenders:oe,onClose:()=>P(!1)})]})},qw=e=>Jt({path:{accountId:e}}),Hw=e=>{const t=ye(),s=Js(),r=ve({...Ef(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:qw(e)})}});return{trigger:()=>{r.mutate({path:{accountId:e}})},triggerAsync:()=>r.mutateAsync({path:{accountId:e}}),isPending:r.isPending,error:r.error,reset:r.reset}},Ww=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:r}=Hw(e);return n.jsx(Ip,{onRefresh:s,isRefreshing:r,children:t})};function Vw({accountId:e,currentMailboxId:t,candidates:s,onMove:r,children:a}){const[o,i]=c.useState(!1),l=Js(),{t:u}=Un("mail",{useSuspense:!1}),f=c.useCallback((w,j)=>u(w,{defaultValue:j}),[u]),{inboxMailboxId:d}=Qa(e),m=Wc(e),{data:h}=de({..._e({path:{accountId:e}}),staleTime:1/0}),g=c.useMemo(()=>{const w=Zs(h?.items??[],m),j=Xs(m);return w.map(y=>({id:y.mailboxId,label:bs(y,j.get(y.mailboxId),f),searchValue:y.fullPath,isCurrent:y.mailboxId===t}))},[h?.items,m,t,f]),v=c.useMemo(()=>d||(g.find(j=>j.label.toLowerCase()==="inbox")?.id??g.find(j=>!j.isCurrent)?.id??""),[d,g]),p=c.useRef(!1);c.useEffect(()=>{p.current||(p.current=!0,Xy(l,s.length))},[l,s.length]);const x=c.useCallback(()=>{Jy(l,s.length),i(!0)},[l,s.length]),b=c.useCallback((w,j)=>{Zy(l,{selected:w.length,total:s.length,toInbox:j===d}),r(w,j)},[l,s.length,d,r]);return n.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[n.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:n.jsx(Mp,{count:s.length,onReview:x})}),n.jsx("div",{className:"min-h-0 flex-1",children:a}),n.jsx(Bp,{open:o,candidates:s,defaultDestinationId:v,availableFolders:g,onConfirmMove:b,onCancel:()=>i(!1)})]})}const Qw="We can verify this sender";function Yw(e){const{data:t}=de({...If({path:{mailboxId:e??""},query:{senderTrust:["vip","wellknown"],dkimMismatch:!1,results:!0,limit:500}}),enabled:!!e,staleTime:6e4});return{candidates:(t?.items??[]).map(r=>({id:r.messageId,senderName:r.fromName||r.fromEmail||"Unknown sender",senderAddress:r.fromEmail??"",subject:r.subject||"(no subject)",snippet:r.snippet??"",trustReason:Qw,trustSubReason:Gy(r.senderTrust),senderTrust:r.senderTrust}))}}const Gw=e=>{const t=new Set,s=[];for(const r of e)t.has(r.threadMessageId)||(t.add(r.threadMessageId),s.push(r));return s},Xw={unread:e=>!e.isRead,flagged:e=>e.hasStars===!0,attachment:e=>!!e.hasAttachment};function Jw(e,t,s){const r=Array.from(s).map(a=>Xw[a]).filter(a=>a!=null);return t==="all"&&r.length===0?e:e.filter(a=>(t==="all"||cn(a.category)===t)&&r.every(o=>o(a)))}const hd="remit:intelligence-open";function Zw(){try{return localStorage.getItem(hd)!=="closed"}catch{return!0}}function Bi(e){try{localStorage.setItem(hd,e?"open":"closed")}catch{}}const ej=(e,t)=>e!==t,tj=(e,t,s)=>{if(!(s||!t))return e.find(r=>r.messageId===t)},pd=c.createContext(null);function dr(){const e=c.useContext(pd);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function sj({mailboxId:e,selectedMessageId:t,children:s}){const r=Oe(),o=lr()==="desktop",i=Js(),{accounts:l,searchQuery:u,searchInput:f,intelligenceOpen:d,onToggleIntelligence:m,onSetIntelligenceOpen:h}=Ce(),g=Ts(),v=Za(u),p=v.length>0,{freeText:x,tokens:b}=Rs(v,g),w=b.find(Y=>Y.type==="from"),j={order:"desc",...x?{query:x}:{},...w?{from:w.value}:{},...b.some(Y=>Y.type==="hasAttachment")?{attachments:!0}:{},...b.some(Y=>Y.type==="isUnread")?{unread:!0}:{}},y=p?rl({path:{mailboxId:e},query:j}):wa({path:{mailboxId:e},query:{order:"desc"}}),{data:I,isLoading:N,isError:k,error:C,refetch:M,fetchNextPage:P,hasNextPage:D,isFetchingNextPage:O}=Sc({queryKey:y,queryFn:async({pageParam:Y})=>{if(p){const{data:Le}=await dl({path:{mailboxId:e},query:{...j,continuationToken:Y},throwOnError:!0});return Le}const{data:tt}=await Rf({path:{mailboxId:e},query:{order:"desc",continuationToken:Y},throwOnError:!0});return tt},initialPageParam:void 0,getNextPageParam:Y=>Y.continuationToken,enabled:p?v.length>0:!0,placeholderData:Tf}),E=c.useCallback(Y=>{t&&Y.includes(t)&&r({to:"/mail/$mailboxId",params:{mailboxId:e},search:tt=>({...tt,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,r]),{deleteMessages:S,isPending:A}=Yt({mailboxId:e,onAfterOptimisticRemove:E}),{accountId:L}=qc(e),T=Oc({accounts:l}),{moveMessages:F,isPending:R}=Qt({mailboxId:e,accountId:L,onAfterOptimisticRemove:E}),$=Yb(Gw(I?.pages.flatMap(Y=>Y.items??[])??[])),[z,V]=c.useState("all"),[ee,X]=c.useState(new Set),Q=c.useMemo(()=>Jw($,z,ee),[$,z,ee]),le=c.useCallback(Y=>{V(Y)},[]),ue=c.useCallback(Y=>{X(tt=>{const Le=new Set(tt);return Le.has(Y)?Le.delete(Y):Le.add(Y),Le})},[]),te=c.useCallback(()=>{V("all"),X(new Set)},[]),K=ej(f,u),U=tj($,t,K),{selectedThreadId:re}=vs({strict:!1}),Ie=c.useMemo(()=>Ju(U,{messageId:t,threadId:K?void 0:re,mailboxId:e}),[U,t,re,K,e]),je=no(),{listCommandsRef:W,onTriageContextChange:J,focusedMessageId:ae,selectedIds:ce}=je,B=Q.find(Y=>Y.messageId===ae)??U,Fe=c.useRef(null);c.useEffect(()=>{const Y=U?.messageId??null;Y&&Fe.current!==Y&&U?.authenticity?.dkimMismatch&&(Fe.current=Y,d||m())},[U?.messageId,U?.authenticity?.dkimMismatch,d,m]);const pe=c.useRef(!1);c.useEffect(()=>{pe.current||o&&U?.messageId&&(pe.current=!0,Zw()&&!d&&h(!0))},[o,U?.messageId,d,h]);const Se=Gx({accounts:l})??$.filter(Y=>!Y.isRead).length,Qe=ye(),{pushError:ts}=Ve(),ze=Qs({thread:U,mailboxId:e,accountId:L,onAfterOptimisticRemove:E}),{draftsMailboxId:Ze}=Vb(L),Be=Ze!==void 0&&Ze===e,{archiveMailboxId:Ke}=Wb(L),ft=Xu(),{requestCompose:Te}=ze,ss=c.useCallback(()=>{Te("reply")},[Te]),Ue=c.useCallback(()=>{Te("reply_all")},[Te]),_t=c.useCallback(()=>{Te("forward")},[Te]),{state:Ne,openCompose:qe,closeCompose:mt}=Dt(),ns=c.useCallback(()=>{qe({mode:"new"})},[qe]),zt=ve({...Hn(),onError:Y=>{ts(Vt("Couldn't discard draft","The draft wasn't deleted.",Y))}}),Z=c.useCallback(()=>{const Y=Ne.outboxMessageId;Y&&(zt.mutate({path:{outboxMessageId:Y}}),Qe.invalidateQueries({queryKey:ka()}),mt())},[Ne.outboxMessageId,zt,Qe,mt]),ie=c.useCallback(()=>{r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Y=>({...Y,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,r]),ne=c.useCallback(Y=>Y?ft(Y):[],[ft]),{toggleStar:oe}=Wa({threadId:B?.threadId??"",mailboxId:e}),{toggleReadFor:he}=rr({mailboxId:e,accountId:L}),{junkMailboxId:me}=or(L),we=me!=null&&me===e,{candidates:Pe}=Yw(we?me:void 0),{moveMessages:Ae}=Qt({mailboxId:e,threadId:B?.threadId,accountId:L,onAfterOptimisticRemove:E}),{deleteMessages:He}=Yt({mailboxId:e,threadId:B?.threadId,onAfterOptimisticRemove:E}),{addressId:De,address:Re}=Vu(B),{updateFlags:Ye}=Qu({addressId:De,senderEmail:B?.fromEmail??void 0}),Ge=c.useCallback(()=>t||!ae?!1:(r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Y=>({...Y,selectedMessageId:ae})}),!0),[t,ae,e,r]),et=c.useCallback(()=>{Ge()||U&&Te("reply")},[Ge,U,Te]),Bt=c.useCallback(()=>{Ge()||U&&Te("reply_all")},[Ge,U,Te]),fr=c.useCallback(()=>{Ge()||U&&Te("forward")},[Ge,U,Te]),wt=c.useCallback(()=>ce.length>0?ce:ne(B),[ce,ne,B]),fn=c.useCallback(()=>{if(W.current?.requestDelete())return;const Y=wt();Y.length>0&&He(Y)},[W,wt,He]),rs=c.useCallback(()=>{if(!me)return;const Y=wt();Y.length!==0&&(Gu(i,{count:Y.length,senderTrust:B?.senderTrust??"unknown",wasRescuable:B?Yu(B):!1}),Ae(Y,me))},[me,wt,Ae,i,B]),mr=c.useCallback(()=>{if(ce.length>0){const Y=!(B?.hasStars??!1),tt=new Set(ce);for(const Le of Q)tt.has(Le.messageId)&&Le.hasStars!==Y&&oe(Le.messageId,Le.hasStars);return}B&&oe(B.messageId,B.hasStars)},[ce,Q,B,oe]),Kt=c.useCallback(()=>{const Y=wt();if(Y.length===0)return;const tt=!(B?.isRead??!1);he(Y,tt)},[wt,B,he]),hr=c.useCallback(()=>{if(!De)return;const Y=Re?.flags?.muted?.value!==!0;Ye({muted:{value:Y}})},[De,Re,Ye]),pr=c.useCallback(()=>{if(!De)return;const Y=Re?.flags?.vip?.value!==!0;Ye({vip:{value:Y}})},[De,Re,Ye]),gr=c.useCallback(()=>{d||m()},[d,m]),jt=c.useCallback(Y=>{r({to:Y})},[r]),As=Be?"drafts":Ke===e?"archive":me===e?"junk":"inbox",mn=c.useRef("");c.useEffect(()=>{const Y=mn.current;mn.current=v,v.length>0&&Y.length===0&&i.recordEvent("search.submitted",{mailboxType:As})},[v,As,i]);const xr=Be&&Ne.isOpen&&!!Ne.outboxMessageId&&!U,{goBack:hn,nextMessageId:pn,previousMessageId:gn}=ro({context:je,orderedIds:Q.map(Y=>Y.messageId),selectedMessageId:t,enabled:!Ne.isOpen,onClose:ie,handlers:{reply:et,replyAll:Bt,forward:fr,delete:fn,toggleStar:mr,toggleRead:Kt,muteSender:hr,blockSender:gr,vipSender:pr,markJunk:rs,toggleIntelligence:U?m:void 0,compose:ns,goBrief:()=>jt("/mail"),goInbox:()=>jt("/mail"),goSent:()=>jt("/mail"),goFlagged:()=>jt("/mail/flagged"),goSettings:()=>jt("/settings")}});Ha({enabled:Ne.isOpen,bindings:[{key:"Escape",handler:mt,preventDefault:!0}]});const br={mailboxId:e,selectedMessageId:t,selectedThread:U,conversation:Ie,threads:Q,isLoading:N,isError:k,error:C,mailboxAccountId:L,mailboxName:T,unreadCount:Se,isDraftsMailbox:Be,isSpamFolder:we,rescueCandidates:Pe,filterCategory:z,filterAttributes:ee,onSelectFilterCategory:le,onToggleFilterAttribute:ue,onClearFilters:te,intelligenceOpen:d,onToggleIntelligence:m,searchPredicate:p?j:void 0,onDeleteMessages:S,onMoveMessages:F,isDeleting:A,isMoving:R,onLoadMore:P,hasMore:D,isLoadingMore:O,onTriageContextChange:J,listCommandsRef:W,onRetry:()=>M(),toolbarComposeRequest:ze.composeRequest,onToolbarReply:ss,onToolbarReplyAll:Ue,onToolbarForward:_t,onClearComposeRequest:ze.clearComposeRequest,onToolbarDelete:ze.deleteThread,onToolbarStar:ze.toggleStar,onToolbarDiscardDraft:Z,onToolbarMove:ze.moveThread,composeState:Ne,closeCompose:mt,hasRemitDraftOpen:xr,onBack:hn,nextMessageId:pn,previousMessageId:gn};return n.jsx(pd.Provider,{value:br,children:s})}function gd(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:r,isError:a,error:o,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,mailboxAccountId:g,mailboxName:v,unreadCount:p,isDraftsMailbox:x,isSpamFolder:b,rescueCandidates:w,onTriageContextChange:j,listCommandsRef:y,onRetry:I,filterCategory:N,filterAttributes:k,onSelectFilterCategory:C,onToggleFilterAttribute:M,onClearFilters:P,searchPredicate:D}=dr(),{searchQuery:O,searchInput:E,accounts:S,resultFolderIndex:A}=Ce(),L=lr(),T=Oe(),F=v??"Inbox",R=c.useMemo(()=>rg(),[]),$=c.useMemo(()=>s.map(K=>uy(K,A)),[s,A]),{hits:z,isLoading:V}=ku({mailboxId:e,filterCategory:N}),ee=c.useMemo(()=>Iu(z,s.map(K=>K.threadId),A),[z,s,A]),X=c.useCallback(K=>T({to:"/mail/$mailboxId",params:{mailboxId:K.mailboxId??e},search:U=>({...U,q:E||void 0,selectedMessageId:K.id,selectedThreadId:K.threadId})}),[e,T,E]);if(x&&g)return n.jsx($0,{mailboxId:e,accountId:g,selectedMessageId:t,imapThreads:s,title:v??"Drafts",unreadCount:p??void 0});const Q=n.jsx(Uw,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:r,isError:a,error:o,onRetry:I,searchQuery:O,searchPredicate:D,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,accountId:g,listTitle:F,hideHeader:!0,onTriageContextChange:j,commandsRef:y}),le=S[0]?.accountId,ue=L==="phone"&&le?n.jsx(Ww,{accountId:le,children:Q}):Q,te=b&&w.length>0&&g?n.jsx(Vw,{accountId:g,currentMailboxId:e,candidates:w,onMove:l,children:ue}):ue;return n.jsx(sd,{title:F,unreadCount:p,preset:R,selectedCategory:N,activeFilters:k,onSelectCategory:C,onToggleFilter:M,onClearFilters:P,searchResults:$,searchLoading:r,relatedResults:ee,relatedLoading:V,onSelectSearchResult:X,searchResultsInBody:!0,children:te})}function nj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:r,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:l,onToolbarReply:u,onToolbarReplyAll:f,onToolbarForward:d,onClearComposeRequest:m,onToolbarDelete:h,onToolbarStar:g,onToolbarDiscardDraft:v,onToolbarMove:p,composeState:x}=dr(),b=Ss()?.showIntelligencePane??!1,w=!!r,j=b&&w,y=x.isOpen&&!r?n.jsx(ad,{}):r?n.jsx(Is,{threadId:r.threadId,mailboxId:r.mailboxId,subject:r.subject,selectedMessageId:r.messageId,authenticity:r.authenticity,onOpenIntelligence:r.authenticity?.dkimMismatch?i:void 0,composeRequest:l,onComposeClose:m}):n.jsx(Es,{});return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(so,{hasThread:w,intelligenceOpen:j&&o,canToggleIntelligence:j,onToggleIntelligence:i,onReply:w?u:void 0,onReplyAll:w?f:void 0,onForward:w?d:void 0,canDelete:w||a,onDelete:w?h:a?v:void 0,onToggleStar:w?g:void 0,isStarred:s?.hasStars,moveContext:w&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:y})]})}function rj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:r}=dr();return n.jsx(Ms,{onClose:r,thread:s,mailboxId:e,accountId:t})}function aj(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:r,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=dr(),f=Oe();if(s){const d=m=>f({to:"/mail/$mailboxId",params:{mailboxId:e},search:h=>({...h,selectedMessageId:m,selectedThreadId:void 0})});return n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:s.threadId,mailboxId:s.mailboxId,subject:s.subject,selectedMessageId:s.messageId,authenticity:s.authenticity,onBack:o,onOpenIntelligence:a,onSwipeNext:i?()=>d(i):void 0,onSwipePrevious:l?()=>d(l):void 0,mobileIntelligenceOpen:r}),n.jsx(Ua,{isOpen:r,onClose:a,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?n.jsx("div",{className:"h-full",children:n.jsx(ad,{})}):n.jsx(gd,{})}const Bs=Object.assign(sj,{List:gd,Reading:nj,Intelligence:rj,Phone:aj}),xd=e=>e==="failed"||e==="blocked",bd=e=>e!=="draft"&&e!=="sent",oo="remit.savedSearches",oj=25;function Bn(){try{const e=localStorage.getItem(oo);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function ij(e){const t=e.trim();if(!t)return Bn();const s=[t,...Bn().filter(r=>r!==t)].slice(0,oj);try{localStorage.setItem(oo,JSON.stringify(s))}catch{return s}return s}function lj(e){const t=Bn().filter(s=>s!==e);try{localStorage.setItem(oo,JSON.stringify(t))}catch{return t}return t}const Ki=e=>/^\d/.test(e),cj=(e,t)=>{const s=Ki(e),r=Ki(t);return s&&!r?-1:!s&&r?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function uj(e,t,s){const r=[],a=[];for(const o of e)t.has(o.mailboxId)?r.push(o):a.push(o);return a.sort((o,i)=>cj(bs(o,void 0,s),bs(i,void 0,s))),{system:r,labels:a}}function dj(e,t,s){const r=Mf(t)&&e.unseenCount>0;return{id:e.mailboxId,name:bs(e,t,s),unseen:r?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function fj(){const e=tr(),t=ya({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 Ui({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const r=ye(),a=Oe(),o=fj(),{searchInput:i,onSearchChange:l}=Ce(),[u,f]=c.useState(Bn),{t:d}=Un("mail",{useSuspense:!1}),m=c.useCallback((C,M)=>d(C,{defaultValue:M}),[d]),h=Ft({queries:e.map(C=>({..._e({path:{accountId:C.accountId}}),staleTime:1/0}))}),{data:g}=de(qn()),v=c.useMemo(()=>(g?.items??[]).filter(C=>bd(C.status)).length,[g?.items]),p=c.useMemo(()=>e.map((C,M)=>{const P=h[M],D=P?.data?.items??[],O=Xs(C.folderAppointments),{system:E,labels:S}=uj(D,O,m),A=P?.isError?"error":P?.isLoading?"loading":"ready";return{id:C.accountId,label:C.email,email:C.email,muted:!!C.muted,outboxPending:v,status:A,onRetry:()=>P?.refetch(),mailboxes:[...E,...S].map(L=>dj(L,O.get(L.mailboxId),m))}}),[e,h,v,m]),x=C=>{r.invalidateQueries({queryKey:wa({path:{mailboxId:C},query:{order:"desc"}})})},b=({navId:C,className:M,ariaLabel:P,title:D,children:O,onClick:E})=>C==="brief"?n.jsx(pt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):C==="outbox"?n.jsx(pt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):C==="flagged"?n.jsx(pt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):C==="settings"?n.jsx(pt,{to:"/settings/accounts",onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):n.jsx(pt,{to:"/mail/$mailboxId",params:{mailboxId:C},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{x(C),E?.()},className:M,"aria-label":P,title:D,children:O}),w=()=>{l(""),t?.()},j=i.trim(),y=j.length>0&&!u.includes(j)?j:void 0,I=c.useCallback(()=>{y&&f(ij(y))},[y]),N=c.useCallback(C=>{f(lj(C))},[]),k=c.useCallback(C=>{l(C),a({to:"/mail",search:{q:C,selectedMessageId:void 0}}),t?.()},[l,a,t]);return n.jsx(sp,{accounts:p,selectedNavId:o,onSelectNav:w,linkComponent:b,variant:s,savedSearches:u,saveableQuery:y,onSaveCurrentSearch:I,onSelectSavedSearch:k,onRemoveSavedSearch:N})}function mj({accounts:e,onMailboxSelect:t}){return Ss()?.showNavPane??!0?n.jsx(Ui,{accounts:e}):n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(Ui,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),n.jsxs("div",{className:"border-t border-line px-2 py-2",children:[n.jsxs(pt,{to:"/settings/accounts",onClick:t,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(Oa,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),n.jsx(Ec,{variant:"drawer"}),n.jsx(Nc,{children:({signOut:a})=>n.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[n.jsx(Bl,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function hj(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const r=[e.subject,e.fromAddress,e.fromName,...e.toAddresses??[],...e.ccAddresses??[]].filter(a=>typeof a=="string").join(" ").toLowerCase();return s.split(/\s+/).every(a=>a.length===0||r.includes(a))}function pj(e){return e.tokens.length>0&&e.freeText.trim().length===0}const vd={queued:{icon:Ta,label:"Queued",className:"text-warning"},sending:{icon:nt,label:"Sending…",className:"text-accent-2"},sent:{icon:$l,label:"Sent",className:"text-positive"},failed:{icon:Gt,label:"Failed",className:"text-danger"},blocked:{icon:fa,label:"Blocked",className:"text-warning"}},gj=e=>Yf(e).toDateString()===new Date().toDateString()?Pn(e,{hour:"numeric",minute:"2-digit"}):Pn(e,{month:"short",day:"numeric"}),qi=e=>Pn(e,{dateStyle:"medium",timeStyle:"short"}),xj=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},yd=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",wd=c.createContext(null);function io(){const e=c.useContext(wd);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function bj({children:e}){const t=Oe(),{selectedOutboxMessageId:s}=vs({strict:!1}),{data:r,isLoading:a}=de(qn()),{searchQuery:o}=Ce(),i=Ts(),l=Za(o),u=Rs(l,i),f=l.length>0,d=pj(u),m=c.useMemo(()=>d?[]:(r?.items??[]).filter(p=>bd(p.status)).filter(p=>hj(p,u.freeText)),[r,u.freeText,d]),h=c.useMemo(()=>m.find(p=>p.outboxMessageId===s),[m,s]),g=c.useCallback(p=>{t({to:"/mail/outbox",search:x=>({...x,selectedOutboxMessageId:p})})},[t]),v={messages:m,hasQuery:f,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:g};return n.jsx(wd.Provider,{value:v,children:e})}function jd({message:e,isSelected:t,onSelect:s}){const r=ye(),{openCompose:a}=Dt(),{pushError:o}=Ve(),i=c.useCallback(()=>{r.invalidateQueries({queryKey:ka()})},[r]),l=ve({...nl(),onSuccess:i,onError:m=>{o(Vt("Couldn't resend message","The message wasn't sent.",m))}}),u=ve({...Hn(),onSuccess:i,onError:m=>{o(Vt("Couldn't delete message","The message wasn't deleted.",m))}}),f=e.status;if(!vd[f])return null;const d=xd(e.status);return n.jsx(Np,{recipients:xj(e),subject:e.subject||"",time:gj(e.sentAt??e.updatedAt),status:f,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:f==="failed"?()=>l.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:l.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function Sd({message:e,onBack:t}){const s=e.status,r=vd[s],a=r?.icon??Gs,o=e.sentAt?qi(e.sentAt):qi(e.updatedAt);return n.jsxs("div",{className:"h-full overflow-y-auto bg-canvas",children:[n.jsxs("div",{className:"border-b border-line p-4",children:[t&&n.jsxs("button",{type:"button",onClick:t,className:"mb-3 inline-flex items-center gap-1 text-sm text-fg-muted hover:text-fg",children:[n.jsx(Pl,{className:"size-4"}),n.jsx("span",{children:"Back"})]}),n.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),n.jsxs("div",{className:"space-y-1 text-sm",children:[n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),n.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),n.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),n.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),n.jsx("span",{className:"text-fg",children:o})]}),r&&n.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[n.jsx(a,{className:be("size-4",r.className,s==="sending"&&"animate-spin")}),n.jsx("span",{className:be("text-xs font-medium",r.className),children:r.label}),xd(e.status)&&e.lastError&&n.jsxs("span",{className:"text-xs text-fg-muted",children:["— ",e.lastError]})]})]})]}),n.jsx("div",{className:"p-4",children:n.jsx(yu,{html:e.htmlBody,text:e.textBody})})]})}function vj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,onSelectMessage:o}=io(),i=c.useRef(null);return Kn({containerRef:i,itemSelector:ia}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Es,{message:yd(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(ao,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(l=>n.jsx(jd,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function yj(){const{selectedMessage:e}=io();return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx("header",{className:"flex h-pane-header shrink-0 items-center border-b border-line px-3"}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Sd,{message:e}):n.jsx(Es,{message:"Select a message to read",showHints:!1})})]})}function wj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=io(),l=c.useRef(null);return Kn({containerRef:l,itemSelector:ia}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?n.jsx(Sd,{message:o,onBack:()=>i(void 0)}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Es,{message:yd(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(ao,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:l,className:"flex-1 overflow-y-auto",children:e.map(u=>n.jsx(jd,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const In=Object.assign(bj,{List:vj,Reading:yj,Phone:wj}),jj=({isOpen:e,onClose:t})=>{const s=c.useCallback(r=>{r.key==="Escape"&&(r.preventDefault(),t())},[t]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:t,onKeyDown:r=>r.key==="Escape"&&t(),children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{className:be("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),onClick:r=>r.stopPropagation(),onKeyDown:r=>{r.key!=="Escape"&&r.stopPropagation()},children:[n.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),n.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:n.jsx(We,{className:"size-5"})})]}),n.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:Lc.map(r=>n.jsxs("div",{children:[n.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:r.title}),n.jsx("div",{className:"space-y-2",children:r.hints.map(a=>n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsx("span",{className:"text-sm",children:a.description}),n.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>n.jsxs(c.Fragment,{children:[i>0&&a.keys[0]==="g"&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),n.jsx(ps,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},r.title))}),n.jsx("div",{className:"mt-6 border-t border-line pt-4",children:n.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",n.jsx(ps,{children:"Esc"})," to close"]})})]})]}):null};function Sj(e){const t=new Map;for(const s of e){const r=s.email.toLowerCase(),a=r.split("@")[0];a&&!t.has(a)&&t.set(a,s.accountId),t.has(r)||t.set(r,s.accountId)}return t}function kj(e){const t=new Map;for(const s of e)for(const r of s){const a=r.fullPath?.toLowerCase();if(!a)continue;const o=a.split("/").pop();t.has(a)||t.set(a,r.mailboxId),o&&!t.has(o)&&t.set(o,r.mailboxId)}return t}function Cj(e){const t=Ft({queries:e.map(s=>({..._e({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>kj(t.map(s=>s.data?.items??[])),[t])}const Nj=e=>e.map(t=>t.data?.items??[]);function Ej(e){const t=Ft({queries:e.map(s=>({..._e({path:{accountId:s.accountId}}),staleTime:1/0})),combine:Nj});return c.useMemo(()=>Af(e.map((s,r)=>({folderAppointments:s.folderAppointments,mailboxes:t[r]??[]}))),[e,t])}var Tn={exports:{}},Hi;function Ij(){if(Hi)return Tn.exports;Hi=1;const e=(t,s,r)=>new Promise((a,o)=>{if(r=Object.assign({concurrency:1/0},r),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=r;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const l=[],u=t[Symbol.iterator]();let f=!1,d=!1,m=0,h=0;const g=()=>{if(f)return;const v=u.next(),p=h;if(h++,v.done){d=!0,m===0&&a(l);return}m++,Promise.resolve(v.value).then(x=>s(x,p)).then(x=>{l[p]=x,m--,g()},x=>{f=!0,o(x)})};for(let v=0;v<i&&(g(),!d);v++);});return Tn.exports=e,Tn.exports.default=e,Tn.exports}var Tj=Ij();const Rj=Df(Tj),Mj=900*1e3,Aj=300,Dj=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},Oj=60*1e3,Pj=e=>Math.max(Dj(e,Aj)*1e3,Oj),On=Pj(Lf().mailboxPollIntervalSeconds),Lj=5,aa=new Set,$j=(e,t,s=Mj)=>e.filter(r=>{const a=r.lastSyncAt;return a==null?!0:t-a>s}).map(r=>r.accountId),Fj=(e,t,s=On)=>e-t>=s,_j=(e,t)=>e.filter(s=>!t.has(s)),Wi=(e,t)=>{if(aa.delete(e),Pf(t,{softError:!0})){ul(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},Vi=(e,t)=>Of({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:Jt({path:{accountId:e}})})}),zj=e=>{const t=ye(),s=c.useRef(e);s.current=e;const r=e.map(a=>a.accountId).join(",");c.useEffect(()=>{const a=Date.now(),i=$j(s.current,a).filter(l=>!aa.has(l));if(i.length!==0)for(const l of i)aa.add(l),Vi(l,t).catch(u=>{Wi(l,u)})},[r,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const d=_j(s.current.map(m=>m.accountId),i);for(const m of d)i.add(m);Rj(d,m=>Vi(m,t).catch(h=>{Wi(m,h)}).finally(()=>{i.delete(m)}),{concurrency:Lj})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,On);return}},f=()=>{document.visibilityState==="visible"&&Fj(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,On))};return o=setTimeout(u,On),document.addEventListener("visibilitychange",f),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",f)}},[r,t])};function Bj(e,t,s){if(e!==t)return s}function Kj(e,t){return e===""?"":t}function Uj(e,t,s){return t!==e?!1:t!==s}function qj(){const{q:e=""}=vs({from:"/mail"}),t=Oe(),s=lr(),r=Tu(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,f]=c.useState(!1),d=c.useCallback(te=>{f(te),Bi(te)},[]),[m,h]=c.useState(e),g=ml(m,200),v=Kj(m,g),p=c.useRef(e);p.current=e;const x=gt({select:te=>Hx(te.matches)}),[b,w]=c.useState(x);if(b!==x){const te=Bj(b,x,e);w(x),te!==void 0&&h(te)}c.useEffect(()=>{Uj(m,v,p.current)&&t({to:".",search:te=>{const K=te.q===v;return{...te,q:v||void 0,...v&&!K?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[m,v,t]);const{data:j,isLoading:y,isError:I,error:N,refetch:k}=de({...xt(),staleTime:1/0}),C=!!(j&&(j.accounts?.length??0)===0);c.useEffect(()=>{C&&t({to:"/onboarding",replace:!0})},[C,t]),Ha({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const M=c.useCallback(te=>{h(te)},[]),P=c.useCallback(()=>{h("")},[]),D=c.useCallback(()=>{h("")},[]),O=c.useCallback(()=>{f(te=>{const K=!te;return Bi(K),K})},[]),E=j?.accounts??[],S=Cj(E),A=Ej(E),L=c.useMemo(()=>Sj(E),[E]),T=gt({select:te=>te.matches.find(U=>"mailboxId"in U.params)?.params.mailboxId}),{selectedMessageId:F}=vs({strict:!1}),R=gt({select:te=>Ka(te.matches)}),$=gt({select:te=>nn(te.matches)}),z=gt({select:te=>sr(te.matches)});zj(E);const V=c.useCallback(()=>{l(!1)},[]),ee={accounts:E,mailboxNameIndex:S,accountNameIndex:L,resultFolderIndex:A,searchQuery:v,searchInput:m,searchViewKey:x,onSearchChange:M,onSearchClear:P,onSearchClearQuery:D,intelligenceOpen:u,onToggleIntelligence:O,onSetIntelligenceOpen:d},X=n.jsx(mj,{accounts:E,onMailboxSelect:V}),Q=r?n.jsx(Kx,{accounts:E}):void 0,le=r?void 0:n.jsx(Zx,{accounts:E}),ue={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return n.jsxs($f.Provider,{value:ee,children:[I?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:n.jsx(Pt,{title:"Couldn't load your account",error:N,onRetry:()=>{k()}})}):R?n.jsx(Fs,{selectedMessageId:F,children:r?n.jsx(kt,{nav:X,list:n.jsx(Fs.Phone,{}),intelligenceOpen:u,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue}):n.jsx(kt,{nav:X,topBar:le,list:n.jsx(Fs.List,{}),reading:n.jsx(Fs.Reading,{}),intelligence:n.jsx(Fs.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue})}):$?n.jsx(_s,{selectedMessageId:F,children:r?n.jsx(kt,{nav:X,list:n.jsx(_s.Phone,{}),intelligenceOpen:u,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue}):n.jsx(kt,{nav:X,topBar:le,list:n.jsx(_s.List,{}),reading:n.jsx(_s.Reading,{}),intelligence:n.jsx(_s.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue})}):T?n.jsx(Bs,{mailboxId:T,selectedMessageId:F,children:r?n.jsx(kt,{nav:X,list:n.jsx(Bs.Phone,{}),intelligenceOpen:u,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue}):n.jsx(kt,{nav:X,topBar:le,list:n.jsx(Bs.List,{}),reading:n.jsx(Bs.Reading,{}),intelligence:n.jsx(Bs.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue})}):z?n.jsx(In,{children:r?n.jsx(kt,{nav:X,list:n.jsx(In.Phone,{}),intelligenceOpen:!1,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue}):n.jsx(kt,{nav:X,topBar:le,list:n.jsx(In.List,{}),reading:n.jsx(In.Reading,{}),intelligenceOpen:!1,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue})}):n.jsx(ht,{}),n.jsx(jj,{isOpen:a,onClose:()=>o(!1)}),n.jsx(Ff,{})]})}const uS=Object.freeze(Object.defineProperty({__proto__:null,component:qj,useMailContext:Ce},Symbol.toStringTag,{value:"Module"}));export{cS as S,Ym as U,uS as m};
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 cv(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function uv(){return Ja(/^Mac/)}function dv(){return Ja(/^iPhone/)}function Ci(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function fv(){return Ja(/^iPad/)||uv()&&navigator.maxTouchPoints>1}function cu(){return dv()||fv()}function Ja(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const mv=24,hv=typeof window<"u"?c.useLayoutEffect:c.useEffect;function Ni(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const Or=typeof document<"u"&&window.visualViewport;function Ei(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function uu(e){for(Ei(e)&&(e=e.parentElement);e&&!Ei(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const pv=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Nn=0,Pr;function gv(e={}){let{isDisabled:t}=e;hv(()=>{if(!t)return Nn++,Nn===1&&cu()&&(Pr=xv()),()=>{Nn--,Nn===0&&Pr?.()}},[t])}function xv(){let e,t=0,s=m=>{e=uu(m.target),!(e===document.documentElement&&e===document.body)&&(t=m.changedTouches[0].pageY)},r=m=>{if(!e||e===document.documentElement||e===document.body){m.preventDefault();return}let h=m.changedTouches[0].pageY,g=e.scrollTop,v=e.scrollHeight-e.clientHeight;v!==0&&((g<=0&&h>t||g>=v&&h<t)&&m.preventDefault(),t=h)},a=m=>{let h=m.target;ea(h)&&h!==document.activeElement&&(m.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=m=>{let h=m.target;ea(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",Or&&(Or.height<window.innerHeight?requestAnimationFrame(()=>{Ii(h)}):Or.addEventListener("resize",()=>Ii(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,f=Ni(bv(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=Ni(Ps(document,"touchstart",s,{passive:!1,capture:!0}),Ps(document,"touchmove",r,{passive:!1,capture:!0}),Ps(document,"touchend",a,{passive:!1,capture:!0}),Ps(document,"focus",o,!0),Ps(window,"scroll",i));return()=>{f(),d(),window.scrollTo(l,u)}}function bv(e,t,s){let r=e.style[t];return e.style[t]=s,()=>{e.style[t]=r}}function Ps(e,t,s,r){return e.addEventListener(t,s,r),()=>{e.removeEventListener(t,s,r)}}function Ii(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=uu(e);if(s!==document.documentElement&&s!==document.body&&s!==e){let r=s.getBoundingClientRect().top,a=e.getBoundingClientRect().top,o=e.getBoundingClientRect().bottom;const i=s.getBoundingClientRect().bottom+mv;o>i&&(s.scrollTop+=a-r)}e=s.parentElement}}function ea(e){return e instanceof HTMLInputElement&&!pv.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function vv(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function yv(...e){return t=>e.forEach(s=>vv(s,t))}function du(...e){return c.useCallback(yv(...e),e)}const fu=new WeakMap;function Ee(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let r={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}r[a]=e.style[a],e.style[a]=o}),!s&&fu.set(e,r)}function wv(e,t){if(!e||!(e instanceof HTMLElement))return;let s=fu.get(e);s&&(e.style[t]=s[t])}const ke=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function En(e,t){if(!e)return null;const s=window.getComputedStyle(e),r=s.transform||s.webkitTransform||s.mozTransform;let a=r.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[ke(t)?13:12]):(a=r.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[ke(t)?5:4]):null)}function jv(e){return 8*(Math.log(e+1)-2)}function Lr(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function Sv(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const xe={DURATION:.5,EASE:[.32,.72,0,1]},mu=.4,kv=.25,Cv=100,hu=8,qt=16,ta=26,$r="vaul-dragging";function pu(e){const t=q.useRef(e);return q.useEffect(()=>{t.current=e}),q.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function Nv({defaultProp:e,onChange:t}){const s=q.useState(e),[r]=s,a=q.useRef(r),o=pu(t);return q.useEffect(()=>{a.current!==r&&(o(r),a.current=r)},[r,a,o]),s}function gu({prop:e,defaultProp:t,onChange:s=()=>{}}){const[r,a]=Nv({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:r,l=pu(s),u=q.useCallback(f=>{if(o){const m=typeof f=="function"?f(e):f;m!==e&&l(m)}else a(f)},[o,e,a,l]);return[i,u]}function Ev({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:r,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:f}){const[d,m]=gu({prop:e,defaultProp:s?.[0],onChange:t}),[h,g]=q.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);q.useEffect(()=>{function k(){g({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]);const v=q.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=q.useMemo(()=>{var k;return(k=s?.findIndex(C=>C===d))!=null?k:null},[s,d]),x=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,b=q.useMemo(()=>{const k=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var C;return(C=s?.map(M=>{const P=typeof M=="string";let D=0;if(P&&(D=parseInt(M,10)),ke(l)){const E=P?D:h?M*k.height:0;return h?l==="bottom"?k.height-E:-k.height+E:E}const O=P?D:h?M*k.width:0;return h?l==="right"?k.width-O:-k.width+O:O}))!=null?C:[]},[s,h,u]),w=q.useMemo(()=>p!==null?b?.[p]:null,[b,p]),j=q.useCallback(k=>{var C;const M=(C=b?.findIndex(P=>P===k))!=null?C:null;i(M),Ee(r.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(l)?`translate3d(0, ${k}px, 0)`:`translate3d(${k}px, 0, 0)`}),b&&M!==b.length-1&&o!==void 0&&M!==o&&M<o?Ee(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"0"}):Ee(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"1"}),m(s?.[Math.max(M,0)])},[r.current,s,b,o,a,m]);q.useEffect(()=>{if(d||e){var k;const C=(k=s?.findIndex(M=>M===e||M===d))!=null?k:-1;b&&C!==-1&&typeof b[C]=="number"&&j(b[C])}},[d,e,s,b,j]);function y({draggedDistance:k,closeDrawer:C,velocity:M,dismissible:P}){if(o===void 0)return;const D=l==="bottom"||l==="right"?(w??0)-k:(w??0)+k,O=p===o-1,E=p===0,S=k>0;if(O&&Ee(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`}),!f&&M>2&&!S){P?C():j(b[0]);return}if(!f&&M>2&&S&&b&&s){j(b[s.length-1]);return}const A=b?.reduce((T,F)=>typeof T!="number"||typeof F!="number"?T:Math.abs(F-D)<Math.abs(T-D)?F:T),L=ke(l)?window.innerHeight:window.innerWidth;if(M>mu&&Math.abs(k)<L*.4){const T=S?1:-1;if(T>0&&v&&s){j(b[s.length-1]);return}if(E&&T<0&&P&&C(),p===null)return;j(b[p+T]);return}j(A)}function I({draggedDistance:k}){if(w===null)return;const C=l==="bottom"||l==="right"?w-k:w+k;(l==="bottom"||l==="right")&&C<b[b.length-1]||(l==="top"||l==="left")&&C>b[b.length-1]||Ee(r.current,{transform:ke(l)?`translate3d(0, ${C}px, 0)`:`translate3d(${C}px, 0, 0)`})}function N(k,C){if(!s||typeof p!="number"||!b||o===void 0)return null;const M=p===o-1;if(p>=o&&C)return 0;if(M&&!C)return 1;if(!x&&!M)return null;const D=M?p+1:p-1,O=M?b[D]-b[D-1]:b[D+1]-b[D],E=k/Math.abs(O);return M?1-E:E}return{isLastSnapPoint:v,activeSnapPoint:d,shouldFade:x,getPercentageDragged:N,setActiveSnapPoint:m,activeSnapPointIndex:p,onRelease:y,onDrag:I,snapPointsOffset:b}}const Iv=()=>()=>{};function Tv(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:r,noBodyStyles:a}=un(),o=q.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-ta)/window.innerWidth}q.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;Sv(r&&!a?Lr(document.body,{background:"black"}):Iv,Lr(u,{transformOrigin:ke(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${xe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${xe.EASE.join(",")})`}));const f=Lr(u,{borderRadius:`${hu}px`,overflow:"hidden",...ke(e)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{f(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},xe.DURATION*1e3)}}},[t,s,i])}let Ls=null;function Rv({isOpen:e,modal:t,nested:s,hasBeenOpened:r,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=q.useState(()=>typeof window<"u"?window.location.href:""),u=q.useRef(0),f=q.useCallback(()=>{if(Ci()&&Ls===null&&e&&!o){Ls={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:m,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-m}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const g=h-window.innerHeight;g&&u.current>=h&&(document.body.style.top=`${-(u.current+g)}px`)}),300)}},[e]),d=q.useCallback(()=>{if(Ci()&&Ls!==null&&!o){const m=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Ls),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,m)}),Ls=null}},[i]);return q.useEffect(()=>{function m(){u.current=window.scrollY}return m(),window.addEventListener("scroll",m),()=>{window.removeEventListener("scroll",m)}},[]),q.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),q.useEffect(()=>{s||!r||(e?(!window.matchMedia("(display-mode: standalone)").matches&&f(),t||window.setTimeout(()=>{d()},500)):d())},[e,r,i,t,s,f,d]),{restorePositionSetting:d}}function Mv({open:e,onOpenChange:t,children:s,onDrag:r,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=kv,scrollLockTimeout:f=Cv,dismissible:d=!0,handleOnly:m=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:g,setActiveSnapPoint:v,fixed:p,modal:x=!0,onClose:b,nested:w,noBodyStyles:j=!1,direction:y="bottom",defaultOpen:I=!1,disablePreventScroll:N=!0,snapToSequentialPoint:k=!1,preventScrollRestoration:C=!1,repositionInputs:M=!0,onAnimationEnd:P,container:D,autoFocus:O=!1}){var E,S;const[A=!1,L]=gu({defaultProp:I,prop:e,onChange:Z=>{t?.(Z),!Z&&!w&&Be(),setTimeout(()=>{P?.(Z)},xe.DURATION*1e3),Z&&!x&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),Z||(document.body.style.pointerEvents="auto")}}),[T,F]=q.useState(!1),[R,$]=q.useState(!1),[z,V]=q.useState(!1),ee=q.useRef(null),X=q.useRef(null),Q=q.useRef(null),le=q.useRef(null),ue=q.useRef(null),te=q.useRef(!1),K=q.useRef(null),U=q.useRef(0),re=q.useRef(!1),Ie=q.useRef(!I),je=q.useRef(0),W=q.useRef(null),J=q.useRef(((E=W.current)==null?void 0:E.getBoundingClientRect().height)||0),ae=q.useRef(((S=W.current)==null?void 0:S.getBoundingClientRect().width)||0),ce=q.useRef(0),B=q.useCallback(Z=>{o&&Z===Qe.length-1&&(X.current=new Date)},[]),{activeSnapPoint:Fe,activeSnapPointIndex:pe,setActiveSnapPoint:ge,onRelease:Se,snapPointsOffset:Qe,onDrag:ts,shouldFade:ze,getPercentageDragged:Ze}=Ev({snapPoints:o,activeSnapPointProp:g,setActiveSnapPointProp:v,drawerRef:W,fadeFromIndex:h,overlayRef:ee,onSnapPointChange:B,direction:y,container:D,snapToSequentialPoint:k});gv({isDisabled:!A||R||!x||z||!T||!M||!N});const{restorePositionSetting:Be}=Rv({isOpen:A,modal:x,nested:w??!1,hasBeenOpened:T,preventScrollRestoration:C,noBodyStyles:j});function Ke(){return(window.innerWidth-ta)/window.innerWidth}function ft(Z){var ie,ne;!d&&!o||W.current&&!W.current.contains(Z.target)||(J.current=((ie=W.current)==null?void 0:ie.getBoundingClientRect().height)||0,ae.current=((ne=W.current)==null?void 0:ne.getBoundingClientRect().width)||0,$(!0),Q.current=new Date,cu()&&window.addEventListener("touchend",()=>te.current=!1,{once:!0}),Z.target.setPointerCapture(Z.pointerId),U.current=ke(y)?Z.pageY:Z.pageX)}function Te(Z,ie){var ne;let oe=Z;const he=(ne=window.getSelection())==null?void 0:ne.toString(),me=W.current?En(W.current,y):null,we=new Date;if(oe.tagName==="SELECT"||oe.hasAttribute("data-vaul-no-drag")||oe.closest("[data-vaul-no-drag]"))return!1;if(y==="right"||y==="left")return!0;if(X.current&&we.getTime()-X.current.getTime()<500)return!1;if(me!==null&&(y==="bottom"?me>0:me<0))return!0;if(he&&he.length>0)return!1;if(ue.current&&we.getTime()-ue.current.getTime()<f&&me===0||ie)return ue.current=we,!1;for(;oe;){if(oe.scrollHeight>oe.clientHeight){if(oe.scrollTop!==0)return ue.current=new Date,!1;if(oe.getAttribute("role")==="dialog")return!0}oe=oe.parentNode}return!0}function ss(Z){if(W.current&&R){const ie=y==="bottom"||y==="right"?1:-1,ne=(U.current-(ke(y)?Z.pageY:Z.pageX))*ie,oe=ne>0,he=o&&!d&&!oe;if(he&&pe===0)return;const me=Math.abs(ne),we=document.querySelector("[data-vaul-drawer-wrapper]"),Pe=y==="bottom"||y==="top"?J.current:ae.current;let Ae=me/Pe;const He=Ze(me,oe);if(He!==null&&(Ae=He),he&&Ae>=1||!te.current&&!Te(Z.target,oe))return;if(W.current.classList.add($r),te.current=!0,Ee(W.current,{transition:"none"}),Ee(ee.current,{transition:"none"}),o&&ts({draggedDistance:ne}),oe&&!o){const Re=jv(ne),Ye=Math.min(Re*-1,0)*ie;Ee(W.current,{transform:ke(y)?`translate3d(0, ${Ye}px, 0)`:`translate3d(${Ye}px, 0, 0)`});return}const De=1-Ae;if((ze||h&&pe===h-1)&&(r?.(Z,Ae),Ee(ee.current,{opacity:`${De}`,transition:"none"},!0)),we&&ee.current&&i){const Re=Math.min(Ke()+Ae*(1-Ke()),1),Ye=8-Ae*8,Ge=Math.max(0,14-Ae*14);Ee(we,{borderRadius:`${Ye}px`,transform:ke(y)?`scale(${Re}) translate3d(0, ${Ge}px, 0)`:`scale(${Re}) translate3d(${Ge}px, 0, 0)`,transition:"none"},!0)}if(!o){const Re=me*ie;Ee(W.current,{transform:ke(y)?`translate3d(0, ${Re}px, 0)`:`translate3d(${Re}px, 0, 0)`})}}}q.useEffect(()=>{window.requestAnimationFrame(()=>{Ie.current=!0})},[]),q.useEffect(()=>{var Z;function ie(){if(!W.current||!M)return;const ne=document.activeElement;if(ea(ne)||re.current){var oe;const he=((oe=window.visualViewport)==null?void 0:oe.height)||0,me=window.innerHeight;let we=me-he;const Pe=W.current.getBoundingClientRect().height||0,Ae=Pe>me*.8;ce.current||(ce.current=Pe);const He=W.current.getBoundingClientRect().top;if(Math.abs(je.current-we)>60&&(re.current=!re.current),o&&o.length>0&&Qe&&pe){const De=Qe[pe]||0;we+=De}if(je.current=we,Pe>he||re.current){const De=W.current.getBoundingClientRect().height;let Re=De;De>he&&(Re=he-(Ae?He:ta)),p?W.current.style.height=`${De-Math.max(we,0)}px`:W.current.style.height=`${Math.max(Re,he-He)}px`}else cv()||(W.current.style.height=`${ce.current}px`);o&&o.length>0&&!re.current?W.current.style.bottom="0px":W.current.style.bottom=`${Math.max(we,0)}px`}}return(Z=window.visualViewport)==null||Z.addEventListener("resize",ie),()=>{var ne;return(ne=window.visualViewport)==null?void 0:ne.removeEventListener("resize",ie)}},[pe,o,Qe]);function Ue(Z){Ne(),b?.(),Z||L(!1),setTimeout(()=>{o&&ge(o[0])},xe.DURATION*1e3)}function _t(){if(!W.current)return;const Z=document.querySelector("[data-vaul-drawer-wrapper]"),ie=En(W.current,y);Ee(W.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`}),Ee(ee.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"1"}),i&&ie&&ie>0&&A&&Ee(Z,{borderRadius:`${hu}px`,overflow:"hidden",...ke(y)?{transform:`scale(${Ke()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${Ke()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${xe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${xe.EASE.join(",")})`},!0)}function Ne(){!R||!W.current||(W.current.classList.remove($r),te.current=!1,$(!1),le.current=new Date)}function qe(Z){if(!R||!W.current)return;W.current.classList.remove($r),te.current=!1,$(!1),le.current=new Date;const ie=En(W.current,y);if(!Z||!Te(Z.target,!1)||!ie||Number.isNaN(ie)||Q.current===null)return;const ne=le.current.getTime()-Q.current.getTime(),oe=U.current-(ke(y)?Z.pageY:Z.pageX),he=Math.abs(oe)/ne;if(he>.05&&(V(!0),setTimeout(()=>{V(!1)},200)),o){Se({draggedDistance:oe*(y==="bottom"||y==="right"?1:-1),closeDrawer:Ue,velocity:he,dismissible:d}),a?.(Z,!0);return}if(y==="bottom"||y==="right"?oe>0:oe<0){_t(),a?.(Z,!0);return}if(he>mu){Ue(),a?.(Z,!1);return}var me;const we=Math.min((me=W.current.getBoundingClientRect().height)!=null?me:0,window.innerHeight);var Pe;const Ae=Math.min((Pe=W.current.getBoundingClientRect().width)!=null?Pe:0,window.innerWidth),He=y==="left"||y==="right";if(Math.abs(ie)>=(He?Ae:we)*u){Ue(),a?.(Z,!1);return}a?.(Z,!0),_t()}q.useEffect(()=>(A&&(Ee(document.documentElement,{scrollBehavior:"auto"}),X.current=new Date),()=>{wv(document.documentElement,"scrollBehavior")}),[A]);function mt(Z){const ie=Z?(window.innerWidth-qt)/window.innerWidth:1,ne=Z?-qt:0;K.current&&window.clearTimeout(K.current),Ee(W.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(y)?`scale(${ie}) translate3d(0, ${ne}px, 0)`:`scale(${ie}) translate3d(${ne}px, 0, 0)`}),!Z&&W.current&&(K.current=setTimeout(()=>{const oe=En(W.current,y);Ee(W.current,{transition:"none",transform:ke(y)?`translate3d(0, ${oe}px, 0)`:`translate3d(${oe}px, 0, 0)`})},500))}function ns(Z,ie){if(ie<0)return;const ne=(window.innerWidth-qt)/window.innerWidth,oe=ne+ie*(1-ne),he=-qt+ie*qt;Ee(W.current,{transform:ke(y)?`scale(${oe}) translate3d(0, ${he}px, 0)`:`scale(${oe}) translate3d(${he}px, 0, 0)`,transition:"none"})}function zt(Z,ie){const ne=ke(y)?window.innerHeight:window.innerWidth,oe=ie?(ne-qt)/ne:1,he=ie?-qt:0;ie&&Ee(W.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(y)?`scale(${oe}) translate3d(0, ${he}px, 0)`:`scale(${oe}) translate3d(${he}px, 0, 0)`})}return q.useEffect(()=>{x||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[x]),q.createElement(Xc,{defaultOpen:I,onOpenChange:Z=>{!d&&!Z||(Z?F(!0):Ue(!0),L(Z))},open:A},q.createElement(lu.Provider,{value:{activeSnapPoint:Fe,snapPoints:o,setActiveSnapPoint:ge,drawerRef:W,overlayRef:ee,onOpenChange:t,onPress:ft,onRelease:qe,onDrag:ss,dismissible:d,shouldAnimate:Ie,handleOnly:m,isOpen:A,isDragging:R,shouldFade:ze,closeDrawer:Ue,onNestedDrag:ns,onNestedOpenChange:mt,onNestedRelease:zt,keyboardIsOpen:re,modal:x,snapPointsOffset:Qe,activeSnapPointIndex:pe,direction:y,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:j,container:D,autoFocus:O}},s))}const xu=q.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:r,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=un(),f=du(t,s),d=r&&r.length>0;if(!l)return null;const m=q.useCallback(h=>a(h),[a]);return q.createElement(tu,{onMouseUp:m,ref:f,"data-vaul-overlay":"","data-vaul-snap-points":i&&d?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});xu.displayName="Drawer.Overlay";const bu=q.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...r},a){const{drawerRef:o,onPress:i,onRelease:l,onDrag:u,keyboardIsOpen:f,snapPointsOffset:d,activeSnapPointIndex:m,modal:h,isOpen:g,direction:v,snapPoints:p,container:x,handleOnly:b,shouldAnimate:w,autoFocus:j}=un(),[y,I]=q.useState(!1),N=du(a,o),k=q.useRef(null),C=q.useRef(null),M=q.useRef(!1),P=p&&p.length>0;Tv();const D=(E,S,A=0)=>{if(M.current)return!0;const L=Math.abs(E.y),T=Math.abs(E.x),F=T>L,R=["bottom","right"].includes(S)?1:-1;if(S==="left"||S==="right"){if(!(E.x*R<0)&&T>=0&&T<=A)return F}else if(!(E.y*R<0)&&L>=0&&L<=A)return!F;return M.current=!0,!0};q.useEffect(()=>{P&&window.requestAnimationFrame(()=>{I(!0)})},[]);function O(E){k.current=null,M.current=!1,l(E)}return q.createElement(su,{"data-vaul-drawer-direction":v,"data-vaul-drawer":"","data-vaul-delayed-snap-points":y?"true":"false","data-vaul-snap-points":g&&P?"true":"false","data-vaul-custom-container":x?"true":"false","data-vaul-animate":w?.current?"true":"false",...r,ref:N,style:d&&d.length>0?{"--snap-point-height":`${d[m??0]}px`,...t}:t,onPointerDown:E=>{b||(r.onPointerDown==null||r.onPointerDown.call(r,E),k.current={x:E.pageX,y:E.pageY},i(E))},onOpenAutoFocus:E=>{s?.(E),j||E.preventDefault()},onPointerDownOutside:E=>{if(e?.(E),!h||E.defaultPrevented){E.preventDefault();return}f.current&&(f.current=!1)},onFocusOutside:E=>{if(!h){E.preventDefault();return}},onPointerMove:E=>{if(C.current=E,b||(r.onPointerMove==null||r.onPointerMove.call(r,E),!k.current))return;const S=E.pageY-k.current.y,A=E.pageX-k.current.x,L=E.pointerType==="touch"?10:2;D({x:A,y:S},v,L)?u(E):(Math.abs(A)>L||Math.abs(S)>L)&&(k.current=null)},onPointerUp:E=>{r.onPointerUp==null||r.onPointerUp.call(r,E),k.current=null,M.current=!1,l(E)},onPointerOut:E=>{r.onPointerOut==null||r.onPointerOut.call(r,E),O(C.current)},onContextMenu:E=>{r.onContextMenu==null||r.onContextMenu.call(r,E),C.current&&O(C.current)}})});bu.displayName="Drawer.Content";const Av=250,Dv=120,vu=q.forwardRef(function({preventCycle:e=!1,children:t,...s},r){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:l,setActiveSnapPoint:u,dismissible:f,handleOnly:d,isOpen:m,onPress:h,onDrag:g}=un(),v=q.useRef(null),p=q.useRef(!1);function x(){if(p.current){j();return}window.setTimeout(()=>{b()},Dv)}function b(){if(o||e||p.current){j();return}if(j(),!i||i.length===0){f||a();return}if(l===i[i.length-1]&&f){a();return}const I=i.findIndex(k=>k===l);if(I===-1)return;const N=i[I+1];u(N)}function w(){v.current=window.setTimeout(()=>{p.current=!0},Av)}function j(){v.current&&window.clearTimeout(v.current),p.current=!1}return q.createElement("div",{onClick:x,onPointerCancel:j,onPointerDown:y=>{d&&h(y),w()},onPointerMove:y=>{d&&g(y)},ref:r,"data-vaul-drawer-visible":m?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},q.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});vu.displayName="Drawer.Handle";function Ov(e){const t=un(),{container:s=t.container,...r}=e;return q.createElement(eu,{container:s,...r})}const Je={Root:Mv,Content:bu,Overlay:xu,Portal:Ov,Handle:vu,Title:au},yu="inline-flex items-center justify-center transition-colors",Pv=be(yu,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Lv=be(yu,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),dn=({accountId:e,currentMailboxId:t,onMove:s,disabled:r=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),f=Ot(),d=c.useRef(null),m=i??"Move to folder",h=c.useId(),{t:g}=Un("mail",{useSuspense:!1}),v=c.useCallback((O,E)=>g(O,{defaultValue:E}),[g]),{data:p,isLoading:x,isError:b,error:w,refetch:j}=de({..._e({path:{accountId:e}}),staleTime:1/0,enabled:l}),y=Vc(e),{createFolder:I}=Sl(e),N=c.useMemo(()=>{const O=Zs(p?.items??[],y),E=Xs(y);return O.map(S=>({id:S.mailboxId,label:bs(S,E.get(S.mailboxId),v),searchValue:S.fullPath,isCurrent:S.mailboxId===t}))},[p?.items,y,t,v]),k=c.useCallback(O=>{u(!1),s(O)},[s]),C=c.useCallback(async(O,E)=>{const S=await I(O,E);return{id:S.id,label:S.label}},[I]);c.useEffect(()=>{if(!l||!f)return;const O=S=>{d.current&&!d.current.contains(S.target)&&u(!1)},E=S=>{S.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",O),document.addEventListener("keydown",E),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("keydown",E)}},[l,f]);const M=r||!!a,P=n.jsxs("button",{type:"button",onClick:O=>{O.stopPropagation(),!M&&u(E=>!E)},"aria-label":m,"aria-haspopup":f?"listbox":"dialog","aria-expanded":l,"aria-controls":l?h:void 0,title:a,className:o==="icon-only"?Pv:Lv,children:[n.jsx(Ia,{className:"size-4"}),o==="compact"&&n.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),D=x?n.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):b?n.jsx("div",{className:"p-3",children:n.jsx(Pt,{variant:"inline",title:"Couldn't load folders",error:w,onRetry:()=>j()})}):n.jsx(kl,{mailboxes:N,onSelect:k,onCreateFolder:C,onCancel:()=>u(!1),autoFocus:!f,labels:{createLabel:O=>`Create "${O}"`,searchPlaceholder:g("move_picker_placeholder",{defaultValue:"Move to…"}),searchAriaLabel:g("move_picker_filter_label",{defaultValue:"Filter folders"}),optionLabel:O=>`Move to ${O}`,currentSuffix:"(current folder)",currentTag:"current",emptyMessage:O=>`No folders match "${O}"`}});return f?n.jsxs("div",{ref:d,className:"relative inline-block",children:[P,l&&n.jsx("div",{id:h,className:be("absolute right-0 mt-1 z-50 w-72 max-h-96 flex flex-col","bg-surface border border-line rounded-md shadow-lg"),children:D})]}):n.jsxs(n.Fragment,{children:[P,n.jsx(Je.Root,{open:l,onOpenChange:u,children:n.jsxs(Je.Portal,{children:[n.jsx(Je.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Je.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{maxHeight:"85dvh"},id:h,children:[n.jsx(Je.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),n.jsx(Je.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),n.jsx("div",{className:"flex-1 overflow-hidden",children:D})]})]})})]})},$v=({messageId:e,threadId:t,mailboxId:s,isRead:r,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const f=ye(),d=Oe(),{pushError:m}=Ve(),{selectedMessageId:h}=vs({strict:!1}),{mutate:g,isPending:v}=ve({...Wn(),onMutate:async A=>{const L=A.body.isRead??!0,T=new Set(A.body.messageIds??[]),F=Zt({path:{threadId:t}}),R=vt([s]);await Promise.all([f.cancelQueries({queryKey:F}),rn(f,R)]);const $=f.getQueriesData({queryKey:F}).filter(V=>V[1]!==void 0).map(([V,ee])=>({queryKey:V,data:ee})),z=an(f,R);return f.setQueriesData({queryKey:F},V=>V&&{...V,items:$n(V.items,T,L)}),on(f,R,V=>$n(V,T,L)),{threadMessagesPrefix:F,listPrefixes:R,previousThreadMessages:$,previousThreadsList:z}},onError:(A,L,T)=>{if(T){for(const R of T.previousThreadMessages)f.setQueryData(R.queryKey,R.data);ln(f,T.previousThreadsList)}const F=L.body.isRead??!0;m({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:st(A),error:A})},onSettled:(A,L,T,F)=>{F&&(f.invalidateQueries({queryKey:F.threadMessagesPrefix}),yt(f,F.listPrefixes))}}),p=c.useCallback(A=>{h&&A.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:L=>({...L,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:x,isPending:b}=Yt({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:w,isPending:j}=Qt({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:y,isPending:I,error:N,reset:k}=Ya({messageId:e}),C=()=>{g({body:{messageIds:[e],isRead:!1}})},M=()=>{x([e])},P=()=>{o&&y(o,i)},D=v||b||j||I,O=D||!o,E=c.useCallback(A=>{w([e],A)},[w,e]),S=o?void 0:"Sender has no parseable address";return n.jsxs("div",{className:"flex flex-col items-end gap-1",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[a&&n.jsx(dn,{accountId:a,currentMailboxId:s,onMove:E,disabled:D,label:"Move this message"}),n.jsxs(Nc,{trigger:n.jsx(zl,{className:"size-4"}),children:[n.jsxs(hs,{onClick:P,disabled:O,children:[i?n.jsx(Xn,{className:"size-4 text-positive"}):n.jsx(Ys,{className:"size-4 opacity-0"}),n.jsx("span",{title:S,children:"Trusted sender"})]}),r&&n.jsxs(hs,{onClick:C,disabled:D,children:[n.jsx(Cs,{className:"size-4"}),"Mark as unread"]}),u&&n.jsxs(hs,{onClick:u,children:[n.jsx(_l,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),n.jsx(Xr,{}),n.jsxs(hs,{onClick:M,disabled:D,destructive:!0,children:[n.jsx(rt,{className:"size-4"}),"Delete"]})]})]}),N&&n.jsx("div",{className:"w-64",children:n.jsx(Pt,{variant:"inline",title:"Couldn't update trust",error:N,onRetry:()=>{k(),P()}})})]})},Fv=()=>{const[e,t]=c.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return c.useEffect(()=>{const s=document.documentElement,r=new MutationObserver(()=>{t(s.classList.contains("dark"))});return r.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>r.disconnect()},[]),e},_v=({blockedImageCount:e,canAlwaysTrust:t,isTrustPending:s,onLoadOnce:r,onAlwaysTrust:a})=>n.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-md bg-surface-sunken/50 px-3 py-2 text-sm",children:[n.jsxs("span",{className:"text-fg-muted",children:[e," image",e>1?"s":""," blocked for privacy"]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:r,className:"text-accent hover:underline",children:"Load once"}),t&&n.jsx("button",{type:"button",onClick:a,"aria-busy":s,className:"text-accent hover:underline aria-busy:opacity-50",children:s?"Trusting…":"Always trust"})]})]}),zv=(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}}},Bv=e=>e instanceof Ht?e.reason:"generic",Kv=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",Uv=({error:e,onRetry:t})=>{const s=Bv(e),r=Kv(e),{title:a,detail:o}=zv(s,r),[i,l]=c.useState(!1),{Account:u}=xa();return i?null:n.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[n.jsx(Gt,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"font-medium text-danger",children:a}),n.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&n.jsx(u,{children:({signOut:f})=>n.jsx("button",{type:"button",onClick:()=>f(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&n.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),n.jsx("button",{type:"button",onClick:()=>l(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:n.jsx(We,{className:"size-4","aria-hidden":"true"})})]})]})},qv=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),Ti=()=>n.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),wu=({bodyParts:e,html:t,text:s,isTrusted:r=!1,messageId:a,fromAddressId:o,category:i,className:l})=>{const[u,f]=c.useState(!1),d=r||u,m=Fv(),{toggleTrusted:h,isPending:g}=Ya({messageId:a??""}),v=!!e&&e.length>0,{picked:p,data:x,isLoading:b,isError:w,error:j,refetch:y}=Fc({messageId:a,bodyParts:e,enabled:v}),I=c.useMemo(()=>kh(e??[]),[e]),N=v&&x?.kind==="html"?x.body:t,k=v&&x?.kind==="text"?x.body:s;if(v){if(b)return n.jsx("div",{className:be("message-body",l),children:n.jsx(qv,{})});if(w)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Uv,{error:j,onRetry:()=>y()})});if(!p)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Ti,{})})}else if(!t&&!s)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Ti,{})});const C=!!(o&&a),M=()=>{!o||g||(f(!0),h(o,!1))};return n.jsx(nc,{className:l,html:N,text:k,isDark:m,category:i,allowImages:d,resolveCid:I,renderBlockedNotice:P=>n.jsx(_v,{blockedImageCount:P,canAlwaysTrust:C,isTrustPending:g,onLoadOnce:()=>f(!0),onAlwaysTrust:M})})},Hv=({messageId:e,threadId:t,mailboxId:s,accountId:r,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:l,isTrusted:u,showRaw:f,onToggleRaw:d,onReply:m,onReplyAll:h,onForward:g})=>{const v=ye(),{deleteMessages:p}=Yt({mailboxId:s,threadId:t}),{moveMessages:x}=Qt({mailboxId:s,threadId:t,accountId:r}),{toggleTrusted:b}=Ya({messageId:e}),{mutate:w}=ve({...Wn(),onSettled:()=>{v.invalidateQueries({queryKey:Zt({path:{threadId:t}})}),yt(v,vt([s]))}}),j=c.useCallback(k=>{x([e],k)},[x,e]),y=c.useCallback(()=>{p([e])},[p,e]),I=c.useCallback(()=>{w({body:{messageIds:[e],isRead:!a}})},[w,e,a]),N=[];return l&&N.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?n.jsx(Xn,{className:"size-4 text-positive"}):n.jsx(Ys,{className:"size-4"}),onSelect:()=>b(l,u)}),d&&N.push({key:"raw",label:f?"Show formatted":"Show raw email",icon:n.jsx(_l,{className:"size-4"}),onSelect:d}),n.jsx(sc,{hasThread:!0,onReply:m,onReplyAll:h,onForward:g,isStarred:o,onToggleStar:i,onDelete:y,isRead:a,onToggleRead:I,overflowItems:N,moveSlot:r?n.jsx(dn,{accountId:r,currentMailboxId:s,onMove:j,label:"Move this message"}):void 0})},Wv=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading raw email",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"})]}),Vv=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:r,isError:a,error:o,refetch:i}=de({...gf({path:{messageId:e}}),enabled:t});if(r)return n.jsx("div",{className:"message-body",children:n.jsx(Wv,{})});if(a)return n.jsx("div",{className:"message-body",children:n.jsx(Pt,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const l=s?.raw??"";return l===""?n.jsx("div",{className:"message-body",children:n.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):n.jsx("div",{className:"message-body",children:n.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:l})})},Qv=()=>n.jsx(Xn,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),ju=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),Su=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:be("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":be("text-fg-subtle hover:text-warning",r&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:n.jsx(At,{className:be("size-3.5",e&&"fill-current")})}),Yv=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:r,isStarPending:a})=>{const o=wl(e.sentDate,"datetime"),i=ju(e,o);return n.jsx(rc,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:n.jsxs(n.Fragment,{children:[e.hasAttachment&&n.jsx(Jn,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx(Su,{isStarred:e.hasStars,onToggleStar:r,isStarPending:a,hoverReveal:!0}),n.jsx("span",{"data-testid":"message-date",className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:o})]})})},Gv=({threadMessage:e,messageData:t,isLoading:s,isError:r,error:a,onRetry:o,isFocused:i,onToggle:l,onToggleStar:u,isStarPending:f,accountId:d,showRaw:m,onToggleRaw:h,mobile:g,onReply:v,onReplyAll:p,onForward:x})=>{const b=wl(e.sentDate,"long"),w=!e.isRead,j=t?.envelope.from[0]?.flags?.trusted?.value===!0,y=t?.envelope.from[0]?.addressId,I=ju(e,b),N=e.autoMoved?n.jsx(Qc,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"md"}):null;return n.jsx(ac,{message:I,isFocused:g?!1:i,onHeaderClick:l,senderBadge:j?n.jsx(Qv,{}):void 0,trailing:n.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:b}),to:t?n.jsx(Jm,{label:"To",addresses:t.envelope.to}):null,indicators:N||!g?n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[N,!g&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n.jsx(Su,{isStarred:e.hasStars,onToggleStar:u,isStarPending:f}),e.hasAttachment&&n.jsx("span",{className:"text-fg-subtle p-0.5",children:n.jsx(Jn,{className:"size-3.5"})})]}),w&&n.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:g?void 0:n.jsx($v,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:y,isTrusted:j,showRaw:m,onToggleRaw:h}),actionBar:g?n.jsx(Hv,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:y,isTrusted:j,showRaw:m,onToggleRaw:h,onReply:v,onReplyAll:p,onForward:x}):void 0,body:s?n.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):r&&xf(a)?n.jsx("div",{className:"mt-3",children:n.jsx(qc,{message:"This message has been deleted"})}):r?n.jsx("div",{className:"mt-3",children:n.jsx(Pt,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):m?n.jsx("div",{className:"mt-3",children:n.jsx(Vv,{messageId:e.messageId})}):n.jsx("div",{className:"mt-3",children:n.jsx(wu,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:j,category:cn(e.category)})})})},Xv=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,mobile:l,onReply:u,onReplyAll:f,onForward:d})=>{const[m,h]=c.useState(!1),{data:g,isLoading:v,isError:p,error:x,refetch:b}=de({...ja({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?n.jsx(Gv,{threadMessage:e,messageData:g,isLoading:v,isError:p,error:x,onRetry:()=>b(),isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,showRaw:m,onToggleRaw:()=>h(w=>!w),mobile:l,onReply:u,onReplyAll:f,onForward:d}):n.jsx(Yv,{threadMessage:e,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o})},Jv=()=>n.jsxs("div",{className:"animate-pulse p-4",children:[n.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),n.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>n.jsxs("div",{className:"flex gap-3 py-3",children:[n.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function Ri({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?n.jsxs("div",{className:"flex items-start gap-2 rounded-none border-b border-danger/20 bg-danger-soft px-5 py-2.5 text-sm",children:[n.jsx(Ns,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",n.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&n.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const Is=({threadId:e,mailboxId:t,subject:s,selectedMessageId:r,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:l,onComposeClose:u,onSwipeNext:f,onSwipePrevious:d,mobileIntelligenceOpen:m})=>{const h=Ot(),{handlers:g}=zb({onSwipeLeft:f,onSwipeRight:d}),{accountId:v}=Hc(t),{data:p,isLoading:x,isError:b,error:w,refetch:j}=de({...bf({path:{threadId:e}})}),y=c.useMemo(()=>p?.items??[],[p?.items]),I=y[y.length-1],N=c.useRef(new Map),[k,C]=c.useState(new Set),[M,P]=c.useState(null),[D,O]=c.useState(0);c.useEffect(()=>{if(y.length>0&&e!==M){P(e);const J=new Set([y[y.length-1].threadMessageId]);if(r){const ae=y.find(ce=>ce.messageId===r);ae&&J.add(ae.threadMessageId)}C(J),O(y.length-1)}},[e,y,M,r]);const E=c.useCallback(J=>{C(ae=>{const ce=new Set(ae);return ce.has(J)?ce.delete(J):ce.add(J),ce})},[]),S=c.useCallback(J=>{const ae=y[J];if(!ae)return;N.current.get(ae.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[y]),A=c.useCallback(()=>{if(y.length===0)return;const J=Math.min(D+1,y.length-1);O(J),S(J)},[y.length,D,S]),L=c.useCallback(()=>{if(y.length===0)return;const J=Math.max(D-1,0);O(J),S(J)},[y.length,D,S]),T=c.useCallback(()=>{const J=y[D];J&&E(J.threadMessageId)},[y,D,E]),{data:F}=de({...xt(),staleTime:1/0}),R=F?.accounts?.[0],$=!!R?.smtpHost;Lb({messages:y,expandedIds:k,threadId:e,mailboxId:t,accountId:R?.accountId});const{toggleStar:z,isPending:V,pendingMessageId:ee}=Wa({threadId:e,mailboxId:t,messages:y}),[X,Q]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(Q(l),u?.())},[l,u]);const{data:le}=de({...ja({path:{messageId:I?.messageId??""}}),enabled:!!I&&X!==null}),ue=c.useCallback(()=>{Q("reply")},[]),te=c.useCallback(()=>{Q("reply_all")},[]),K=c.useCallback(()=>{Q("forward")},[]),U=c.useCallback(()=>{Q(null),u?.()},[u]);if(Ha({enabled:!x&&y.length>0&&X===null,bindings:[{key:"j",handler:A,preventDefault:!0},{key:"ArrowDown",handler:A,preventDefault:!0},{key:"k",handler:L,preventDefault:!0},{key:"ArrowUp",handler:L,preventDefault:!0},{key:"Enter",handler:T,preventDefault:!0},{key:"o",handler:T,preventDefault:!0},...$?[{key:"r",handler:ue,preventDefault:!0},{key:"R",handler:te,noModifiers:!1,preventDefault:!0},{key:"f",handler:K,preventDefault:!0}]:[]]}),x)return n.jsx(Jv,{});if(b)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(Pt,{title:"Couldn't load this conversation",error:w,onRetry:()=>j()})});if(y.length===0)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(qc,{message:"No messages in this thread"})});const re=s||y[0]?.subject||"(No subject)",Ie=y.length,je=J=>n.jsx("div",{children:y.map((ae,ce)=>n.jsx("div",{ref:B=>{B&&N.current.set(ae.threadMessageId,B)},children:n.jsx(Xv,{threadMessage:ae,isExpanded:k.has(ae.threadMessageId),isFocused:ce===D,onToggle:()=>E(ae.threadMessageId),onToggleStar:()=>z(ae.messageId,ae.hasStars),isStarPending:V&&ee===ae.messageId,accountId:v,mobile:J,onReply:J&&$?ue:void 0,onReplyAll:J&&$?te:void 0,onForward:J&&$?K:void 0})},ae.threadMessageId))}),W=n.jsxs("header",{className:"border-b border-line px-5 pt-5 pb-3",children:[n.jsx("h1",{className:"max-w-2xl text-lg font-semibold leading-snug text-fg",children:re}),n.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Ie," ",Ie===1?"message":"messages"]})]});return h?n.jsxs("article",{className:"h-full flex flex-col",children:[W,a?.dkimMismatch&&n.jsx(Ri,{authenticity:a,onOpenIntelligence:o}),n.jsx("div",{className:"flex-1 overflow-auto",children:je(!1)}),X!==null&&n.jsx(wi,{mode:X,account:R,sourceMessage:le,onClose:U})]}):n.jsxs(Yh,{thread:{subject:re,messages:[]},onBack:i??(()=>{}),intelligenceOpen:m,onToggleIntelligence:o,touchHandlers:g,children:[a?.dkimMismatch&&n.jsx(Ri,{authenticity:a,onOpenIntelligence:o}),je(!0),X!==null&&n.jsx(wi,{mode:X,account:R,sourceMessage:le,onClose:U})]})};function Ts(){const{mailboxNameIndex:e,accountNameIndex:t}=Ce();return{...gt({select:r=>Dc(r.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Za=e=>e.trim().toLocaleLowerCase(),Zv=/^\d{4}-\d{2}-\d{2}$/;function Mi(e,t,s){if(!Zv.test(s))return;const r=Date.parse(`${s}T00:00:00Z`);if(!Number.isNaN(r))return{type:e,raw:t,value:s,epochSeconds:Math.floor(r/1e3)}}function ey(e,t){const s=e.toLowerCase();if(s.startsWith("from:")&&e.length>5)return{type:"from",raw:e,value:e.slice(5)};if(s==="has:attachment")return{type:"hasAttachment",raw:e};if(s==="is:unread")return{type:"isUnread",raw:e};if(s.startsWith("before:")&&e.length>7)return Mi("before",e,e.slice(7));if(s.startsWith("after:")&&e.length>6)return Mi("after",e,e.slice(6));if(s.startsWith("in:")&&e.length>3){const r=e.slice(3),a=t.mailboxesByName?.get(r.toLowerCase());return a?{type:"in",raw:e,value:r,mailboxId:a}:void 0}if(s.startsWith("account:")&&e.length>8){const r=e.slice(8),a=t.accountsByName?.get(r.toLowerCase());return a?{type:"account",raw:e,value:r,accountId:a}:void 0}}function Rs(e,t={}){const s=e.split(/\s+/).filter(o=>o.length>0),r=[],a=[];for(const o of s){const i=ey(o,t);i?r.push(i):a.push(o)}return{freeText:a.join(" "),tokens:r}}function ty(e,t){return e.split(/\s+/).filter(s=>s.length>0&&s!==t.raw).join(" ")}function ku(e){switch(e.type){case"from":return`From: ${e.value}`;case"hasAttachment":return"Has attachment";case"isUnread":return"Unread";case"before":return`Before ${e.value}`;case"after":return`After ${e.value}`;case"in":return`In: ${e.value}`;case"account":return`Account: ${e.value}`}}const sy=20,ny=new Set(Object.values(it)),ry=e=>e!==void 0&&ny.has(e)?e:void 0;function Cu({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Ce(),r=Ts(),a=gt({select:w=>w.matches}),o=Za(s),{freeText:i,tokens:l}=Rs(o,r),u=i.length>0,f=ry(t),d=l.some(w=>w.type==="hasAttachment")?!0:void 0,m=l.some(w=>w.type==="isUnread")?!1:void 0,h=l.find(w=>w.type==="after"),g=l.find(w=>w.type==="before"),v=l.find(w=>w.type==="in"),p=Qx({matches:a,callerMailboxId:e,inTokenMailboxId:v?.mailboxId}),{data:x,isLoading:b}=de({...ll({query:{query:i,mailboxId:p,limit:sy,...f!==void 0?{category:f}:{},...d!==void 0?{hasAttachment:d}:{},...m!==void 0?{isRead:m}:{},...h?{sentDateFrom:h.epochSeconds}:{},...g?{sentDateTo:g.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:x?.items??[],isLoading:u&&b}}const ay=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),oy=e=>[...e].sort(ay);function sa(e){const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId??e.accountConfigId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:cn(e.category),suspicious:t}}function Ai(e){return e.filter(t=>t.muted!==!0)}function iy(e,t){const s=new Set,r=[];for(const a of[...e,...t])s.has(a.id)||(s.add(a.id),r.push(a));return r.sort((a,o)=>(o.sentDate??0)-(a.sentDate??0))}const Di=[{id:"personal",label:"Personal",category:it.personal},{id:"transactional",label:"Transactional",category:it.transactional},{id:"newsletter",label:"Newsletter",category:it.newsletter},{id:"marketing",label:"Marketing",category:it.marketing},{id:"social",label:"Social",category:it.social},{id:"automated",label:"Automated",category:it.automated},{id:"uncategorized",label:"Unclassified",category:it.uncategorized}];function ly(e){const t=new Map(Di.map(r=>[r.category,[]]));for(const r of e){const a=r.category??it.uncategorized;(t.get(a)??t.get(it.uncategorized))?.push(r)}const s=[];for(const r of Di){const a=t.get(r.category);a&&a.length>0&&s.push({id:r.id,label:r.label,threads:a})}return s}function Nu(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Eu(e,t){return t.every(s=>{switch(s.type){case"from":{const r=s.value.toLowerCase();return e.fromEmail.toLowerCase().includes(r)||e.fromName.toLowerCase().includes(r)}case"hasAttachment":return e.hasAttachment===!0;case"isUnread":return!e.isRead;case"after":return e.sentDate!=null&&e.sentDate>=s.epochSeconds*1e3;case"before":return e.sentDate!=null&&e.sentDate<s.epochSeconds*1e3;case"in":return e.mailboxId===s.mailboxId;case"account":return e.accountId===s.accountId;default:return!1}})}const cy={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function uy(e){return cy[e]??e}function dy(e,t){const{folder:s}=Sa(t,[e.mailboxId]);return{id:e.messageId,sender:e.fromName??e.fromEmail??"Unknown",subject:e.subject??"(No subject)",snippet:e.snippet??"",date:Lt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Iu(e,t){const{folder:s}=Sa(t,e.mailboxId?[e.mailboxId]:[]);return{id:e.id,sender:e.fromName,subject:e.subject,snippet:e.snippet,date:e.timeLabel,unread:!e.isRead,flagged:e.starred===!0,...e.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function fy(e,t){const{mailboxId:s,folder:r}=Sa(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?Lt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:uy(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...r?{folder:r}:{}}}function Tu(e,t,s){const r=new Set(t),a=[];for(const o of[...e].sort((i,l)=>l.score-i.score))r.has(o.threadId)||(r.add(o.threadId),a.push(fy(o,s)));return a}const my=768,hy=1024,Ru=e=>e!=="desktop",lr=()=>{const e=wo(`(min-width: ${my}px)`);return wo(`(min-width: ${hy}px)`)?"desktop":e?"tablet":"phone"},py=new Set(["hasAttachment","isUnread","before","after"]),Mu=(e,{searchHadSemanticReach:t})=>{const s=[],r=[];let a,o;for(const u of e.tokens){if(u.type==="from"){s.push({field:"From",value:u.value});continue}if(u.type==="in"){a={mailboxId:u.mailboxId,label:u.value};continue}if(u.type==="account"){o=u.accountId;continue}py.has(u.type)&&r.push({type:u.type,label:ku(u)})}const i=e.freeText.trim(),l=i.length>0;return l&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:r,targetAccountId:o,keptTerms:l,droppedSemantic:l&&t}},gy=e=>e.clauses.length>0,Au=(e,{scope:t="standing",moveMailboxId:s}={})=>({clauses:e.clauses.map((r,a)=>({id:`search-${a}`,field:r.field,value:r.value})),matchOperator:e.matchOperator,moveMailboxId:s,scope:t,name:""}),Du="remit.recentSearches",xy=5;function na(){try{const e=localStorage.getItem(Du);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Oi(e){const t=e.trim();if(!t)return na();const s=[t,...na().filter(r=>r!==t)].slice(0,xy);try{localStorage.setItem(Du,JSON.stringify(s))}catch{return s}return s}const by=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function vy(e){const{spam:t}=ic([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let r;for(const[a,o]of s)(!r||o>r.count)&&(r={mailboxId:a,count:o});return r}const yy=(e,t)=>{const s=ve(cl()),{mutate:r,reset:a}=s,o=c.useCallback(()=>{e&&(a(),r({path:{accountId:e},body:qr({matchOperator:t.matchOperator,literalClauses:t.literalClauses})}))},[e,t.matchOperator,t.literalClauses,r,a]);return c.useEffect(()=>{o()},[o]),{seedCount:s.data?.matchedCount,isPending:s.isPending||s.data===void 0,isError:s.isError,error:s.error,retry:o}},Ou=({initialRule:e,widenAnchorCount:t=1})=>{const[s,r]=c.useState(e),[a,o]=c.useState(),i=c.useRef(0);return{rule:s,setRule:N=>r(N),handlers:{clauseEdit:a,onStartAddClause:()=>o({mode:"add",draft:{field:Na[0],value:""}}),onStartEditClause:N=>{const k=s.clauses.find(C=>C.id===N);k&&o({mode:"edit",clauseId:N,draft:{field:k.field,value:k.value}})},onRemoveClause:N=>r(k=>({...k,clauses:k.clauses.filter(C=>C.id!==N)})),onChangeDraftField:N=>o(k=>k&&{...k,draft:{...k.draft,field:N}}),onChangeDraftValue:N=>o(k=>k&&{...k,draft:{...k.draft,value:N}}),onSubmitClause:()=>{if(!a)return;const N=a.draft.field,k=qf(N,a.draft.value);k!==""&&(r(C=>a.mode==="edit"&&a.clauseId?{...C,clauses:C.clauses.map(M=>M.id===a.clauseId?{id:M.id,field:N,value:k}:M)}:(i.current+=1,{...C,clauses:[...C.clauses,{id:`clause-${i.current}`,field:N,value:k}]})),o(void 0))},onCancelClause:()=>o(void 0),onAddWiden:()=>r(N=>({...N,widen:{anchorCount:Math.max(t,1)}})),onRemoveWiden:()=>r(N=>({...N,widen:void 0})),onChangeMatchOperator:N=>r(k=>({...k,matchOperator:N})),onChangeMove:N=>r(k=>({...k,moveMailboxId:N||void 0})),onChangeLabel:N=>r(k=>({...k,labelId:N||void 0})),onChangeScope:N=>r(k=>({...k,scope:N})),onChangeName:N=>r(k=>({...k,name:N})),onChangeUntil:N=>r(k=>({...k,until:N}))}}};function Pu({progress:e,isDone:t,runningLabel:s,onClose:r}){const a=e.state==="Failed";return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[t?a?n.jsx("span",{className:"text-sm font-semibold text-danger",children:"Organize failed"}):n.jsx(Yn,{className:"size-8 text-positive"}):n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),!t&&n.jsx("p",{className:"text-sm font-medium text-fg",children:s}),t&&!a&&n.jsxs("div",{className:"text-sm text-fg",children:[n.jsx("p",{className:"font-medium",children:"Done"}),n.jsxs("p",{className:"mt-1 text-xs text-fg-muted",children:[e.appliedCount," of ",e.matchedCount," moved",e.failedCount>0?` · ${e.failedCount} failed`:"","."]})]}),t&&a&&n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:e.errorMessage||"Something went wrong. Please try again."}),t&&n.jsx(G,{variant:"primary",onClick:r,className:"mt-2",children:"Done"})]})}function ra(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Saving rule…"})]})}function Lu({onClose:e}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(Yn,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Filter saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"You can see it, and when it expires, under Settings › Filters."}),n.jsx(G,{variant:"primary",onClick:e,className:"mt-2",children:"Done"})]})}function wy({onRetry:e,onClose:t}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(Yn,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Rule saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"New mail follows it automatically. Moving the mail already in your mailbox didn't run — try again?"}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(G,{variant:"primary",onClick:e,children:"Move existing mail"}),n.jsx(G,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function $u({onRetry:e,onClose:t}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't save the rule"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(G,{variant:"primary",onClick:e,children:"Try again"}),n.jsx(G,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function jy({accountId:e,conversion:t,seedCount:s,onClose:r}){const[a]=c.useState(()=>Au(t)),{rule:o,handlers:i}=Ou({initialRule:a}),{data:l}=de({..._e({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),u=c.useMemo(()=>Zs(l?.items??[]).map(g=>({id:g.mailboxId,label:Vn(g.fullPath)})),[l?.items]),f=gl(e,Ea(o),s),d=xl(e),m=bl(e),h=()=>{const g=vl(o);if(o.scope==="once"){d.start(g);return}m.createFilter(g,o.scope==="standing"?"standing":"temporary",(o.name??"").trim())};return d.isStarting||d.isRunning||d.isDone?n.jsx(Pu,{progress:d.progress,isDone:d.isDone,runningLabel:"Organizing your mail…",onClose:r}):m.isPending?n.jsx(ra,{}):m.isSuccess?n.jsx(Lu,{onClose:r}):m.isError?n.jsx($u,{onRetry:m.reset,onClose:r}):n.jsx(ul,{rule:o,folders:u,preview:f,notice:n.jsx(Qp,{notice:{scopedOutFolder:t.scopedOut?.label,droppedFacets:t.droppedFacets.map(g=>g.label),droppedSemantic:t.droppedSemantic}}),semanticAvailable:!1,clauseFields:Na,...i,onCommit:h,onCancel:r})}function Sy({open:e,accountId:t,parsed:s,searchHadSemanticReach:r,onClose:a}){const o=c.useMemo(()=>Mu(s,{searchHadSemanticReach:r}),[s,r]),i=c.useMemo(()=>Ea(Au(o)),[o]),{seedCount:l,isPending:u,isError:f,retry:d}=yy(e?t:void 0,i);return e?n.jsx(ua,{open:e,onClose:a,title:"Filter rule",children:f?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't build the filter"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(G,{variant:"primary",onClick:d,children:"Try again"}),n.jsx(G,{variant:"ghost",onClick:a,children:"Not now"})]})]}):u||l===void 0?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Turning your search into a filter…"})]}):n.jsx(jy,{accountId:t,conversion:o,seedCount:l,onClose:a})}):null}function Fu({title:e,unreadCount:t,children:s,footer:r,searchFilter:a,searchResults:o,searchLoading:i,relatedResults:l,relatedLoading:u,onSelectSearchResult:f,searchResultsLabel:d="Top matches",relatedResultsLabel:m="Related",searchResultsInBody:h=!1}){const{accounts:g,resultFolderIndex:v,searchQuery:p,searchInput:x,onSearchChange:b,onSearchClear:w,searchViewKey:j}=Ce(),y=Ts(),I=Oe(),N=Ss(),k=lr(),[C,M]=c.useState(!1),[P,D]=c.useState(na),[O,E]=c.useState(!1),S=c.useRef(j);c.useEffect(()=>{S.current!==j&&(S.current=j,M(!1))},[j]);const A=x.trim().length>0,{mailboxesByName:L,accountsByName:T}=y,F=c.useMemo(()=>Rs(x,{mailboxesByName:L,accountsByName:T}),[x,L,T]),R=F.tokens.map(pe=>({label:ku(pe),onRemove:()=>b(ty(x,pe))})),$=o??[],z=l??[],V=A?[{id:"top",label:d,results:$},{id:"related",label:m,results:z}]:[],X=!($.length+z.length>0)&&(i===!0||u===!0),{scope:Q}=Lc(g),le=gt({select:pe=>pe.matches}),ue=Oc(le),te=Gx(le,Q,ue?v.get(ue)?.role:void 0),K=te.kind==="global"?vy([...$,...z]):void 0,U=K?{kind:"global",onScopeToSpam:()=>I({to:"/mail/$mailboxId",params:{mailboxId:K.mailboxId},search:{q:p||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:te,Ie=F.tokens.find(pe=>pe.type==="account")?.accountId??g[0]?.accountId,je=z.length>0,W=A&&Ie?{onClick:()=>E(!0),disabledReason:gy(Mu(F,{searchHadSemanticReach:je}))?void 0:"Add a sender or words to filter on"}:void 0,J=O&&Ie?n.jsx(Sy,{open:O,accountId:Ie,parsed:F,searchHadSemanticReach:je,onClose:()=>E(!1)}):null;if(k==="phone"&&C){const pe=ge=>{D(Oi(x)),M(!1),f?.(ge)};return n.jsxs(n.Fragment,{children:[n.jsx(kp,{value:x,onChange:b,onClear:w,onCancel:()=>{M(!1),w()},filter:a,recentSearches:P,onPickRecent:b,makeFilter:W,sections:V,loading:X,onSelectResult:pe,tokens:R,scope:U}),J]})}const ae=by({tier:k,hasLiveInput:A,hasCommittedQuery:p.trim().length>0,bodyRendersCommittedResults:h}),ce=pe=>{D(Oi(x)),f?.(pe)},B=n.jsx(lc,{value:x,sections:V,loading:X,onSelectResult:ce,tokens:R,scope:U,makeFilter:W}),Fe=ae?a?n.jsx(da,{...a,children:B}):n.jsx("div",{className:"h-full overflow-y-auto",children:B}):s;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsx(hp,{title:e,unreadCount:t,isDesktop:!1,showSearch:Ru(k),onMenuClick:()=>N?.openNav(),searchValue:x,onSearchChange:b,onSearchClear:w,searchOpen:C,onSearchOpenChange:M}),n.jsx("div",{className:"min-h-0 flex-1",children:Fe}),r,J]})}const ky=(e,t,s)=>{const r=e.indexOf(s);if(r===-1)return[];const a=t===void 0?-1:e.indexOf(t);if(a===-1)return[s];const o=Math.min(a,r),i=Math.max(a,r);return e.slice(o,i+1)},Cy=(e,t,s,r)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:r,Ny=(e,t)=>{const s=new Set(t),r=new Set;for(const a of e)s.has(a)&&r.add(a);return r},_u=(e,t,s)=>{if(e.length===0)return;const r=t===void 0?-1:e.indexOf(t);if(r===-1)return s>0?e[0]:e[e.length-1];const a=Math.min(Math.max(r+s,0),e.length-1);return e[a]},zu=e=>{const[t,s]=c.useState(new Set),[r,a]=c.useState(void 0),o=c.useCallback(p=>t.has(p),[t]),i=c.useCallback(p=>{a(p),s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},[]),l=c.useCallback(p=>{a(p),s(x=>{if(x.has(p))return x;const b=new Set(x);return b.add(p),b})},[]),u=c.useCallback(p=>{s(x=>{if(!x.has(p))return x;const b=new Set(x);return b.delete(p),b})},[]),f=c.useCallback(p=>{s(new Set(p))},[]),d=c.useCallback(()=>{a(void 0),s(new Set)},[]),m=c.useCallback(p=>{s(x=>p.every(w=>x.has(w))?new Set:new Set(p))},[]),h=c.useCallback(p=>{a(p)},[]),g=c.useCallback(p=>{s(x=>{if(x.size===0)return x;const b=Ny(x,p);return b.size===x.size?x:b})},[]),v=c.useCallback((p,x,b)=>{const w=Cy(p,r,b,x);s(j=>{const y=ky(p,w,x);if(y.length===0)return j;const I=new Set(j);for(const N of y)I.add(N);return I}),a(w)},[r]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:l,deselect:u,selectAll:f,clearSelection:d,toggleAll:m,selectRange:v,setAnchor:h,anchorId:r,intersectWith:g}},Bu=(e,t)=>!t&&e>0,Ey=(e,t)=>e==="BACK"&&t,Iy=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:r})=>{const[a,o]=c.useState(s),i=zu(),{selectedCount:l,toggle:u,clearSelection:f,selectRange:d,setAnchor:m,selectAll:h}=i,g=Bu(l,t),v=c.useRef(null),p=c.useRef(!1),x=c.useCallback(()=>{r?.(),f()},[f,r]),b=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),w=c.useCallback(E=>{if(E<0||E>=e.length)return;const S=e[E];if(g){u(S);return}v.current=S,p.current=!1,o(S)},[e,g,u]),j=c.useCallback(()=>{e.length!==0&&w(b<0?0:Math.min(b+1,e.length-1))},[e.length,b,w]),y=c.useCallback(()=>{e.length!==0&&w(b<=0?0:b-1)},[e.length,b,w]),I=c.useCallback(()=>w(0),[w]),N=c.useCallback(()=>w(e.length-1),[w,e.length]),k=c.useCallback(()=>{a&&u(a)},[a,u]),C=c.useCallback((E,S)=>S.shiftKey?(d(e,E,a),!0):S.metaKey||S.ctrlKey?(u(E),!0):(x(),m(E),!1),[e,a,d,u,x,m]),M=c.useCallback(E=>{const S=_u(e,a,E);S!==void 0&&(d(e,S),v.current=S,p.current=!1,o(S))},[e,a,d]),P=c.useCallback(()=>M(-1),[M]),D=c.useCallback(()=>M(1),[M]),O=c.useCallback(()=>{e.length>0&&h(e)},[e,h]);return{focusedMessageId:a,setFocusedMessageId:o,focusIndex:b,pendingDomFocusRef:v,cursorMovedByPointerRef:p,selection:i,isMultiSelectMode:g,exitSelection:x,moveFocusToIndex:w,focusNext:j,focusPrevious:y,focusFirst:I,focusLast:N,toggleFocusedSelection:k,extendRangeUp:P,extendRangeDown:D,selectAllLoaded:O,handleRowSelect:C}};function Ku(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Ty=e=>{const{mailboxId:t,messages:s}=e,r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i}=ve({...vf(),onError:(u,f)=>{a({title:f.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:st(u),error:u})},onSettled:(u,f,d)=>{yt(r,vt(nr(d.body.messageIds??[],s??[],t)))}});return{applyLabel:c.useCallback((u,f,d)=>{u.length!==0&&o({body:{messageIds:u,labelId:f,action:d}})},[o]),isPending:i}};function Ry({accountId:e,mailboxId:t,messageIds:s}){const{labels:r}=Cl(e),{applyLabel:a}=Ty({mailboxId:t}),o=c.useMemo(()=>r.map(i=>({key:i.labelId,label:i.name,icon:n.jsx("span",{className:`size-2.5 rounded-full ${yf(i.color)?yo[i.color]:yo.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[r,s,a]);return o.length===0?null:n.jsx(tc,{triggerLabel:"Apply label to selected messages",triggerIcon:n.jsx(wf,{className:"size-4"}),items:o})}const Uu=({selectedCount:e,onDelete:t,onClearSelection:s,onMarkAsRead:r,onMove:a,onOrganize:o,isDeleting:i=!1,isMoving:l=!1,accountId:u,currentMailboxId:f,selectedMessageIds:d,moveDisabledHint:m,selectAll:h,statusLabel:g,isCounting:v=!1,progress:p,notice:x})=>{if(e===0)return null;const b=p!==void 0,w=i||l||b,j=!b&&!v,y=!!a&&!!u&&!!f,I=!!u&&!!f&&!!d?.length,N=!!o&&!!u&&!!f&&!m&&!g,k=h?.checked?`All ${e} loaded selected`:`${e} ${e===1?"message":"messages"} selected`;return n.jsxs("div",{className:"sticky top-0 z-10 flex flex-col bg-surface-sunken border-b border-line",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:s,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded hover:bg-surface-raised transition-colors","aria-label":"Clear selection",children:n.jsx(We,{className:"size-4 text-fg-muted"})}),h&&n.jsx("label",{className:"flex size-11 shrink-0 cursor-pointer items-center justify-center",children:n.jsx(sn,{"aria-label":"Select all",checked:h.checked,indeterminate:h.indeterminate,onChange:h.onChange})}),n.jsx("span",{className:"text-sm font-medium",children:g??k}),m&&!x&&n.jsx("span",{className:"text-xs text-fg-muted",role:"status","aria-live":"polite",children:m})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[N&&o&&n.jsxs("button",{type:"button",onClick:w?void 0:o,className:"min-h-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Organize similar messages",children:[n.jsx(ut,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:"Organize"})]}),j&&r&&n.jsx("button",{type:"button",onClick:w?void 0:r,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Mark as read","aria-busy":w,children:n.jsx(Cs,{className:"size-4"})}),j&&y&&a&&u&&f&&n.jsx(dn,{accountId:u,currentMailboxId:f,onMove:w?()=>{}:a,disabledHint:m,variant:"icon-only",label:"Move selected messages"}),j&&I&&u&&f&&d&&n.jsx(Ry,{accountId:u,mailboxId:f,messageIds:d}),j&&n.jsxs("button",{type:"button",onClick:w?void 0:t,className:be("min-h-11 min-w-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors","bg-danger text-canvas hover:bg-danger/90"),"aria-label":"Delete selected messages","aria-busy":i,children:[i?n.jsx(nt,{className:"size-4 animate-spin"}):n.jsx(rt,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:i?"Deleting...":"Delete"})]})]})]}),p&&n.jsx("div",{className:"px-3 pb-2",children:n.jsx(Pa,{value:p.value,max:p.max,tone:p.tone})}),x&&n.jsx(Xt,{tone:x.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-3 mb-2",children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[x.text&&n.jsx("span",{children:x.text}),x.action&&n.jsx("button",{type:"button",onClick:x.action.onClick,className:"-my-1 min-h-11 shrink-0 inline-flex items-center px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised",children:x.action.label})]})})]})},eo=c.createContext(null),My=e=>{const t=c.useContext(eo);return t?t.rowInteraction(e):null},Ay=()=>{const e=c.useContext(eo);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},Dy="[data-message-id]",Oy=e=>Array.from(e.querySelectorAll(Dy)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),Py=(e,t)=>e.length===t.length&&e.every((s,r)=>s===t[r]),Ly=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const r=e.current;if(!r)return;const a=()=>{const i=Oy(r);s(l=>Py(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(r,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function qu({selectedMessageId:e,onOpen:t,onDeleteMessages:s,isDeleting:r=!1,commandsRef:a,onTriageContextChange:o,children:i}){const l=Ot(),u=c.useRef(null),f=Ly(u),d=Iy({orderedIds:f,isDesktop:l,initialFocusedId:e}),{focusedMessageId:m,setFocusedMessageId:h,pendingDomFocusRef:g,cursorMovedByPointerRef:v,selection:p,isMultiSelectMode:x,exitSelection:b,handleRowSelect:w}=d,{selectedIds:j,selectedCount:y,isSelected:I,toggle:N,select:k}=p,{intersectWith:C}=p;c.useEffect(()=>{C(f)},[C,f]),c.useEffect(()=>{const Q=g.current;Q!==null&&(g.current=null,u.current?.querySelector(`[data-message-id="${Q}"]`)?.focus())});const M=c.useCallback(Q=>{v.current=!0,h(Q)},[v,h]),P=c.useCallback(Q=>{l||k(Q)},[l,k]),D=c.useCallback(()=>{m&&t(m)},[m,t]),[O,E]=c.useState(null),S=c.useCallback(Q=>!s||Q.length===0?!1:(E(Q),!0),[s]),A=c.useCallback(()=>{S(Array.from(j))},[S,j]),L=c.useCallback(()=>O!==null?!0:y>0?S(Array.from(j)):m?S([m]):!1,[O,y,j,m,S]),T=c.useCallback(()=>{O!==null&&(s?.(O),E(null),b())},[O,s,b]),F=c.useCallback(()=>E(null),[]),R=c.useCallback(()=>y===0?!1:(b(),!0),[y,b]),$=f.length>0;c.useEffect(()=>{if(a){if(!$){a.current=null;return}return a.current={focusNext:d.focusNext,focusPrevious:d.focusPrevious,focusFirst:d.focusFirst,focusLast:d.focusLast,openFocused:D,toggleSelect:d.toggleFocusedSelection,extendSelectDown:d.extendRangeDown,extendSelectUp:d.extendRangeUp,selectAll:d.selectAllLoaded,clearSelection:R,requestDelete:L,toggleDensity:()=>{}},()=>{a.current=null}}},[a,$,d.focusNext,d.focusPrevious,d.focusFirst,d.focusLast,d.toggleFocusedSelection,d.extendRangeDown,d.extendRangeUp,d.selectAllLoaded,D,R,L]);const z=c.useMemo(()=>Array.from(j),[j]),V=O!==null;c.useEffect(()=>{o?.({focusedMessageId:m,selectedIds:z,orderedIds:f,hasList:$,blocksKeyboard:V})},[o,m,z,f,$,V]);const ee=Ku(f,m),X=c.useMemo(()=>({selectedIds:j,selectedCount:y,exitSelection:b,requestDeleteSelection:A,rowInteraction:Q=>({focused:Q===m,isTabStop:Q===ee,isDesktop:l,onFocusRow:M,selection:{isChecked:I(Q),onToggleCheck:N,onRowSelect:w,isMultiSelectMode:x,onLongPress:P}})}),[j,y,b,A,m,ee,l,M,I,N,w,x,P]);return n.jsxs(eo.Provider,{value:X,children:[n.jsx("div",{ref:u,className:"contents",children:i}),n.jsx(Ra,{isOpen:V,title:jl(O?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:r,onConfirm:T,onCancel:F})]})}function Hu({onMarkAsRead:e,isDeleting:t}){const{selectedIds:s,selectedCount:r,exitSelection:a,requestDeleteSelection:o}=Ay(),i=c.useCallback(()=>{e?.(Array.from(s)),a()},[e,s,a]);return n.jsx(Uu,{selectedCount:r,onDelete:o,onClearSelection:a,onMarkAsRead:e?i:void 0,isDeleting:t})}const $y=({thread:e,active:t=!1,focused:s,isTabStop:r,density:a="comfortable",isDesktop:o,badge:i,selection:l,inListbox:u=!1,linkMailboxId:f,onClick:d,onFocusRow:m})=>{const h=ye(),g=e.id,v=My(g),p=s??v?.focused??!1,x=r??v?.isTabStop??!1,b=l??v?.selection,w=m??v?.onFocusRow,j=o??v?.isDesktop??!0,y=b?.isChecked??!1,I=b?.isMultiSelectMode??!1,N=b?.onToggleCheck,k=b?.onRowSelect,C=b?.onLongPress,M=c.useCallback(R=>{R.preventDefault(),R.stopPropagation(),N?.(g)},[N,g]),P=c.useCallback(R=>{if(!j){if(I){R.preventDefault(),R.stopPropagation(),N?.(g);return}d?.();return}const $={shiftKey:R.shiftKey,metaKey:R.metaKey,ctrlKey:R.ctrlKey};if(k?.(g,$)){R.preventDefault(),R.stopPropagation(),$.shiftKey&&window.getSelection()?.removeAllRanges();return}d?.()},[j,I,N,k,d,g]),D=c.useCallback(R=>{j&&R.shiftKey&&R.preventDefault()},[j]),O=c.useCallback(()=>{C?.(g)},[C,g]),{longPressProps:E}=Jl({onLongPress:O,delayMs:500,accessibilityDescription:y?"Deselect message":"Select message"}),S=c.useCallback(()=>{h.prefetchQuery(ja({path:{messageId:g}}))},[h,g]),A=c.useCallback(()=>{S(),w?.(g)},[S,w,g]),L=ks({"data-list-row":"","data-message-row":!0,"data-message-id":g,...u?{role:"option","aria-selected":y}:{},tabIndex:x?0:-1,onClick:P,onMouseDown:D,onMouseEnter:S,onFocus:A},j||!b?{}:E),T=be(a==="compact"?Yl({active:t,focused:p}):be("group",tn({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",y&&"bg-accent-soft",!j&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?n.jsx(Gl,{thread:e}):n.jsx(Xl,{thread:e,badge:i,selection:b?{checked:y,alwaysVisible:I,onToggle:M}:void 0});return f===void 0?n.jsx("button",{type:"button",...L,className:T,children:F}):n.jsx(pt,{to:"/mail/$mailboxId",params:{mailboxId:f},search:R=>({...R,selectedMessageId:g}),...L,className:T,children:F})},to=c.memo($y),Fy=200,_y={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0,contacts:e=>e.trust==="vip"||e.trust==="wellknown",today:e=>e.sentDate!=null&&new Date(e.sentDate).toDateString()===new Date().toDateString()},Pi=()=>n.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>n.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[n.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsxs("div",{className:"flex justify-between gap-2",children:[n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),zy=({accountEmail:e})=>{const t=Oe();return n.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[n.jsx(Gt,{className:"size-3.5 shrink-0"}),n.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),n.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})};function By({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:r,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i,onMarkMessagesRead:l}){const{searchQuery:u,resultFolderIndex:f}=Ce(),d=Ts(),m=Ot(),h=c.useMemo(()=>oy(e.filter(K=>!K.muted?.value)),[e]),[g,v]=c.useState("all"),[p,x]=c.useState("all"),[b,w]=c.useState(new Set),[j,y]=c.useState(!1),I=c.useCallback(K=>{w(U=>{const re=new Set(U);return re.has(K)?re.delete(K):re.add(K),re})},[]),{data:N,isLoading:k,isError:C,refetch:M}=de({...Kr(),staleTime:6e4}),P=Ft({queries:h.map(K=>({..._e({path:{accountId:K.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),D=c.useMemo(()=>{const K=new Map;for(let U=0;U<h.length;U++){const re=h[U].accountId,je=(P[U]?.data?.items??[]).reduce((W,J)=>W+(J.unseenCount??0),0);K.set(re,je)}return K},[h,P]),O=c.useMemo(()=>h.filter((K,U)=>{const re=P[U];return re?.isError?!Ur(re.error):!1}),[h,P]),{freeText:E,tokens:S}=Rs(u.trim().toLowerCase(),d),{data:A,isFetching:L}=de({...Kr({query:{query:E,limit:Fy}}),enabled:E.length>0,staleTime:3e4}),T=c.useMemo(()=>{const K=Ai(N?.items??[]).map(sa);return(E?iy(K.filter(re=>Nu(re,E)),Ai(A?.items??[]).map(sa)):K).filter(re=>(g==="all"||re.accountId===g)&&Eu(re,S))},[N,A,g,E,S]),F=c.useMemo(()=>ly(T),[T]),R=c.useMemo(()=>h.length<=1?[]:[{id:"all",label:"All",active:g==="all"},...h.map(K=>({id:K.accountId,label:K.email.split("@")[0]??K.email,count:D.get(K.accountId),active:g===K.accountId}))],[h,D,g]),$=c.useMemo(()=>e.filter(K=>K.muted?.value).length,[e]),z=c.useMemo(()=>Array.from(D.values()).reduce((K,U)=>K+U,0),[D]),V=c.useMemo(()=>{const K=Array.from(b).map(U=>_y[U]).filter(U=>U!=null);return T.filter(U=>(p==="all"||U.category===p)&&K.every(re=>re(U))).map(U=>Iu(U,f))},[T,p,b,f]),{hits:ee,isLoading:X}=Cu(),Q=c.useMemo(()=>{const K=new Map;for(const re of N?.items??[])K.set(re.messageId,re.threadId);const U=V.map(re=>K.get(re.id)).filter(re=>re!=null);return Tu(ee,U,f)},[ee,V,N,f]),le=c.useMemo(()=>{const K=rg(R.map(U=>({id:U.id,label:U.label,count:U.count,active:U.active})));return{categories:K.categories,filters:K.filters,sources:K.sources,sourcesNote:$>0?`+${$} muted`:void 0,selectedCategory:p,activeFilters:b,expanded:j,onExpandedChange:y,onSelectCategory:U=>x(U),onSelectSource:v,onToggleFilter:I,onClear:()=>{x("all"),v("all"),w(new Set)}}},[R,$,p,b,j,I]),ue=F.length===0&&g==="all"&&E.length===0,te=k?n.jsxs("div",{className:"h-full overflow-y-auto",children:[n.jsx(Pi,{}),n.jsx(Pi,{})]}):C?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[n.jsx(Gt,{className:"size-8 text-danger"}),n.jsx("p",{children:"Couldn't load your messages"}),n.jsxs("button",{type:"button",onClick:()=>M(),className:"flex items-center gap-1 text-accent underline text-xs",children:[n.jsx(Ul,{className:"size-3.5"}),"Try again"]})]}):ue?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[n.jsx(ut,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"You're caught up"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Nothing needs attention."})]}):n.jsx(qu,{selectedMessageId:t,onOpen:K=>s?.(K),onDeleteMessages:i,commandsRef:a,onTriageContextChange:o,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[i?n.jsx(Hu,{onMarkAsRead:l}):null,n.jsx("div",{className:"min-h-0 flex-1",children:n.jsx(Yi,{sections:F,Row:to,manageFocus:!1,briefCategory:p,onSelectBriefCategory:x,sources:R,sourcesNote:$>0?`+${$} muted`:void 0,onSelectSource:v,selectedThreadId:t,onSelectThread:s})})]})});return n.jsx(Fu,{title:"Daily brief",unreadCount:z,footer:m?n.jsx(Vl,{}):void 0,searchFilter:le,searchResults:V,searchLoading:k||L,relatedResults:Q,relatedLoading:X,onSelectSearchResult:r,children:n.jsxs("div",{className:"flex h-full flex-col",children:[O.map(K=>n.jsx(zy,{accountEmail:K.email,accountId:K.accountId},K.accountId)),n.jsx("div",{className:"min-h-0 flex-1",children:te})]})})}const Ky=10,Wu=e=>({q:e?.toLowerCase()??"",limit:Ky}),Uy=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(r=>r.normalizedEmail===s)};function qy(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Pn(t,{month:"short",year:"numeric"})}function Vu(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const Hy="We can't verify the sender of this email, which could mean it's from an insecure source.",Wy="We couldn't read this sender's address, so we can't confirm who really sent this message.";function Vy(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?qy(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Vu(e.fromEmail)}}function Qy(e){return e?.flags?{vip:e.flags.vip?.value===!0,muted:e.flags.muted?.value===!0,blocked:e.flags.blocked?.value===!0,unsubscribed:e.flags.unsubscribed?.value===!0}:{}}function Yy(e,t){const s=t>0?t:void 0;if(Vu(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:Wy,similarCount:s};const r=e.authenticity;if(!r)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:Hy};if(!r.dkimMismatch)return{verdict:"aligned",fromDomain:r.fromDomain,dkimDomain:r.dkimDomain,summary:r.dkimDomain?`We verified this message was really sent by ${r.fromDomain}.`:"Nothing looks unusual about this sender."};const a=r.fromDomain,o=r.dkimDomain,i=e.fromName&&e.fromName!==e.fromEmail?e.fromName:void 0,l=i?`The display name claims "${i}", but this message was actually sent from ${o??"another sender"} — not ${a}. Real senders use their own address.`:`This message claims to be from ${a}, but it was actually sent from ${o??"a different sender"}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:l,similarCount:s}}function Qu(e,t){const s=e?.fromEmail??null,r=e?.subject??"",{data:a,error:o}=de({...nl({query:Wu(s??void 0)}),enabled:!!s,staleTime:3e4}),i=Uy(a?.items,s??void 0),l=[r,s].filter(Boolean).join(" "),{data:u,isLoading:f,error:d}=de({...ll({query:{query:l,limit:5}}),enabled:!!(e&&l.length>3),staleTime:6e4,retry:1});return{data:c.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(b=>b.messageId!==e.messageId).map(b=>({id:b.messageId,mailboxId:t!=null&&b.mailboxIds.includes(t)?t:b.mailboxIds[0]??"",fromName:b.fromName??"",subject:b.subject??"(No subject)",timeLabel:b.sentDate!=null?Lt(b.sentDate*1e3):"",matched:b.matchedChunkType})),g=Vy(e,i),v=Yy(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},x=Qy(i);return{sender:g,authenticity:v,category:p,flags:x,similar:h}},[e,i,u,t]),isSimilarLoading:f,similarError:d,similarErrorIsFatal:Ur(d),addressErrorIsFatal:Ur(o),addressId:i?.addressId,address:i}}function Gy(e,t){const s={...e??{}};for(const[r,a]of Object.entries(t))a==null?delete s[r]:s[r]={...a,setAt:a.setAt??Date.now()};return s}function Yu({addressId:e,senderEmail:t}){const s=ye(),{pushError:r}=Ve(),a=jf({query:Wu(t)}),{mutate:o,isPending:i}=ve({...il(),onMutate:async u=>{const f=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,m=>m&&{...m,items:m.items.map(h=>h.addressId===u.path.addressId?{...h,flags:Gy(h.flags,f)}:h)}),{previous:d}},onError:(u,f,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),r({title:"Couldn't update sender preference",detail:st(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){dl(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 Xy=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Gu=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function Jy(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function Zy(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function e0(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Xu(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const t0=["personal","newsletter","marketing","automated","transactional","social"],s0=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:r}=e;return t?s&&t===s?r?"notSpam":null:s?"markSpam":null:null},n0=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:r}=e;return t&&!s?"error":r?"loading":"ready"};function r0(){return n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(ut,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"h-8 rounded bg-surface"})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>n.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function a0({isOpen:e,current:t,onSelect:s,onCancel:r}){return e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:r,children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),n.jsx("div",{className:"mt-4 flex flex-col gap-1",children:t0.map(a=>n.jsxs("button",{type:"button",onClick:()=>s(a),className:`flex min-h-11 items-center justify-between rounded px-3 text-left text-sm capitalize transition-colors hover:bg-surface-raised ${a===t?"font-semibold text-accent":"text-fg"}`,children:[a,a===t&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"current"})]},a))}),n.jsx("div",{className:"mt-6 flex justify-end",children:n.jsx("button",{type:"button",onClick:r,className:"inline-flex min-h-11 items-center justify-center rounded border border-line px-4 text-sm font-medium transition-colors hover:bg-surface-raised",children:"Cancel"})})]})]}):null}function o0({thread:e,onClose:t,mailboxId:s,accountId:r,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:f}=Qu(e,s),[d,m]=c.useState(!1),[h,g]=c.useState(!1),v=e.fromEmail??void 0,{updateFlags:p,isPending:x}=Yu({addressId:i,senderEmail:v}),{junkMailboxId:b}=or(r),{inboxMailboxId:w}=Qa(r),{moveMessages:j}=Qt({mailboxId:s??"",threadId:e.threadId,accountId:r}),y=Js(),I=s0({mailboxId:s,junkMailboxId:b,inboxMailboxId:w}),N=c.useCallback(()=>{w&&j([e.messageId],w)},[w,j,e.messageId]),k=c.useCallback(()=>{b&&(Xu(y,{count:1,senderTrust:e.senderTrust,wasRescuable:Gu(e)}),j([e.messageId],b))},[b,j,e,y]),C=c.useCallback(()=>{},[]),M=c.useCallback(()=>{const R=o?.flags?.vip!==!0;p({vip:{value:R}})},[o?.flags?.vip,p]),P=c.useCallback(()=>{const R=o?.flags?.muted!==!0;p({muted:{value:R}})},[o?.flags?.muted,p]),D=c.useCallback(()=>{o?.flags?.blocked===!0?p({blocked:{value:!1}}):m(!0)},[o?.flags?.blocked,p]),O=c.useCallback(()=>{m(!1),p({blocked:{value:!0}})},[p]),E=c.useCallback(()=>{const R=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:R}})},[o?.flags?.unsubscribed,p]),S=c.useCallback(R=>{g(!1),p({category:{value:R}})},[p]),A=i!==void 0,L={onToggleVip:A?M:void 0,onToggleMute:A?P:void 0,onToggleBlock:A?D:void 0,onToggleUnsubscribe:A?E:void 0,onReclassify:A?()=>g(!0):void 0,onNotSpam:I==="notSpam"?N:void 0,onMarkSpam:I==="markSpam"?k:void 0},T=({mailboxId:R,messageId:$,className:z,ariaLabel:V,children:ee})=>n.jsx(pt,{to:"/mail/$mailboxId",params:{mailboxId:R},search:X=>({...X,selectedMessageId:$}),className:z,"aria-label":V,children:ee});if(!o)return n.jsx(r0,{});const F=n0({similarError:u,similarErrorIsFatal:f,isSimilarLoading:l});return n.jsxs(n.Fragment,{children:[n.jsx(Wl,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:C,actions:L,similarState:F,similarLinkComponent:T,className:"border-l-0 h-full w-full"}),n.jsx(Ra,{isOpen:d,title:"Block this sender?",description:`Messages from ${v??"this sender"} will never load images and will be flagged. You can undo this in Settings → Senders.`,confirmLabel:"Block sender",destructive:!0,isBusy:x,onConfirm:O,onCancel:()=>m(!1)}),n.jsx(a0,{isOpen:h,current:o.category.value,onSelect:S,onCancel:()=>g(!1)})]})}const Ms=({onClose:e,thread:t,mailboxId:s,accountId:r,hideCloseButton:a})=>t?n.jsx(o0,{thread:t,onClose:e,mailboxId:s,accountId:r,hideCloseButton:a}):n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(ut,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[n.jsx(ut,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),Fr="Open a message first",so=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:r,onReply:a,onReplyAll:o,onForward:i,onDelete:l,canDelete:u,onToggleStar:f,isStarred:d,moveContext:m})=>{const[h,g]=c.useState(null),v=u??e,p=x=>()=>g(x);return n.jsx(wh,{hasThread:e,isStarred:d,onUnavailable:x=>g(Fr),unavailableHint:h,replyTitle:`Reply ${fs("reply")}`,replyAllTitle:`Reply all ${fs("replyAll")}`,forwardTitle:`Forward ${fs("forward")}`,deleteTitle:`Move to Trash ${fs("delete")}`,flagTitle:`Star ${fs("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:v?l:p(Fr),onToggleStar:f,onMove:p(Fr),moveSlot:m?n.jsx(dn,{accountId:m.accountId,currentMailboxId:m.currentMailboxId,onMove:m.onMove,label:"Move to mailbox"}):void 0,children:n.jsx(yh,{open:t,enabled:s,onToggle:r})})},Ju=()=>{const e=ye();return c.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])},Qs=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=t??e?.mailboxId,o=s??e?.accountConfigId,i=Ju(),{deleteMessages:l}=Yt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{moveMessages:u}=Qt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{toggleStar:f}=Wa({threadId:e?.threadId??"",mailboxId:a??""}),d=c.useCallback(()=>{e&&l(i(e))},[e,i,l]),m=c.useCallback(x=>{e&&u(i(e),x)},[e,i,u]),h=c.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[g,v]=c.useState(null),p=c.useCallback(()=>v(null),[]);return{mailboxId:a,accountId:o,isStarred:e?.hasStars,deleteThread:d,moveThread:m,toggleStar:h,composeRequest:g,requestCompose:v,clearComposeRequest:p}},$s={action:null,nextPrefix:null,preventDefault:!1},i0={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},l0={j:{action:"focusNext"},k:{action:"focusPrevious"},arrowdown:{action:"focusNext"},arrowup:{action:"focusPrevious"},home:{action:"focusFirst"},end:{action:"focusLast"},enter:{action:"openFocused"}," ":{action:"toggleSelect"},delete:{action:"delete"},backspace:{action:"delete"},u:{action:"toggleRead"},x:{action:"toggleSelect"},r:{action:"reply"},a:{action:"replyAll"},f:{action:"forward"},"#":{action:"delete"},s:{action:"toggleStar"},m:{action:"muteSender"},b:{action:"blockSender"},v:{action:"vipSender"},"!":{action:"markJunk"},i:{action:"toggleIntelligence"},d:{action:"toggleDensity"},"/":{action:"focusSearch"},c:{action:"compose"},"?":{action:"help"}};function c0(e,t){const s=e.key.toLowerCase(),r=e.metaKey||e.ctrlKey;if(e.inEditable)return{...$s,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...$s,nextPrefix:t==="g"?null:t};if(r&&s==="n")return{action:"compose",nextPrefix:null,preventDefault:!0};if(r&&s==="a")return{action:"selectAll",nextPrefix:null,preventDefault:!0};if(r)return{...$s,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=i0[s===","?",":s]??null;return{action:i,nextPrefix:null,preventDefault:i!==null}}if(s==="g"&&!e.shiftKey)return{action:null,nextPrefix:"g",preventDefault:!0};if(e.shiftKey){const o=s==="j"||s==="arrowdown";if(o||(s==="k"||s==="arrowup"))return{action:o?"extendSelectDown":"extendSelectUp",nextPrefix:null,preventDefault:!0}}const a=l0[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?$s:{action:a.action,nextPrefix:null,preventDefault:!0}}return $s}function u0(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const d0="data-message-row",f0='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function m0(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(f0);return t?!t.hasAttribute(d0):!1}function h0({handlers:e,enabled:t=!0,sequenceTimeoutMs:s=1e3}){const r=c.useRef(e);r.current=e;const a=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{if(!t)return;const i=()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},l=u=>{const f=c0({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:u0(u.target),onControl:m0(u.target)},a.current);if(i(),a.current=f.nextPrefix,f.nextPrefix!==null&&(o.current=setTimeout(()=>{a.current=null,o.current=null},s)),f.action===null)return;const d=r.current[f.action];d&&(f.preventDefault&&u.preventDefault(),d())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l),i(),a.current=null}},[t,s])}const Li=(e,t,s)=>{if(!t)return null;const r=e.indexOf(t);if(r===-1)return null;const a=s==="next"?r+1:r-1;return a<0||a>=e.length?null:e[a]},no=()=>{const[e,t]=c.useState(void 0),[s,r]=c.useState([]),[a,o]=c.useState([]),i=c.useRef(null),[l,u]=c.useState(!1),[f,d]=c.useState(!1),m=c.useCallback(h=>{t(h.focusedMessageId),r(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:m,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:l,blocksKeyboard:f}},ro=({context:e,orderedIds:t,selectedMessageId:s,enabled:r=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:l,blocksKeyboard:u}=e,f=c.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return h0({enabled:r&&!u,handlers:{...l?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:f,...o}}),{goBack:f,nextMessageId:Li(t,s,"next")??void 0,previousMessageId:Li(t,s,"previous")??void 0}};function p0(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function Zu(e,t){if(e)return p0(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const ed=c.createContext(null);function cr(){const e=c.useContext(ed);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function g0({selectedMessageId:e,children:t}){const s=Oe(),{searchInput:r}=Ce(),{selectedThreadId:a,selectedMailboxId:o}=vs({strict:!1}),{data:i}=de({...Kr(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(P=>P.messageId===e)},[i,e]),u=c.useMemo(()=>Zu(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),f=c.useCallback(P=>{s({to:"/mail",search:D=>({...D,selectedMessageId:P,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),d=c.useCallback(P=>{s({to:"/mail",search:D=>({...D,q:r||void 0,selectedMessageId:P.id,selectedThreadId:P.threadId,selectedMailboxId:P.mailboxId})})},[s,r]),m=c.useCallback(P=>{e&&P.includes(e)&&s({to:"/mail",search:D=>({...D,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=Qs({thread:l,onAfterOptimisticRemove:m}),g=c.useCallback(()=>{s({to:"/mail",search:P=>({...P,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),v=no(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:x}=Yt({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:m}),{toggleReadFor:b}=rr({mailboxId:l?.mailboxId??"",messages:p}),w=c.useCallback(P=>b(P,!0),[b]),j=v.focusedMessageId,I=c.useMemo(()=>i?.items.find(P=>P.messageId===j),[i,j])??l,N=Qs({thread:I}),{nextMessageId:k,previousMessageId:C}=ro({context:v,orderedIds:v.orderedIds,selectedMessageId:e,onClose:g,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{v.listCommandsRef.current?.requestDelete()||N.deleteThread()},toggleStar:N.toggleStar,toggleRead:()=>{const P=v.selectedIds.length>0?v.selectedIds:I?[I.messageId]:[];P.length!==0&&b(P,!(I?.isRead??!1))},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),M={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:f,onSelectSearchResult:d,onCloseThread:g,actions:h,triage:v,onDeleteMessages:x,onMarkMessagesRead:w,nextMessageId:k,previousMessageId:C};return n.jsx(ed.Provider,{value:M,children:t})}function td(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:r,onDeleteMessages:a,onMarkMessagesRead:o}=cr(),{accounts:i}=Ce();return n.jsx(By,{accounts:i,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:r.listCommandsRef,onTriageContextChange:r.onTriageContextChange,onDeleteMessages:a,onMarkMessagesRead:o})}function x0(){const{conversation:e,actions:t}=cr(),{intelligenceOpen:s,onToggleIntelligence:r}=Ce(),a=Ss()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(so,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Es,{})})]})}function b0(){const{selectedThread:e}=cr(),{onToggleIntelligence:t}=Ce();return n.jsx(Ms,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function v0(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:r,nextMessageId:a,previousMessageId:o}=cr(),{intelligenceOpen:i,onToggleIntelligence:l}=Ce();return t?n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:r,onOpenIntelligence:l,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:i}),n.jsx(Ua,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:l,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(td,{})})}const Fs=Object.assign(g0,{List:td,Reading:x0,Intelligence:b0,Phone:v0}),y0=()=>ol({query:{starred:!0,order:"desc"}});function sd(){const{data:e,isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=kc({queryKey:y0(),queryFn:async({pageParam:f})=>{const{data:d}=await Sf({query:{starred:!0,order:"desc",continuationToken:f},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:f=>f.continuationToken,staleTime:6e4});return{threads:c.useMemo(()=>(e?.pages??[]).flatMap(f=>f.items??[]),[e]),isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}}const w0=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function nd({title:e,unreadCount:t,preset:s,selectedCategory:r,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:l,onClearFilters:u,children:f,footer:d,searchResults:m,searchLoading:h,relatedResults:g,relatedLoading:v,onSelectSearchResult:p,searchResultsLabel:x,relatedResultsLabel:b,searchResultsInBody:w}){const[j,y]=c.useState(!1),I={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:r,activeFilters:a,expanded:j,onExpandedChange:y,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return n.jsx(Fu,{title:e,unreadCount:t,footer:d,searchFilter:I,searchResults:m,searchLoading:h,relatedResults:g,relatedLoading:v,onSelectSearchResult:p,searchResultsLabel:x,relatedResultsLabel:b,searchResultsInBody:w,children:n.jsx(da,{...I,children:f})})}const j0={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function S0({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:r,onDeleteMessages:a,onMarkMessagesRead:o}){const{searchQuery:i,resultFolderIndex:l}=Ce(),u=Ts(),f=Ot(),[d,m]=c.useState("all"),[h,g]=c.useState(new Set),v=c.useCallback(T=>{g(F=>{const R=new Set(F);return R.has(T)?R.delete(T):R.add(T),R})},[]),p=c.useCallback(()=>{m("all"),g(new Set)},[]),{threads:x,isLoading:b,isError:w,error:j,refetch:y,fetchNextPage:I,hasNextPage:N,isFetchingNextPage:k}=sd(),{freeText:C,tokens:M}=Rs(i.trim().toLowerCase(),u),P=c.useMemo(()=>{const T=Array.from(h).map(F=>j0[F]).filter(F=>F!=null);return w0(x).map(sa).filter(F=>(d==="all"||F.category===d)&&T.every(R=>R(F))&&(!C||Nu(F,C))&&Eu(F,M))},[x,d,h,C,M]),D=c.useMemo(()=>og(),[]),O=c.useMemo(()=>P.map(T=>Iu(T,l)),[P,l]),E=c.useMemo(()=>P.filter(T=>!T.isRead).length,[P]),S=b?"loading":w?"error":P.length===0?"empty":"ready",A=c.useCallback(()=>{const T=va(ba());window.open(T,"_blank","noopener,noreferrer")},[]),L=n.jsx(qu,{selectedMessageId:e,onOpen:T=>t?.(T),onDeleteMessages:a,commandsRef:s,onTriageContextChange:r,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a?n.jsx(Hu,{onMarkAsRead:o}):null,n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.jsx("div",{className:"divide-y divide-line",children:P.map(T=>n.jsx(to,{thread:T,active:T.id===e,onClick:()=>t?.(T.id)},T.id))}),N?n.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>I(),disabled:k,children:k?"Loading…":"Load more"}):null]})]})});return n.jsx(nd,{title:"Starred",unreadCount:E,preset:D,selectedCategory:d,activeFilters:h,onSelectCategory:m,onToggleFilter:v,onClearFilters:p,searchResults:O,searchLoading:b,onSelectSearchResult:T=>t?.(T.id),children:n.jsx(ec,{listTitle:"Starred",sections:[{id:"flagged",threads:P}],flatList:!0,hideHeader:!0,listState:S,searchQuery:C?i:void 0,errorMessage:w?yl(j):void 0,onRetry:()=>y(),onReportError:A,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:f,listBody:S==="ready"?L:void 0})})}const rd=c.createContext(null);function ur(){const e=c.useContext(rd);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function k0({selectedMessageId:e,children:t}){const s=Oe(),{threads:r}=sd(),a=c.useMemo(()=>{if(e)return r.find(y=>y.messageId===e)},[r,e]),o=c.useCallback(y=>{s({to:"/mail/flagged",search:I=>({...I,selectedMessageId:y})})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:y=>({...y,selectedMessageId:void 0})})},[s]),l=c.useCallback(y=>{e&&y.includes(e)&&i()},[e,i]),u=Qs({thread:a,onAfterOptimisticRemove:l}),f=no(),{deleteMessages:d}=Yt({mailboxId:a?.mailboxId??"",messages:r,onAfterOptimisticRemove:l}),{toggleReadFor:m}=rr({mailboxId:a?.mailboxId??"",messages:r}),h=c.useCallback(y=>m(y,!0),[m]),g=f.focusedMessageId,p=c.useMemo(()=>r.find(y=>y.messageId===g),[r,g])??a,x=Qs({thread:p}),{nextMessageId:b,previousMessageId:w}=ro({context:f,orderedIds:f.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{f.listCommandsRef.current?.requestDelete()||x.deleteThread()},toggleStar:x.toggleStar,toggleRead:()=>{const y=f.selectedIds.length>0?f.selectedIds:p?[p.messageId]:[];y.length!==0&&m(y,!(p?.isRead??!1))},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),j={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:f,onDeleteMessages:d,onMarkMessagesRead:h,nextMessageId:b,previousMessageId:w};return n.jsx(rd.Provider,{value:j,children:t})}function ad(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:r,onMarkMessagesRead:a}=ur();return n.jsx(S0,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:r,onMarkMessagesRead:a})}function C0(){const{selectedThread:e,actions:t}=ur(),{intelligenceOpen:s,onToggleIntelligence:r}=Ce(),a=Ss()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(so,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Es,{})})]})}function N0(){const{selectedThread:e}=ur(),{onToggleIntelligence:t}=Ce();return n.jsx(Ms,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function E0(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:r,previousMessageId:a}=ur(),{intelligenceOpen:o,onToggleIntelligence:i}=Ce();return e?n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:i,onSwipeNext:r?()=>s(r):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:o}),n.jsx(Ua,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:i,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(ad,{})})}const _s=Object.assign(k0,{List:ad,Reading:C0,Intelligence:N0,Phone:E0}),I0={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},T0=()=>{const e=c.useRef(!1);return c.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector("[data-slate-editor]")?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},R0=()=>{const{state:e,closeCompose:t}=Dt(),s=T0(),[r,a]=c.useState(!1),{isError:o,error:i,refetch:l}=de({...xt(),staleTime:1/0}),u=c.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),f=c.useCallback(()=>{a(!1),t()},[t]),d=c.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const m=I0[e.mode]??"New Message";return n.jsxs(Je.Root,{open:e.isOpen,onOpenChange:u,children:[n.jsxs(Je.Portal,{children:[n.jsx(Je.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Je.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[n.jsx(Je.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),n.jsx(Je.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:m}),o?n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(Pt,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):n.jsx("div",{className:"flex-1 overflow-hidden",children:n.jsx(qa,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),r&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50",children:n.jsxs("div",{className:"mx-4 w-full max-w-sm rounded-xl bg-canvas p-6 shadow-xl",children:[n.jsx("h3",{className:"text-lg font-semibold",children:"Discard draft?"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Your message has unsaved content. Are you sure you want to discard it?"}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:d,className:"rounded-md px-4 py-2 text-sm font-medium hover:bg-surface-raised transition-colors",children:"Keep editing"}),n.jsx("button",{type:"button",onClick:f,className:"rounded-md bg-danger px-4 py-2 text-sm font-medium text-canvas hover:bg-danger/90 transition-colors",children:"Discard"})]})]})})]})},M0={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},od=()=>{const{state:e,closeCompose:t}=Dt(),s=Ot(),{isError:r,error:a,refetch:o}=de({...xt(),staleTime:1/0});if(!s)return n.jsx(R0,{});if(!e.isOpen)return null;const i=M0[e.mode]??"New Message",l=n.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[n.jsx("div",{className:"flex items-center gap-2 min-w-0",children:n.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:n.jsx(We,{className:"size-5"})})]});return r?n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[l,n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(Pt,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[l,n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:n.jsx(qa,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function A0(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:Lt(e.updatedAt),isRead:!0}}function D0(e){return{id:e.messageId,accountId:e.accountConfigId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function O0({outboxMessages:e,accountId:t,imapThreads:s}){const r=e.filter(i=>i.status==="draft"&&i.accountId===t).map(A0),a=s.map(D0),o=[];return r.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:r}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function ao(){const e=Ss();return!e||e.showNavPane?null:n.jsx(G,{variant:"ghost",size:"sm",icon:n.jsx(Ca,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const P0=({label:e,count:t})=>n.jsxs("div",{className:"sticky top-0 z-10 flex items-baseline justify-between border-b border-line bg-surface-sunken px-row-inset py-1",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:t})]}),L0=({row:e,isSelected:t,onOpen:s,onDelete:r,isDeleting:a})=>n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:H("group",tn({active:t})),children:[n.jsx(Xi,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),n.jsx(Hs,{thread:e}),n.jsx("div",{className:"flex items-center gap-1 shrink-0",children:n.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),r(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:n.jsx(rt,{className:"size-3.5"})})})]}),$0=({row:e,isSelected:t,onOpen:s})=>{const r=!e.isRead;return n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:H("group",tn({active:t})),children:[r&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"sm"}),n.jsx(Hs,{thread:e})]})};function F0({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:r,title:a,unreadCount:o}){const{openCompose:i,state:l}=Dt(),u=Oe(),f=ye(),{data:d}=de(qn()),m=c.useMemo(()=>O0({outboxMessages:d?.items??[],accountId:t,imapThreads:r}),[d?.items,t,r]),h=ve({...Hn(),onSuccess:()=>{f.invalidateQueries({queryKey:ka()})}}),g=b=>{h.mutate({path:{outboxMessageId:b}})},v=b=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:b})},p=b=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:b}})},x=m.length===0;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(ao,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:a}),(o??0)>0&&n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:[o," unread"]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:x?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[n.jsx(ca,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):m.map(b=>n.jsxs("div",{children:[b.label&&n.jsx(P0,{label:b.label,count:b.threads.length}),n.jsx("div",{className:"divide-y divide-line",children:b.threads.map(w=>b.id==="remit-drafts"?n.jsx(L0,{row:w,isSelected:l.isOpen&&w.id===l.outboxMessageId,onOpen:v,onDelete:g,isDeleting:h.isPending},w.id):n.jsx($0,{row:w,isSelected:w.id===s,onOpen:p},w.id))})]},b.id))})]})}function _0(e,t,s){const r=new Array(e);return new Proxy(r,{get(a,o,i){if(typeof o=="string"){const l=o.charCodeAt(0);if(l>=48&&l<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let f=a[u];if(!f){const d=t[u*2];f=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return f}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function ds(e,t,s){let r=s.initialDeps??[],a,o=!0;function i(){const l=e();return(l.length!==r.length||l.some((f,d)=>r[d]!==f))&&(r=l,a=t(...l),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=l=>{r=l},i}function $i(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const z0=(e,t)=>Math.abs(e-t)<1.01,B0=(e,t,s)=>{let r;return function(...a){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,a),s)}};let zs;const _r=()=>{if(zs!==void 0)return zs;if(typeof navigator>"u")return zs=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zs=!0;const e=navigator.maxTouchPoints;return zs=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Fi=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},K0=e=>e,U0=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,a=new Array(r);for(let o=0;o<r;o++)a[o]=t+o;return a},q0=(e,t)=>{const s=e.scrollElement;if(!s)return;const r=e.targetWindow;if(!r)return;const a=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(a(Fi(s)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u?.borderBoxSize){const f=u.borderBoxSize[0];if(f){a({width:f.inlineSize,height:f.blockSize});return}}a(Fi(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},_n={passive:!0},H0=typeof window>"u"?!0:"onscrollend"in window,W0=(e,t,s)=>{const r=e.scrollElement;if(!r)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&H0;let i=0;const l=o?null:B0(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=m=>()=>{i=s(r),l?.(),t(i,m)},f=u(!0),d=u(!1);return r.addEventListener("scroll",f,_n),o&&r.addEventListener("scrollend",d,_n),()=>{r.removeEventListener("scroll",f),o&&r.removeEventListener("scrollend",d)}},V0=(e,t)=>W0(e,t,s=>{const{horizontal:r,isRtl:a}=e.options;return r?s.scrollLeft*(a&&-1||1):s.scrollTop}),Q0=(e,t,s)=>{if(s.options.useCachedMeasurements){const r=s.indexFromElement(e),a=s.options.getItemKey(r);return s.itemSizeCache.get(a)??s.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[s.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=s.indexFromElement(e),a=s.options.getItemKey(r),o=s.itemSizeCache.get(a);if(o!==void 0)return o}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},Y0=(e,{adjustments:t=0,behavior:s},r)=>{var a,o;(o=(a=r.scrollElement)==null?void 0:a.scrollTo)==null||o.call(a,{[r.options.horizontal?"left":"top"]:e+t,behavior:s})},G0=Y0;class X0{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,r,a;return((a=(r=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:r.now)==null?void 0:a.call(r))??Date.now()},this.observer=(()=>{let s=null;const r=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const l=o.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[f,d]of this.elementsCache)if(d===l){this.elementsCache.delete(f);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=r())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=r())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=r())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var r,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:K0,rangeExtractor:U0,onChange:()=>{},measureElement:Q0,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in s){const g=s[h];g!==void 0&&(o[h]=g)}const i=this.options;let l=null,u=null,f=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,g=o.count,v=this.getMeasurements(),p=h>0?((r=v[0])==null?void 0:r.key)??i.getItemKey(0):null,x=h>0?((a=v[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(g!==h||h>0&&g>0&&(o.getItemKey(0)!==p||o.getItemKey(g-1)!==x)){f=!0;const j=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??v[0]:null;j&&(l=[j.key,this.getScrollOffset()-j.start]);const y=o.followOnAppend===!0?"auto":o.followOnAppend||null;y&&g>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(g-1)!==x)&&(u=y)}}this.options=o,f&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,m=0;if(l&&this.scrollOffset!==null){const[h,g]=l,v=this.getMeasurements(),{count:p,getItemKey:x}=this.options;let b=0;for(;b<p&&x(b)!==h;)b++;if(b<p){const w=v[b];if(w){const j=w.start+g;j!==this.scrollOffset&&(m=j-this.scrollOffset,this.scrollOffset=j,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,u,m])},this.notify=s=>{var r,a;(a=(r=this.options).onChange)==null||a.call(r,this,s)},this.maybeNotify=ds(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===o?this.scrollDirection:l<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!_r()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,_n),o.addEventListener("touchend",l,_n),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,l,u]=a;o!==null&&!l&&(_r()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),r=this.getMaxScrollOffset();if(s<0||s>r)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=ds(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,r,a,o,i,l,u,f)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f}),{key:!1}),this.getMeasurements=ds(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f},d)=>{const m=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const b of this.laneAssignments.keys())b>=s&&this.laneAssignments.delete(b);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(b=>{this.itemSizeCache.set(b.key,b.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),l===1){const b=s*2;let w=this._flatMeasurements;if(!w||w.length<b){const I=new Float64Array(b);w&&h>0&&I.set(w.subarray(0,h*2)),w=I,this._flatMeasurements=w}let j;if(h===0)j=r+a;else{const I=h-1;j=w[I*2]+w[I*2+1]+f}for(let I=h;I<s;I++){const N=o(I),k=m.get(N),C=typeof k=="number"?k:this.options.estimateSize(I);w[I*2]=j,w[I*2+1]=C,j+=C+f}const y=_0(s,w,o);return this.measurementsCache=y,y}const g=this.measurementsCache.slice(0,h),v=new Array(l).fill(void 0),p=new Float64Array(l);let x=0;for(let b=0;b<h;b++){const w=g[b];w&&(v[w.lane]===void 0&&x++,v[w.lane]=b,p[w.lane]=w.end)}for(let b=h;b<s;b++){const w=o(b),j=this.laneAssignments.get(b);let y,I;const N=u==="estimate"||m.has(w);if(j!==void 0&&this.options.lanes>1){y=j;const P=v[y],D=P!==void 0?g[P]:void 0;I=D?D.end+f:r+a}else if(x===l){let P=0,D=p[0],O=v[0];for(let E=1;E<l;E++){const S=p[E];(S<D||S===D&&v[E]<O)&&(P=E,D=S,O=v[E])}y=P,I=D+f,N&&this.laneAssignments.set(b,y)}else y=b%this.options.lanes,I=r+a,N&&this.laneAssignments.set(b,y);const k=m.get(w),C=typeof k=="number"?k:this.options.estimateSize(b),M=I+C;g[b]={index:b,start:I,size:C,end:M,key:w,lane:y},v[y]===void 0&&x++,v[y]=b,p[y]=M}return this.measurementsCache=g,g},{key:!1,debug:()=>this.options.debug}),this.calculateRange=ds(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,r,a,o)=>s.length===0||r===0?(this.range=null,null):(this.range=Z0(s,r,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ds(()=>{let s=null,r=null;const a=this.calculateRange();return a&&(s=a.startIndex,r=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,r]},(s,r,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:r,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const r=this.options.indexAttribute,a=s.getAttribute(r);return a?parseInt(a,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),l=Math.min(this.options.count-1,a+o);return s>=i&&s<=l}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const r=this.indexFromElement(s),a=this.options.getItemKey(r),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,r)=>{var a,o;if(s<0||s>=this.options.count)return;let i,l,u;const f=this._flatMeasurements;if(this.options.lanes===1&&f!==null)u=this.options.getItemKey(s),l=f[s*2],i=f[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,l=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,m=r-d;if(m!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,g=h?this.getTotalSize():0,v=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:l,size:i,end:l+i,lane:0},m,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,r),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-g):v&&this.applyScrollAdjustment(m),this.notify(!1)}},this.getVirtualItems=ds(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,r)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const l=s[o],u=r[l];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const r=this.getMeasurements();if(r.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=id(0,r.length-1,o?l=>a[l*2]:l=>$i(r[l]).start,s);return $i(r[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,r,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=s>=i+o?"end":"start"),r==="center"?s+=(a-o)/2:r==="end"&&(s-=o);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,r="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(r==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)r="end";else if(i.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,i.size),r]},this.scrollToOffset=(s,{align:r="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,r),i=this.now();this.scrollState={index:null,align:r,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:r="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,r);if(!o)return;const[i,l]=o,u=this.now();this.scrollState={index:s,align:l,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:r="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const r=this.getMeasurements();let a;if(r.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=r[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&o.some(l=>l===null);){const l=r[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}a=Math.max(...o.filter(l=>l!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const r=this.getMeasurements();for(const a of r)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:r,behavior:a})=>{this._intendedScrollOffset=s+(r??0),this.options.scrollToFn(s,{behavior:a,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&(_r()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=r?r[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&z0(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),f=this.scrollState.behavior==="smooth"&&u>l;this.scrollState.lastTargetOffset=a,f||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:f?"smooth":"auto"})}this.scheduleScrollReconcile()}}const id=(e,t,s,r)=>{for(;e<=t;){const a=(e+t)/2|0,o=s(a);if(o<r)e=a+1;else if(o>r)t=a-1;else return a}return e>0?e-1:0};function J0(e,t,s){let r=0;for(;r<=t;){const a=(r+t)/2|0,o=e[a*2];if(o<s)r=a+1;else if(o>s)t=a-1;else return a}return r>0?r-1:0}function Z0(e,t,s,r,a){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&a!==null){const f=J0(a,o,s);let d=f;const m=s+t;for(;d<o&&a[d*2]+a[d*2+1]<m;)d++;return{startIndex:f,endIndex:d}}let l=id(0,o,f=>e[f].start,s),u=l;if(r===1)for(;u<o&&e[u].end<s+t;)u++;else if(r>1){const f=Array(r).fill(0);for(;u<o&&f.some(m=>m<s+t);){const m=e[u];f[m.lane]=m.end,u++}const d=Array(r).fill(s+t);for(;l>=0&&d.some(m=>m>=s);){const m=e[l];d[m.lane]=m.start,l--}l=Math.max(0,l-l%r),u=Math.min(o,u+(r-1-u%r))}return{startIndex:l,endIndex:u}}const zr=typeof document<"u"?c.useLayoutEffect:c.useEffect;function ew({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...r}){const a=c.useReducer(f=>f+1,0)[1],o=c.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=f=>{const d=o.current;if(!d.enabled||!d.container)return;const m=f.getTotalSize();if(m!==d.lastSize){d.lastSize=m;const b=f.options.horizontal?"width":"height";d.container.style[b]=`${m}px`}const h=!!f.options.horizontal,g=d.mode==="transform",v=h?"left":"top",p=f.options.scrollMargin,x=f.getVirtualItems();for(const b of x){const w=b.start-p,j=f.elementsCache.get(b.key);j&&d.lastPositions.get(j)!==w&&(d.lastPositions.set(j,w),g?j.style.transform=h?`translate3d(${w}px, 0, 0)`:`translate3d(0, ${w}px, 0)`:j.style[v]=`${w}px`)}},l={...r,onChange:(f,d)=>{var m;const h=o.current;let g=!0;if(h.enabled){i(f);const v=f.range,p=h.prevRange;g=!p||p.isScrolling!==f.isScrolling||p.startIndex!==v?.startIndex||p.endIndex!==v?.endIndex,g&&(h.prevRange=v?{startIndex:v.startIndex,endIndex:v.endIndex,isScrolling:f.isScrolling}:null)}g&&(e&&d?ha.flushSync(a):a()),(m=r.onChange)==null||m.call(r,f,d)}},[u]=c.useState(()=>{const f=new X0(l);return Object.assign(f,{containerRef:d=>{const m=o.current;if(m.container=d,m.lastSize=null,d&&m.enabled){const h=f.getTotalSize();m.lastSize=h;const g=f.options.horizontal?"width":"height";d.style[g]=`${h}px`}}})});return u.setOptions(l),zr(()=>u._didMount(),[]),zr(()=>u._willUpdate()),zr(()=>{i(u)}),u}function tw(e){return ew({observeElementRect:q0,observeElementOffset:V0,scrollToFn:G0,...e})}const sw={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},ld={delete:"moved to Trash",move:"moved",markRead:"marked as read"},cd={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},nw={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},rw={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},aw=(e,t,s)=>sw[e](ct(t),ct(s)),_i=(e,t)=>`${ct(t)} ${ld[e]}. Your mail server is still catching up.`,ow=(e,t,s)=>`${ct(t)} ${ld[e]}. ${ct(s)} ${cd[e]}.`,iw=(e,t)=>t>0?`Stopped after ${ct(t)} — some messages ${cd[e]}`:nw[e],lw=e=>rw[e],cw=e=>e==="delete"?"danger":"info",ud=100,zn=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),uw=(e,t=ud)=>{if(e.length===0)return[];const s=[];for(let r=0;r<e.length;r+=t)s.push(e.slice(r,r+t));return s},dw=async(e,t,s,r)=>{const a=uw(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(r())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const f=a[u],d=await zn(t(f));if(!d.ok)return l.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:l,cancelled:!1,error:d.error};i+=f.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},fw=async(e,t,s,r,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await zn(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const f=u.value;if(f.ids.length>0){const d=await zn(s(f.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=f.ids.length,r({done:o,total:t})}l=f.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},mw=e=>({done:e.done,total:Math.max(e.total,e.done)}),hw=async(e,t,s)=>{let r=0,a;do{if(s())return{total:r,cancelled:!0};const o=await zn(e(a));if(!o.ok)return{total:r,cancelled:!1,error:o.error};const i=o.value;r+=i.ids.length,t(r),a=i.continuationToken}while(a);return{total:r,cancelled:!1}},pw=e=>e.failedIds.length>0?{exit:!1,retryIds:e.failedIds}:e.cancelled||e.error?{exit:!1,retryIds:[]}:{exit:!0,retryIds:[]},gw=100,xw=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],bw=({mailboxId:e,accountId:t,enabled:s,predicateKey:r,searchQuery:a})=>{const[o,i]=c.useState({kind:"idle"}),[l,u]=c.useState(void 0),[f,d]=c.useState(void 0),m=c.useRef(!1),h=ye(),{pushError:g}=Ve();c.useEffect(()=>{m.current=!0,i({kind:"idle"})},[s,r]);const v=c.useRef(a);v.current=a;const p=c.useCallback(async N=>{const{data:k}=await fl({path:{mailboxId:e},query:{...v.current,continuationToken:N,limit:gw},throwOnError:!0});return{ids:(k.items??[]).map(C=>C.messageId),continuationToken:k.continuationToken}},[e]),x=c.useCallback(N=>async k=>{if(N.kind==="move"){const{data:M}=await kf({body:{messageIds:k,destinationMailboxId:N.destinationMailboxId},throwOnError:!0});return M}if(N.kind==="markRead"){const{data:M}=await Cf({body:{messageIds:k,isRead:!0},throwOnError:!0});return M}const{data:C}=await Nf({body:{messageIds:k},throwOnError:!0});return C},[]),b=c.useCallback(N=>{yt(h,vt(xw(N,e))),t&&h.invalidateQueries({queryKey:Jt({path:{accountId:t}})})},[h,e,t]),w=c.useCallback(()=>{m.current=!1,i({kind:"counting",countSoFar:0}),hw(p,N=>i({kind:"counting",countSoFar:N}),()=>m.current).then(N=>{if(N.error){g(Vt("Couldn't count matching messages","The count didn't finish.",N.error)),i({kind:"idle"});return}if(N.cancelled){i({kind:"idle"});return}i({kind:"escalated",total:N.total})})},[p,g]),j=c.useCallback(()=>{m.current=!0},[]),y=c.useCallback(()=>{m.current=!0,i({kind:"idle"})},[]),I=c.useCallback(async(N,k)=>{m.current=!1,u(N);const C=D=>d(mw(D)),M=x(N),P=k!==void 0?await dw(k,M,C,()=>m.current):await fw(p,o.kind==="escalated"?o.total:0,M,C,()=>m.current);return u(void 0),d(void 0),i({kind:"idle"}),P.error&&g(Vt(iw(N.kind,P.done),lw(N.kind),P.error)),P.done>0&&b(N),P},[x,p,o,g,b]);return{phase:o,escalate:w,stop:j,clear:y,isRunning:l!==void 0,runningAction:l,progress:f,runAction:I}},dd=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",vw=e=>`Select all ${dd(e)}`,yw=(e,t)=>`All ${ct(t)} ${dd(e)} selected`,ww=e=>e.isRunning?"running":e.isCounting?"counting":e.isEscalated?"escalated":"idle",jw=2,Sw=(e,t,s=!1)=>e>=jw||t!=="idle"||s,fd=(e,t,s)=>{const r=ve(cl()),{mutate:a,reset:o}=r,[i,l]=c.useState(!1),u=c.useMemo(()=>Hf(s),[s]),f=c.useCallback(()=>{!e||!t||(l(!1),a({path:{accountId:e},body:qr({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=c.useCallback(()=>{l(!1),o()},[o]),m=r.data,h=m?.semanticUnavailable===!0&&!i&&u.length>0;c.useEffect(()=>{!h||!e||(l(!0),a({path:{accountId:e},body:qr(Wf(u))}))},[h,e,u,a]);const g=i||(m?.semanticUnavailable??!1),v=r.isPending||h,p=i?{matchOperator:"Or",literalClauses:Vf(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:f,reset:d,matchedCount:v?void 0:m?.matchedCount,messageIds:v?void 0:m?.messageIds,semanticUnavailable:g,senderFallback:i,senders:u,matchPredicate:p,isPending:v,isError:r.isError,error:r.error}},kw=({entry:e,hasSeed:t,previewStatus:s,matchedCount:r})=>{if(e==="something-else"&&!t)return{kind:"something-else"};if(s==="error")return{kind:"error"};if(s!=="success")return{kind:"widening"};const a=r??0;return{kind:"organize",matchedCount:a,fallback:a===0}};function md({accountId:e,selectedMessageIds:t,seedCount:s,semanticUnavailable:r=!1,senders:a=[],seedMailboxId:o,seedScope:i,onClose:l}){const u=t[0],f=r&&a.length>0,[d]=c.useState(()=>Qf({anchorMessageId:u,semanticUnavailable:r,senders:a,selectionCount:t.length,seedMailboxId:o,seedScope:i})),{rule:m,handlers:h}=Ou({initialRule:d,widenAnchorCount:t.length}),{data:g}=de({..._e({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),v=c.useMemo(()=>Zs(g?.items??[]).map(O=>({id:O.mailboxId,label:Vn(O.fullPath)})),[g?.items]),{labels:p}=Cl(e),x=c.useMemo(()=>p.map(O=>({id:O.labelId,name:O.name,color:O.color})),[p]),{createLabel:b}=Zf(e),w=async O=>{const E=await b(O);return{id:E.labelId,name:E.name,color:E.color}},j=gl(e,Ea(m,u),s),y=xl(e),I=bl(e),{createFolder:N}=Sl(e),[k,C]=c.useState(),M=c.useRef(!1),P=()=>{const O=vl(m,u);if(m.scope==="once"){y.start(O);return}M.current=!1,C(Yf(O)?O:void 0),I.createFilter(O,m.scope==="standing"?"standing":"temporary",(m.name??"").trim())};c.useEffect(()=>{!k||M.current||!I.isSuccess||(M.current=!0,y.start(k))},[k,I.isSuccess,y.start]);const D=()=>{k&&y.start(k)};return y.isStarting||y.isRunning||y.isDone?n.jsx(Pu,{progress:y.progress,isDone:y.isDone,runningLabel:f?"Organizing mail from these senders…":"Organizing similar mail…",onClose:l}):I.isSuccess&&y.isError?n.jsx(wy,{onRetry:D,onClose:l}):I.isPending?n.jsx(ra,{}):I.isSuccess?k?n.jsx(ra,{}):n.jsx(Lu,{onClose:l}):I.isError?n.jsx($u,{onRetry:I.reset,onClose:l}):n.jsx(ul,{rule:m,folders:v,labels:x,preview:j,semanticAvailable:!r,clauseFields:Na,...h,onCreateFolder:N,onCreateLabel:w,onCommit:P,onCancel:l})}const zi=(e,t)=>e.find(s=>s.label.toLowerCase()===t),Cw=(e,t)=>{const s=[],r=zi(e,"inbox");r&&s.push({id:"keep-inbox",label:"Always keep in Inbox",seed:{moveMailboxId:r.id,scope:"standing"}});const a=zi(e,"archive");a&&s.push({id:"file-archive",label:"File in Archive",seed:{moveMailboxId:a.id}});const o=t?e.find(i=>i.id===t):void 0;return o&&s.push({id:"move-junk",label:`Move to ${o.label}`,seed:{moveMailboxId:o.id}}),s},Nw=(e,t)=>{const s=e.toLowerCase(),r=t.find(o=>s.includes(o.label.toLowerCase())),a=/\b(always|keep|future|from now)\b/.test(s);return{moveMailboxId:r?.id,scope:a?"standing":void 0}};function Ew({folderOptions:e,junkMailboxId:t,onSeed:s}){const[r,a]=c.useState(""),o=c.useMemo(()=>Cw(e,t),[e,t]),i=()=>{const l=r.trim();l&&s(Nw(l,e))};return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"border-b border-line px-5 py-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg",children:"What should Remit do?"}),n.jsx("p",{className:"mt-0.5 text-xs text-fg-muted",children:"Pick a shortcut or say it in your own words."})]}),n.jsx("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto px-5 py-4",children:o.map(l=>n.jsx(G,{variant:"secondary",onClick:()=>s(l.seed),className:"h-12 w-full justify-start px-4",children:l.label},l.id))}),n.jsxs("div",{className:"flex items-center gap-2 border-t border-line px-5 py-3",children:[n.jsx(Ef,{value:r,onChange:l=>a(l.target.value),onKeyDown:l=>l.key==="Enter"&&i(),placeholder:"Tell Remit what to do…","aria-label":"Tell Remit what to do",className:"flex-1"}),n.jsx(G,{variant:"primary","aria-label":"Send",onClick:i,disabled:!r.trim(),icon:n.jsx(Fm,{className:"size-4"}),className:"size-9 shrink-0 px-0"})]})]})}const Iw=e=>e?.scope==="standing"?"standing":void 0,Tw=(e,t,s)=>e?"error":t?"pending":s!==void 0?"success":"idle";function Rw({entry:e,accountId:t,selectedMessageIds:s,selectedSenders:r,junkMailboxId:a,onClose:o}){const i=s[0],[l,u]=c.useState(),{preview:f,matchedCount:d,semanticUnavailable:m,senders:h,isPending:g,isError:v,error:p}=fd(t,i,r);c.useEffect(()=>{f()},[f]);const{data:x}=de({..._e({path:{accountId:t}}),staleTime:Number.POSITIVE_INFINITY}),b=c.useMemo(()=>Zs(x?.items??[]).map(j=>({id:j.mailboxId,label:Vn(j.fullPath)})),[x?.items]),w=kw({entry:e,hasSeed:l!==void 0,previewStatus:Tw(v,g,d),matchedCount:d});return n.jsxs(pl,{open:!0,onClose:o,dismissLabel:"Dismiss organize",children:[w.kind==="something-else"&&n.jsx(Ew,{folderOptions:b,junkMailboxId:a,onSeed:u}),w.kind==="widening"&&n.jsx(Mw,{}),w.kind==="error"&&n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:p instanceof Error?p.message:"Please try again."}),n.jsx(G,{variant:"ghost",onClick:o,className:"mt-2",children:"Close"})]}),w.kind==="organize"&&n.jsx(md,{accountId:t,selectedMessageIds:s,seedCount:w.matchedCount,seedScope:Iw(l),seedMailboxId:l?.moveMailboxId,semanticUnavailable:m,senders:h,onClose:o})]})}function Mw(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]})}function Aw({open:e,accountId:t,selectedMessageIds:s,selectedSenders:r,onClose:a}){const o=s[0],{preview:i,reset:l,matchedCount:u,semanticUnavailable:f,senders:d,isPending:m,isError:h,error:g}=fd(t,o,r);c.useEffect(()=>{e&&i()},[e,i]);const v=()=>{l(),a()};return e?n.jsx(ua,{open:e,onClose:v,title:"Filter rule",children:m||u===void 0?h?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:g instanceof Error?g.message:"Please try again."}),n.jsx(G,{variant:"ghost",onClick:v,className:"mt-2",children:"Close"})]}):n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]}):n.jsx(md,{accountId:t,selectedMessageIds:s,seedCount:u,semanticUnavailable:f,senders:d,onClose:v})}):null}const Dw=(e,t)=>({id:e.messageId,accountId:e.accountConfigId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:cn(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),Ow=({thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,messageCount:d,isMultiSelectMode:m,onLongPress:h,isDesktop:g,density:v})=>n.jsx(to,{thread:Dw(e,d),linkMailboxId:t,inListbox:!0,active:r,focused:a,isTabStop:o,density:v,isDesktop:g,onFocusRow:i,selection:{isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:m,onLongPress:h},badge:e.autoMoved?n.jsx(Qc,{accountId:s,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"sm"}):void 0}),Pw=c.memo(Ow),Lw=e=>{const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountConfigId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:cn(e.category),suspicious:t}},$w=({thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:d,onLongPress:m,isDesktop:h,onDelete:g,onToggleRead:v,density:p})=>{const[x,b]=c.useState("none"),w=c.useCallback(I=>{navigator.vibrate?.(10),I==="trailing"?g(e.messageId):v(e.messageId,e.isRead),b("none")},[g,v,e.messageId,e.isRead]),j=c.useCallback(()=>{m(e.messageId)},[m,e.messageId]),y=c.useCallback(()=>{u(e.messageId)},[u,e.messageId]);return h||d?n.jsx(Pw,{thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:d,onLongPress:m,isDesktop:h,density:p}):n.jsx(Zl,{thread:Lw(e),selectionMode:!1,checked:!1,active:r,peek:x,onPeek:b,onToggleCheck:y,onLongPress:j,onOpen:()=>{},onAct:w,linkComponent:({onOpenClick:I,children:N,...k})=>n.jsx(pt,{...k,to:"/mail/$mailboxId",params:{mailboxId:t},search:C=>({...C,selectedMessageId:e.messageId}),"data-message-row":!0,onClick:I,children:N})})},Fw=72,_w=32,zw=5,hd="remit:list-density",Bw={kind:"delete"},Bi={kind:"markRead"},Kw=()=>{try{const e=localStorage.getItem(hd);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},Uw=({query:e,count:t})=>n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[n.jsx(Qn,{className:"size-4 text-fg-muted"}),n.jsxs("span",{className:"text-sm text-fg-muted",children:[t," ",t===1?"result":"results"," for “",e,"”"]})]}),qw=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:r,isError:a=!1,error:o,onRetry:i,searchQuery:l,searchPredicate:u,onDeleteMessages:f,onMoveMessages:d,isDeleting:m=!1,isMoving:h=!1,onLoadMore:g,hasMore:v=!1,isLoadingMore:p=!1,accountId:x,listTitle:b,listMeta:w,onTriageContextChange:j,commandsRef:y,hideHeader:I=!1})=>{const N=c.useRef(null),k=Oe(),C=Ot(),[M,P]=c.useState(!1),[D,O]=c.useState(null),E=!!l?.trim(),[S,A]=c.useState(s),[L,T]=c.useState(Kw),F=c.useCallback(()=>{T(_=>{const se=_==="comfortable"?"compact":"comfortable";try{localStorage.setItem(hd,se)}catch{}return se})},[]),{toggleReadFor:R}=rr({mailboxId:e}),{junkMailboxId:$}=or(x),{selectedIds:z,selectedCount:V,hasSelection:ee,isSelected:X,toggle:Q,select:le,clearSelection:ue,selectRange:te,setAnchor:K,selectAll:U,toggleAll:re,intersectWith:Ie}=zu(),je=Bu(V,C);c.useEffect(()=>{V===0&&O(null)},[V]);const[W,J]=c.useState(null),ae=E&&!!u,ce=`${e}|${JSON.stringify(u??{})}`,B=bw({mailboxId:e,accountId:x,enabled:ae,predicateKey:ce,searchQuery:u??{}}),Fe=B.phase.kind,pe=B.clear,ge=c.useCallback(()=>{Fe==="escalated"&&pe(),ue()},[ue,pe,Fe]),[Se,Qe]=c.useState(null),[ts,ze]=c.useState(null),Ze=c.useRef(null),Be=c.useRef(!1),Ke=c.useRef(null),ft=!r&&t.length>0,Te=W!==null,ss=c.useCallback((_,se)=>{const{exit:St,retryIds:Xe}=pw(se);if(St){ze(_i(_.kind,se.done)),Qe(null),ge();return}if(Xe.length>0){Qe({action:_,succeeded:se.done}),U(Xe);return}Qe(null)},[ge,U]),Ue=tw({count:t.length,getScrollElement:()=>N.current,estimateSize:()=>L==="compact"?_w:Fw,overscan:zw}),_t=s?t.findIndex(_=>_.messageId===s):-1,Ne=S?t.findIndex(_=>_.messageId===S):-1,qe=c.useCallback(_=>{if(_<0||_>=t.length)return;const se=t[_];if(je){Q(se.messageId);return}Ze.current=se.messageId,Be.current=!1,A(se.messageId)},[t,je,Q]),mt=c.useCallback(()=>{if(t.length===0)return;const _=Ne<0?0:Math.min(Ne+1,t.length-1);qe(_)},[t.length,Ne,qe]),ns=c.useCallback(()=>{if(t.length===0)return;const _=Ne<=0?0:Ne-1;qe(_)},[t.length,Ne,qe]),zt=c.useCallback(()=>qe(0),[qe]),Z=c.useCallback(()=>qe(t.length-1),[qe,t.length]),ie=c.useCallback(()=>{S&&Q(S)},[S,Q]),ne=c.useMemo(()=>t.map(_=>_.messageId),[t]),oe=c.useMemo(()=>{const _=[];for(const se of t)z.has(se.messageId)&&se.fromEmail&&_.push(se.fromEmail);return _},[t,z]),he=c.useCallback((_,se)=>se.shiftKey?(te(ne,_,S),!0):se.metaKey||se.ctrlKey?(Q(_),!0):(ge(),K(_),!1),[ne,S,te,Q,ge,K]),me=c.useCallback(_=>{!f||_.length===0||(Ke.current=S??null,J({source:"ids",ids:_}))},[f,S]),we=c.useCallback(()=>{B.phase.kind==="escalated"&&(Ke.current=S??null,J({source:"predicate",total:B.phase.total}))},[B.phase,S]),Pe=c.useCallback(_=>{const se=_u(ne,S,_);se!==void 0&&(te(ne,se),Ze.current=se,Be.current=!1,A(se))},[ne,S,te]),Ae=c.useCallback(()=>Pe(-1),[Pe]),He=c.useCallback(()=>Pe(1),[Pe]),De=c.useCallback(()=>{ne.length>0&&U(ne)},[ne,U]),Re=c.useCallback(()=>W!==null?!0:f?V>0?(me(Array.from(z)),!0):S?(me([S]),!0):!1:!1,[W,f,V,z,S,me]),Ye=c.useCallback(()=>{S&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:_=>({..._,selectedMessageId:S})})},[S,k,e]),Ge=c.useCallback(()=>{V>0&&me(Array.from(z))},[me,V,z]),et=c.useCallback(async(_,se)=>{const St=await B.runAction(_,se);ss(_,St)},[B,ss]),Bt=c.useCallback(async _=>{J(null),Ke.current=null,await et(Bw,_)},[et]),fr=c.useCallback(()=>{if(!W)return;if(W.source==="predicate"){Bt(void 0);return}const{ids:_}=W;if(_.length===0){J(null);return}if(_.length>ud){Bt(_);return}const se=new Set(_),St=t.findIndex($e=>se.has($e.messageId));let Xe;for(let $e=St+1;$e<t.length;$e++)if(!se.has(t[$e].messageId)){Xe=t[$e].messageId;break}if(Xe===void 0){for(let $e=St-1;$e>=0;$e--)if(!se.has(t[$e].messageId)){Xe=t[$e].messageId;break}}f?.(_),ge(),Ke.current=null,J(null),Xe!==void 0&&(Ze.current=Xe,Be.current=!1,A(Xe),C&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:$e=>({...$e,selectedMessageId:Xe}),replace:!0})),C||ze(_i("delete",_.length))},[W,t,f,ge,k,e,C,Bt]),wt=c.useCallback(()=>{const _=Ke.current;Ke.current=null,J(null),_!==null&&(Ze.current=_,Be.current=!1,A(_))},[]),fn=c.useCallback(()=>{if(B.phase.kind==="escalated"){et(Bi);return}V!==0&&et(Bi,Array.from(z))},[B.phase,et,V,z]),rs=c.useCallback(_=>{if(B.phase.kind==="escalated"){et({kind:"move",destinationMailboxId:_});return}!d||V===0||(d(Array.from(z),_),ge())},[B.phase,et,d,V,z,ge]),mr=c.useCallback(()=>{$&&rs($)},[$,rs]),Kt=c.useMemo(()=>{if(V===0)return;const _=new Set;for(const se of t)z.has(se.messageId)&&_.add(se.accountConfigId);if(_.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[V,z,t]),hr=c.useCallback(_=>{f?.([_])},[f]),pr=c.useCallback((_,se)=>{R([_],!se)},[R]),gr=c.useCallback(_=>{C||le(_)},[C,le]),jt=c.useCallback(()=>{if(B.phase.kind==="escalated"){we();return}Ge()},[B.phase,we,Ge]),As=c.useCallback(()=>{if(B.isRunning||B.phase.kind==="counting"){B.stop();return}ge()},[B,ge]),mn=c.useCallback(()=>{B.clear()},[B]),xr=c.useCallback(()=>{if(!Se)return;const _=Array.from(z);if(Se.action.kind==="delete"){Bt(_);return}et(Se.action,_)},[Se,Bt,et,z]);c.useEffect(()=>{if(Be.current||!C&&s)return;const _=Ne>=0?Ne:_t;_>=0&&Ue.scrollToIndex(_,{align:"auto"})},[Ne,_t,Ue,C,s]),c.useEffect(()=>{s&&(Be.current=!1,A(s))},[s]),c.useEffect(()=>{S&&(t.some(_=>_.messageId===S)||A(t[0]?.messageId))},[t,S]),c.useEffect(()=>{j?.({focusedMessageId:S,selectedIds:Array.from(z),hasList:ft,blocksKeyboard:Te})},[S,z,ft,Te,j]);const hn=c.useRef(j);hn.current=j,c.useEffect(()=>()=>hn.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{B.phase.kind!=="idle"||B.isRunning||Ie(t.map(_=>_.messageId))},[t,Ie,B.phase,B.isRunning]);const pn=c.useRef(e);c.useEffect(()=>{pn.current!==e&&(pn.current=e,ge())},[e,ge]),Fx({shouldBlockFn:({action:_})=>Ey(_,ee)?(ge(),!0):!1,enableBeforeUnload:!1,disabled:!ee}),c.useEffect(()=>{const _=N.current;if(!_||!v||!g)return;const se=()=>{if(p)return;const{scrollTop:St,scrollHeight:Xe,clientHeight:$e}=_;St+$e>=Xe-200&&g()};return _.addEventListener("scroll",se,{passive:!0}),se(),()=>_.removeEventListener("scroll",se)},[v,p,g]),c.useEffect(()=>{const _=Ze.current;if(!_)return;const se=N.current?.querySelector(`[data-message-id="${_}"]`);se&&(Ze.current=null,se.focus({preventScroll:!0}))}),c.useEffect(()=>{if(y){if(!ft){y.current=null;return}return y.current={focusNext:mt,focusPrevious:ns,focusFirst:zt,focusLast:Z,openFocused:Ye,toggleSelect:ie,extendSelectDown:He,extendSelectUp:Ae,selectAll:De,clearSelection:()=>ee?(ge(),!0):!1,requestDelete:Re,toggleDensity:F},()=>{y.current=null}}},[y,ft,mt,ns,zt,Z,Ye,ie,He,Ae,De,ee,ge,Re,F]);const gn=r?"loading":a?"error":t.length===0?"empty":"ready",br=a?yl(o):void 0,Y=c.useCallback(()=>{const _=va(ba());window.open(_,"_blank","noopener,noreferrer")},[]),tt=[{id:"inbox",threads:[]}],Le=ne.length>0&&ne.every(_=>z.has(_)),Cd=ae&&v&&Le&&!m&&!h&&B.phase.kind==="idle"&&!B.isRunning,Nd=m||h||B.isRunning,vr=B.phase.kind==="escalated"?B.phase.total:V,lo=B.runningAction?aw(B.runningAction.kind,B.progress?.done??0,B.progress?.total??0):B.phase.kind==="counting"?B.phase.countSoFar>=5e3?`Counting… ${ct(B.phase.countSoFar)} so far. This is a big result set.`:`Counting… ${ct(B.phase.countSoFar)} so far`:B.phase.kind==="escalated"?yw(u??{},B.phase.total):void 0,co=B.phase.kind!=="escalated"&&ne.length>0?{checked:Le,indeterminate:V>0&&!Le,onChange:()=>re(ne)}:void 0,uo=B.runningAction&&B.progress?{value:B.progress.done,max:B.progress.total,tone:cw(B.runningAction.kind)}:void 0,fo=B.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:B.stop}}:B.phase.kind==="escalated"&&!B.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:mn}}:Cd?{tone:"info",text:"",action:{label:vw(u??{}),onClick:B.escalate}}:Se!==null&&V>0?{tone:"danger",text:ow(Se.action.kind,Se.succeeded,V),action:{label:`Retry ${ct(V)}`,onClick:xr}}:void 0,mo=fo??(Kt?{tone:"warning",text:Kt}:void 0),ho=ww({isRunning:B.isRunning,isCounting:B.phase.kind==="counting",isEscalated:B.phase.kind==="escalated"}),po=!C&&je&&Sw(vr,ho,mo!==void 0),Ed=(d||B.phase.kind==="escalated")&&x&&e?n.jsx(dn,{accountId:x,currentMailboxId:e,onMove:m||h?()=>{}:rs,disabledHint:Kt,label:"Move selected messages"}):void 0,go=D&&x&&!C&&V>0?n.jsx(Rw,{entry:D,accountId:x,selectedMessageIds:Array.from(z),selectedSenders:oe,junkMailboxId:$,onClose:()=>{O(null),ge()}}):void 0,xo=po?n.jsx(tg,{count:vr,mode:ho,onCancel:As,onDelete:jt,onJunk:$&&$!==e&&!Kt?mr:void 0,onMarkRead:fn,onSelectSimilar:x?()=>O("select-similar"):void 0,onSomethingElse:x?()=>O("something-else"):void 0,moveSlot:Ed,isBusy:Nd,selectAll:co,statusLabel:lo,progress:uo,notice:mo}):void 0,Id=xo||go?n.jsxs(n.Fragment,{children:[xo,go]}):void 0,Td=ee&&C?n.jsx(Uu,{selectedCount:vr,onDelete:jt,onClearSelection:As,onMarkAsRead:fn,onMove:d?rs:void 0,onOrganize:()=>P(!0),isDeleting:m,isMoving:h,accountId:x,currentMailboxId:e,selectedMessageIds:Array.from(z),moveDisabledHint:Kt,selectAll:ae?co:void 0,statusLabel:lo,isCounting:B.phase.kind==="counting",progress:uo,notice:fo}):void 0,Rd=Ku(ne,S),Md=c.useCallback(_=>{Be.current=!0,A(_)},[]),Ad=n.jsxs(n.Fragment,{children:[E&&l&&n.jsx(Uw,{query:l,count:t.length}),n.jsxs("div",{ref:N,role:"listbox","aria-multiselectable":!0,"aria-label":b,className:"flex-1 overflow-y-auto",style:po?{paddingBottom:Ks}:void 0,children:[n.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${Ue.getTotalSize()}px`},children:Ue.getVirtualItems().map(_=>{const se=t[_.index];return n.jsx("div",{role:"presentation","data-index":_.index,ref:Ue.measureElement,className:be("absolute left-0 top-0 w-full border-b border-line",B.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${_.start}px)`},children:n.jsx($w,{thread:se,mailboxId:e,accountId:x,isSelected:s===se.messageId,isFocused:S===se.messageId,isTabStop:Rd===se.messageId,onFocusRow:Md,isChecked:X(se.messageId),onToggleCheck:Q,onRowSelect:he,isMultiSelectMode:je,onLongPress:gr,isDesktop:C,onDelete:hr,onToggleRead:pr,density:L})},_.key)})}),p&&n.jsx("div",{className:"flex justify-center py-4",children:n.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-fg-muted border-t-transparent"})})]})]}),Dd=W?W.source==="ids"?W.ids.length:W.total:0,bo=W?.source==="predicate";return n.jsxs(n.Fragment,{children:[ts&&!C&&n.jsx(Xt,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>ze(null),children:ts}),n.jsx(ec,{listTitle:b,listMeta:w,sections:tt,flatList:!0,listState:gn,searchQuery:E?l:void 0,errorMessage:br,onRetry:i,onReportError:Y,density:L,selectedThreadId:s,onSelectThread:_=>k({to:"/mail/$mailboxId",params:{mailboxId:e},search:se=>({...se,selectedMessageId:_})}),onSelectBriefCategory:()=>{},isDesktop:C,hideHeader:I,selectionBar:Td,selectionSheet:Id,listBody:gn==="ready"?Ad:void 0}),n.jsx(Ra,{isOpen:W!==null,title:jl(Dd,bo),description:bo?"This count is a snapshot — new mail arriving during the delete won't be included. You can restore what's deleted from Trash later.":"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:m,onConfirm:fr,onCancel:wt}),M&&x&&n.jsx(Aw,{open:M,accountId:x,selectedMessageIds:Array.from(z),selectedSenders:oe,onClose:()=>P(!1)})]})},Hw=e=>Jt({path:{accountId:e}}),Ww=e=>{const t=ye(),s=Js(),r=ve({...If(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:Hw(e)})}});return{trigger:()=>{r.mutate({path:{accountId:e}})},triggerAsync:()=>r.mutateAsync({path:{accountId:e}}),isPending:r.isPending,error:r.error,reset:r.reset}},Vw=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:r}=Ww(e);return n.jsx(Tp,{onRefresh:s,isRefreshing:r,children:t})};function Qw({accountId:e,currentMailboxId:t,candidates:s,onMove:r,children:a}){const[o,i]=c.useState(!1),l=Js(),{t:u}=Un("mail",{useSuspense:!1}),f=c.useCallback((w,j)=>u(w,{defaultValue:j}),[u]),{inboxMailboxId:d}=Qa(e),m=Vc(e),{data:h}=de({..._e({path:{accountId:e}}),staleTime:1/0}),g=c.useMemo(()=>{const w=Zs(h?.items??[],m),j=Xs(m);return w.map(y=>({id:y.mailboxId,label:bs(y,j.get(y.mailboxId),f),searchValue:y.fullPath,isCurrent:y.mailboxId===t}))},[h?.items,m,t,f]),v=c.useMemo(()=>d||(g.find(j=>j.label.toLowerCase()==="inbox")?.id??g.find(j=>!j.isCurrent)?.id??""),[d,g]),p=c.useRef(!1);c.useEffect(()=>{p.current||(p.current=!0,Jy(l,s.length))},[l,s.length]);const x=c.useCallback(()=>{Zy(l,s.length),i(!0)},[l,s.length]),b=c.useCallback((w,j)=>{e0(l,{selected:w.length,total:s.length,toInbox:j===d}),r(w,j)},[l,s.length,d,r]);return n.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[n.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:n.jsx(Ap,{count:s.length,onReview:x})}),n.jsx("div",{className:"min-h-0 flex-1",children:a}),n.jsx(Kp,{open:o,candidates:s,defaultDestinationId:v,availableFolders:g,onConfirmMove:b,onCancel:()=>i(!1)})]})}const Yw="We can verify this sender";function Gw(e){const{data:t}=de({...Tf({path:{mailboxId:e??""},query:{senderTrust:["vip","wellknown"],dkimMismatch:!1,results:!0,limit:500}}),enabled:!!e,staleTime:6e4});return{candidates:(t?.items??[]).map(r=>({id:r.messageId,senderName:r.fromName||r.fromEmail||"Unknown sender",senderAddress:r.fromEmail??"",subject:r.subject||"(no subject)",snippet:r.snippet??"",trustReason:Yw,trustSubReason:Xy(r.senderTrust),senderTrust:r.senderTrust}))}}const Xw=e=>{const t=new Set,s=[];for(const r of e)t.has(r.threadMessageId)||(t.add(r.threadMessageId),s.push(r));return s},Jw={unread:e=>!e.isRead,flagged:e=>e.hasStars===!0,attachment:e=>!!e.hasAttachment};function Zw(e,t,s){const r=Array.from(s).map(a=>Jw[a]).filter(a=>a!=null);return t==="all"&&r.length===0?e:e.filter(a=>(t==="all"||cn(a.category)===t)&&r.every(o=>o(a)))}const pd="remit:intelligence-open";function ej(){try{return localStorage.getItem(pd)!=="closed"}catch{return!0}}function Ki(e){try{localStorage.setItem(pd,e?"open":"closed")}catch{}}const tj=(e,t)=>e!==t,sj=(e,t,s)=>{if(!(s||!t))return e.find(r=>r.messageId===t)},gd=c.createContext(null);function dr(){const e=c.useContext(gd);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function nj({mailboxId:e,selectedMessageId:t,children:s}){const r=Oe(),o=lr()==="desktop",i=Js(),{accounts:l,searchQuery:u,searchInput:f,intelligenceOpen:d,onToggleIntelligence:m,onSetIntelligenceOpen:h}=Ce(),g=Ts(),v=Za(u),p=v.length>0,{freeText:x,tokens:b}=Rs(v,g),w=b.find(Y=>Y.type==="from"),j={order:"desc",...x?{query:x}:{},...w?{from:w.value}:{},...b.some(Y=>Y.type==="hasAttachment")?{attachments:!0}:{},...b.some(Y=>Y.type==="isUnread")?{unread:!0}:{}},y=p?al({path:{mailboxId:e},query:j}):wa({path:{mailboxId:e},query:{order:"desc"}}),{data:I,isLoading:N,isError:k,error:C,refetch:M,fetchNextPage:P,hasNextPage:D,isFetchingNextPage:O}=kc({queryKey:y,queryFn:async({pageParam:Y})=>{if(p){const{data:Le}=await fl({path:{mailboxId:e},query:{...j,continuationToken:Y},throwOnError:!0});return Le}const{data:tt}=await Mf({path:{mailboxId:e},query:{order:"desc",continuationToken:Y},throwOnError:!0});return tt},initialPageParam:void 0,getNextPageParam:Y=>Y.continuationToken,enabled:p?v.length>0:!0,placeholderData:Rf}),E=c.useCallback(Y=>{t&&Y.includes(t)&&r({to:"/mail/$mailboxId",params:{mailboxId:e},search:tt=>({...tt,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,r]),{deleteMessages:S,isPending:A}=Yt({mailboxId:e,onAfterOptimisticRemove:E}),{accountId:L}=Hc(e),T=Pc({accounts:l}),{moveMessages:F,isPending:R}=Qt({mailboxId:e,accountId:L,onAfterOptimisticRemove:E}),$=Gb(Xw(I?.pages.flatMap(Y=>Y.items??[])??[])),[z,V]=c.useState("all"),[ee,X]=c.useState(new Set),Q=c.useMemo(()=>Zw($,z,ee),[$,z,ee]),le=c.useCallback(Y=>{V(Y)},[]),ue=c.useCallback(Y=>{X(tt=>{const Le=new Set(tt);return Le.has(Y)?Le.delete(Y):Le.add(Y),Le})},[]),te=c.useCallback(()=>{V("all"),X(new Set)},[]),K=tj(f,u),U=sj($,t,K),{selectedThreadId:re}=vs({strict:!1}),Ie=c.useMemo(()=>Zu(U,{messageId:t,threadId:K?void 0:re,mailboxId:e}),[U,t,re,K,e]),je=no(),{listCommandsRef:W,onTriageContextChange:J,focusedMessageId:ae,selectedIds:ce}=je,B=Q.find(Y=>Y.messageId===ae)??U,Fe=c.useRef(null);c.useEffect(()=>{const Y=U?.messageId??null;Y&&Fe.current!==Y&&U?.authenticity?.dkimMismatch&&(Fe.current=Y,d||m())},[U?.messageId,U?.authenticity?.dkimMismatch,d,m]);const pe=c.useRef(!1);c.useEffect(()=>{pe.current||o&&U?.messageId&&(pe.current=!0,ej()&&!d&&h(!0))},[o,U?.messageId,d,h]);const Se=Xx({accounts:l})??$.filter(Y=>!Y.isRead).length,Qe=ye(),{pushError:ts}=Ve(),ze=Qs({thread:U,mailboxId:e,accountId:L,onAfterOptimisticRemove:E}),{draftsMailboxId:Ze}=Qb(L),Be=Ze!==void 0&&Ze===e,{archiveMailboxId:Ke}=Vb(L),ft=Ju(),{requestCompose:Te}=ze,ss=c.useCallback(()=>{Te("reply")},[Te]),Ue=c.useCallback(()=>{Te("reply_all")},[Te]),_t=c.useCallback(()=>{Te("forward")},[Te]),{state:Ne,openCompose:qe,closeCompose:mt}=Dt(),ns=c.useCallback(()=>{qe({mode:"new"})},[qe]),zt=ve({...Hn(),onError:Y=>{ts(Vt("Couldn't discard draft","The draft wasn't deleted.",Y))}}),Z=c.useCallback(()=>{const Y=Ne.outboxMessageId;Y&&(zt.mutate({path:{outboxMessageId:Y}}),Qe.invalidateQueries({queryKey:ka()}),mt())},[Ne.outboxMessageId,zt,Qe,mt]),ie=c.useCallback(()=>{r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Y=>({...Y,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,r]),ne=c.useCallback(Y=>Y?ft(Y):[],[ft]),{toggleStar:oe}=Wa({threadId:B?.threadId??"",mailboxId:e}),{toggleReadFor:he}=rr({mailboxId:e,accountId:L}),{junkMailboxId:me}=or(L),we=me!=null&&me===e,{candidates:Pe}=Gw(we?me:void 0),{moveMessages:Ae}=Qt({mailboxId:e,threadId:B?.threadId,accountId:L,onAfterOptimisticRemove:E}),{deleteMessages:He}=Yt({mailboxId:e,threadId:B?.threadId,onAfterOptimisticRemove:E}),{addressId:De,address:Re}=Qu(B),{updateFlags:Ye}=Yu({addressId:De,senderEmail:B?.fromEmail??void 0}),Ge=c.useCallback(()=>t||!ae?!1:(r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Y=>({...Y,selectedMessageId:ae})}),!0),[t,ae,e,r]),et=c.useCallback(()=>{Ge()||U&&Te("reply")},[Ge,U,Te]),Bt=c.useCallback(()=>{Ge()||U&&Te("reply_all")},[Ge,U,Te]),fr=c.useCallback(()=>{Ge()||U&&Te("forward")},[Ge,U,Te]),wt=c.useCallback(()=>ce.length>0?ce:ne(B),[ce,ne,B]),fn=c.useCallback(()=>{if(W.current?.requestDelete())return;const Y=wt();Y.length>0&&He(Y)},[W,wt,He]),rs=c.useCallback(()=>{if(!me)return;const Y=wt();Y.length!==0&&(Xu(i,{count:Y.length,senderTrust:B?.senderTrust??"unknown",wasRescuable:B?Gu(B):!1}),Ae(Y,me))},[me,wt,Ae,i,B]),mr=c.useCallback(()=>{if(ce.length>0){const Y=!(B?.hasStars??!1),tt=new Set(ce);for(const Le of Q)tt.has(Le.messageId)&&Le.hasStars!==Y&&oe(Le.messageId,Le.hasStars);return}B&&oe(B.messageId,B.hasStars)},[ce,Q,B,oe]),Kt=c.useCallback(()=>{const Y=wt();if(Y.length===0)return;const tt=!(B?.isRead??!1);he(Y,tt)},[wt,B,he]),hr=c.useCallback(()=>{if(!De)return;const Y=Re?.flags?.muted?.value!==!0;Ye({muted:{value:Y}})},[De,Re,Ye]),pr=c.useCallback(()=>{if(!De)return;const Y=Re?.flags?.vip?.value!==!0;Ye({vip:{value:Y}})},[De,Re,Ye]),gr=c.useCallback(()=>{d||m()},[d,m]),jt=c.useCallback(Y=>{r({to:Y})},[r]),As=Be?"drafts":Ke===e?"archive":me===e?"junk":"inbox",mn=c.useRef("");c.useEffect(()=>{const Y=mn.current;mn.current=v,v.length>0&&Y.length===0&&i.recordEvent("search.submitted",{mailboxType:As})},[v,As,i]);const xr=Be&&Ne.isOpen&&!!Ne.outboxMessageId&&!U,{goBack:hn,nextMessageId:pn,previousMessageId:gn}=ro({context:je,orderedIds:Q.map(Y=>Y.messageId),selectedMessageId:t,enabled:!Ne.isOpen,onClose:ie,handlers:{reply:et,replyAll:Bt,forward:fr,delete:fn,toggleStar:mr,toggleRead:Kt,muteSender:hr,blockSender:gr,vipSender:pr,markJunk:rs,toggleIntelligence:U?m:void 0,compose:ns,goBrief:()=>jt("/mail"),goInbox:()=>jt("/mail"),goSent:()=>jt("/mail"),goFlagged:()=>jt("/mail/flagged"),goSettings:()=>jt("/settings")}});Ha({enabled:Ne.isOpen,bindings:[{key:"Escape",handler:mt,preventDefault:!0}]});const br={mailboxId:e,selectedMessageId:t,selectedThread:U,conversation:Ie,threads:Q,isLoading:N,isError:k,error:C,mailboxAccountId:L,mailboxName:T,unreadCount:Se,isDraftsMailbox:Be,isSpamFolder:we,rescueCandidates:Pe,filterCategory:z,filterAttributes:ee,onSelectFilterCategory:le,onToggleFilterAttribute:ue,onClearFilters:te,intelligenceOpen:d,onToggleIntelligence:m,searchPredicate:p?j:void 0,onDeleteMessages:S,onMoveMessages:F,isDeleting:A,isMoving:R,onLoadMore:P,hasMore:D,isLoadingMore:O,onTriageContextChange:J,listCommandsRef:W,onRetry:()=>M(),toolbarComposeRequest:ze.composeRequest,onToolbarReply:ss,onToolbarReplyAll:Ue,onToolbarForward:_t,onClearComposeRequest:ze.clearComposeRequest,onToolbarDelete:ze.deleteThread,onToolbarStar:ze.toggleStar,onToolbarDiscardDraft:Z,onToolbarMove:ze.moveThread,composeState:Ne,closeCompose:mt,hasRemitDraftOpen:xr,onBack:hn,nextMessageId:pn,previousMessageId:gn};return n.jsx(gd.Provider,{value:br,children:s})}function xd(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:r,isError:a,error:o,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,mailboxAccountId:g,mailboxName:v,unreadCount:p,isDraftsMailbox:x,isSpamFolder:b,rescueCandidates:w,onTriageContextChange:j,listCommandsRef:y,onRetry:I,filterCategory:N,filterAttributes:k,onSelectFilterCategory:C,onToggleFilterAttribute:M,onClearFilters:P,searchPredicate:D}=dr(),{searchQuery:O,searchInput:E,accounts:S,resultFolderIndex:A}=Ce(),L=lr(),T=Oe(),F=v??"Inbox",R=c.useMemo(()=>ag(),[]),$=c.useMemo(()=>s.map(K=>dy(K,A)),[s,A]),{hits:z,isLoading:V}=Cu({mailboxId:e,filterCategory:N}),ee=c.useMemo(()=>Tu(z,s.map(K=>K.threadId),A),[z,s,A]),X=c.useCallback(K=>T({to:"/mail/$mailboxId",params:{mailboxId:K.mailboxId??e},search:U=>({...U,q:E||void 0,selectedMessageId:K.id,selectedThreadId:K.threadId})}),[e,T,E]);if(x&&g)return n.jsx(F0,{mailboxId:e,accountId:g,selectedMessageId:t,imapThreads:s,title:v??"Drafts",unreadCount:p??void 0});const Q=n.jsx(qw,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:r,isError:a,error:o,onRetry:I,searchQuery:O,searchPredicate:D,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,accountId:g,listTitle:F,hideHeader:!0,onTriageContextChange:j,commandsRef:y}),le=S[0]?.accountId,ue=L==="phone"&&le?n.jsx(Vw,{accountId:le,children:Q}):Q,te=b&&w.length>0&&g?n.jsx(Qw,{accountId:g,currentMailboxId:e,candidates:w,onMove:l,children:ue}):ue;return n.jsx(nd,{title:F,unreadCount:p,preset:R,selectedCategory:N,activeFilters:k,onSelectCategory:C,onToggleFilter:M,onClearFilters:P,searchResults:$,searchLoading:r,relatedResults:ee,relatedLoading:V,onSelectSearchResult:X,searchResultsInBody:!0,children:te})}function rj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:r,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:l,onToolbarReply:u,onToolbarReplyAll:f,onToolbarForward:d,onClearComposeRequest:m,onToolbarDelete:h,onToolbarStar:g,onToolbarDiscardDraft:v,onToolbarMove:p,composeState:x}=dr(),b=Ss()?.showIntelligencePane??!1,w=!!r,j=b&&w,y=x.isOpen&&!r?n.jsx(od,{}):r?n.jsx(Is,{threadId:r.threadId,mailboxId:r.mailboxId,subject:r.subject,selectedMessageId:r.messageId,authenticity:r.authenticity,onOpenIntelligence:r.authenticity?.dkimMismatch?i:void 0,composeRequest:l,onComposeClose:m}):n.jsx(Es,{});return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(so,{hasThread:w,intelligenceOpen:j&&o,canToggleIntelligence:j,onToggleIntelligence:i,onReply:w?u:void 0,onReplyAll:w?f:void 0,onForward:w?d:void 0,canDelete:w||a,onDelete:w?h:a?v:void 0,onToggleStar:w?g:void 0,isStarred:s?.hasStars,moveContext:w&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:y})]})}function aj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:r}=dr();return n.jsx(Ms,{onClose:r,thread:s,mailboxId:e,accountId:t})}function oj(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:r,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=dr(),f=Oe();if(s){const d=m=>f({to:"/mail/$mailboxId",params:{mailboxId:e},search:h=>({...h,selectedMessageId:m,selectedThreadId:void 0})});return n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:s.threadId,mailboxId:s.mailboxId,subject:s.subject,selectedMessageId:s.messageId,authenticity:s.authenticity,onBack:o,onOpenIntelligence:a,onSwipeNext:i?()=>d(i):void 0,onSwipePrevious:l?()=>d(l):void 0,mobileIntelligenceOpen:r}),n.jsx(Ua,{isOpen:r,onClose:a,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?n.jsx("div",{className:"h-full",children:n.jsx(od,{})}):n.jsx(xd,{})}const Bs=Object.assign(nj,{List:xd,Reading:rj,Intelligence:aj,Phone:oj}),bd=e=>e==="failed"||e==="blocked",vd=e=>e!=="draft"&&e!=="sent",oo="remit.savedSearches",ij=25;function Bn(){try{const e=localStorage.getItem(oo);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function lj(e){const t=e.trim();if(!t)return Bn();const s=[t,...Bn().filter(r=>r!==t)].slice(0,ij);try{localStorage.setItem(oo,JSON.stringify(s))}catch{return s}return s}function cj(e){const t=Bn().filter(s=>s!==e);try{localStorage.setItem(oo,JSON.stringify(t))}catch{return t}return t}const Ui=e=>/^\d/.test(e),uj=(e,t)=>{const s=Ui(e),r=Ui(t);return s&&!r?-1:!s&&r?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function dj(e,t,s){const r=[],a=[];for(const o of e)t.has(o.mailboxId)?r.push(o):a.push(o);return a.sort((o,i)=>uj(bs(o,void 0,s),bs(i,void 0,s))),{system:r,labels:a}}function fj(e,t,s){const r=Af(t)&&e.unseenCount>0;return{id:e.mailboxId,name:bs(e,t,s),unseen:r?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function mj(){const e=tr(),t=ya({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 qi({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const r=ye(),a=Oe(),o=mj(),{searchInput:i,onSearchChange:l}=Ce(),[u,f]=c.useState(Bn),{t:d}=Un("mail",{useSuspense:!1}),m=c.useCallback((C,M)=>d(C,{defaultValue:M}),[d]),h=Ft({queries:e.map(C=>({..._e({path:{accountId:C.accountId}}),staleTime:1/0}))}),{data:g}=de(qn()),v=c.useMemo(()=>(g?.items??[]).filter(C=>vd(C.status)).length,[g?.items]),p=c.useMemo(()=>e.map((C,M)=>{const P=h[M],D=P?.data?.items??[],O=Xs(C.folderAppointments),{system:E,labels:S}=dj(D,O,m),A=P?.isError?"error":P?.isLoading?"loading":"ready";return{id:C.accountId,label:C.email,email:C.email,muted:!!C.muted,outboxPending:v,status:A,onRetry:()=>P?.refetch(),mailboxes:[...E,...S].map(L=>fj(L,O.get(L.mailboxId),m))}}),[e,h,v,m]),x=C=>{r.invalidateQueries({queryKey:wa({path:{mailboxId:C},query:{order:"desc"}})})},b=({navId:C,className:M,ariaLabel:P,title:D,children:O,onClick:E})=>C==="brief"?n.jsx(pt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):C==="outbox"?n.jsx(pt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):C==="flagged"?n.jsx(pt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):C==="settings"?n.jsx(pt,{to:"/settings/accounts",onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):n.jsx(pt,{to:"/mail/$mailboxId",params:{mailboxId:C},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{x(C),E?.()},className:M,"aria-label":P,title:D,children:O}),w=()=>{l(""),t?.()},j=i.trim(),y=j.length>0&&!u.includes(j)?j:void 0,I=c.useCallback(()=>{y&&f(lj(y))},[y]),N=c.useCallback(C=>{f(cj(C))},[]),k=c.useCallback(C=>{l(C),a({to:"/mail",search:{q:C,selectedMessageId:void 0}}),t?.()},[l,a,t]);return n.jsx(np,{accounts:p,selectedNavId:o,onSelectNav:w,linkComponent:b,variant:s,savedSearches:u,saveableQuery:y,onSaveCurrentSearch:I,onSelectSavedSearch:k,onRemoveSavedSearch:N})}function hj({accounts:e,onMailboxSelect:t}){return Ss()?.showNavPane??!0?n.jsx(qi,{accounts:e}):n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(qi,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),n.jsxs("div",{className:"border-t border-line px-2 py-2",children:[n.jsxs(pt,{to:"/settings/accounts",onClick:t,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(Oa,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),n.jsx(Ic,{variant:"drawer"}),n.jsx(Ec,{children:({signOut:a})=>n.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[n.jsx(Kl,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function pj(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const r=[e.subject,e.fromAddress,e.fromName,...e.toAddresses??[],...e.ccAddresses??[]].filter(a=>typeof a=="string").join(" ").toLowerCase();return s.split(/\s+/).every(a=>a.length===0||r.includes(a))}function gj(e){return e.tokens.length>0&&e.freeText.trim().length===0}const yd={queued:{icon:Ta,label:"Queued",className:"text-warning"},sending:{icon:nt,label:"Sending…",className:"text-accent-2"},sent:{icon:Fl,label:"Sent",className:"text-positive"},failed:{icon:Gt,label:"Failed",className:"text-danger"},blocked:{icon:fa,label:"Blocked",className:"text-warning"}},xj=e=>Gf(e).toDateString()===new Date().toDateString()?Pn(e,{hour:"numeric",minute:"2-digit"}):Pn(e,{month:"short",day:"numeric"}),Hi=e=>Pn(e,{dateStyle:"medium",timeStyle:"short"}),bj=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},wd=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",jd=c.createContext(null);function io(){const e=c.useContext(jd);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function vj({children:e}){const t=Oe(),{selectedOutboxMessageId:s}=vs({strict:!1}),{data:r,isLoading:a}=de(qn()),{searchQuery:o}=Ce(),i=Ts(),l=Za(o),u=Rs(l,i),f=l.length>0,d=gj(u),m=c.useMemo(()=>d?[]:(r?.items??[]).filter(p=>vd(p.status)).filter(p=>pj(p,u.freeText)),[r,u.freeText,d]),h=c.useMemo(()=>m.find(p=>p.outboxMessageId===s),[m,s]),g=c.useCallback(p=>{t({to:"/mail/outbox",search:x=>({...x,selectedOutboxMessageId:p})})},[t]),v={messages:m,hasQuery:f,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:g};return n.jsx(jd.Provider,{value:v,children:e})}function Sd({message:e,isSelected:t,onSelect:s}){const r=ye(),{openCompose:a}=Dt(),{pushError:o}=Ve(),i=c.useCallback(()=>{r.invalidateQueries({queryKey:ka()})},[r]),l=ve({...rl(),onSuccess:i,onError:m=>{o(Vt("Couldn't resend message","The message wasn't sent.",m))}}),u=ve({...Hn(),onSuccess:i,onError:m=>{o(Vt("Couldn't delete message","The message wasn't deleted.",m))}}),f=e.status;if(!yd[f])return null;const d=bd(e.status);return n.jsx(Ep,{recipients:bj(e),subject:e.subject||"",time:xj(e.sentAt??e.updatedAt),status:f,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:f==="failed"?()=>l.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:l.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function kd({message:e,onBack:t}){const s=e.status,r=yd[s],a=r?.icon??Gs,o=e.sentAt?Hi(e.sentAt):Hi(e.updatedAt);return n.jsxs("div",{className:"h-full overflow-y-auto bg-canvas",children:[n.jsxs("div",{className:"border-b border-line p-4",children:[t&&n.jsxs("button",{type:"button",onClick:t,className:"mb-3 inline-flex items-center gap-1 text-sm text-fg-muted hover:text-fg",children:[n.jsx(Ll,{className:"size-4"}),n.jsx("span",{children:"Back"})]}),n.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),n.jsxs("div",{className:"space-y-1 text-sm",children:[n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),n.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),n.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),n.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),n.jsx("span",{className:"text-fg",children:o})]}),r&&n.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[n.jsx(a,{className:be("size-4",r.className,s==="sending"&&"animate-spin")}),n.jsx("span",{className:be("text-xs font-medium",r.className),children:r.label}),bd(e.status)&&e.lastError&&n.jsxs("span",{className:"text-xs text-fg-muted",children:["— ",e.lastError]})]})]})]}),n.jsx("div",{className:"p-4",children:n.jsx(wu,{html:e.htmlBody,text:e.textBody})})]})}function yj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,onSelectMessage:o}=io(),i=c.useRef(null);return Kn({containerRef:i,itemSelector:ia}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Es,{message:wd(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(ao,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(l=>n.jsx(Sd,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function wj(){const{selectedMessage:e}=io();return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx("header",{className:"flex h-pane-header shrink-0 items-center border-b border-line px-3"}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(kd,{message:e}):n.jsx(Es,{message:"Select a message to read",showHints:!1})})]})}function jj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=io(),l=c.useRef(null);return Kn({containerRef:l,itemSelector:ia}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?n.jsx(kd,{message:o,onBack:()=>i(void 0)}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Es,{message:wd(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(ao,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:l,className:"flex-1 overflow-y-auto",children:e.map(u=>n.jsx(Sd,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const In=Object.assign(vj,{List:yj,Reading:wj,Phone:jj}),Sj=({isOpen:e,onClose:t})=>{const s=c.useCallback(r=>{r.key==="Escape"&&(r.preventDefault(),t())},[t]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:t,onKeyDown:r=>r.key==="Escape"&&t(),children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{className:be("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),onClick:r=>r.stopPropagation(),onKeyDown:r=>{r.key!=="Escape"&&r.stopPropagation()},children:[n.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),n.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:n.jsx(We,{className:"size-5"})})]}),n.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:$c.map(r=>n.jsxs("div",{children:[n.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:r.title}),n.jsx("div",{className:"space-y-2",children:r.hints.map(a=>n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsx("span",{className:"text-sm",children:a.description}),n.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>n.jsxs(c.Fragment,{children:[i>0&&a.keys[0]==="g"&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),n.jsx(ps,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},r.title))}),n.jsx("div",{className:"mt-6 border-t border-line pt-4",children:n.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",n.jsx(ps,{children:"Esc"})," to close"]})})]})]}):null};function kj(e){const t=new Map;for(const s of e){const r=s.email.toLowerCase(),a=r.split("@")[0];a&&!t.has(a)&&t.set(a,s.accountId),t.has(r)||t.set(r,s.accountId)}return t}function Cj(e){const t=new Map;for(const s of e)for(const r of s){const a=r.fullPath?.toLowerCase();if(!a)continue;const o=a.split("/").pop();t.has(a)||t.set(a,r.mailboxId),o&&!t.has(o)&&t.set(o,r.mailboxId)}return t}function Nj(e){const t=Ft({queries:e.map(s=>({..._e({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>Cj(t.map(s=>s.data?.items??[])),[t])}const Ej=e=>e.map(t=>t.data?.items??[]);function Ij(e){const t=Ft({queries:e.map(s=>({..._e({path:{accountId:s.accountId}}),staleTime:1/0})),combine:Ej});return c.useMemo(()=>Df(e.map((s,r)=>({folderAppointments:s.folderAppointments,mailboxes:t[r]??[]}))),[e,t])}var Tn={exports:{}},Wi;function Tj(){if(Wi)return Tn.exports;Wi=1;const e=(t,s,r)=>new Promise((a,o)=>{if(r=Object.assign({concurrency:1/0},r),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=r;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const l=[],u=t[Symbol.iterator]();let f=!1,d=!1,m=0,h=0;const g=()=>{if(f)return;const v=u.next(),p=h;if(h++,v.done){d=!0,m===0&&a(l);return}m++,Promise.resolve(v.value).then(x=>s(x,p)).then(x=>{l[p]=x,m--,g()},x=>{f=!0,o(x)})};for(let v=0;v<i&&(g(),!d);v++);});return Tn.exports=e,Tn.exports.default=e,Tn.exports}var Rj=Tj();const Mj=Of(Rj),Aj=900*1e3,Dj=300,Oj=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},Pj=60*1e3,Lj=e=>Math.max(Oj(e,Dj)*1e3,Pj),On=Lj($f().mailboxPollIntervalSeconds),$j=5,aa=new Set,Fj=(e,t,s=Aj)=>e.filter(r=>{const a=r.lastSyncAt;return a==null?!0:t-a>s}).map(r=>r.accountId),_j=(e,t,s=On)=>e-t>=s,zj=(e,t)=>e.filter(s=>!t.has(s)),Vi=(e,t)=>{if(aa.delete(e),Lf(t,{softError:!0})){dl(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},Qi=(e,t)=>Pf({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:Jt({path:{accountId:e}})})}),Bj=e=>{const t=ye(),s=c.useRef(e);s.current=e;const r=e.map(a=>a.accountId).join(",");c.useEffect(()=>{const a=Date.now(),i=Fj(s.current,a).filter(l=>!aa.has(l));if(i.length!==0)for(const l of i)aa.add(l),Qi(l,t).catch(u=>{Vi(l,u)})},[r,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const d=zj(s.current.map(m=>m.accountId),i);for(const m of d)i.add(m);Mj(d,m=>Qi(m,t).catch(h=>{Vi(m,h)}).finally(()=>{i.delete(m)}),{concurrency:$j})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,On);return}},f=()=>{document.visibilityState==="visible"&&_j(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,On))};return o=setTimeout(u,On),document.addEventListener("visibilitychange",f),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",f)}},[r,t])};function Kj(e,t,s){if(e!==t)return s}function Uj(e,t){return e===""?"":t}function qj(e,t,s){return t!==e?!1:t!==s}function Hj(){const{q:e=""}=vs({from:"/mail"}),t=Oe(),s=lr(),r=Ru(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,f]=c.useState(!1),d=c.useCallback(te=>{f(te),Ki(te)},[]),[m,h]=c.useState(e),g=hl(m,200),v=Uj(m,g),p=c.useRef(e);p.current=e;const x=gt({select:te=>Wx(te.matches)}),[b,w]=c.useState(x);if(b!==x){const te=Kj(b,x,e);w(x),te!==void 0&&h(te)}c.useEffect(()=>{qj(m,v,p.current)&&t({to:".",search:te=>{const K=te.q===v;return{...te,q:v||void 0,...v&&!K?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[m,v,t]);const{data:j,isLoading:y,isError:I,error:N,refetch:k}=de({...xt(),staleTime:1/0}),C=!!(j&&(j.accounts?.length??0)===0);c.useEffect(()=>{C&&t({to:"/onboarding",replace:!0})},[C,t]),Ha({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const M=c.useCallback(te=>{h(te)},[]),P=c.useCallback(()=>{h("")},[]),D=c.useCallback(()=>{h("")},[]),O=c.useCallback(()=>{f(te=>{const K=!te;return Ki(K),K})},[]),E=j?.accounts??[],S=Nj(E),A=Ij(E),L=c.useMemo(()=>kj(E),[E]),T=gt({select:te=>te.matches.find(U=>"mailboxId"in U.params)?.params.mailboxId}),{selectedMessageId:F}=vs({strict:!1}),R=gt({select:te=>Ka(te.matches)}),$=gt({select:te=>nn(te.matches)}),z=gt({select:te=>sr(te.matches)});Bj(E);const V=c.useCallback(()=>{l(!1)},[]),ee={accounts:E,mailboxNameIndex:S,accountNameIndex:L,resultFolderIndex:A,searchQuery:v,searchInput:m,searchViewKey:x,onSearchChange:M,onSearchClear:P,onSearchClearQuery:D,intelligenceOpen:u,onToggleIntelligence:O,onSetIntelligenceOpen:d},X=n.jsx(hj,{accounts:E,onMailboxSelect:V}),Q=r?n.jsx(Ux,{accounts:E}):void 0,le=r?void 0:n.jsx(eb,{accounts:E}),ue={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return n.jsxs(Ff.Provider,{value:ee,children:[I?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:n.jsx(Pt,{title:"Couldn't load your account",error:N,onRetry:()=>{k()}})}):R?n.jsx(Fs,{selectedMessageId:F,children:r?n.jsx(kt,{nav:X,list:n.jsx(Fs.Phone,{}),intelligenceOpen:u,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue}):n.jsx(kt,{nav:X,topBar:le,list:n.jsx(Fs.List,{}),reading:n.jsx(Fs.Reading,{}),intelligence:n.jsx(Fs.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue})}):$?n.jsx(_s,{selectedMessageId:F,children:r?n.jsx(kt,{nav:X,list:n.jsx(_s.Phone,{}),intelligenceOpen:u,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue}):n.jsx(kt,{nav:X,topBar:le,list:n.jsx(_s.List,{}),reading:n.jsx(_s.Reading,{}),intelligence:n.jsx(_s.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue})}):T?n.jsx(Bs,{mailboxId:T,selectedMessageId:F,children:r?n.jsx(kt,{nav:X,list:n.jsx(Bs.Phone,{}),intelligenceOpen:u,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue}):n.jsx(kt,{nav:X,topBar:le,list:n.jsx(Bs.List,{}),reading:n.jsx(Bs.Reading,{}),intelligence:n.jsx(Bs.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue})}):z?n.jsx(In,{children:r?n.jsx(kt,{nav:X,list:n.jsx(In.Phone,{}),intelligenceOpen:!1,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue}):n.jsx(kt,{nav:X,topBar:le,list:n.jsx(In.List,{}),reading:n.jsx(In.Reading,{}),intelligenceOpen:!1,overlay:Q,skeleton:n.jsx(ht,{}),isLoading:y||C,...ue})}):n.jsx(ht,{}),n.jsx(Sj,{isOpen:a,onClose:()=>o(!1)}),n.jsx(_f,{})]})}const dS=Object.freeze(Object.defineProperty({__proto__:null,component:Hj,useMailContext:Ce},Symbol.toStringTag,{value:"Module"}));export{uS as S,Gm as U,dS as m};