@remit/web-client-dist 0.0.310 → 0.0.311

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/{ErrorState-DiX_zNTK.js → ErrorState-BnQkLG51.js} +1 -1
  2. package/assets/{OnboardingWizard-r-N3eGPg.js → OnboardingWizard-CRlV4w12.js} +1 -1
  3. package/assets/{account-form-helpers-BHUowns0.js → account-form-helpers-BeqVh_T2.js} +1 -1
  4. package/assets/{accounts-B4-7wVt4.js → accounts-B98RfNOy.js} +1 -1
  5. package/assets/{advanced-Dlyjnb6l.js → advanced-B7t32yk3.js} +1 -1
  6. package/assets/{appearance-Drfetqy5.js → appearance-DdKiTKpf.js} +1 -1
  7. package/assets/{avatar-Ci3CMhdo.js → avatar-BRL7rg_o.js} +1 -1
  8. package/assets/{browser-ponyfill-BhnZT7aq.js → browser-ponyfill-6RnWTcYh.js} +2 -2
  9. package/assets/{circle-check-BM6iE_RP.js → circle-check-CYydPTdN.js} +1 -1
  10. package/assets/{confirm-dialog-F7nDmx5t.js → confirm-dialog-DIbYqfat.js} +1 -1
  11. package/assets/{download-Bg6cLSAV.js → download-DLEDqw0R.js} +1 -1
  12. package/assets/{filters-CsWlycJW.js → filters-x0P7h-Ub.js} +1 -1
  13. package/assets/{flagged-CuV2oZw_.js → flagged-BDPGXIn3.js} +1 -1
  14. package/assets/{folders-Dg7RilCS.js → folders-7p36e-xH.js} +1 -1
  15. package/assets/{index-BSJKHoKS.js → index-BgEpwwZ1.js} +1 -1
  16. package/assets/index-Der6CHju.js +1 -0
  17. package/assets/{index-xOALrEh8.js → index-vBthhplL.js} +65 -65
  18. package/assets/{kbd-C00o9L4B.js → kbd-BqpSg06H.js} +1 -1
  19. package/assets/{labels-pEUVx_Ue.js → labels-C7QYU5Yl.js} +1 -1
  20. package/assets/mail-Khqgk4gG.js +118 -0
  21. package/assets/{move-options-B2c-WWEl.js → move-options-CSHlm2K-.js} +1 -1
  22. package/assets/{onboarding-DKy8Q5MV.js → onboarding-DINPCyhf.js} +1 -1
  23. package/assets/{pencil-CZK87pI9.js → pencil-Cr_WV_aT.js} +1 -1
  24. package/assets/{rich-text-CoTs3nIc.js → rich-text-CK9ku6ou.js} +1 -1
  25. package/assets/{senders-p6LBrcYb.js → senders-Duc6-2A0.js} +1 -1
  26. package/assets/settings-O6iTQjei.js +1 -0
  27. package/assets/{settings-screen-C7xmJsXG.js → settings-screen-UJjBjmzD.js} +1 -1
  28. package/assets/{shield-check-CdES_QdC.js → shield-check-Ba6MRuh5.js} +1 -1
  29. package/assets/{suggested-vips-BQoY6-Yl.js → suggested-vips-CYPl0djC.js} +1 -1
  30. package/assets/{useDebouncedValue-Ck8McJvG.js → useDebouncedValue-BenM649w.js} +1 -1
  31. package/assets/{useFilters-DMt8Gx-P.js → useFilters-D0U-Wctv.js} +1 -1
  32. package/assets/{useLabels-oSXOt6KZ.js → useLabels-CpCaRFPt.js} +1 -1
  33. package/assets/{useSignature-BQN3IL24.js → useSignature-C7yUh-MN.js} +1 -1
  34. package/index.html +1 -1
  35. package/package.json +1 -1
  36. package/assets/index-dsr8I39S.js +0 -1
  37. package/assets/mail-Chm12_Xz.js +0 -118
  38. package/assets/settings-C2TANSwS.js +0 -1
@@ -0,0 +1,118 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/rich-text-CK9ku6ou.js","assets/index-vBthhplL.js","assets/index-C2fo0j9f.css","assets/confirm-dialog-DIbYqfat.js","assets/pencil-Cr_WV_aT.js","assets/avatar-BRL7rg_o.js","assets/kbd-BqpSg06H.js","assets/shield-check-Ba6MRuh5.js","assets/account-form-helpers-BeqVh_T2.js","assets/useSignature-C7yUh-MN.js","assets/useDebouncedValue-BenM649w.js","assets/useFilters-D0U-Wctv.js","assets/ErrorState-BnQkLG51.js","assets/format-CKZmh-Ru.js","assets/move-options-CSHlm2K-.js","assets/download-DLEDqw0R.js","assets/useLabels-CpCaRFPt.js","assets/circle-check-CYydPTdN.js"])))=>i.map(i=>d[i]);
2
+ import{R as W,c as Qf,r as l,a as _e,j as r,C as Gt,b as Ts,X as Et,d as Q,B as ce,e as jt,S as Jt,f as Dt,g as Pt,L as ms,h as Gf,i as Yf,k as nc,l as hn,T as Lt,m as Xf,u as or,n as Qn,o as rc,I as ac,F as _a,p as oc,q as za,s as Jf,A as Ba,D as Zf,t as pn,v as em,w as ir,O as tm,M as sm,x as nm,y as ic,z as lc,E as cc,G as Ua,H as rm,J as am,K as om,N as gn,P as im,Q as lm,U as cm,V as um,W as uc,Y as hs,Z as dm,_ as dc,$ as fm,a0 as mm,a1 as hm,a2 as pm,a3 as Ka,a4 as qa,a5 as qt,a6 as fc,a7 as gm,a8 as xm,a9 as bm,aa as vm,ab as ym,ac as mc,ad as wm,ae as Sm,af as Ft,ag as Ha,ah as Ve,ai as lr,aj as gt,ak as Gn,al as Pe,am as Fe,an as Ps,ao as $t,ap as hc,aq as pc,ar as Wa,as as Va,at as Qa,au as ft,av as gc,aw as Yn,ax as Je,ay as xc,az as Ce,aA as Ga,aB as bc,aC as Ue,aD as Cm,aE as km,aF as cr,aG as ur,aH as _t,aI as st,aJ as jm,aK as Nm,aL as dt,aM as vc,aN as us,aO as dr,aP as Em,aQ as Im,aR as Rm,aS as fr,aT as Ya,aU as Xa,aV as mr,aW as Zt,aX as Tm,aY as Mm,aZ as Am,a_ as Om,a$ as Dm,b0 as xa,b1 as Pm,b2 as yc,b3 as Ms,b4 as Ja,b5 as Za,b6 as Lm,b7 as hr,b8 as Fm,b9 as $m,ba as wc,bb as eo,bc as _m,bd as ai,be as zm,bf as Bm,bg as Um,bh as Km,bi as oi,bj as qm,bk as Hm,bl as Wm,bm as ba,bn as Vm,bo as Qm,bp as Gm,bq as Sc,br as Ym,bs as Xm,bt as Jm,bu as Zm,bv as ii,bw as eh,bx as th,by as sh,bz as nh,bA as to,bB as va,bC as ya,bD as rh,bE as Cc,bF as ah,bG as kc,bH as oh,bI as so,bJ as ih,bK as lh,bL as ch,bM as uh,bN as dh,bO as fh,bP as mh,bQ as hh,bR as ph,bS as Ut,bT as Ot,bU as gh}from"./index-vBthhplL.js";import{P as xh}from"./pencil-Cr_WV_aT.js";import{A as Nt,M as pr,C as bh}from"./avatar-BRL7rg_o.js";import{K as Es}from"./kbd-BqpSg06H.js";import{S as xn,C as no,R as vh}from"./shield-check-Ba6MRuh5.js";import{M as jc,a as yh}from"./account-form-helpers-BeqVh_T2.js";import{R as wh,u as Sh}from"./useSignature-C7yUh-MN.js";import{u as gr}from"./useDebouncedValue-BenM649w.js";import{D as Nc,B as Ch,u as es,a as li,b as ci,c as kh,d as jh,e as Nh,n as Eh,o as Ih,f as Rh,g as Th,S as Mh}from"./useFilters-D0U-Wctv.js";import{E as ts,f as Ec}from"./ErrorState-BnQkLG51.js";import{f as Ic,a as xt,b as Rc,c as Yt,d as Xn,t as Ah}from"./format-CKZmh-Ru.js";import{P as ui,u as ro,a as Tc,b as ao,f as oo,C as Oh,M as lt,D as di}from"./move-options-CSHlm2K-.js";import{D as Dh}from"./download-DLEDqw0R.js";import{u as io}from"./useLabels-CpCaRFPt.js";import{C as lo}from"./confirm-dialog-DIbYqfat.js";import{C as Ph}from"./circle-check-CYydPTdN.js";function on(e){if(Lh())e.focus({preventScroll:!0});else{let t=Fh(e);e.focus(),$h(t)}}let Rn=null;function Lh(){if(Rn==null){Rn=!1;try{document.createElement("div").focus({get preventScroll(){return Rn=!0,!0}})}catch{}}return Rn}function Fh(e){let t=e.parentNode,s=[],n=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==n;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return n instanceof HTMLElement&&s.push({element:n,scrollTop:n.scrollTop,scrollLeft:n.scrollLeft}),s}function $h(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const Vt=e=>e?.ownerDocument??document,Xt=e=>e&&"window"in e&&e.window===e?e:Vt(e).defaultView||window;function _h(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function zh(e){return _h(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let Bh=!1;function Mc(){return Bh}function Ct(e,t){if(!Mc())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:zh(s)?s=s.host:s=s.parentNode}return!1}function Xe(e){if(Mc()&&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 Uh=typeof Element<"u"&&"checkVisibility"in Element.prototype;function Kh(e){const t=Xt(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:n}=e.style,a=s!=="none"&&n!=="hidden"&&n!=="collapse";if(a){const{getComputedStyle:o}=Xt(e);let{display:i,visibility:c}=o(e);a=i!=="none"&&c!=="hidden"&&c!=="collapse"}return a}function qh(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 Ac(e,t){return Uh?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&Kh(e)&&qh(e,t)&&(!e.parentElement||Ac(e.parentElement,e))}const Oc=["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"],Hh=Oc.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";Oc.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function Wh(e,t){return e.matches(Hh)&&!Vh(e)&&(t?.skipVisibilityCheck||Ac(e))}function Vh(e){let t=e;for(;t!=null;){if(t instanceof Xt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const co=typeof document<"u"?W.useLayoutEffect:()=>{};function Qh(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function Gh(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function Yh(e){for(;e&&!Wh(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Xt(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=d=>{(Xe(d)===s||n)&&d.stopImmediatePropagation()},o=d=>{(Xe(d)===s||n)&&(d.stopImmediatePropagation(),!e&&!n&&(n=!0,on(s),u()))},i=d=>{(Xe(d)===e||n)&&d.stopImmediatePropagation()},c=d=>{(Xe(d)===e||n)&&(d.stopImmediatePropagation(),n||(n=!0,on(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",c,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",c,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function xr(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 uo(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function ss(e){let t=null;return()=>(t==null&&(t=e()),t)}const Jn=ss(function(){return uo(/^Mac/i)}),Xh=ss(function(){return uo(/^iPhone/i)}),Dc=ss(function(){return uo(/^iPad/i)||Jn()&&navigator.maxTouchPoints>1}),Pc=ss(function(){return Xh()||Dc()}),Jh=ss(function(){return xr(/AppleWebKit/i)&&!Zh()}),Zh=ss(function(){return xr(/Chrome/i)}),Lc=ss(function(){return xr(/Android/i)}),ep=ss(function(){return xr(/Firefox/i)});function tp(e){return e.pointerType===""&&e.isTrusted?!0:Lc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function sp(e){return!Lc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function ln(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;ep()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Jn()?n=!0:a=!0);let c=Jh()&&Jn()&&!Dc()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});ln.isOpening=s,on(e),e.dispatchEvent(c),ln.isOpening=!1}ln.isOpening=!1;let Ht=new Map,wa=new Set;function fi(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=Xe(n);if(!e(n)||!a)return;let o=Ht.get(a);o||(o=new Set,Ht.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=Xe(n);if(!e(n)||!a)return;let o=Ht.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Ht.delete(a)),Ht.size===0)){for(let i of wa)i();wa.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?fi():document.addEventListener("DOMContentLoaded",fi));function np(){for(const[e]of Ht)"isConnected"in e&&!e.isConnected&&Ht.delete(e)}function rp(e){requestAnimationFrame(()=>{np(),Ht.size===0?e():wa.add(e)})}function Fc(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let Sa=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{Sa.delete(e)});function ap(e,t){if(e===t)return e;let s=Sa.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=Sa.get(t);return n?(n.forEach(a=>a.current=e),e):t}function op(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=mi(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():mi(e[o],null)})}}}function mi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ls(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let n=e[s];for(let a in n){let o=t[a],i=n[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=Fc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=Qf(o,i):a==="id"&&o&&i?t.id=ap(o,i):a==="ref"&&o&&i?t.ref=op(o,i):t[a]=i!==void 0?i:o}}return t}function ip(e,t){co(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const lp=W.useInsertionEffect??co;function Hr(e){const t=l.useRef(null);return lp(()=>{t.current=e},[e]),l.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let Ns="default",Ca="",Un=new WeakMap;function cp(e){if(Pc()){if(Ns==="default"){const t=Vt(e);Ca=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}Ns="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Un.set(e,e.style[t]),e.style[t]="none"}}function hi(e){if(Pc()){if(Ns!=="disabled")return;Ns="restoring",setTimeout(()=>{rp(()=>{if(Ns==="restoring"){const t=Vt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=Ca||""),Ca="",Ns="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Un.has(e)){let t=Un.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Un.delete(e)}}function pi(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Wr=new WeakMap;function up(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return pi(t);if(Wr.has(t))return Wr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof Xt(s).HTMLMetaElement&&(s.nonce||s.content)||pi(t)||void 0;return n!==void 0&&Wr.set(t,n),n}const $c=W.createContext({register:()=>{}});$c.displayName="PressResponderContext";function _c(){let e=l.useRef(new Map),t=l.useCallback((a,o,i,c)=>{let u=c?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:c}),a.addEventListener(o,u,c)},[]),s=l.useCallback((a,o,i,c)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,c),e.current.delete(i)},[]),n=l.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return l.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function dp(e){let t=l.useContext($c);if(t){let{register:s,ref:n,...a}=t;e=Ls(a,e),s()}return ip(t,e.ref),e}class Tn{#e;constructor(t,s,n,a){this.#e=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let c,u=0,m,d=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,d=n.clientY),i&&(m!=null&&d!=null?(c=m-i.left,u=d-i.top):(c=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=n.currentTarget,this.shiftKey=n.shiftKey,this.metaKey=n.metaKey,this.ctrlKey=n.ctrlKey,this.altKey=n.altKey,this.x=c,this.y=u,this.key=n.key}continuePropagation(){this.#e=!1}get shouldStopPropagation(){return this.#e}}const gi=Symbol("linkClicked"),xi="react-aria-pressable-style",bi="data-react-aria-pressable";function fp(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:c,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:f,ref:h,...v}=dp(e),[x,p]=l.useState(!1),b=l.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:y,removeAllGlobalListeners:S}=_c(),g=l.useCallback((k,I)=>{let O=b.current;if(c||O.didFirePressStart)return!1;let M=!0;if(O.isTriggeringEvent=!0,n){let F=new Tn("pressstart",I,k);n(F),M=F.shouldStopPropagation}return s&&s(!0),O.isTriggeringEvent=!1,O.didFirePressStart=!0,p(!0),M},[c,n,s]),w=l.useCallback((k,I,O=!0)=>{let M=b.current;if(!M.didFirePressStart)return!1;M.didFirePressStart=!1,M.isTriggeringEvent=!0;let F=!0;if(a){let E=new Tn("pressend",I,k);a(E),F=E.shouldStopPropagation}if(s&&s(!1),p(!1),t&&O&&!c){let E=new Tn("press",I,k);t(E),F&&=E.shouldStopPropagation}return M.isTriggeringEvent=!1,F},[c,a,s,t]),C=Hr(w),R=l.useCallback((k,I)=>{let O=b.current;if(c)return!1;if(o){O.isTriggeringEvent=!0;let M=new Tn("pressup",I,k);return o(M),O.isTriggeringEvent=!1,M.shouldStopPropagation}return!0},[c,o]),A=Hr(R),j=l.useCallback(k=>{let I=b.current;if(I.isPressed&&I.target){I.didFirePressStart&&I.pointerType!=null&&w(as(I.target,k),I.pointerType,!1),I.isPressed=!1,I.isOverTarget=!1,I.activePointerId=null,I.pointerType=null,S(),f||hi(I.target);for(let O of I.disposables)O();I.disposables=[]}},[f,S,w]),T=Hr(j);l.useEffect(()=>{c&&b.current.isPressed&&T({currentTarget:b.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[c]);let P=l.useCallback(k=>{d&&j(k)},[d,j]),N=l.useCallback(k=>{c||i?.(k)},[c,i]),L=l.useCallback((k,I)=>{if(!c&&i){let O=new MouseEvent("click",k);Gh(O,I),i(Qh(O))}},[c,i]),D=l.useMemo(()=>{let k=b.current,I={onKeyDown(M){if(Vr(M.nativeEvent,M.currentTarget)&&Ct(M.currentTarget,Xe(M))){vi(Xe(M),M.key)&&M.preventDefault();let F=!0;!k.isPressed&&!M.repeat&&(k.target=M.currentTarget,k.isPressed=!0,k.pointerType="keyboard",F=g(M,"keyboard"));let E=M.currentTarget,V=X=>{Vr(X,E)&&!X.repeat&&Ct(E,Xe(X))&&k.target&&A(as(k.target,X),"keyboard")};y(Vt(M.currentTarget),"keyup",Fc(V,O),!0),F&&M.stopPropagation(),M.metaKey&&Jn()&&k.metaKeyEvents?.set(M.key,M.nativeEvent)}else M.key==="Meta"&&(k.metaKeyEvents=new Map)},onClick(M){if(!(M&&!Ct(M.currentTarget,Xe(M)))&&M&&M.button===0&&!k.isTriggeringEvent&&!ln.isOpening){let F=!0;if(c&&M.preventDefault(),!k.ignoreEmulatedMouseEvents&&!k.isPressed&&(k.pointerType==="virtual"||tp(M.nativeEvent))){let E=g(M,"virtual"),V=A(M,"virtual"),X=C(M,"virtual");N(M),F=E&&V&&X}else if(k.isPressed&&k.pointerType!=="keyboard"){let E=k.pointerType||M.nativeEvent.pointerType||"virtual",V=A(as(M.currentTarget,M),E),X=C(as(M.currentTarget,M),E,!0);F=V&&X,k.isOverTarget=!1,N(M),T(M)}k.ignoreEmulatedMouseEvents=!1,F&&M.stopPropagation()}}},O=M=>{if(k.isPressed&&k.target&&Vr(M,k.target)){vi(Xe(M),M.key)&&M.preventDefault();let F=Xe(M),E=Ct(k.target,F);C(as(k.target,M),"keyboard",E),E&&L(M,k.target),S(),M.key!=="Enter"&&fo(k.target)&&Ct(k.target,F)&&!M[gi]&&(M[gi]=!0,ln(k.target,M,!1)),k.isPressed=!1,k.metaKeyEvents?.delete(M.key)}else if(M.key==="Meta"&&k.metaKeyEvents?.size){let F=k.metaKeyEvents;k.metaKeyEvents=void 0;for(let E of F.values())k.target?.dispatchEvent(new KeyboardEvent("keyup",E))}};if(typeof PointerEvent<"u"){I.onPointerDown=E=>{if(E.button!==0||!Ct(E.currentTarget,Xe(E)))return;if(sp(E.nativeEvent)){k.pointerType="virtual";return}k.pointerType=E.pointerType;let V=!0;if(!k.isPressed){k.isPressed=!0,k.isOverTarget=!0,k.activePointerId=E.pointerId,k.target=E.currentTarget,f||cp(k.target),V=g(E,k.pointerType);let X=Xe(E);"releasePointerCapture"in X&&("hasPointerCapture"in X?X.hasPointerCapture(E.pointerId)&&X.releasePointerCapture(E.pointerId):X.releasePointerCapture(E.pointerId)),y(Vt(E.currentTarget),"pointerup",M,!1),y(Vt(E.currentTarget),"pointercancel",F,!1)}V&&E.stopPropagation()},I.onMouseDown=E=>{if(Ct(E.currentTarget,Xe(E))&&E.button===0){if(m){let V=Yh(E.target);V&&k.disposables.push(V)}E.stopPropagation()}},I.onPointerUp=E=>{!Ct(E.currentTarget,Xe(E))||k.pointerType==="virtual"||E.button===0&&!k.isPressed&&A(E,k.pointerType||E.pointerType)},I.onPointerEnter=E=>{E.pointerId===k.activePointerId&&k.target&&!k.isOverTarget&&k.pointerType!=null&&(k.isOverTarget=!0,g(as(k.target,E),k.pointerType))},I.onPointerLeave=E=>{E.pointerId===k.activePointerId&&k.target&&k.isOverTarget&&k.pointerType!=null&&(k.isOverTarget=!1,C(as(k.target,E),k.pointerType,!1),P(E))};let M=E=>{if(E.pointerId===k.activePointerId&&k.isPressed&&E.button===0&&k.target){if(Ct(k.target,Xe(E))&&k.pointerType!=null){let V=!1,X=setTimeout(()=>{k.isPressed&&k.target instanceof HTMLElement&&(V?T(E):(on(k.target),k.target.click()))},80);y(E.currentTarget,"click",()=>V=!0,!0),k.disposables.push(()=>clearTimeout(X))}else T(E);k.isOverTarget=!1}},F=E=>{T(E)};I.onDragStart=E=>{Ct(E.currentTarget,Xe(E))&&T(E)}}return I},[y,c,m,S,f,P,g,N,L]);return l.useEffect(()=>{if(!h)return;const k=Vt(h.current);if(!k||!k.head||k.getElementById(xi))return;const I=k.createElement("style");I.id=xi;let O=up(k);O&&(I.nonce=O),I.textContent=`
3
+ @layer {
4
+ [${bi}] {
5
+ touch-action: pan-x pan-y pinch-zoom;
6
+ }
7
+ }
8
+ `.trim(),k.head.prepend(I)},[h]),l.useEffect(()=>{let k=b.current;return()=>{f||hi(k.target??void 0);for(let I of k.disposables)I();k.disposables=[]}},[f]),{isPressed:u||x,pressProps:Ls(v,D,{[bi]:!0})}}function fo(e){return e.tagName==="A"&&e.hasAttribute("href")}function Vr(e,t){const{key:s,code:n}=e,a=t,o=a.getAttribute("role");return(s==="Enter"||s===" "||s==="Spacebar"||n==="Space")&&!(a instanceof Xt(a).HTMLInputElement&&!zc(a,s)||a instanceof Xt(a).HTMLTextAreaElement||a.isContentEditable)&&!((o==="link"||!o&&fo(a))&&s!=="Enter")}function as(e,t){let s=t.clientX,n=t.clientY;return{currentTarget:e,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,altKey:t.altKey,clientX:s,clientY:n,key:t.key}}function mp(e){return e instanceof HTMLInputElement?!1:e instanceof HTMLButtonElement?e.type!=="submit"&&e.type!=="reset":!fo(e)}function vi(e,t){return e instanceof HTMLInputElement?!zc(e,t):mp(e)}const hp=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function zc(e,t){return e.type==="checkbox"||e.type==="radio"?t===" ":hp.has(e.type)}let pp=0;const Qr=new Map;function gp(e){let[t,s]=l.useState();return co(()=>{if(!e)return;let n=Qr.get(e);if(n)s(n.element.id);else{let a=`react-aria-description-${pp++}`;s(a);let o=document.createElement("div");o.id=a,o.style.display="none",o.textContent=e,document.body.appendChild(o),n={refCount:0,element:o},Qr.set(e,n)}return n.refCount++,()=>{n&&--n.refCount===0&&(n.element.remove(),Qr.delete(e))}},[e]),{"aria-describedby":e?t:void 0}}const xp=500;function bp(e){let{isDisabled:t,onLongPressStart:s,onLongPressEnd:n,onLongPress:a,threshold:o=xp,accessibilityDescription:i}=e;const c=l.useRef(void 0);let{addGlobalListener:u,removeGlobalListener:m}=_c(),{pressProps:d}=fp({isDisabled:t,onPressStart(h){if(h.continuePropagation(),(h.pointerType==="mouse"||h.pointerType==="touch")&&(s&&s({...h,type:"longpressstart"}),c.current=setTimeout(()=>{h.target.dispatchEvent(new PointerEvent("pointercancel",{bubbles:!0})),Vt(h.target).activeElement!==h.target&&on(h.target),a&&a({...h,type:"longpress"}),c.current=void 0},o),h.pointerType==="touch")){let v=p=>{p.preventDefault()},x=Xt(h.target);u(h.target,"contextmenu",v,{once:!0}),u(x,"pointerup",()=>{setTimeout(()=>{m(h.target,"contextmenu",v)},30)},{once:!0})}},onPressEnd(h){c.current&&clearTimeout(c.current),n&&(h.pointerType==="mouse"||h.pointerType==="touch")&&n({...h,type:"longpressend"})}}),f=gp(a&&!t?i:void 0);return{longPressProps:Ls(d,f)}}const br=_e("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 Bc=_e("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 vp=_e("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 Uc=_e("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 mo=_e("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 Kc=_e("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);const qc=_e("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 Hc=_e("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 Wc=_e("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 yp=_e("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 vr=_e("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 wp=_e("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 Sp=_e("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const yr=_e("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 ho=_e("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 Vc=_e("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 Qc=_e("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 Gc=_e("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 Fs=_e("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 Cp=_e("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 kp=_e("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 jp=_e("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 Np=_e("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"}]]),Ep=({address:e,showTrustedBadge:t=!1})=>{const s=t?r.jsx(br,{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?r.jsxs("span",{children:[r.jsx("span",{className:"text-fg",children:e.displayName}),r.jsxs("span",{className:"text-fg-muted",children:[" ","<",e.normalizedEmail,">"]}),s]}):r.jsxs("span",{className:"text-fg",children:[e.normalizedEmail,s]})},Ip=({label:e,addresses:t,showTrustedBadge:s=!1})=>{const[n,a]=l.useState(!1);if(t.length===0)return null;const o=t.length>3,i=c=>{const u=s&&c.flags?.trusted?.value===!0;return r.jsx(Ep,{address:c,showTrustedBadge:u})};return r.jsxs("div",{className:"flex gap-2 text-sm",children:[r.jsxs("span",{className:"text-fg-muted shrink-0 w-12",children:[e,":"]}),r.jsx("div",{className:"flex-1 min-w-0",children:n?r.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((c,u)=>r.jsxs("span",{children:[i(c),u<t.length-1&&", "]},u))}):r.jsx("div",{className:"truncate",children:t.map((c,u)=>r.jsxs("span",{children:[i(c),u<t.length-1&&", "]},u))})}),o&&r.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),a(!n)},className:"shrink-0 text-fg-muted hover:text-fg transition-colors","aria-label":n?"Collapse":"Expand",children:n?r.jsx(Gt,{className:"h-4 w-4"}):r.jsx(Ts,{className:"h-4 w-4"})})]})},Rp=({email:e,displayName:t,onRemove:s,className:n})=>r.jsxs("span",{className:Q("inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-accent-2-soft text-sm max-w-[200px]",n),children:[r.jsx("span",{className:"truncate",children:t||e}),r.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:r.jsx(Et,{className:"size-3"})})]}),Tp={unknown:{label:"Unknown sender",tone:"neutral"},wellknown:{label:"Known sender",tone:"positive"},vip:{label:"VIP",tone:"accent"}};function ys({label:e,children:t,className:s}){return r.jsxs("section",{className:Q("border-b border-line px-row-inset py-3",s),children:[r.jsx("h3",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),r.jsx("div",{className:"mt-2",children:t})]})}function Mp({sender:e}){const t=Tp[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 r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(Nt,{name:e.name,email:e.email,size:"md"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"truncate text-sm font-semibold text-fg",children:e.name}),r.jsx("div",{className:"truncate text-2xs text-fg-subtle",children:e.email})]})]}),r.jsx("div",{className:"mt-2 flex items-center gap-2",children:e.addressUnverified?r.jsx(jt,{tone:"danger",dot:!0,children:"Address couldn't be verified"}):r.jsx(jt,{tone:t.tone,dot:!0,children:t.label})}),r.jsxs("p",{className:"mt-2 text-xs text-fg-muted",children:["First seen ",e.firstSeenLabel,s?` · ${s}`:""]})]})}function Ap({auth:e,onShowSimilar:t}){if(e.verdict==="aligned")return r.jsxs("div",{className:"flex items-start gap-2 text-xs text-fg-muted",children:[r.jsx(xn,{className:"mt-0.5 size-3.5 shrink-0 text-positive"}),r.jsx("span",{children:e.summary})]});if(e.verdict==="caution")return r.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-warning/10 p-3 text-warning",children:[r.jsx(Cp,{className:"mt-0.5 size-4 shrink-0"}),r.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 r.jsxs("div",{className:"rounded-md bg-danger-soft p-3",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(Fs,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm font-semibold text-danger",children:s}),r.jsx("p",{className:"mt-1 text-xs leading-relaxed text-fg",children:e.summary}),!e.addressUnreadable&&e.dkimDomain&&r.jsxs("p",{className:"mt-1 text-2xs text-fg-muted",children:["Sent from"," ",r.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.dkimDomain}),", claims to be"," ",r.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.fromDomain})]})]})]}),e.similarCount!=null&&e.similarCount>0&&r.jsxs(ce,{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 Ws({icon:e,label:t,active:s,danger:n,onClick:a,pending:o}){const i=a===void 0||o===!0;return r.jsxs("button",{type:"button",onClick:a,disabled:i,className:Q("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",n&&!s&&"text-danger hover:bg-danger-soft",i&&"cursor-not-allowed opacity-50 hover:border-line"),children:[e,t]})}const Op={sender:"matched: sender",recipient:"matched: recipient",subject:"matched: subject",attachment:"matched: attachment",body:"matched: body",entities:"matched: entities"};function Yc({data:e,onClose:t,onShowSimilar:s,actions:n,similarState:a="ready",similarLinkComponent:o,className:i,hideCloseButton:c=!1,reportSpamPending:u=!1,notSpamPending:m=!1}){const{sender:d,authenticity:f,category:h,flags:v={},similar:x}=e,p=f.verdict==="mismatch";return r.jsxs("aside",{className:Q("flex w-76 shrink-0 flex-col overflow-y-auto border-l border-line bg-surface",i),children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center justify-between border-b border-line px-row-inset",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"}),!c&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Et,{className:"size-3.5"}),onClick:t,"aria-label":"Collapse intelligence sidebar"})]}),r.jsx(ys,{label:"Sender",children:r.jsx(Mp,{sender:d})}),r.jsx(ys,{label:"Authenticity",children:r.jsx(Ap,{auth:f,onShowSimilar:s})}),r.jsx(ys,{label:"Category",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(jt,{tone:p?"danger":"neutral",children:h.value}),h.overridden&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"your override"}),r.jsx("button",{type:"button",className:Q("ml-auto text-2xs text-accent hover:underline",!n?.onReclassify&&"cursor-not-allowed opacity-50 hover:no-underline"),disabled:!n?.onReclassify,onClick:n?.onReclassify,children:"reclassify"})]})}),r.jsxs(ys,{label:"Quick actions",children:[r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[r.jsx(Ws,{icon:r.jsx(Jt,{className:"size-3.5"}),label:"VIP",active:v.vip,onClick:n?.onToggleVip}),r.jsx(Ws,{icon:r.jsx(Bc,{className:"size-3.5"}),label:"Mute",active:v.muted,onClick:n?.onToggleMute}),n?.onNotSpam&&r.jsx(Ws,{icon:r.jsx(yp,{className:"size-3.5"}),label:m?"Undoing…":"Not spam",active:!0,onClick:n.onNotSpam,pending:m}),n?.onReportSpam&&r.jsx(Ws,{icon:r.jsx(kp,{className:"size-3.5"}),label:u?"Reporting…":"Report spam",danger:!0,onClick:n.onReportSpam,pending:u}),r.jsx(Ws,{icon:r.jsx(wp,{className:"size-3.5"}),label:"Unsubscribe",active:v.unsubscribed,onClick:n?.onToggleUnsubscribe})]}),n?.onNotSpam&&r.jsx("p",{className:"mt-1.5 text-2xs text-fg-subtle",children:"You reported this message as spam"})]}),(a!=="ready"||x.length>0)&&r.jsx(ys,{label:"Similar messages",children:a==="loading"?r.jsx("div",{className:"animate-pulse space-y-2",children:Array.from({length:3}).map((b,y)=>r.jsxs("div",{className:"space-y-1",children:[r.jsx("div",{className:"h-3 w-3/4 rounded bg-surface-sunken"}),r.jsx("div",{className:"h-2.5 w-1/2 rounded bg-surface-sunken"})]},y))}):a==="error"?r.jsx("p",{className:"text-xs text-fg-subtle",children:"Similarity search unavailable"}):r.jsx("ul",{className:"-mx-1 space-y-1",children:x.map(b=>{const y="block w-full rounded-md px-1 py-1 text-left hover:bg-surface-sunken",S=`Open message from ${b.fromName||"unknown sender"}: ${b.subject}`,g=r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[r.jsx("span",{className:"truncate text-xs font-medium text-fg",children:b.fromName}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:b.timeLabel})]}),r.jsx("div",{className:"truncate text-xs text-fg-muted",children:b.subject}),r.jsx("span",{className:"mt-1 inline-block rounded-full bg-surface-sunken px-1.5 py-px text-2xs text-fg-subtle",children:Op[b.matched]})]});return r.jsx("li",{children:o?o({mailboxId:b.mailboxId,messageId:b.id,className:y,ariaLabel:S,children:g}):r.jsx("div",{className:y,children:g})},b.id)})})}),r.jsx(ys,{label:"Coming soon",className:"border-b-0 opacity-70",children:r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[r.jsx(Dt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Suggested actions"}),r.jsx("div",{className:"text-2xs text-fg-subtle",children:'"Create a filter for messages like this" — on-device model'})]})]}),r.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[r.jsx(Dt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Thread summary"}),r.jsx("div",{className:"text-2xs text-fg-subtle",children:"One-paragraph digest — Bedrock"})]})]})]})})]})}const po=[{action:"focusNext",keys:["j","k"],label:"navigate"},{action:"muteSender",keys:["m"],label:"mute"},{action:"help",keys:["?"],label:"all shortcuts"}];function Dp(e){return po.filter(t=>e[t.action]!==void 0)}const Xc=[{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 Pp(e){for(const t of Xc){const s=t.hints.find(n=>n.action===e);if(s)return s.keys}}function Jc(e){const t=Pp(e);return!t||t.length===0?"":t.length===1?t[0]??"":t[0]==="g"?t.join(" then "):t.join("")}function Vs(e){const t=Jc(e);return t===""?"":`(${t})`}const Zn=e=>({shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey}),yi=e=>e.shiftKey||e.metaKey||e.ctrlKey,Lp=e=>e.shiftKey?"range":e.metaKey||e.ctrlKey?"toggle":"open",go=(e,t)=>!t&&e>0,Fp=(e,t,s)=>{const n=e.indexOf(s);if(n===-1)return[];const a=t===void 0?-1:e.indexOf(t);if(a===-1)return[s];const o=Math.min(a,n),i=Math.max(a,n);return e.slice(o,i+1)},$p=(e,t,s,n)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:n,_p=(e,t)=>{const s=new Set(t),n=new Set;for(const a of e)s.has(a)&&n.add(a);return n},Zc=(e,t,s)=>{if(e.length===0)return;const n=t===void 0?-1:e.indexOf(t);if(n===-1)return s>0?e[0]:e[e.length-1];const a=Math.min(Math.max(n+s,0),e.length-1);return e[a]},eu=e=>{const[t,s]=l.useState(()=>new Set(e?.initialSelectedIds)),[n,a]=l.useState(void 0),o=l.useCallback(p=>t.has(p),[t]),i=l.useCallback(p=>{a(p),s(b=>{const y=new Set(b);return y.has(p)?y.delete(p):y.add(p),y})},[]),c=l.useCallback(p=>{a(p),s(b=>{if(b.has(p))return b;const y=new Set(b);return y.add(p),y})},[]),u=l.useCallback(p=>{s(b=>{if(!b.has(p))return b;const y=new Set(b);return y.delete(p),y})},[]),m=l.useCallback(p=>{s(new Set(p))},[]),d=l.useCallback(()=>{a(void 0),s(new Set)},[]),f=l.useCallback(p=>{s(b=>p.every(S=>b.has(S))?new Set:new Set(p))},[]),h=l.useCallback(p=>{a(p)},[]),v=l.useCallback(p=>{s(b=>{if(b.size===0)return b;const y=_p(b,p);return y.size===b.size?b:y})},[]),x=l.useCallback((p,b,y)=>{const S=$p(p,n,y,b);s(g=>{const w=Fp(p,S,b);if(w.length===0)return g;const C=new Set(g);for(const R of w)C.add(R);return C}),a(S)},[n]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:c,deselect:u,selectAll:m,clearSelection:d,toggleAll:f,selectRange:x,setAnchor:h,anchorId:n,intersectWith:v}};function tu({hints:e=po,className:t}){return e.length===0?null:r.jsx("footer",{className:Q("flex items-center gap-2 border-t border-line px-row-inset py-1 text-2xs text-fg-subtle",t),children:e.map(s=>r.jsx(zp,{hint:s},s.label))})}function zp({hint:e}){return r.jsxs("span",{className:"flex items-center gap-1",children:[e.keys.map(t=>r.jsx(Es,{children:t},t)),r.jsx("span",{children:e.label})]})}function Bp(){return r.jsx("div",{className:"space-y-0",role:"status","aria-busy":"true","aria-label":"Loading messages",children:Array.from({length:8}).map((e,t)=>r.jsxs("div",{className:"animate-pulse border-b border-line px-3 py-2",children:[r.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[r.jsx("div",{className:"h-4 w-32 rounded bg-surface-sunken"}),r.jsx("div",{className:"h-3 w-16 rounded bg-surface-sunken"})]}),r.jsx("div",{className:"mb-2 h-4 w-48 rounded bg-surface-sunken"}),r.jsx("div",{className:"h-3 w-full rounded bg-surface-sunken"})]},t))})}function Up({filter:e,scopeLabel:t,searchQuery:s}){const n=s?.trim();return e?r.jsxs(wi,{children:[r.jsx("p",{className:"font-medium text-fg",children:Hp(e.label,t,n)}),r.jsx("p",{className:"mt-1 text-sm text-fg-muted",children:Kp[e.reach]}),r.jsx(ce,{variant:"secondary",size:"sm",className:"mt-4",onClick:e.onClear,children:"Clear filter"})]}):r.jsx(wi,{children:r.jsx("p",{className:"text-fg-muted",children:qp(n,t)})})}const Kp={"whole-folder":"Every message in this folder was checked.","loaded-pages":"Only the messages loaded so far were checked."};function qp(e,t){return e?"No messages match your search":t?`No messages in ${t}`:"No messages in this mailbox"}function Hp(e,t,s){return s?`No results for “${s}” in ${e}`:t?`No ${e} mail in ${t}`:`No ${e} mail`}function wi({children:e}){return r.jsx("div",{className:"flex h-full flex-1 items-center justify-center",children:r.jsx("div",{className:"flex max-w-sm flex-col items-center justify-center p-8 text-center",children:e})})}function Wp(){return r.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-sm text-fg-muted",role:"status","aria-live":"polite",children:[r.jsx(ms,{className:"size-4 animate-spin","aria-hidden":"true"}),r.jsx("span",{children:"Loading more…"})]})}function Vp({message:e="Something went wrong loading this mailbox.",onRetry:t,onReport:s}){return r.jsx("div",{className:"flex h-full flex-1 items-center justify-center p-4",children:r.jsxs("div",{role:"alert",className:"flex max-w-sm flex-col items-center justify-center gap-3 text-center",children:[r.jsx(Pt,{className:"size-8 text-danger","aria-hidden":"true"}),r.jsxs("div",{children:[r.jsx("p",{className:"font-medium text-danger",children:"Couldn't load messages"}),r.jsx("p",{className:"mt-1 break-words text-sm text-fg-muted",children:e})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t&&r.jsx(ce,{variant:"secondary",size:"sm",onClick:t,children:"Retry"}),s&&r.jsx(ce,{variant:"ghost",size:"sm",onClick:s,children:"Report a problem"})]})]})})}const Qs={action:null,nextPrefix:null,preventDefault:!1},Qp={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},Gp={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 Yp(e,t){const s=e.key.toLowerCase(),n=e.metaKey||e.ctrlKey;if(e.inEditable)return{...Qs,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...Qs,nextPrefix:t==="g"?null:t};if(n&&s==="n")return{action:"compose",nextPrefix:null,preventDefault:!0};if(n&&s==="a")return{action:"selectAll",nextPrefix:null,preventDefault:!0};if(n)return{...Qs,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=Qp[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=Gp[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?Qs:{action:a.action,nextPrefix:null,preventDefault:!0}}return Qs}function Xp(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const su="data-message-row",Jp='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function Zp(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(Jp);return t?!t.hasAttribute(su):!1}const nu="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",ru=({active:e,focused:t})=>Q("relative flex h-8 w-full items-center gap-2 px-row-inset text-left",nu,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"),$s=({active:e,focused:t})=>Q("relative flex w-full items-start gap-3 py-2 pl-5 pr-row-inset text-left transition-colors",nu,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 au({thread:e}){const t=!e.isRead;return r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"flex w-4 shrink-0 items-center justify-center",children:e.suspicious?r.jsx(Fs,{className:"size-3.5 text-danger"}):e.starred?r.jsx(Jt,{className:"size-3 fill-warning text-warning"}):t?r.jsx("span",{className:"size-1.5 rounded-full bg-accent"}):null}),r.jsx("span",{className:Q("w-36 shrink-0 truncate text-xs",t?"font-semibold text-fg":"text-fg-muted"),children:e.fromName}),r.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs",children:[r.jsx("span",{className:Q(t?"font-medium text-fg":"text-fg-muted"),children:e.subject}),r.jsxs("span",{className:"text-fg-subtle",children:[" — ",e.snippet]})]}),e.hasAttachment&&r.jsx(yr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"}),r.jsx("span",{className:"w-11 shrink-0 text-right text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]})}function Si(e,t){const s=t?.trim();if(!s)return e;const n=e.toLowerCase(),a=s.toLowerCase(),o=[];let i=0,c=n.indexOf(a,i),u=0;for(;c!==-1;)c>i&&o.push(e.slice(i,c)),o.push(r.jsx("mark",{className:"bg-transparent font-semibold text-fg",children:e.slice(c,c+a.length)},u++)),i=c+a.length,c=n.indexOf(a,i);return i<e.length&&o.push(e.slice(i)),o}function cn({thread:e,badge:t,highlightQuery:s}){const n=!e.isRead;return r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsxs("span",{className:"flex items-baseline justify-between gap-2",children:[r.jsxs("span",{className:Q("flex min-w-0 items-center gap-1.5 truncate text-sm",n?"font-semibold text-fg":"font-medium text-fg-muted"),children:[e.trust==="vip"&&r.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-accent-2"}),r.jsx("span",{className:"truncate",children:e.fromName}),e.messageCount!=null&&e.messageCount>1&&r.jsx("span",{className:"shrink-0 text-2xs font-normal text-fg-subtle",children:e.messageCount})]}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:Q("truncate text-sm",n?"text-fg":"text-fg-muted"),children:Si(e.subject,s)}),e.suspicious&&r.jsx(Fs,{className:"size-3.5 shrink-0 text-danger"}),e.starred&&r.jsx(Jt,{className:"size-3 shrink-0 fill-warning text-warning"}),e.hasAttachment&&r.jsx(yr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"})]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"line-clamp-1 min-w-0 flex-1 text-xs text-fg-subtle",children:Si(e.snippet,s)}),e.category&&e.category!=="personal"&&r.jsx(jt,{tone:Gf[e.category],className:"shrink-0",children:e.category}),e.labels?.map(a=>r.jsx(Yf,{label:a,className:"max-w-20"},a.labelId)),t]})]})}function eg({thread:e,selection:t}){if(!t)return r.jsx(Nt,{name:e.fromName,email:e.fromEmail,size:"sm"});const{checked:s,alwaysVisible:n}=t;return r.jsxs("span",{className:"relative size-7 shrink-0",children:[r.jsx(Nt,{name:e.fromName,email:e.fromEmail,size:"sm",className:Q("absolute inset-0 transition-opacity sm:group-hover:opacity-0",(s||n)&&"opacity-0")}),r.jsx("span",{role:"button",tabIndex:-1,onClick:t.onToggle,onKeyDown:a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),a.stopPropagation(),t.onToggle(a))},className:Q("absolute inset-0 size-7 items-center justify-center rounded-full border transition-opacity",n?"flex":"hidden sm:flex",s?"bg-accent border-accent text-accent-fg opacity-100":n?"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&&r.jsx(hn,{className:"size-3"})})]})}function xo({thread:e,selection:t,badge:s,highlightQuery:n}){const a=!e.isRead;return r.jsxs(r.Fragment,{children:[a&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx(eg,{thread:e,selection:t}),r.jsx(cn,{thread:e,badge:s,highlightQuery:n})]})}const ou=e=>({...nc,[su]:"","data-message-id":e.id});function tg({thread:e,active:t,focused:s,tabIndex:n,onClick:a}){return r.jsx("button",{type:"button",...ou(e),tabIndex:n,onClick:a,className:ru({active:t,focused:s}),children:r.jsx(au,{thread:e})})}function sg({thread:e,active:t,focused:s,tabIndex:n,selection:a,onClick:o}){return r.jsx("button",{type:"button",...ou(e),tabIndex:n,onClick:o,className:Q("group",$s({active:t,focused:s})),children:r.jsx(xo,{thread:e,selection:a})})}let Is;const ng=5e3;function iu(e){e.preventDefault(),er()}function er(){Is!==void 0&&(clearTimeout(Is),Is=void 0,document.removeEventListener("contextmenu",iu,!0),document.removeEventListener("pointerup",er,!0))}function rg(){Is===void 0?(document.addEventListener("contextmenu",iu,!0),document.addEventListener("pointerup",er,!0)):clearTimeout(Is),Is=setTimeout(er,ng)}function lu({onLongPress:e,isDisabled:t,delayMs:s=500,accessibilityDescription:n}){const{longPressProps:a}=bp({isDisabled:t,threshold:s,accessibilityDescription:n,onLongPress:e}),o=l.useCallback(i=>{i.pointerType!=="touch"&&i.pointerType!=="pen"||rg()},[]);return{longPressProps:Ls(a,{onPointerDown:o})}}const ds=72,Ci=10,ag=ds/2,ki="__swipeableRowAxisCancel";function ji(e){return e==="leading"?ds:e==="trailing"?-ds:0}function og(e){return e>=ds/2?"leading":e<=-ds/2?"trailing":"none"}function cu({thread:e,selectionMode:t,checked:s,active:n,peek:a,onPeek:o,onToggleCheck:i,onLongPress:c,onOpen:u,onAct:m}){const d=l.useRef(null),[f,h]=l.useState(null),{longPressProps:v}=lu({onLongPress:c,isDisabled:t,accessibilityDescription:"Select message"}),x=N=>{const L=new PointerEvent("pointercancel",{bubbles:!0});L[ki]=!0,N.currentTarget.dispatchEvent(L)},g=Ls(v,{onPointerDown:N=>{d.current={startX:N.clientX,startY:N.clientY,axis:"none",escaped:!1}},onPointerMove:N=>{if(t)return;const L=d.current;if(!L)return;const D=N.clientX-L.startX,k=N.clientY-L.startY;if(L.axis==="none"&&(Math.abs(k)>Ci&&Math.abs(k)>Math.abs(D)?L.axis="vertical":Math.abs(D)>Ci&&Math.abs(D)>Math.abs(k)&&(L.axis="horizontal",N.currentTarget.setPointerCapture(N.pointerId))),L.axis==="none")return;const I=L.axis==="horizontal"?Math.abs(D):Math.abs(k);if(!L.escaped&&I>ag&&(L.escaped=!0,x(N)),L.axis!=="horizontal")return;const O=ji(a),M=Math.max(-ds,Math.min(ds,O+D));h(M)},onPointerUp:N=>{const L=d.current;d.current=null;const D=f;if(h(null),!!L){if(L.axis!=="none"&&!L.escaped&&x(N),L.axis==="horizontal"){D!==null&&o(og(D));return}if(L.axis!=="vertical"){if(t){i();return}if(a!=="none"){o("none");return}u()}}},onPointerCancel:N=>{N.nativeEvent[ki]||(d.current=null,h(null))}}),w=f??ji(a),C=w>0?"leading":w<0?"trailing":"none",R=Q("relative touch-pan-y bg-surface","select-none",$s({active:s||n})),A={transform:w!==0?`translateX(${w}px)`:void 0,transition:f===null?"transform 150ms ease":"none",minHeight:44},j=!e.isRead,T=N=>N.stopPropagation(),P=t?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:Q("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&&r.jsx(hn,{className:"size-3.5"})}),r.jsx(cn,{thread:e})]}):r.jsxs(r.Fragment,{children:[j&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx("span",{role:"checkbox",tabIndex:0,"aria-checked":s,"aria-label":`Select message from ${e.fromName}`,onPointerDown:T,onPointerMove:T,onPointerUp:T,onClick:N=>{N.preventDefault(),N.stopPropagation(),c()},onKeyDown:N=>{N.key!=="Enter"&&N.key!==" "||(N.preventDefault(),N.stopPropagation(),c())},className:"-m-2 inline-flex size-11 shrink-0 items-center justify-center rounded-full",children:r.jsx(Nt,{name:e.fromName,email:e.fromEmail,size:"sm"})}),r.jsx(cn,{thread:e})]});return r.jsxs("div",{className:"relative overflow-hidden",children:[C==="leading"&&r.jsx("button",{type:"button",onClick:()=>m("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?r.jsx(jc,{className:"size-6"}):r.jsx(vr,{className:"size-6"})}),C==="trailing"&&r.jsx("button",{type:"button",onClick:()=>m("trailing"),"aria-label":"Delete message",className:"absolute inset-y-0 right-0 flex items-center justify-end bg-danger px-6 text-canvas",children:r.jsx(Lt,{className:"size-6"})}),r.jsx("button",{type:"button",role:t?"checkbox":void 0,"aria-checked":t?s:void 0,"data-message-row":!0,"data-message-id":e.id,...g,className:R,style:A,children:P})]})}function ig({sections:e,selectedThreadId:t,selectionMode:s,checkedIds:n,initialPeek:a,onToggleCheck:o,onEnterSelection:i,onOpenThread:c,onRefresh:u,refreshing:m,busy:d=!1}){const[f,h]=l.useState(new Set),[v,x]=l.useState(new Map),p=e.flatMap(g=>g.threads).filter(g=>!f.has(g.id)).map(g=>{const w=v.get(g.id);return w===void 0?g:{...g,isRead:w}}),[b,y]=l.useState(a&&a!=="none"&&p[1]?{id:p[1].id,side:a}:null),S=(g,w)=>{if(w==="trailing")h(C=>new Set(C).add(g));else{const C=p.find(R=>R.id===g);x(R=>new Map(R).set(g,!C?.isRead))}y(null)};return r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[m&&r.jsxs("div",{className:"flex items-center justify-center gap-2 border-b border-line py-3 text-fg-muted",children:[r.jsx(ho,{className:"size-4 animate-spin"}),r.jsx("span",{className:"text-xs",children:"Checking for new mail…"})]}),r.jsx("div",{className:"divide-y divide-line",children:p.map(g=>r.jsx("div",{className:d?"pointer-events-none opacity-50":void 0,children:r.jsx(cu,{thread:g,selectionMode:s,checked:n.has(g.id),active:g.id===t,peek:b?.id===g.id?b.side:"none",onPeek:w=>y(w==="none"?null:{id:g.id,side:w}),onToggleCheck:()=>o(g.id),onLongPress:()=>i(g.id),onOpen:()=>c(g.id),onAct:w=>S(g.id,w)})},g.id))}),!s&&!m&&!d&&r.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"})]})}const lg=new Set;function uu({listTitle:e,listMeta:t,sections:s,briefFilters:n,flatList:a,listState:o="ready",searchQuery:i,listFilter:c,listScopeLabel:u,errorMessage:m,onRetry:d,onReportError:f,briefFilter:h,selectedThreadId:v,density:x="comfortable",onSelectThread:p,onOpenNav:b,isDesktop:y,initialTouchState:S,selection:g,keyboard:w,selectionBar:C,paneOverlay:R,listBody:A,hideHeader:j=!1}){const T=x==="compact"?tg:sg,P=l.useRef(null),N=l.useRef(null),L=Xf(w);or({containerRef:P,itemSelector:Qn,enabled:!L});const D=L?w.focusedId:void 0,k=L?D??s[0]?.threads[0]?.id:void 0,I=l.useCallback(B=>k===void 0?void 0:B===k?0:-1,[k]);l.useEffect(()=>{if(D===void 0)return;const B=N.current;if(!B)return;const U=B.querySelector(`${Qn}[data-message-id="${D}"]`);!U||U===B.ownerDocument.activeElement||U.focus({preventScroll:!1})},[D]),l.useEffect(()=>{if(!L)return;const B=N.current;if(!B)return;const U=B.ownerDocument.activeElement;U!==null&&U!==B.ownerDocument.body||B.focus({preventScroll:!0})},[L]);const O=!y&&!n&&o==="ready",[M,F]=l.useState(!1),E=S==="peek-trailing"?"trailing":S==="peek-leading"?"leading":void 0,V=()=>{F(!0),setTimeout(()=>F(!1),1400)},X=g?.selectedIds??lg,Z=g?.onToggle,ae=g?.onRowSelect,ie=go(X.size,y),oe=l.useCallback(B=>{if(Z)return{checked:X.has(B),onToggle:U=>{U.preventDefault(),U.stopPropagation(),Z(B)}}},[X,Z]),ue=l.useCallback((B,U)=>ae?.(B,Zn(U))?(U.preventDefault(),U.shiftKey&&window.getSelection()?.removeAllRanges(),!0):!1,[ae]),ge=l.useCallback(({thread:B,active:U,onClick:he})=>r.jsx(T,{thread:B,active:U,focused:B.id===D,tabIndex:I(B.id),selection:oe(B.id),onClick:me=>{ue(B.id,me)||he?.()}}),[T,oe,ue,D,I]);return r.jsxs("section",{ref:B=>{N.current=B,w?.ref(B)},tabIndex:L?-1:void 0,className:"relative flex h-full w-full flex-col bg-surface outline-none",children:[C??(j?null:r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[b&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(pr,{className:"size-4"}),onClick:b,"aria-label":"Open folders",className:"-ml-1 shrink-0"}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),t&&r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:t})]})),o==="loading"?r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(Bp,{})}):o==="empty"?r.jsx(Up,{filter:c,scopeLabel:u,searchQuery:i}):o==="error"?r.jsx(Vp,{message:m,onRetry:d,onReport:f}):n?r.jsx(rc,{...h??{},sections:s,selectedThreadId:v,Row:ge,keyboard:w,onSelectThread:p}):A??(O?r.jsx(ig,{sections:s,selectedThreadId:v,selectionMode:ie,checkedIds:X,initialPeek:E,onToggleCheck:B=>Z?.(B),onEnterSelection:B=>Z?.(B),onOpenThread:B=>p?.(B),onRefresh:V,refreshing:M}):r.jsx("div",{ref:P,className:"flex-1 overflow-y-auto",children:s.map(B=>r.jsxs("div",{children:[!a&&B.label&&r.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:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:B.label}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:B.threads.length})]}),r.jsx("div",{className:"divide-y divide-line",children:B.threads.map(U=>r.jsx(T,{thread:U,active:U.id===v,focused:U.id===D,tabIndex:I(U.id),selection:oe(U.id),onClick:he=>{ue(U.id,he)||p?.(U.id)}},U.id))})]},B.id))})),y&&r.jsx(tu,{hints:w?Dp(w.handlers):po}),R]})}function bo({triggerLabel:e,triggerIcon:t,triggerText:s,items:n,align:a="end",touch:o=!0,className:i,triggerClassName:c,nested:u=!1,children:m}){const[d,f]=l.useState(!1),h=l.useRef(null);return l.useEffect(()=>{if(!d)return;const v=p=>{h.current&&!h.current.contains(p.target)&&f(!1)},x=p=>{p.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",x),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",x)}},[d]),n.length===0&&!m?null:r.jsxs("div",{ref:h,className:Q("relative",i),...u?{role:"none"}:{},children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:t??r.jsx(qc,{className:"size-5"}),onClick:()=>f(v=>!v),"aria-label":e,"aria-haspopup":"menu","aria-expanded":d,...u?{role:"menuitem"}:{},className:Q(o&&"min-h-11 min-w-11 px-0",c),children:s}),d&&r.jsxs("div",{role:"menu",className:Q("absolute top-full z-50 mt-1 flex max-h-[60dvh] min-w-44 flex-col overflow-y-auto overscroll-contain rounded-md border border-line bg-surface py-1 shadow-lg",a==="end"?"right-0":"left-0"),children:[n.map(v=>r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{f(!1),v.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:[v.icon&&r.jsx("span",{className:"shrink-0 text-fg-subtle",children:v.icon}),v.label]},v.key)),m]})]})}const Gs="min-h-11 min-w-11 px-0";function du({hasThread:e,onReply:t,onReplyAll:s,onForward:n,isStarred:a,onToggleStar:o,onDelete:i,isRead:c,onToggleRead:u,moveSlot:m,overflowItems:d=[],onUnavailable:f,unavailableHint:h,className:v}){const x=(b,y)=>()=>{if(!e){f?.(b);return}y?.()},p=u?[{key:"toggle-read",label:c?"Mark as unread":"Mark as read",icon:c?r.jsx(jc,{className:"size-4"}):r.jsx(vr,{className:"size-4"}),onSelect:x("toggleRead",u)}]:[];return r.jsxs("div",{className:Q("relative",v),children:[r.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-0.5 bg-canvas px-1",children:[t&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Qc,{className:"size-5"}),onClick:x("reply",t),"aria-label":"Reply",title:"Reply",className:Gs}),s&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Vc,{className:"size-5"}),onClick:x("replyAll",s),"aria-label":"Reply all",title:"Reply all",className:Gs}),n&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Hc,{className:"size-5"}),onClick:x("forward",n),"aria-label":"Forward",title:"Forward",className:Gs}),r.jsx("div",{className:"flex-1"}),o&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Jt,{className:Q("size-5",a&&"fill-warning text-warning")}),onClick:x("star",o),"aria-label":a?"Unstar":"Star","aria-pressed":a,title:a?"Unstar":"Star",className:Gs}),m,i&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Lt,{className:"size-5"}),onClick:x("delete",i),"aria-label":"Move to Trash",title:"Move to Trash",className:Gs}),r.jsx(bo,{triggerLabel:"More actions",items:[...p,...d]})]}),!e&&h&&r.jsx("p",{role:"status",className:"bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:h})]})}function cg({open:e=!1,enabled:t=!0,onToggle:s,className:n}){return r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(ac,{className:"size-4"}),title:"Intelligence","aria-label":e?"Hide intelligence sidebar":"Show intelligence sidebar","aria-pressed":e,disabled:!t,onClick:s,className:Q(e&&"bg-accent-2-soft text-accent-2",n)})}function ug({hasThread:e,onUnavailable:t,unavailableHint:s,isStarred:n,showTriage:a=!0,onReply:o,onReplyAll:i,onForward:c,onDelete:u,onToggleStar:m,moveSlot:d,onMove:f,replyTitle:h="Reply (r)",replyAllTitle:v="Reply all (a)",forwardTitle:x="Forward (f)",deleteTitle:p="Move to Trash (#)",flagTitle:b="Star (s)",children:y,className:S}){const g=(w,C)=>()=>{if(!e){t?.(w);return}C?.()};return r.jsxs("div",{className:"relative",children:[r.jsxs("header",{className:Q("flex h-pane-header shrink-0 items-center gap-1 border-b border-line bg-surface px-3",S),children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Qc,{className:"size-4"}),title:h,"aria-label":"Reply",onClick:g("reply",o)}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Vc,{className:"size-4"}),title:v,"aria-label":"Reply all",onClick:g("replyAll",i)}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Hc,{className:"size-4"}),title:x,"aria-label":"Forward",onClick:g("forward",c)}),a&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"mx-1 h-4 w-px bg-line","aria-hidden":!0}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Lt,{className:"size-4"}),title:p,"aria-label":"Move to Trash",onClick:g("delete",u)}),d??r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(_a,{className:"size-4"}),title:"Move to mailbox","aria-label":"Move to mailbox",onClick:g("move",f)}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Jt,{className:Q("size-4",n&&"fill-warning text-warning")}),title:b,"aria-label":"Star",onClick:g("flag",m)})]}),r.jsx("div",{className:"flex-1"}),y]}),!e&&s&&r.jsx("p",{role:"status",className:"border-b border-line bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:s})]})}const dg=(e,t)=>{const n=e==="newsletter"||e==="marketing"||t;return{framed:n,isPlain:!n}},fg=()=>`
9
+ /* Zero the UA default body margin and clamp the document to the iframe width so
10
+ wide author markup can't push the body (and the page) past the viewport. */
11
+ html, body {
12
+ margin: 0;
13
+ padding: 0;
14
+ max-width: 100%;
15
+ }
16
+ body {
17
+ overflow-wrap: anywhere;
18
+ word-break: break-word;
19
+ }
20
+ /* Media never wider than the frame; keep aspect ratio when width is capped. */
21
+ img, video, iframe, svg, canvas {
22
+ max-width: 100% !important;
23
+ height: auto;
24
+ }
25
+ /* Fixed-width author tables (\`<table width="600">\`) collapse to fit. */
26
+ table {
27
+ max-width: 100% !important;
28
+ table-layout: auto;
29
+ }
30
+ /* Cells carry the fixed widths in real newsletters (\`<td width="600">\`);
31
+ cap them too or the table can't actually shrink. */
32
+ td, th {
33
+ max-width: 100% !important;
34
+ }
35
+ /* \`max-width\` alone can't beat an inline \`min-width\`; zeroing the min lets
36
+ flex / grid / table children actually collapse to the clamped width. */
37
+ * {
38
+ min-width: 0;
39
+ }
40
+ /* Long unbroken strings (URLs, tokens) wrap instead of forcing a wide line. */
41
+ pre, code {
42
+ white-space: pre-wrap;
43
+ overflow-wrap: anywhere;
44
+ word-break: break-word;
45
+ }
46
+ `,mg=e=>{const t=new Map;for(const s of e){if(!s.contentId||s.contentUrl.length===0)continue;const n=s.contentId.replace(/^<|>$/g,"");t.set(n,s.contentUrl)}return s=>t.get(s.replace(/^<|>$/g,""))},hg=/^(none|transparent|inherit|initial|unset)\s*$/i,pg=e=>{const t=[],s=/<style[^>]*>([\s\S]*?)<\/style>/gi;let n;for(n=s.exec(e);n!==null;)t.push(n[1]),n=s.exec(e);return t},gg=e=>{const t=/background(?:-color)?\s*:\s*([^;}\n]+)/gi;let s;for(s=t.exec(e);s!==null;){const n=s[1].trim();if(!hg.test(n))return!0;s=t.exec(e)}return!1},xg=e=>{if(/\bstyle\s*=\s*["'][^"']*background/i.test(e)||/\bbgcolor\s*=/i.test(e))return!0;for(const t of pg(e))if(gg(t))return!0;return!1},bg=["script","iframe","object","embed","form","input","button","textarea","select","meta","link","base"],vg=["onerror","onload","onclick","onmouseover","onmouseout","onfocus","onblur","onsubmit","onkeydown","onkeyup","formaction","xlink:href","data-bind"],yg="data:image/svg+xml,"+encodeURIComponent(`
47
+ <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
48
+ <rect fill="#f0f0f0" width="100" height="100"/>
49
+ <text x="50" y="50" text-anchor="middle" dy=".3em" fill="#999" font-size="12">
50
+ Image blocked
51
+ </text>
52
+ </svg>
53
+ `),wg=e=>e.replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Sg=e=>e.replace(/@import[^;]*;/gi,"/* @import blocked */").replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Cg=(e={})=>{const t=oc(),s={FORBID_TAGS:bg,FORBID_ATTR:vg,ALLOW_DATA_ATTR:!1,ALLOW_UNKNOWN_PROTOCOLS:!1};return t.addHook("afterSanitizeAttributes",n=>{if(n.tagName==="IMG"){const a=n.getAttribute("src")||"";if(a.startsWith("data:"))return;if(a.startsWith("cid:")){const i=a.slice(4).replace(/^<|>$/g,""),c=e.resolveCid?.(i);c&&(n.setAttribute("src",c),n.classList.add("inline-content"));return}e.allowExternalImages||(n.setAttribute("data-blocked-src",a),n.setAttribute("src",yg),n.setAttribute("alt","[Blocked image]"),n.classList.add("blocked-image"))}if(n.tagName==="A"){const a=n.getAttribute("href")||"";if(/^(javascript|data):/i.test(a)){n.removeAttribute("href");return}n.setAttribute("target","_blank"),n.setAttribute("rel","noopener noreferrer nofollow"),n.classList.add("external-link")}if(n.hasAttribute("style")){const a=n.getAttribute("style")||"";n.setAttribute("style",wg(a))}}),t.addHook("uponSanitizeElement",(n,a)=>{if(a.tagName==="style"){const o=n.textContent||"";n.textContent=Sg(o)}}),n=>{const a=xg(n),o=t.sanitize(n,s);return{html:`<style>${fg()}</style>${o}`,hasAuthorBackground:a}}},kg='"Geist Variable", "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',Ni={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)"}},jg=/prefers-color-scheme\s*:\s*dark|color-scheme\s*:\s*[^;}"']*\bdark\b/i,Ei='<meta name="viewport" content="width=device-width, initial-scale=1">',Ng=e=>{const t=e?Ni.dark:Ni.light;return`
54
+ /* Plain-email base: UI font-stack + theme-aware colors (#424) */
55
+ html, body {
56
+ font-family: ${kg};
57
+ font-size: 14px;
58
+ line-height: 1.6;
59
+ color: ${t.fg};
60
+ background-color: ${t.surface};
61
+ margin: 0;
62
+ padding: 0;
63
+ }
64
+ /* Strip author unreadable text colors and element backgrounds, scoped to body
65
+ descendants so the themed html/body surface above survives this reset. */
66
+ body * {
67
+ color: inherit !important;
68
+ background-color: transparent !important;
69
+ }
70
+ a, a:visited {
71
+ color: ${t.accent} !important;
72
+ text-decoration: underline;
73
+ }
74
+ `},Eg=(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}",Ig=(e,t,s)=>{if(t==="plain")return`${Ei}<style>${Ng(s)}</style>${e}`;const n=jg.test(e);return`${Ei}<style>${Eg(s,n)}</style>${e}`},Rg=5e4,Tg=1e4,Mg="(max-width: 640px)",Ag=.4,Og="allow-same-origin allow-popups allow-popups-to-escape-sandbox",Ii=(e,t,s)=>Math.min(Math.ceil(Math.max(e,t)),s),Dg=(e,t)=>e<=0||t<=0||e<=t?1:Math.max(Ag,t/e),Pg=e=>{const[t,s]=l.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return l.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Lg=new Set(["Enter","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"]),Fg=e=>e===" "?!1:e.length===1?!0:Lg.has(e),Ri=e=>{if(e.metaKey||e.ctrlKey||e.altKey||!Fg(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}))},Ti=({html:e,variant:t="framed",isDark:s=!1,className:n})=>{const a=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(0),[u,m]=l.useState(0),[d,f]=l.useState(0),h=Pg(Mg),v=l.useMemo(()=>Ig(e,t,s),[e,t,s]);l.useEffect(()=>{const g=a.current;if(!g)return;const w=()=>f(R=>R===g.clientWidth?R:g.clientWidth);w();const C=new ResizeObserver(w);return C.observe(g),()=>C.disconnect()},[]),l.useEffect(()=>{const g=o.current;if(!g)return;const w=()=>{const j=g.contentDocument;if(!j?.body)return;const T=j.documentElement,P=Ii(j.body.scrollHeight,T?.scrollHeight??0,Rg);c(L=>L===P?L:P);const N=Ii(j.body.scrollWidth,T?.scrollWidth??0,Tg);m(L=>L===N?L:N)};let C,R;const A=()=>{w();const j=g.contentDocument;j?.body&&(C=new ResizeObserver(w),C.observe(j.body),j.documentElement&&C.observe(j.documentElement),j.addEventListener("keydown",Ri),R=j)};return g.addEventListener("load",A),()=>{g.removeEventListener("load",A),R?.removeEventListener("keydown",Ri),C?.disconnect()}},[]);const x=h?Dg(u,d):1,p=x<1,b=p?`${u}px`:h?"100%":t==="framed"&&u>0?`max(100%, ${u}px)`:u===0?"100%":`${u}px`,y=i===0?"1px":`${i}px`,S=r.jsx("iframe",{ref:o,title:"Email content",sandbox:Og,srcDoc:v,className:p?void 0:n,scrolling:"no",style:{width:b,maxWidth:p?"none":void 0,border:"none",display:"block",height:y,overflow:"hidden",transform:p?`scale(${x})`:void 0,transformOrigin:p?"top left":void 0,colorScheme:"normal"}});return r.jsx("div",{ref:a,className:p?n:void 0,children:p?r.jsx("div",{style:{width:"100%",height:`${Math.ceil(i*x)}px`,overflow:"hidden"},children:S}):S})},Mi=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),fu=({html:e,text:t,isDark:s=!1,category:n,allowImages:a=!1,resolveCid:o,className:i,renderBlockedNotice:c})=>{const u=l.useMemo(()=>!e||typeof document>"u"?null:Cg({allowExternalImages:a,resolveCid:o})(e),[e,a,o]),m=u?.html??null,{framed:d,isPlain:f}=dg(n,u?.hasAuthorBackground??!1),h=l.useMemo(()=>!m||a?0:(m.match(/data-blocked-src/g)||[]).length,[m,a]);return!m&&!t?r.jsx("div",{className:Q("message-body",i),children:r.jsx(Mi,{})}):r.jsxs("div",{className:Q("message-body",i),children:[h>0&&r.jsx("div",{className:"message-body-notice",children:c?.(h)}),m?d?r.jsx("div",{className:"w-full max-w-full overflow-x-auto",children:r.jsx(Ti,{html:m,variant:"framed",isDark:s})}):r.jsx("div",{className:"max-w-full overflow-x-auto lg:max-w-2xl",children:r.jsx(Ti,{html:m,variant:f?"plain":"framed",isDark:s})}):t?r.jsx("pre",{className:"email-text whitespace-pre-wrap text-sm leading-relaxed",children:t}):r.jsx(Mi,{})]})};function _s({message:e="Select a thread to read",icon:t,showHints:s=!0,className:n}){return r.jsxs("div",{className:Q("flex flex-1 flex-col items-center justify-center text-center",n),children:[t??r.jsx(za,{className:"size-10 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:e}),s&&r.jsxs("p",{className:"text-2xs text-fg-subtle",children:[r.jsx(Es,{children:"j"})," / ",r.jsx(Es,{children:"k"})," to move, ",r.jsx(Es,{children:"Enter"})," to open"]})]})}function mu({message:e,onClick:t,isFocused:s,isUnread:n,trailing:a}){const o=r.jsxs(r.Fragment,{children:[r.jsx(Ts,{className:"size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{className:"relative shrink-0",children:[r.jsx(Nt,{name:e.fromName,email:e.fromEmail,size:"md"}),n&&r.jsx("span",{className:"absolute -top-0.5 -right-0.5 size-2 rounded-full border border-canvas bg-accent"})]}),r.jsx("span",{className:Q("w-36 shrink-0 truncate text-sm",n?"font-semibold text-fg":"font-medium text-fg-muted"),children:e.fromName}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-fg-subtle",children:e.snippet}),a??r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.dateLabel})]}),i=Q("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?r.jsx("div",{role:"button",tabIndex:0,"aria-expanded":!1,onClick:t,onKeyDown:c=>{Jf(c)&&(c.preventDefault(),t())},className:Q(i,"cursor-pointer"),children:o}):r.jsx("div",{className:i,children:o})}function hu({message:e,warning:t,onHeaderClick:s,isFocused:n,senderBadge:a,trailing:o,to:i,indicators:c,actionMenu:u,actionBar:m,body:d}){const f=r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[r.jsxs("span",{className:"text-sm font-semibold text-fg",children:[e.fromName,a]}),o??r.jsx("span",{className:"text-2xs text-fg-subtle",children:e.dateLabel})]}),r.jsx("div",{className:"text-xs text-fg-subtle",children:e.fromEmail}),i!==null&&r.jsx("div",{className:"text-xs text-fg-subtle",children:i??r.jsxs(r.Fragment,{children:["to ",e.toLabel]})})]});return r.jsxs("div",{className:Q("px-2 py-3 lg:px-4",n&&"ring-1 ring-inset ring-accent/30"),children:[r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(Gt,{className:"mt-1 size-3.5 shrink-0 text-fg-subtle"}),r.jsx(Nt,{name:e.fromName,email:e.fromEmail,size:"md"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[s?r.jsx("button",{type:"button",onClick:s,className:"w-full text-left",children:f}):f,c]}),u&&r.jsx("div",{className:"shrink-0",children:u})]}),t&&r.jsxs("div",{className:"mt-3 flex items-start gap-3 rounded-md bg-danger-soft p-3",children:[r.jsx(Fs,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("div",{className:"text-sm text-fg",children:[r.jsx("span",{className:"font-semibold text-danger",children:"Caution: "}),t," ",r.jsx("button",{type:"button",className:"text-accent underline",children:"Why?"})]})]}),m&&r.jsx("div",{className:"mt-3 -mx-2 lg:-mx-4",children:m}),r.jsx("div",{className:"-mx-2 [&_.message-body-notice]:px-2 lg:mx-0 lg:[&_.message-body-notice]:px-0",children:d??r.jsx(fu,{className:"mt-3",html:e.bodyHtml,category:e.framed?"newsletter":"personal",allowImages:!0})})]})}function $g({thread:e,onBack:t,intelligence:s,intelligenceOpen:n,onToggleIntelligence:a,actions:o,children:i,touchHandlers:c}){const[u,m]=l.useState(!1),d=a!==void 0,f=d?n??!1:u,h=!!s||d,v=()=>{if(d){a?.();return}m(p=>!p)},x=()=>{if(d){f&&a?.();return}m(!1)};return r.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Ba,{className:"size-4"}),onClick:t,"aria-label":"Back to messages",className:"-ml-1 shrink-0"}),r.jsx("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e.subject}),h&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(ac,{className:"size-4"}),onClick:v,"aria-label":f?"Hide intelligence panel":"Show intelligence panel","aria-pressed":f,title:"Intelligence",className:Q("shrink-0",f&&"bg-accent-2-soft text-accent-2")})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",style:c?{touchAction:"pan-y"}:void 0,...c,children:i??e.messages.map(p=>{const b=y=>y?()=>y(p.id):void 0;return p.expanded?r.jsx(hu,{message:p,warning:e.warning,onHeaderClick:b(o?.onToggleExpand),actionBar:r.jsx(du,{hasThread:!0,onReply:b(o?.onReply),onReplyAll:b(o?.onReplyAll),onForward:b(o?.onForward),onToggleStar:b(o?.onToggleStar),onDelete:b(o?.onDelete),onToggleRead:b(o?.onToggleRead),moveSlot:o?.moveSlot?.(p.id)})},p.id):r.jsx(mu,{message:p,onClick:b(o?.onToggleExpand)},p.id)})}),s&&!d&&r.jsx(Zf,{open:f,onClose:x,title:"Intelligence",anchor:"right",className:"p-0",children:r.jsx(Yc,{data:s,onClose:x,className:"h-full w-full border-l-0"})})]})}const _g="button:not([disabled]), a[href]",cs="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface-sunken";function zg({active:e,dimmed:t,indent:s}){return Q("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors",cs,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 Bg({icon:e,label:t,count:s,active:n}){return r.jsxs(r.Fragment,{children:[e&&r.jsx("span",{className:Q("shrink-0",n?"text-accent-2":"text-fg-subtle"),children:e}),r.jsx("span",{className:"flex-1 truncate",children:t}),s!=null&&s>0&&r.jsx("span",{className:Q("text-2xs tabular-nums",n?"text-accent-2":"text-fg-subtle"),children:s})]})}function rn({icon:e,label:t,count:s,active:n,dimmed:a,indent:o,navId:i,linkComponent:c,ariaLabel:u,title:m,onClick:d}){const f=zg({active:n,dimmed:a,indent:o}),h=r.jsx(Bg,{icon:e,label:t,count:s,active:n});return i&&c?c({navId:i,className:f,ariaLabel:u??t,title:m,onClick:d,children:h}):r.jsx("button",{type:"button",onClick:d,className:f,"aria-label":u,title:m,children:h})}const Ai={inbox:0,flagged:1,drafts:2,sent:3,archive:4,all:5,junk:6,trash:7};function Ug(e){switch(e){case"inbox":return r.jsx(za,{className:"size-4"});case"flagged":return r.jsx(Jt,{className:"size-4"});case"drafts":return r.jsx(ic,{className:"size-4"});case"sent":return r.jsx(pn,{className:"size-4"});case"archive":return r.jsx(nm,{className:"size-4"});case"all":return r.jsx(sm,{className:"size-4"});case"junk":return r.jsx(tm,{className:"size-4"});case"trash":return r.jsx(Lt,{className:"size-4"})}}const Oi=e=>e.role!=null,Gr=8,Di="remit.nav.folders.open.",Pi="remit.nav.account.open.";function Li(e,t,s){if(typeof localStorage>"u")return s;const n=localStorage.getItem(e+t);return n===null?s:n!=="0"}function Fi(e,t,s){typeof localStorage>"u"||localStorage.setItem(e+t,s?"1":"0")}function Kg({query:e,onSelect:t,onRemove:s}){return r.jsxs("div",{className:"group flex w-full items-center gap-1 rounded-md pr-1 hover:bg-surface",children:[r.jsxs("button",{type:"button",onClick:t,className:Q("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",cs),children:[r.jsx(ir,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate",children:e})]}),s&&r.jsx("button",{type:"button",onClick:s,"aria-label":`Remove saved search: ${e}`,className:Q("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",cs),children:r.jsx(Et,{className:"size-3.5"})})]})}function qg({savedSearches:e,saveableQuery:t,onSelectSavedSearch:s,onRemoveSavedSearch:n,onSaveCurrentSearch:a}){return e.length===0&&!t?null:r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:"px-2 pb-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Saved searches"}),t&&r.jsxs("button",{type:"button",onClick:a,className:Q("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-accent transition-colors hover:bg-surface",cs),children:[r.jsx(vp,{className:"size-4 shrink-0"}),r.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Save “",t,"”"]})]}),e.map(o=>r.jsx(Kg,{query:o,onSelect:()=>s?.(o),onRemove:n?()=>n(o):void 0},o))]})}function Hg({account:e,selectedNavId:t,onSelectNav:s,linkComponent:n}){const[a,o]=l.useState(()=>Li(Pi,e.id,!0)),[i,c]=l.useState(()=>Li(Di,e.id,!0)),[u,m]=l.useState(!1),d=()=>{o(S=>{const g=!S;return Fi(Pi,e.id,g),g})},f=()=>{c(S=>{const g=!S;return Fi(Di,e.id,g),g})},h=e.mailboxes.filter(Oi).sort((S,g)=>Ai[S.role]-Ai[g.role]),v=e.mailboxes.filter(S=>!Oi(S)),x=u||v.length<=Gr?v:v.slice(0,Gr),p=v.length-x.length,b=e.status??"ready",y=b==="ready"&&h.length===0&&v.length===0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("button",{type:"button",onClick:d,"aria-expanded":a,className:Q("flex w-full items-center gap-1.5 px-2 pb-1 text-left transition-colors hover:text-fg",cs,e.muted&&"opacity-55"),children:[a?r.jsx(Gt,{className:"size-3 shrink-0 text-fg-subtle"}):r.jsx(Ts,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"truncate text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),e.muted&&r.jsxs(r.Fragment,{children:[r.jsx(Bc,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:"muted"})]})]}),a&&r.jsxs(r.Fragment,{children:[b==="loading"&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"Loading…"}),b==="error"&&r.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:[r.jsx(Pt,{className:"mt-0.5 size-4 shrink-0 text-danger","aria-hidden":"true"}),r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx("p",{className:"font-medium text-danger",children:"Couldn't load mailboxes"})}),e.onRetry&&r.jsx("button",{type:"button",onClick:e.onRetry,className:"shrink-0 text-sm font-medium text-accent hover:underline",children:"Retry"})]}),y&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"No mailboxes"}),b==="ready"&&r.jsxs(r.Fragment,{children:[h.map(S=>r.jsx(rn,{navId:S.id,linkComponent:n,icon:Ug(S.role),label:S.name,ariaLabel:S.name,title:S.fullPath??S.name,count:S.unseen,active:t===S.id,dimmed:e.muted,onClick:()=>s?.(S.id)},S.id)),e.outboxPending!==void 0&&r.jsx(rn,{navId:"outbox",linkComponent:n,icon:r.jsx(pn,{className:"size-4"}),label:"Outbox",ariaLabel:"Outbox",count:e.outboxPending>0?e.outboxPending:void 0,active:t==="outbox",dimmed:e.muted,onClick:()=>s?.("outbox")}),v.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",onClick:f,"aria-expanded":i,className:Q("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",cs),children:[i?r.jsx(Gt,{className:"size-3 shrink-0"}):r.jsx(Ts,{className:"size-3 shrink-0"}),r.jsx("span",{className:"flex-1",children:"Folders"}),r.jsx("span",{className:"tabular-nums opacity-70",children:v.length})]}),i&&r.jsxs(r.Fragment,{children:[x.map(S=>r.jsx(rn,{navId:S.id,linkComponent:n,icon:r.jsx(em,{className:"size-4"}),label:S.name,ariaLabel:S.name,title:S.fullPath??S.name,count:S.unseen,active:t===S.id,dimmed:e.muted,onClick:()=>s?.(S.id)},S.id)),(p>0||u)&&v.length>Gr&&r.jsx("button",{type:"button",onClick:()=>m(S=>!S),className:Q("ml-7 flex items-center px-2 py-1 text-2xs font-medium text-accent transition-colors hover:underline",cs),children:u?"Show less":`Show all (${v.length})`})]})]})]})]})]})}function Wg({accounts:e,selectedNavId:t,briefUnseen:s,onSelectNav:n,variant:a="desktop",linkComponent:o,savedSearches:i=[],saveableQuery:c,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:d}){const f=l.useRef(null);or({containerRef:f,itemSelector:_g});const h=a==="drawer",v=r.jsxs("nav",{ref:h?f:void 0,className:h?"px-2 py-2":"flex-1 overflow-y-auto px-2 py-2","aria-label":"Mailboxes",children:[r.jsx(rn,{navId:"brief",linkComponent:o,icon:r.jsx(Dt,{className:"size-4"}),label:"Daily brief",ariaLabel:"Daily brief",count:s,active:t==="brief",onClick:()=>n?.("brief")}),r.jsx(rn,{navId:"flagged",linkComponent:o,icon:r.jsx(Jt,{className:"size-4"}),label:"Starred",ariaLabel:"Starred",active:t==="flagged",onClick:()=>n?.("flagged")}),r.jsx(qg,{savedSearches:i,saveableQuery:c,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:d}),e.length===0?r.jsx("div",{className:"px-2 py-4 text-center text-sm text-fg-muted",children:"No accounts configured"}):e.map(x=>r.jsx(Hg,{account:x,selectedNavId:t,onSelectNav:n,linkComponent:o},x.id))]});return h?v:r.jsx("aside",{ref:f,className:"flex h-full w-full flex-col bg-surface-sunken",children:v})}function Vg({leading:e,search:t,actions:s,className:n}){return r.jsxs("header",{className:Q("flex min-h-pane-header w-full shrink-0 items-center gap-2 border-b border-line bg-canvas px-row-inset py-1",n),children:[e&&r.jsx("div",{className:"flex shrink-0 items-center gap-1",children:e}),r.jsx("div",{className:"flex min-w-0 flex-1 justify-start",children:r.jsx("div",{className:"w-full max-w-xs transition-[max-width] duration-150 ease-out focus-within:max-w-lg",children:t})}),s&&r.jsx("div",{className:"flex shrink-0 items-center gap-1",children:s})]})}const Qg=/[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069\ufeff]/g,Gg=/[<>:"|?*]/g,Yg=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,$i=120,Xg=12,Jg="attachment",_i=e=>{const t=[...e];if(t.length<=$i)return e;const s=e.lastIndexOf("."),n=s>0&&[...e.slice(s)].length<=Xg?e.slice(s):"",a=$i-[...n].length;return t.slice(0,a).join("")+n},Zg=(e,t=Jg)=>{const n=e.replace(Qg,"").split(/[/\\]/),o=(n[n.length-1]??"").replace(Gg,"_").replace(/^[.\s]+/,"").replace(/[.\s]+$/,"");if(o.length===0)return _i(t);const i=Yg.test(o)?`_${o}`:o;return _i(i)},zi=["KB","MB","GB","TB"],ex=e=>{if(!Number.isFinite(e)||e<0)return"unknown size";const t=Math.round(e);if(t<1024)return t===1?"1 byte":`${t} bytes`;const s=1023.95;let n=t/1024,a=0;for(;n>=s&&a<zi.length-1;)n/=1024,a+=1;return`${n.toFixed(1).replace(/\.0$/,"")} ${zi[a]}`};function tx({state:e,onRetry:t}){return r.jsxs("div",{role:"alert","data-testid":"attachment-error",className:"flex items-start gap-2 border-t border-danger/30 bg-danger-soft px-2 py-2 text-xs",children:[r.jsx(Pt,{className:"mt-0.5 size-3.5 shrink-0 text-danger","aria-hidden":!0}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"font-medium text-danger",children:e.title}),r.jsx("p",{className:"mt-0.5 text-fg-muted",children:e.detail})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[r.jsx("button",{type:"button",onClick:t,className:"font-medium text-accent hover:underline",children:"Try again"}),e.reportUrl&&r.jsx("a",{href:e.reportUrl,target:"_blank",rel:"noreferrer",className:"font-medium text-accent hover:underline",children:"Report this"})]})]})}function sx({attachments:e,onDownload:t,hasUnlistedAttachment:s=!1,className:n}){return e.length===0&&!s?null:r.jsxs("section",{"aria-label":"Attachments","data-testid":"attachment-list",className:Q("space-y-1.5",n),children:[r.jsxs("h3",{className:"flex items-center gap-1.5 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:[r.jsx(yr,{className:"size-3","aria-hidden":!0}),e.length===0?"Attachment":e.length===1?"1 attachment":`${e.length} attachments`]}),e.length>0&&r.jsx("ul",{className:"overflow-hidden rounded-sm border border-line bg-surface",children:e.map(a=>{const o=a.download.status==="downloading";return r.jsxs("li",{className:"border-t border-line first:border-t-0",children:[r.jsxs("button",{type:"button",onClick:()=>t(a.attachmentId),disabled:o,"data-testid":"attachment-download","aria-label":`Download ${a.filename}`,className:"flex w-full items-center gap-2 px-2 py-2 text-left transition-colors hover:bg-surface-sunken disabled:cursor-progress disabled:opacity-60",children:[r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsx("bdi",{className:"block truncate text-sm text-fg",title:a.filename,children:a.filename}),r.jsxs("span",{className:"block truncate text-2xs text-fg-subtle",children:[a.typeLabel," ·"," ",ex(a.sizeOctets)]})]}),o?r.jsx(ms,{className:"size-4 shrink-0 animate-spin text-fg-subtle","aria-hidden":!0}):r.jsx(Dh,{className:"size-4 shrink-0 text-fg-subtle","aria-hidden":!0})]}),a.download.status==="failed"&&r.jsx(tx,{state:a.download,onRetry:()=>t(a.attachmentId)})]},a.attachmentId)})}),s&&r.jsx("p",{role:"alert","data-testid":"attachment-unlisted",className:"rounded-sm border border-line bg-surface px-2 py-2 text-xs text-fg-muted",children:"The mail server says this message carries an attachment, but none of its parts describe one. Re-sync the account from Settings; if the attachment still does not appear, the message is worth reporting."})]})}function nx({label:e,onUndo:t,undoLabel:s="Undo",filtersHref:n,className:a}){return r.jsxs(jt,{tone:"accent",className:Q("py-1 text-xs",a),children:[r.jsx(Np,{className:"size-3.5 shrink-0","aria-hidden":!0}),r.jsx("span",{children:e}),t&&r.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),t()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:s}),n&&r.jsx("a",{href:n,onClick:o=>{o.stopPropagation()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:"Manage filter"})]})}function rx({sync:e}){return e?r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",role:"status","aria-live":"polite",children:[r.jsx(ms,{className:"size-8 animate-spin text-fg-subtle","aria-hidden":"true"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"Still syncing your mail"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:ax(e)})]}):r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[r.jsx(Dt,{className:"size-8 text-fg-subtle","aria-hidden":"true"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"You're caught up"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Nothing needs attention."})]})}function ax({synced:e,total:t}){return t>0?`${e.toLocaleString()} of ${t.toLocaleString()} messages downloaded. This list fills in as they arrive.`:"Downloading your messages. This list fills in as they arrive."}const ox="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",Bi="pointer-events-none absolute inset-0 m-auto size-3.5 text-accent-fg";function vo({label:e,description:t,indeterminate:s=!1,checked:n,onChange:a,className:o,...i}){const c=l.useRef(null);l.useEffect(()=>{c.current&&(c.current.indeterminate=s)},[s]);const u=r.jsxs("span",{className:"relative inline-flex",children:[r.jsx("input",{ref:c,type:"checkbox",checked:n,onChange:a,className:ox,...i}),r.jsx(hn,{className:Q(Bi,"hidden peer-checked:block"),"aria-hidden":!0}),r.jsx(Sp,{className:Q(Bi,"hidden peer-indeterminate:block"),"aria-hidden":!0})]});return e===void 0&&t===void 0?r.jsx("span",{className:o,children:u}):r.jsxs("label",{className:Q("flex min-h-11 cursor-pointer items-center gap-3 text-left",o),children:[u,r.jsxs("span",{className:"flex min-w-0 flex-col",children:[e!==void 0&&r.jsx("span",{className:"text-sm text-fg",children:e}),t!==void 0&&r.jsx("span",{className:"text-xs text-fg-subtle",children:t})]})]})}const ix=({status:e})=>e==="saving"?r.jsx("span",{className:"animate-pulse text-xs text-fg-muted",children:"Saving..."}):e==="saved"?r.jsx("span",{className:"text-xs text-fg-muted",children:"Draft saved"}):e==="error"?r.jsx("span",{className:"text-xs text-danger",children:"Save failed"}):null;function lx({onSend:e,onDiscard:t,sending:s,canSend:n,saveStatus:a="idle",unavailableReason:o,onUnavailable:i}){return r.jsxs("div",{className:"flex items-center justify-between border-t border-line px-3 py-2",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(ce,{variant:"primary",size:"md","aria-busy":s,title:n?void 0:o,className:"min-h-11 rounded-full px-4",icon:s?r.jsx(ms,{className:"size-4 animate-spin"}):r.jsx(pn,{className:"size-4"}),onClick:()=>{if(!s){if(!n){o&&i?.(o);return}e()}},children:"Send"}),r.jsx(ix,{status:a})]}),r.jsx(ce,{variant:"ghost",size:"md","aria-busy":s,"aria-label":"Discard",className:"min-h-11 min-w-11 px-2 hover:text-danger",icon:r.jsx(Lt,{className:"size-4"}),onClick:()=>{s||t()}})]})}const cx=["Tab",","],Ui=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),ux=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const n=s[1].trim(),a=s[2].trim();if(Ui(a))return{email:a,displayName:n}}if(Ui(t))return{email:t}},dx=({label:e,addresses:t,onChange:s,placeholder:n,suggestions:a=[],onQueryChange:o})=>{const[i,c]=l.useState(""),u=l.useRef(null),m=new Set(t.map(g=>g.email.toLowerCase())),d=i.length>=2?a.filter(g=>!m.has(g.email.toLowerCase())):[],f=l.useCallback(g=>{m.has(g.email.toLowerCase())||(s([...t,g]),c(""),o?.(""))},[t,m,s,o]),h=l.useCallback(g=>{s(t.filter((w,C)=>C!==g))},[t,s]),v=l.useCallback(g=>{f(g),u.current?.focus()},[f]),x=l.useCallback(()=>{const g=ux(i);g&&f(g)},[i,f]),p=lc({count:d.length,acceptKeys:cx,onAccept:g=>v(d[g])}),b=l.useMemo(()=>d.map(g=>({value:g.email,label:g.displayName??g.email,...g.displayName?{hint:g.email}:{}})),[d]),y=l.useCallback(g=>{if(g.key==="Backspace"&&i===""&&t.length>0){h(t.length-1);return}p.handleKeyDown(g)||(g.key==="Enter"||g.key==="Tab"||g.key===",")&&i.trim()&&(g.preventDefault(),x())},[i,t.length,h,p.handleKeyDown,x]),S=l.useCallback(()=>{setTimeout(()=>{x(),p.dismiss()},150)},[x,p.dismiss]);return r.jsxs("div",{className:"relative",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),r.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:()=>u.current?.focus(),onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&u.current?.focus()},children:[t.map((g,w)=>r.jsx(Rp,{email:g.email,displayName:g.displayName,onRemove:()=>h(w)},g.email)),r.jsx("input",{ref:u,id:`address-field-${e}`,type:"text",value:i,onChange:g=>{p.reopen(),c(g.target.value),o?.(g.target.value)},onKeyDown:y,onBlur:S,placeholder:t.length===0?n:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5",autoComplete:"off",...p.comboboxProps})]})]}),p.open&&r.jsx(cc,{id:p.listId,suggestions:b,activeIndex:p.activeIndex,optionId:p.optionId,onPick:g=>{const w=d.find(C=>C.email===g.value);w&&v(w)},onHighlight:p.setActiveIndex,label:`${e} suggestions`,className:"absolute left-12 right-0 z-50 mt-1 max-h-[200px] shadow-lg"})]})};function fx({banner:e,header:t,children:s,quoted:n,actionBar:a}){return r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e,t,r.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-auto","data-testid":"compose-body-area",children:[s,n&&r.jsx("div",{className:"shrink-0 px-3 pb-2",children:n})]}),a]})}const Yr=({label:e,onClick:t})=>r.jsx("button",{type:"button",onClick:t,className:"text-xs text-fg-muted hover:text-fg transition-colors",children:e}),mx=({to:e,cc:t,bcc:s,subject:n})=>{const a=[];return e.length>0&&a.push(`To: ${e.map(o=>o.displayName??o.email).join(", ")}`),t.length>0&&a.push(`Cc: ${t.length}`),s.length>0&&a.push(`Bcc: ${s.length}`),n&&a.push(n),a.join(" · ")},hx=({collapsed:e=!1,summary:t="",from:s,to:n,cc:a,bcc:o,subject:i,onShowCc:c,onShowBcc:u})=>e?r.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:[r.jsx("span",{className:"truncate text-xs text-fg-muted",children:t||"…"}),r.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:"…"})]}):r.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[s,n,a??r.jsxs("div",{className:"flex gap-2 pl-14",children:[r.jsx(Yr,{label:"Cc",onClick:c}),r.jsx(Yr,{label:"Bcc",onClick:u})]}),a&&!o&&r.jsx("div",{className:"pl-14",children:r.jsx(Yr,{label:"Bcc",onClick:u})}),o,i]}),px=({onConfigure:e})=>r.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:[r.jsx(Ua,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),r.jsxs("button",{type:"button",onClick:e,className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",r.jsx(rm,{className:"size-3","aria-hidden":"true"})]})]})]}),gx=({value:e,onChange:t})=>r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),r.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})]});function xx({key:e,shiftKey:t=!1,repeat:s=!1,caretAtStart:n,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"?!n||o===0?{type:"none"}:s?{type:"none"}:{type:"focusChip",index:i}:{type:"none"}}function bx({key:e,repeat:t=!1,index:s,chipCount:n}){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>=n-1?{type:"focusInput"}:{type:"focusChip",index:s+1}:e==="Enter"||e===" "?{type:"activateChip",index:s}:e==="Escape"?{type:"focusInput"}:{type:"none"}}function vx(e,t){const s=t-1;return s<=0?null:e<s?e:s-1}const yx=e=>e instanceof HTMLElement?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable:!1,wx=({chips:e=[],onRemoveChip:t,value:s,onChange:n,onClear:a,onClearQuery:o,placeholder:i="Search mail...",globalFocusKey:c=!0,showClearButton:u=!0,size:m="sm",inputId:d,suggest:f,className:h})=>{const v=l.useId(),x=d??v,p=l.useRef(null),b=l.useRef([]),y=o??a,[S,g]=l.useState(null),w=l.useRef(void 0),[C,R]=l.useState(""),A=e.length>0;l.useEffect(()=>{g(I=>I!==null&&I>=e.length?null:I)},[e.length]),l.useEffect(()=>{const I=w.current;if(I!==void 0){if(w.current=void 0,I===null){p.current?.focus();return}b.current[I]?.focus()}});const j=l.useRef(void 0);l.useEffect(()=>{const I=f?.caret;if(!I||I===j.current)return;j.current=I;const O=p.current;!O||O.ownerDocument.activeElement!==O||(O.setSelectionRange(I.cursor,I.cursor),f?.onCaretChange(I.cursor))});const T=I=>{f?.onCaretChange(I.selectionStart??I.value.length)},P=l.useCallback(I=>{g(I),w.current=I},[]),N=l.useCallback(I=>{const O=e[I];O&&t&&(P(vx(I,e.length)),R(`${O.label} removed`),t(O.id))},[e,t,P]),L=l.useCallback(()=>{P(null),a()},[a,P]),D=l.useCallback(I=>{const O=I.currentTarget;if(f?.onKeyDown(I))return;const M=xx({key:I.key,shiftKey:I.shiftKey,repeat:I.repeat,caretAtStart:O.selectionStart===0&&O.selectionEnd===0,hasValue:s.length>0,chipCount:e.length});switch(M.type){case"focusChip":I.preventDefault(),P(M.index);return;case"clearQuery":y();return;case"blur":O.blur();return;case"none":return}},[e.length,s,y,P,f]),k=l.useCallback(I=>O=>{const M=bx({key:O.key,repeat:O.repeat,index:I,chipCount:e.length});switch(M.type!=="none"&&O.preventDefault(),M.type){case"removeChip":N(M.index);return;case"focusChip":P(M.index);return;case"focusInput":P(null);return;case"activateChip":return;case"none":return}},[e,N,P]);return l.useEffect(()=>{if(!c)return;const I=O=>{O.key!=="/"||O.metaKey||O.ctrlKey||O.altKey||yx(O.target)||(O.preventDefault(),p.current?.focus())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[c]),r.jsxs("label",{htmlFor:x,className:Q("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",m==="lg"?"rounded-xl px-4 py-2":"rounded-md px-2.5 py-1",h),children:[r.jsx(ir,{className:Q("shrink-0 text-fg-muted pointer-events-none",m==="lg"?"size-5":"size-4")}),r.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1",children:[A&&r.jsx("div",{role:"grid","aria-label":"Search filters",className:"flex min-w-0 flex-wrap items-center gap-1",children:e.map((I,O)=>r.jsx(am,{ref:M=>{b.current[O]=M},label:I.label,tone:I.tone,focused:S===O,onFocusLabel:()=>g(O),onKeyDown:k(O),onRemove:()=>N(O)},I.id))}),r.jsx("input",{ref:p,id:x,name:"q",type:"text","aria-label":"Search mail",autoComplete:"off",value:s,tabIndex:S===null?0:-1,onChange:I=>{n(I.target.value),T(I.target)},onKeyDown:D,onKeyUp:I=>T(I.currentTarget),onClick:I=>T(I.currentTarget),onFocus:I=>{g(null),f?.onFocusChange?.(!0),T(I.currentTarget)},onBlur:()=>f?.onFocusChange?.(!1),...f?.comboboxProps,placeholder:A?void 0:i,className:"min-w-24 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted"})]}),(s||A)&&u&&r.jsx("button",{type:"button",onClick:L,className:"shrink-0 rounded p-0.5 hover:bg-surface-raised transition-colors","aria-label":"Clear search",children:r.jsx(Et,{className:Q("text-fg-muted",m==="lg"?"size-5":"size-4")})}),r.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:C})]})},yo=({value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i="Search mail...",globalFocusKey:c=!0,showClearButton:u=!0,size:m,inputId:d,suggest:f,className:h})=>r.jsx(wx,{value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i,globalFocusKey:c,showClearButton:u,size:m,inputId:d,suggest:f,className:h});function Sx(e){return{id:e.id,fromName:e.sender,fromEmail:e.senderEmail??e.sender,subject:e.subject,snippet:e.snippet,timeLabel:e.date,isRead:!e.unread,starred:e.flagged,...e.mailboxId?{mailboxId:e.mailboxId}:{}}}function Cx({result:e,onClick:t,query:s,showFolder:n=!0}){const a=n&&e.folder?om(e.folder):void 0;return r.jsx("button",{type:"button",onClick:t,className:Q("group",$s({}),"border-b border-line"),children:r.jsx(xo,{thread:Sx(e),highlightQuery:s,badge:r.jsxs(r.Fragment,{children:[a&&r.jsx(jt,{tone:"neutral",className:"shrink-0",children:a}),e.category&&r.jsx(jt,{tone:e.category.tone??"neutral",className:"shrink-0",children:e.category.label}),e.matchedChunkLabel&&r.jsx(jt,{tone:"neutral",className:"shrink-0",children:`matched: ${e.matchedChunkLabel}`}),e.score!=null&&r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.score.toFixed(2)})]})})})}const kx=e=>e===1?"result":"results";function pu({count:e,onScopeToSpam:t}){return r.jsx(gn,{tone:"info",variant:"soft",className:"items-center justify-between gap-3 rounded-none border-b border-line",children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("p",{className:"min-w-0 text-xs text-fg-muted",children:[r.jsx("span",{className:"font-semibold text-fg tabular-nums",children:e})," ",`${kx(e)} from Spam`]}),r.jsx(ce,{variant:"ghost",size:"sm",onClick:t,className:"shrink-0 text-accent",children:"Go to Spam"})]})})}const Ki=6,jx={kind:"global"},Nx=e=>e.kind==="folder"&&e.role==="junk",Ex=e=>e.folder?.role==="junk";function wo(e){const t=[],s=[];for(const n of e)Ex(n)?s.push(n):t.push(n);return{kept:t,spam:s}}function gu({onClick:e,blockedReason:t}){const s=l.useId(),[n,a]=l.useState(!1);return r.jsxs("div",{className:"border-b border-line px-row-inset py-1.5",children:[r.jsxs("button",{type:"button",onClick:()=>{if(t){a(!0);return}e()},"aria-describedby":t?s:void 0,className:Q("flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs font-medium transition-colors",t?"text-fg-subtle opacity-55":"text-accent hover:bg-surface-sunken"),children:[r.jsx(im,{className:"size-3.5 shrink-0","aria-hidden":"true"}),r.jsx("span",{children:"Make this a filter"})]}),t&&r.jsx(lm,{id:s,reason:t,nudged:n,className:"px-2 pt-1 text-2xs text-warning"})]})}function Ix({section:e,query:t,onSelectResult:s,showFolder:n}){const[a,o]=l.useState(e.initialCollapsed??!1),[i,c]=l.useState(!1),u=e.results.length>Ki,d=!i&&u?e.results.slice(0,Ki):e.results,f=e.results.length-d.length;return r.jsxs("div",{children:[r.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:[r.jsx("span",{className:"flex-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:e.results.length}),r.jsx(Gt,{className:Q("size-3 shrink-0 text-fg-subtle transition-transform duration-200",a?"rotate-0":"rotate-180")})]}),!a&&r.jsxs(r.Fragment,{children:[d.map(h=>r.jsx(Cx,{result:h,query:t,showFolder:n,onClick:s?()=>s(h):void 0},h.id)),u&&r.jsxs("button",{type:"button",onClick:()=>c(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 ${f} more`,!i&&r.jsx(Gt,{className:"ml-1 size-3"})]})]})]})}function xu({value:e,recentSearches:t,onPickRecent:s,sections:n,loading:a,onSelectResult:o,tokens:i,scope:c=jx,makeFilter:u}){if(!(e.trim().length>0))return t&&t.length>0?r.jsxs("div",{className:"flex flex-col",children:[r.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(w=>r.jsxs("button",{type:"button",onClick:()=>s?.(w),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:[r.jsx(no,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-fg-muted",children:w})]},w))]}):r.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&&r.jsx(cm,{tokens:i}),f=u&&r.jsx(gu,{...u});if(a)return r.jsxs("div",{className:"flex flex-col",children:[f,d,r.jsx("div",{className:"flex flex-col gap-3 px-row-inset py-4",children:[0,1,2,3].map(w=>r.jsxs("div",{className:"flex flex-col gap-1.5",children:[r.jsx("div",{className:"h-3 w-1/3 animate-pulse rounded bg-surface-sunken"}),r.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-surface-sunken"}),r.jsx("div",{className:"h-2.5 w-1/2 animate-pulse rounded bg-surface-sunken"})]},w))})]});const h=c.kind==="global",v=Nx(c)||c.kind==="collection",x=h||c.kind==="collection",p=(n??[]).map(w=>{if(v)return{section:w,spam:[]};const{kept:C,spam:R}=wo(w.results);return{section:{...w,results:C},spam:R}}),b=p.map(w=>w.section),y=p.reduce((w,C)=>w+C.spam.length,0),S=c.kind==="global"&&y>0&&c.onScopeToSpam!==void 0?r.jsx(pu,{count:y,onScopeToSpam:c.onScopeToSpam}):void 0;return b.some(w=>w.results.length>0)?r.jsxs("div",{className:"flex flex-col",children:[f,d,S,b.filter(w=>w.results.length>0).map(w=>r.jsx(Ix,{section:w,query:e,showFolder:x,onSelectResult:o},w.id))]}):r.jsxs("div",{className:"flex flex-col",children:[f,d,S,r.jsxs("div",{className:"px-row-inset py-10 text-center",children:[r.jsxs("p",{className:"text-sm font-medium text-fg",children:["No matches for “",e,"”"]}),r.jsx("p",{className:"mt-1 text-xs text-fg-subtle",children:"Try a different word, or adjust the filters above."})]})]})}function Rx({value:e,onChange:t,onClear:s,onCancel:n,filter:a,recentSearches:o,onPickRecent:i,sections:c,loading:u,onSelectResult:m,tokens:d,chips:f,onRemoveChip:h,scope:v,makeFilter:x,suggest:p,suggestList:b}){const y=r.jsx(xu,{value:e,recentSearches:o,onPickRecent:i,sections:c,loading:u,onSelectResult:m,tokens:d,scope:v,makeFilter:x});return r.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(yo,{value:e,onChange:t,onClear:s,chips:f,onRemoveChip:h,globalFocusKey:!1,showClearButton:!1,suggest:p})}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Et,{className:"size-4"}),onClick:n,"aria-label":"Clear and close search",className:"-mr-1 shrink-0"})]}),b,a&&e.trim().length===0?r.jsx(um,{children:r.jsx(uc,{...a,children:y})}):r.jsx("div",{className:"flex-1 overflow-y-auto",children:y})]})}function Tx(){const e=hs();if(!e)return null;const t=e.showNavPane?!e.navCollapsed:!1;return r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(pr,{className:"size-4"}),onClick:e.toggleNav,"aria-label":t?"Hide folders":"Show folders","aria-expanded":t,title:"Folders",className:"shrink-0"})}const Mx={queued:{icon:no,label:"Queued",className:"text-warning"},sending:{icon:ms,label:"Sending…",className:"text-accent-2",spin:!0},sent:{icon:mo,label:"Sent",className:"text-positive"},failed:{icon:Pt,label:"Failed",className:"text-danger"},blocked:{icon:Ua,label:"Blocked",className:"text-warning"}};function qi({status:e,iconOnly:t,className:s}){const n=Mx[e],a=n.icon;return r.jsxs("span",{className:Q("inline-flex items-center gap-1.5 text-xs font-medium",n.className,s),children:[r.jsx(a,{className:Q("size-4",n.spin&&"animate-spin")}),!t&&n.label]})}const Ax=(e,t)=>t?"bg-accent-2-soft":e==="failed"?"bg-danger-soft":e==="blocked"?"bg-warning/10":"";function Ox({recipients:e,subject:t,time:s,status:n,error:a,selected:o,onSelect:i,onRetry:c,retrying:u,onEdit:m,onDelete:d,deleting:f}){const h=n==="failed"||n==="blocked";return r.jsxs("div",{className:Q("flex items-start gap-3 border-b border-line px-4 py-3 transition-colors hover:bg-surface-raised",Ax(n,o)),children:[r.jsxs("button",{type:"button",...nc,onClick:i,className:"flex flex-1 min-w-0 items-start gap-3 text-left",children:[r.jsx("div",{className:"mt-0.5 shrink-0",children:r.jsx(qi,{status:n,iconOnly:!0})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"truncate text-sm font-medium",children:e}),r.jsx("span",{className:"shrink-0 text-xs text-fg-muted",children:s})]}),r.jsx("div",{className:"truncate text-sm",children:t||"No subject"}),r.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[r.jsx(qi,{status:n}),a&&r.jsxs("span",{className:"truncate text-xs text-fg-muted",children:["— ",a]})]})]})]}),h&&r.jsx("div",{className:"shrink-0",children:r.jsx(wh,{actions:[...n==="failed"&&c?[{label:"Retry sending",iconOnly:!0,icon:r.jsx(vh,{className:"size-3.5"}),busy:u,onClick:c}]:[],{label:"Edit as draft",iconOnly:!0,icon:r.jsx(pn,{className:"size-3.5"}),onClick:m}],destructive:{label:"Delete message",iconOnly:!0,icon:r.jsx(Lt,{className:"size-3.5"}),busy:f,confirm:{prompt:"Delete this message?",confirmLabel:"Delete"},onClick:d}})})]})}const Dx=e=>{const[t,s]=l.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return l.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Px=({children:e,onRefresh:t,isRefreshing:s})=>Dx(Nc)?e:r.jsx(dm,{onRefresh:t,isPullable:!s,children:e}),Lx=({text:e,html:t,senderName:s,date:n})=>{const[a,o]=l.useState(!1);if(!e&&!t)return null;const i=[s,n].filter(Boolean).join(" on ");return r.jsxs("div",{className:"mt-2 px-3 pb-2",children:[r.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?r.jsx(Gt,{className:"size-3"}):r.jsx(Ts,{className:"size-3"}),i?`${i} wrote:`:"Show quoted text"]}),a&&r.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?r.jsx("div",{dangerouslySetInnerHTML:{__html:t}}):e.split(`
75
+ `).map((c,u)=>r.jsx("p",{className:"min-h-[1.2em]",children:c},u))})]})};function So({state:e,onRefresh:t,label:s,errorMessage:n,hasUpdate:a,size:o="sm",className:i}){const c=e==="refreshing",u=e==="error",m=e==="success",d=u?r.jsx(Pt,{className:"size-4 text-danger"}):m?r.jsx(mo,{className:"size-4 text-positive"}):r.jsx(ho,{className:Q("size-4",c&&"animate-spin")}),f=u?`${s} — failed: ${n??"try again"}`:c?`${s} — refreshing`:m?`${s} — up to date`:a?`${s} — new mail`:s;return r.jsxs("div",{className:"relative inline-flex",children:[r.jsx(ce,{variant:"ghost",size:o,icon:d,onClick:t,disabled:c,"aria-label":f,"aria-busy":c||void 0,title:u?n:s,className:i}),e==="idle"&&a&&r.jsx("span",{"aria-hidden":"true",className:"absolute right-1 top-1 size-1.5 rounded-full bg-accent-2"})]})}const Fx=e=>e===1?"message":"messages";function $x({count:e,onReview:t,onDismiss:s,actionLabel:n="Review & rescue"}){return r.jsx(gn,{tone:"info",variant:"soft",onDismiss:s,children:r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsxs("p",{className:"flex items-start gap-2 text-sm text-fg",children:[r.jsx(xn,{className:"mt-0.5 size-4 shrink-0 text-positive","aria-hidden":!0}),r.jsxs("span",{children:[r.jsx("span",{className:"font-semibold text-fg",children:`${e} ${Fx(e)} here`})," ","may not be spam — they're from senders we can verify."]})]}),r.jsx(ce,{variant:"primary",size:"sm",onClick:t,className:"self-start",children:n})]})})}const _x=(e,t)=>e==="vip"?"vip":e==="unknown"&&t==="md"?"unknown-pill":"hidden",bu=({senderTrust:e,size:t="sm",className:s})=>{const n=_x(e,t);return n==="vip"?r.jsx(Dt,{className:Q("text-warning shrink-0",t==="sm"&&"size-3.5",t==="md"&&"size-4",s),"aria-label":"VIP sender","data-testid":"sender-trust-vip"}):n==="unknown-pill"?r.jsx("span",{className:Q("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 zx({candidate:e,selected:t,onToggle:s,hideSender:n=!1}){const{senderName:a,senderAddress:o,subject:i,snippet:c,trustReason:u,trustSubReason:m,senderTrust:d}=e;return r.jsxs("label",{className:Q("flex w-full cursor-pointer items-start gap-3 px-3 py-2.5 text-left transition-colors",n&&"pl-11",t?"bg-positive/10":"bg-surface hover:bg-surface-sunken"),children:[r.jsx(vo,{className:"mt-0.5",checked:t,onChange:s,"aria-label":`${t?"Deselect":"Select"} ${n?i:`message from ${a}`}`}),!n&&r.jsx(Nt,{name:a,email:o,size:"sm"}),r.jsxs("span",{className:"min-w-0 flex-1",children:[!n&&r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"truncate text-sm font-medium text-fg",children:a}),d&&r.jsx(bu,{senderTrust:d,size:"sm"}),r.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:o})]}),r.jsx("span",{className:"block truncate text-sm text-fg-muted",children:i}),r.jsx("span",{className:"block line-clamp-1 text-xs text-fg-subtle",children:c}),!n&&r.jsxs("span",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[r.jsxs(jt,{tone:"positive",children:[r.jsx(xn,{className:"size-3","aria-hidden":!0}),u]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:m})]})]})]})}const Bx=e=>{const t=new Map,s=[];for(const n of e){const a=(n.senderAddress||n.senderName).toLowerCase(),o=t.get(a);if(o){o.messages.push(n);continue}t.set(a,{key:a,senderName:n.senderName,senderAddress:n.senderAddress,trustReason:n.trustReason,trustSubReason:n.trustSubReason,senderTrust:n.senderTrust,messages:[n]}),s.push(a)}return s.map(n=>t.get(n)).sort((n,a)=>a.messages.length-n.messages.length)},Ux=(e,t)=>{const s=e.messages.filter(n=>t.has(n.id)).length;return s===0?"none":s===e.messages.length?"all":"some"},Hi=e=>e===1?"message":"messages";function Kx({group:e,selected:t,onToggleGroup:s,onToggleMessage:n}){const[a,o]=l.useState(!1),i=Ux(e,t),c=e.messages.length,u=a?Gt:Ts;return r.jsxs("div",{className:Q(i!=="none"?"bg-positive/10":"bg-surface"),children:[r.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-2.5",children:[r.jsx(vo,{className:"mt-0.5",checked:i==="all",indeterminate:i==="some",onChange:()=>s(e,i!=="all"),"aria-label":`${i==="all"?"Deselect":"Select"} all ${c} ${Hi(c)} from ${e.senderName}`}),r.jsx(Nt,{name:e.senderName,email:e.senderAddress,size:"sm"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"truncate text-sm font-medium text-fg",children:e.senderName}),e.senderTrust&&r.jsx(bu,{senderTrust:e.senderTrust,size:"sm"}),r.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:e.senderAddress})]}),r.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[r.jsxs(jt,{tone:"positive",children:[r.jsx(xn,{className:"size-3","aria-hidden":!0}),e.trustReason]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:e.trustSubReason})]})]}),r.jsxs("button",{type:"button",onClick:()=>o(m=>!m),"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:[`${c} ${Hi(c)}`,r.jsx(u,{className:"size-3.5","aria-hidden":!0})]})]}),a&&r.jsx("div",{className:"divide-y divide-line border-t border-line",children:e.messages.map(m=>r.jsx(zx,{candidate:m,selected:t.has(m.id),onToggle:()=>n(m.id),hideSender:!0},m.id))})]})}const Co=e=>e===1?"message":"messages",qx=(e,t)=>`Moves ${e===1?"this message":`these ${e} ${Co(e)}`} out of Spam to ${t} now. Nothing later.`,ka=(e,t)=>e.find(s=>s.id===t)?.label??"Inbox";function Hx(){return r.jsx(gn,{tone:"info",variant:"soft",children:r.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 Wx({candidates:e,selected:t,onToggle:s,onToggleGroup:n,onSelectAll:a,onSelectNone:o,onContinue:i,onCancel:c}){const[u,m]=l.useState(!1),d=t.size,f=l.useMemo(()=>Bx(e),[e]);return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("h2",{className:"flex items-center gap-2 text-sm font-semibold text-fg",children:[r.jsx(xn,{className:"size-4 text-positive","aria-hidden":!0}),"Rescue from Spam"]}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(bh,{className:"size-3.5"}),onClick:()=>m(h=>!h),className:"-mr-1.5 -mt-0.5",children:"Why these?"})]}),r.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&&r.jsx("div",{className:"mt-2",children:r.jsx(Hx,{})})]}),r.jsxs("div",{className:"flex items-center justify-between px-row-inset pb-1.5",children:[r.jsx("span",{className:"text-2xs font-medium text-fg-muted",children:`${d} of ${e.length} selected · ${f.length} ${f.length===1?"sender":"senders"}`}),r.jsxs("span",{className:"flex gap-1",children:[r.jsx(ce,{variant:"ghost",size:"sm",onClick:a,children:"Select all"}),r.jsx(ce,{variant:"ghost",size:"sm",onClick:o,children:"Select none"})]})]}),r.jsx("div",{className:"min-h-0 flex-1 divide-y divide-line overflow-y-auto border-y border-line",children:f.map(h=>r.jsx(Kx,{group:h,selected:t,onToggleGroup:n,onToggleMessage:s},h.key))}),r.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[r.jsx(ce,{variant:"primary",onClick:i,className:"h-11 w-full font-semibold",children:`Continue with ${d} ${Co(d)}`}),r.jsx(ce,{variant:"ghost",onClick:c,className:"h-11 w-full",children:"Cancel"})]})]})}function Vx({count:e,folders:t,delimiter:s,destination:n,onPick:a,onMove:o,onBack:i}){const[c,u]=l.useState(!1);return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[r.jsx("h2",{className:"text-sm font-semibold text-fg",children:"Where should they go?"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Pick a folder, then we move them out of Spam."})]}),r.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-row-inset py-2",children:c?r.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden rounded-xl border border-line bg-surface",children:r.jsx(dc,{folders:t,selectedId:n,delimiter:s,onSelect:a,onCancel:()=>u(!1)})}):r.jsxs("div",{className:"rounded-xl border border-line bg-surface-sunken p-3",children:[r.jsx("p",{className:"text-2xs text-fg-subtle",children:"Destination"}),r.jsx("p",{className:"mt-0.5 text-sm font-medium text-fg",children:ka(t,n)}),r.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"mt-2 px-0",children:"Move to a different folder"})]})}),r.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[r.jsx("p",{className:"text-2xs text-fg-subtle",children:qx(e,ka(t,n))}),r.jsx(ce,{variant:"primary",onClick:o,className:"h-11 w-full font-semibold",children:`Move ${e} out of Spam`}),r.jsx(ce,{variant:"ghost",onClick:i,className:"h-11 w-full",children:"Back"})]})]})}function Qx({count:e,destinationLabel:t,onClose:s}){return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 px-row-inset py-10 text-center",children:[r.jsx(Ph,{className:"size-10 text-positive","aria-hidden":!0}),r.jsx("p",{className:"text-base font-semibold text-fg",children:`Moved ${e} ${Co(e)} out of Spam.`}),r.jsx("p",{className:"text-2xs text-fg-subtle",children:`You'll find them in ${t}.`})]}),r.jsx("div",{className:"border-t border-line bg-surface px-row-inset py-3",children:r.jsx(ce,{variant:"primary",onClick:s,className:"h-11 w-full font-semibold",children:"Done"})})]})}function Gx({open:e,candidates:t,defaultDestinationId:s,availableFolders:n,delimiter:a,onConfirmMove:o,onCancel:i}){const[c,u]=l.useState("review"),[m,d]=l.useState(()=>e?new Set(t.map(w=>w.id)):new Set),[f,h]=l.useState(s),[v,x]=l.useState(0),p=l.useRef(!1);l.useEffect(()=>{e&&!p.current&&(u("review"),d(new Set(t.map(w=>w.id))),h(s),x(0)),p.current=e},[e,t,s]);const b=m.size,y=w=>{d(C=>{const R=new Set(C);return R.has(w)?R.delete(w):R.add(w),R})},S=(w,C)=>{d(R=>{const A=new Set(R);for(const j of w.messages)C?A.add(j.id):A.delete(j.id);return A})},g=()=>{const w=Array.from(m);x(w.length),o(w,f),u("done")};return r.jsxs(Ch,{open:e,onClose:i,dismissLabel:"Close rescue",children:[c==="review"&&r.jsx(Wx,{candidates:t,selected:m,onToggle:y,onToggleGroup:S,onSelectAll:()=>d(new Set(t.map(w=>w.id))),onSelectNone:()=>d(new Set),onContinue:()=>u("destination"),onCancel:i}),c==="destination"&&r.jsx(Vx,{count:b,folders:n,delimiter:a,destination:f,onPick:h,onMove:g,onBack:()=>u("review")}),c==="done"&&r.jsx(Qx,{count:v,destinationLabel:ka(n,f),onClose:i})]})}const Yx={html:"",text:"",formatting:[]},Wi=e=>e.toLocaleString();function Vi({selectAll:e,selecting:t,className:s}){return r.jsx(vo,{className:s,checked:e.checked,indeterminate:e.indeterminate,onChange:e.onChange,label:r.jsx("span",{className:"font-medium text-accent",children:e.checked&&t?"Deselect all":"Select all"})})}function ko({title:e,count:t,onCancel:s,onDelete:n,onMove:a,onOrganize:o,onJunk:i,onMarkRead:c,navSlot:u,titleMeta:m,searchSlot:d,searchField:f,idleSlot:h,overflowSlot:v,isBusy:x=!1,isCounting:p=!1,selectAll:b,statusLabel:y,progress:S,notice:g}){const w=t>0||p,C=b?.checked?`All ${Wi(t)} loaded selected`:`${Wi(t)} ${t===1?"message":"messages"} selected`,R=[];return i&&!x&&!p&&R.push({key:"junk",label:"Junk",icon:r.jsx(Fs,{className:"size-4"}),onSelect:i}),c&&!x&&!p&&R.push({key:"mark-read",label:"Mark read",icon:r.jsx(vr,{className:"size-4"}),onSelect:c}),r.jsxs("header",{"data-selection-bar":"",className:"flex shrink-0 flex-col border-b border-line bg-surface-sunken",children:[r.jsxs("div",{"data-selection-bar-row":"actions",className:"flex h-pane-header items-center gap-1 px-row-inset",children:[w?r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(Ba,{className:"size-5"}),onClick:s,"aria-label":"Cancel selection",className:"-ml-2 shrink-0"}):u,b&&r.jsx(Vi,{selectAll:b,selecting:w,className:"hidden shrink-0 pr-2 md:flex"}),w?r.jsx("span",{"data-selection-count":"",className:"min-w-0 flex-1 truncate px-1 text-sm font-medium text-fg",role:"status","aria-live":"polite",children:y??C}):f?r.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:f}):r.jsxs(r.Fragment,{children:[r.jsx("h1",{className:"min-w-0 flex-1 truncate px-1 text-sm font-semibold text-fg",children:e}),m,d]}),w&&!p&&r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",size:"touch",icon:x?r.jsx(ms,{className:"size-5 animate-spin"}):r.jsx(Lt,{className:"size-5 text-danger"}),onClick:x?void 0:n,"aria-label":"Move selected messages to Trash","aria-busy":x||void 0,className:"shrink-0"}),!x&&a&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(_a,{className:"size-5"}),onClick:a,"aria-label":"Move selected messages",className:"shrink-0"}),!x&&o&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(Dt,{className:"size-5"}),onClick:o,"aria-label":"Organize selected messages",className:"shrink-0"})]}),w&&r.jsx(bo,{triggerLabel:"More actions",items:R,className:"shrink-0",children:!x&&!p&&v})]}),!w&&h,w&&b&&r.jsx("div",{"data-selection-bar-row":"select-all",className:"px-row-inset pb-2 md:hidden",children:r.jsx(Vi,{selectAll:b,selecting:w,className:"w-full"})}),S&&r.jsx("div",{className:"px-row-inset pb-2",children:r.jsx(fm,{value:S.value,max:S.max,tone:S.tone})}),g&&r.jsx(gn,{"data-selection-notice":"",tone:g.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-row-inset mb-2",children:r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.text&&r.jsx("span",{children:g.text}),g.action&&r.jsx(ce,{variant:"ghost",size:"md",onClick:g.action.onClick,className:"-my-1 min-h-11 shrink-0",children:g.action.label})]})})]})}const Xx={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function Jx({search:e,onCompose:t,onReportBug:s,onOpenSettings:n,composeShortcut:a,refreshControl:o,account:i}){return r.jsx(Vg,{leading:r.jsx(Tx,{}),search:r.jsx(yo,{value:e.value,onChange:e.onChange,onClear:e.onClear,onClearQuery:e.onClearQuery,chips:e.chips,onRemoveChip:e.onRemoveChip,placeholder:Xx[e.scope]}),actions:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(jp,{className:"size-4"}),title:a?`Compose (${a})`:"Compose","aria-label":"Compose",onClick:t}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Uc,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:s}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Gc,{className:"size-4"}),title:"Settings","aria-label":"Settings",onClick:n}),o,i]})})}const jo=[{id:"all",label:"All",tone:"neutral"},{id:"personal",label:"Personal",tone:"accent"},{id:"uncategorized",label:"Unclassified",tone:"neutral"},{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"}],vu={id:"unread",label:"Unread"},Zx={id:"flagged",label:"Starred"},yu={id:"attachment",label:"Has attachment"};function eb(e){if(!(e.length<=1))return e.map(t=>({id:t.id,label:t.label,count:t.count,active:t.active}))}function tb(e=[]){return{categories:[...jo],filters:mm,sources:eb(e)}}function wu(){return{categories:[...jo],filters:[vu,Zx,yu]}}function sb(){return{categories:[...jo],filters:[vu,yu]}}const nb=["p","br","div","h1","h2","h3","h4","h5","h6","strong","b","em","i","u","s","ul","ol","li","blockquote","pre","code","hr","table","thead","tbody","tr","th","td","a","img"],rb=["href","src","alt","colspan","rowspan","lang","dir"],ab=/^(?:https?:|mailto:)/i,ob=/^(?:https:|data:image\/)/i,ib=e=>{const t=oc();if(!t.isSupported)throw new Error("adopted HTML cannot be sanitized: no DOM is available");return t.addHook("afterSanitizeAttributes",s=>{if(s.tagName==="A"){ab.test(s.getAttribute("href")??"")||s.removeAttribute("href"),e==="quoted"&&(s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer nofollow"));return}if(s.tagName==="IMG"){if(e==="quoted"){s.remove();return}ob.test(s.getAttribute("src")??"")||s.remove()}}),t},Qi=new Map,lb=e=>{const t=Qi.get(e);if(t)return t;const s=ib(e);return Qi.set(e,s),s},Su=(e,t)=>lb(t).sanitize(e,{ALLOWED_TAGS:nb,ALLOWED_ATTR:rb,ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1}),WN=e=>Su(e,"outgoing"),cb=e=>Su(e,"quoted");function wr(e){const t=[];let s=-1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];if(o==='"'){n=!n,s<0&&(s=a);continue}if(!n&&/\s/.test(o)){s>=0&&t.push({raw:e.slice(s,a),start:s,end:a}),s=-1;continue}s<0&&(s=a)}return s>=0&&t.push({raw:e.slice(s),start:s,end:e.length}),t}const ub=e=>{if(!e.startsWith('"'))return e;const t=e.slice(1);return t.endsWith('"')?t.slice(0,-1):t};function Sr(e){const t=e.indexOf(":");if(t<=0)return;const s=e.slice(t+1);return{name:e.slice(0,t).toLowerCase(),value:ub(s),rawValue:s}}const db=e=>/[\s"]/.test(e),fb=e=>db(e)?`"${e.replace(/"/g,"")}"`:e,Cr=(e,t)=>`${e}:${fb(t)}`,Cu=[{id:"unread",name:"is",value:"unread"},{id:"attachment",name:"has",value:"attachment"}],ku="category",mb={unclassified:"uncategorized"},bn=e=>wr(e).map(t=>t.raw),un=e=>e.join(" "),No=e=>{const t=Sr(e);if(t)return Cu.find(s=>s.name===t.name&&s.value===t.value.toLowerCase())?.id},Eo=e=>{const t=Sr(e);if(!t||t.name!==ku)return;const s=t.value.toLowerCase(),n=mb[s];if(n)return n;if(!(!hm(s)||s==="all"))return s},ju=e=>Cu.find(t=>t.id===e),Nu=e=>ju(e)!==void 0,hb=e=>{const t=new Set;for(const s of bn(e)){const n=No(s);n&&t.add(n)}return t},pb=e=>{let t="all";for(const s of bn(e)){const n=Eo(s);n&&(t=n)}return t},gb=(e,t)=>{const s=ju(t);if(!s)return;const n=bn(e),a=n.filter(o=>No(o)!==t);return a.length<n.length?un(a):un([...n,Cr(s.name,s.value)])},xb=(e,t)=>{const s=bn(e).filter(n=>!Eo(n));return un(t==="all"?s:[...s,Cr(ku,t)])},bb=e=>un(bn(e).filter(t=>!No(t)&&!Eo(t))),Eu=e=>e.trim().length>0,vb=e=>{if(!Eu(e.query))return e.ownFilters;const t=new Set(hb(e.query));for(const s of e.ownFilters)Nu(s)||t.add(s);return t},yb=e=>Eu(e.query)?pb(e.query):e.ownCategory,wb=e=>typeof e=="string"&&e.length>0?"rich":"plain",VN=(e,t)=>t.length>0,Sb={plain:"Couldn't switch to plain text",rich:"Couldn't switch to rich text"},QN=(e,t,s)=>t.trim()===""||s.trim()!==""?{outcome:"switch"}:{outcome:"blocked",title:Sb[e],detail:"The conversion came back empty, so your message is unchanged."};function Cb(e,t){return e.endsWith(t)?e.length===t.length||e[e.length-t.length-1]===".":!1}function kb(e,t){const s=e.length-t.length-2,n=e.lastIndexOf(".",s);return n===-1?e:e.slice(n+1)}function jb(e,t,s){if(s.validHosts!==null){const a=s.validHosts;for(const o of a)if(Cb(t,o))return o}let n=0;if(t.startsWith("."))for(;n<t.length&&t[n]===".";)n+=1;return e.length===t.length-n?null:kb(t,e)}const Xr=/[\t\n\r]/g;let ja=!1;function Gi(e){return e>=97&&e<=122||e>=48&&e<=57||e>127||e>=65&&e<=90||e===45||e===95}function Yi(e,t,s){const n=s-t,a=e.charCodeAt(t)|32;if(n===2)return a===119&&(e.charCodeAt(t+1)|32)===115?1:0;if(n===3){const o=e.charCodeAt(t+1)|32,i=e.charCodeAt(t+2)|32;return a===119&&o===115&&i===115||a===102&&o===116&&i===112?1:0}else if(n===4){const o=e.charCodeAt(t+1)|32,i=e.charCodeAt(t+2)|32,c=e.charCodeAt(t+3)|32;return a===104&&o===116&&i===116&&c===112?1:a===102&&o===105&&i===108&&c===101?2:0}else if(n===5)return a===104&&(e.charCodeAt(t+1)|32)===116&&(e.charCodeAt(t+2)|32)===116&&(e.charCodeAt(t+3)|32)===112&&(e.charCodeAt(t+4)|32)===115?1:0;return 0}function an(e,t,s=!1){let n=0,a=e.length,o=!1,i=!1;if(ja=!1,!t){if(e.startsWith("data:"))return null;for(;n<e.length&&e.charCodeAt(n)<=32;)n+=1;for(;a>n+1&&e.charCodeAt(a-1)<=32;)a-=1;if(e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47)n+=2;else{const b=e.indexOf(":/",n);if(b!==-1){const y=Yi(e,n,b);if(y===1)for(i=!0,n=b+2;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1;else if(y===2){i=!0,n=b+1;let S=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&S<2;)n+=1,S+=1;if(S<2)return null}else{for(let S=n;S<b;S+=1){const g=e.charCodeAt(S)|32;if(!(g>=97&&g<=122||g>=48&&g<=57||g===46||g===45||g===43)){const w=e.charCodeAt(S);return w===9||w===10||w===13?an(e.replace(Xr,""),t,s):null}}if(e.charCodeAt(b+2)===47)n=b+3;else return null}}else if(e.charCodeAt(n)!==91){let y=-1;for(let S=n;S<a;S+=1){const g=e.charCodeAt(S);if(g===9||g===10||g===13)return an(e.replace(Xr,""),t,s);if(g===58){y=S;break}if(g===47||g===92||g===63||g===35)break}if(y!==-1){let S=!1;for(let g=y+1;g<a;g+=1){const w=e.charCodeAt(g);if(w===47||w===92||w===63||w===35)break;if(w===64){S=!0;break}}if(!S){let g=!0,w=y+1;for(;w<a;w+=1){const C=e.charCodeAt(w);if(C===47||C===92||C===63||C===35)break;if(C<48||C>57){g=!1;break}}if(w===y+1&&(g=!1),!g){const C=Yi(e,n,y);if(C===0){let R=!1;for(let A=y+1;A<a;A+=1){const j=e.charCodeAt(A);if(j===47||j===92||j===63||j===35)break;if(j===58){R=!0;break}}if(!R)return null}else if(i=!0,n=y+1,C===2){let R=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&R<2;)n+=1,R+=1;if(R<2)return null}else for(;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1}}}}}let u=-1,m=-1,d=-1,f=-1,h=!1,v=s,x=n-1,p=-1;if(s&&n<a){const b=e.charCodeAt(n);(!(Gi(b)||b===46||b===95)||b===45)&&(v=!1)}for(let b=n;b<a;b+=1){const y=e.charCodeAt(b);if(y<64)if(y===47||y===35||y===63){a=b;break}else y===58?(f===-1&&(f=b),d=b):y===9||y===10||y===13?h=!0:s&&(y===46?((b-x>64||p===46||p===45)&&(v=!1),x=b):(y<48||y>57)&&(y!==45||p===46)&&(v=!1));else if(i&&y===92){a=b;break}else y===64?(u=b,f=-1):y===93?m=b:y>=65&&y<=90?o=!0:s&&!Gi(y)&&(v=!1);s&&(p=y)}if(h)return an(e.replace(Xr,""),t,s);if(u!==-1&&u>=n&&u<a&&(n=u+1),e.charCodeAt(n)===91)return m!==-1?e.slice(n+1,m).toLowerCase():null;if(d!==-1&&d>n&&d<a&&f===d&&(a=d),n>=a)return null;s&&v&&u===-1&&d===-1&&m===-1&&e.charCodeAt(a-1)!==46&&a-n<=255&&a-x-1<=63&&p!==45&&(ja=!0)}for(;a>n+1&&e.charCodeAt(a-1)===46;)a-=1;const c=n!==0||a!==e.length?e.slice(n,a):e;return o?c.toLowerCase():c}function Nb(e){if(e.length<7||e.length>15)return!1;let t=0;for(let s=0;s<e.length;s+=1){const n=e.charCodeAt(s);if(n===46)t+=1;else if(n<48||n>57)return!1}return t===3&&e.charCodeAt(0)!==46&&e.charCodeAt(e.length-1)!==46}function Eb(e){if(e.length<3)return!1;let t=e.startsWith("[")?1:0,s=e.length;if(e[s-1]==="]"&&(s-=1),s-t>39)return!1;let n=!1;for(;t<s;t+=1){const a=e.charCodeAt(t);if(a===58)n=!0;else if(!(a>=48&&a<=57||a>=97&&a<=102||a>=65&&a<=70))return!1}return n}function Ib(e){return Eb(e)||Nb(e)}function Xi(e){return e>=97&&e<=122||e>=48&&e<=57||e>127}function Ji(e){if(e.length>255||e.length===0||!Xi(e.charCodeAt(0))&&e.charCodeAt(0)!==46&&e.charCodeAt(0)!==95)return!1;let t=-1,s=-1;const n=e.length;for(let a=0;a<n;a+=1){const o=e.charCodeAt(a);if(o===46){if(a-t>64||s===46||s===45)return!1;t=a}else if(!(Xi(o)||o===45||o===95)||o===45&&s===46)return!1;s=o}return n-t-1<=63&&s!==45}function Rb({allowIcannDomains:e=!0,allowPrivateDomains:t=!1,detectIp:s=!0,detectSpecialUse:n=!1,extractHostname:a=!0,mixedInputs:o=!0,validHosts:i=null,validateHostname:c=!0}){return{allowIcannDomains:e,allowPrivateDomains:t,detectIp:s,detectSpecialUse:n,extractHostname:a,mixedInputs:o,validHosts:i,validateHostname:c}}const Tb=Rb({});function Mb(e){return Tb}function Ab(){return{domain:null,domainWithoutSuffix:null,hostname:null,isIcann:null,isIp:null,isPrivate:null,isSpecialUse:null,publicSuffix:null,subdomain:null}}function Ob(e){e.domain=null,e.domainWithoutSuffix=null,e.hostname=null,e.isIcann=null,e.isIp=null,e.isPrivate=null,e.isSpecialUse=null,e.publicSuffix=null,e.subdomain=null}function Db(e,t,s,n,a){const o=Mb();if(typeof e!="string")return a;let i=!1;return o.extractHostname?o.mixedInputs?(i=Ji(e),a.hostname=an(e,i,o.validateHostname)):a.hostname=an(e,!1,o.validateHostname):a.hostname=e,o.detectIp&&a.hostname!==null&&(a.isIp=Ib(a.hostname),a.isIp)?a:o.validateHostname&&o.extractHostname&&a.hostname!==null&&!(i&&a.hostname===e)&&!ja&&!Ji(a.hostname)?(a.hostname=null,a):(a.hostname===null||(s(a.hostname,o,a),a.publicSuffix===null)||(a.domain=jb(a.publicSuffix,a.hostname,o)),a)}const Zi=Ab();function Pb(e,t){return Ob(Zi),Db(e,3,pm,t,Zi).domain}const kr=e=>{const t=new Set,s=[];for(const n of e){const a=n.trim();if(a==="")continue;const o=a.toLowerCase();t.has(o)||(t.add(o),s.push(a))}return s},Lb=e=>{const t=e.lastIndexOf("@");return t>=0?e.slice(t+1):e},Iu=e=>Pb(Lb(e.trim())),Fb=e=>{const t=kr(e);if(t.length<2)return null;let s=null;for(const n of t){const a=Iu(n);if(a===null)return null;if(s===null)s=a;else if(s!==a)return null}return s},jr=e=>{const t=Fb(e);return t!==null?[{field:"FromDomain",value:t}]:kr(e).map(s=>({field:"From",value:s}))},$b=e=>{const t=new Map;for(const a of e){const o=a.normalizedEmail.trim().toLowerCase();if(o==="")continue;const i=t.get(o);i?i.count+=1:t.set(o,{sender:a,count:1})}let s,n=0;for(const{sender:a,count:o}of t.values())o<=n||(s=a,n=o);return s},Ru=e=>e.displayName?.trim()||e.normalizedEmail,_b=/^\s*(?:(?:re|aw|fwd?|vs|sv|antw|res|enc|tr)\s*(?:\[\d+\])?\s*:|\[[^\]]{1,32}\])\s*/i,zb=e=>{let t=e.replace(/\s+/g," ").trim();for(;;){const s=t.replace(_b,"");if(s===t)return t.trim();t=s}},Bb=new Set(["a","an","and","are","as","at","be","by","for","from","has","have","in","is","it","me","my","new","of","on","or","our","the","this","to","was","we","with","you","your"]),Ub=3,Jr=e=>e.split(" ").filter(t=>t!==""),el=e=>e.length===0||e.join(" ").length<Ub?!1:e.some(t=>!Bb.has(t.toLowerCase())),Kb=(e,t)=>e.findIndex((s,n)=>t.every((a,o)=>e[n+o]?.toLowerCase()===a.toLowerCase())),qb=e=>{const t=e.map(zb).filter(o=>o!=="");if(t.length===0)return;const[s,...n]=t;if(n.length===0)return el(Jr(s))?s:void 0;const a=Jr(s);for(let o=a.length;o>0;o-=1)for(let i=0;i+o<=a.length;i+=1){const c=a.slice(i,i+o);if(el(c)&&n.every(u=>Kb(Jr(u),c)>=0))return c.join(" ")}},Hb=(e,t)=>{const s=jr(e);if(kr(e).length===1||s.length===1&&s[0].field==="FromDomain")return s;const n=qb(t);return n!==void 0?[{field:"Subject",value:n}]:s},Wb=({match:e,sender:t,folder:s})=>{const n=e??t;return n?s?`${n} → ${s}`:e?`Mail matching ${e}`:`Mail from ${n}`:s?`Mail to ${s}`:""},Vb=e=>e.clauses.length>0,Qb=e=>({scopedOutFolder:e.scopedOut?.label,droppedFacets:e.droppedFacets.map(t=>t.label),droppedSemantic:e.droppedSemantic}),Gb=({orderedIds:e,isDesktop:t,initialFocusedId:s,initialSelectedIds:n,onExitSelection:a})=>{const[o,i]=l.useState(s),[c,u]=l.useState(),m=l.useCallback(M=>{u(F=>F===M?F:void 0),i(M)},[]),d=eu({initialSelectedIds:n}),{selectedCount:f,toggle:h,clearSelection:v,selectRange:x,setAnchor:p,selectAll:b}=d,y=go(f,t),S=l.useRef(null),g=l.useRef(!1),w=l.useCallback(()=>{a?.(),v()},[v,a]),C=l.useMemo(()=>o?e.indexOf(o):-1,[e,o]),R=l.useCallback(M=>{if(M<0||M>=e.length)return;const F=e[M];if(y){h(F);return}S.current=F,g.current=!1,u(F),i(F)},[e,y,h]),A=l.useCallback(()=>{e.length!==0&&R(C<0?0:Math.min(C+1,e.length-1))},[e.length,C,R]),j=l.useCallback(()=>{e.length!==0&&R(C<=0?0:C-1)},[e.length,C,R]),T=l.useCallback(()=>R(0),[R]),P=l.useCallback(()=>R(e.length-1),[R,e.length]),N=l.useCallback(()=>{o&&h(o)},[o,h]),L=l.useCallback((M,F)=>{const E=Lp(F);return E==="range"?(x(e,M,o),!0):E==="toggle"?(h(M),!0):(w(),p(M),!1)},[e,o,x,h,w,p]),D=l.useCallback(M=>{const F=Zc(e,o,M);F!==void 0&&(x(e,F),S.current=F,g.current=!1,u(void 0),i(F))},[e,o,x]),k=l.useCallback(()=>D(-1),[D]),I=l.useCallback(()=>D(1),[D]),O=l.useCallback(()=>{e.length>0&&b(e)},[e,b]);return{focusedMessageId:o,setFocusedMessageId:m,keyboardFocusedMessageId:c,focusIndex:C,pendingDomFocusRef:S,cursorMovedByPointerRef:g,selection:d,isMultiSelectMode:y,exitSelection:w,moveFocusToIndex:R,focusNext:A,focusPrevious:j,focusFirst:T,focusLast:P,toggleFocusedSelection:N,extendRangeUp:k,extendRangeDown:I,selectAllLoaded:O,handleRowSelect:L}};function Tu({handlers:e,enabled:t=!0,target:s,sequenceTimeoutMs:n=1e3}){const a=l.useRef(e);a.current=e;const o=l.useRef(null),i=l.useRef(null);l.useEffect(()=>{if(!t)return;const c=()=>{i.current!==null&&(clearTimeout(i.current),i.current=null)},u=d=>{const f=Yp({key:d.key,shiftKey:d.shiftKey,metaKey:d.metaKey,ctrlKey:d.ctrlKey,altKey:d.altKey,inEditable:Xp(d.target),onControl:Zp(d.target)},o.current);if(c(),o.current=f.nextPrefix,f.nextPrefix!==null&&(i.current=setTimeout(()=>{o.current=null,i.current=null},n)),f.action===null)return;const h=a.current[f.action];h&&(f.preventDefault&&d.preventDefault(),h())},m=s===void 0?window:s;if(m!==null)return m.addEventListener("keydown",u),()=>{m.removeEventListener("keydown",u),c(),o.current=null}},[t,n,s])}function Qt(e,t,{checkForDefaultPrevented:s=!0}={}){return function(a){if(e?.(a),s===!1||!a||!a.defaultPrevented)return t?.(a)}}function tl(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Yb(...e){return t=>{let s=!1;const n=e.map(a=>{const o=tl(a,t);return!s&&typeof o=="function"&&(s=!0),o});if(s)return()=>{for(let a=0;a<n.length;a++){const o=n[a];typeof o=="function"?o():tl(e[a],null)}}}}function ps(...e){return l.useCallback(Yb(...e),e)}function Xb(e,t=[]){let s=[];function n(o,i){const c=l.createContext(i);c.displayName=o+"Context";const u=s.length;s=[...s,i];const m=f=>{const{scope:h,children:v,...x}=f,p=h?.[e]?.[u]||c,b=l.useMemo(()=>x,Object.values(x));return r.jsx(p.Provider,{value:b,children:v})};m.displayName=o+"Provider";function d(f,h,v={}){const{optional:x=!1}=v,p=h?.[e]?.[u]||c,b=l.useContext(p);if(b)return b;if(i!==void 0)return i;if(!x)throw new Error(`\`${f}\` must be used within \`${o}\``)}return[m,d]}const a=()=>{const o=s.map(i=>l.createContext(i));return function(c){const u=c?.[e]||o;return l.useMemo(()=>({[`__scope${e}`]:{...c,[e]:u}}),[c,u])}};return a.scopeName=e,[n,Jb(a,...t)]}function Jb(...e){const t=e[0];if(e.length===1)return t;const s=()=>{const n=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(o){const i=n.reduce((c,{useScope:u,scopeName:m})=>{const f=u(o)[`__scope${m}`];return{...c,...f}},{});return l.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return s.scopeName=t.scopeName,s}var dn=globalThis?.document?l.useLayoutEffect:()=>{},Zb=Ka[" useInsertionEffect ".trim().toString()]||dn;function ev({prop:e,defaultProp:t,onChange:s=()=>{},caller:n}){const[a,o,i]=tv({defaultProp:t,onChange:s}),c=e!==void 0,u=c?e:a;{const d=l.useRef(e!==void 0);l.useEffect(()=>{const f=d.current;f!==c&&console.warn(`${n} is changing from ${f?"controlled":"uncontrolled"} to ${c?"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=c},[c,n])}const m=l.useCallback(d=>{if(c){const f=sv(d)?d(e):d;f!==e&&i.current?.(f)}else o(d)},[c,e,o,i]);return[u,m]}function tv({defaultProp:e,onChange:t}){const[s,n]=l.useState(e),a=l.useRef(s),o=l.useRef(t);return Zb(()=>{o.current=t},[t]),l.useEffect(()=>{a.current!==s&&(o.current?.(s),a.current=s)},[s,a]),[s,n,o]}function sv(e){return typeof e=="function"}function Mu(e){const t=l.forwardRef((s,n)=>{let{children:a,...o}=s,i=null,c=!1;const u=[];sl(a)&&typeof Mn=="function"&&(a=Mn(a._payload)),l.Children.forEach(a,h=>{if(iv(h)){c=!0;const v=h;let x="child"in v.props?v.props.child:v.props.children;sl(x)&&typeof Mn=="function"&&(x=Mn(x._payload)),i=rv(v,x),u.push(i?.props?.children)}else u.push(h)}),i?i=l.cloneElement(i,void 0,u):!c&&l.Children.count(a)===1&&l.isValidElement(a)&&(i=a);const m=i?ov(i):void 0,d=ps(n,m);if(!i){if(a||a===0)throw new Error(c?dv(e):uv(e));return a}const f=av(o,i.props??{});return i.type!==l.Fragment&&(f.ref=n?d:m),l.cloneElement(i,f)});return t.displayName=`${e}.Slot`,t}var nv=Symbol.for("radix.slottable"),rv=(e,t)=>{if("child"in e.props){const s=e.props.child;return l.isValidElement(s)?l.cloneElement(s,void 0,e.props.children(s.props.children)):null}return l.isValidElement(t)?t:null};function av(e,t){const s={...t};for(const n in t){const a=e[n],o=t[n];/^on[A-Z]/.test(n)?a&&o?s[n]=(...c)=>{const u=o(...c);return a(...c),u}:a&&(s[n]=a):n==="style"?s[n]={...a,...o}:n==="className"&&(s[n]=[a,o].filter(Boolean).join(" "))}return{...e,...s}}function ov(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 iv(e){return l.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===nv}var lv=Symbol.for("react.lazy");function sl(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===lv&&"_payload"in e&&cv(e._payload)}function cv(e){return typeof e=="object"&&e!==null&&"then"in e}var uv=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,dv=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Mn=Ka[" use ".trim().toString()],fv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],zt=fv.reduce((e,t)=>{const s=Mu(`Primitive.${t}`),n=l.forwardRef((a,o)=>{const{asChild:i,...c}=a,u=i?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),r.jsx(u,{...c,ref:o})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function mv(e,t){e&&qa.flushSync(()=>e.dispatchEvent(t))}function fn(e){const t=l.useRef(e);return l.useEffect(()=>{t.current=e}),l.useMemo(()=>((...s)=>t.current?.(...s)),[])}var hv="DismissableLayer",Na="dismissableLayer.update",pv="dismissableLayer.pointerDownOutside",gv="dismissableLayer.focusOutside",nl,Io=l.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Au=l.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:n=!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:c,onDismiss:u,...m}=e,d=l.useContext(Io),[f,h]=l.useState(null),v=f?.ownerDocument??globalThis?.document,[,x]=l.useState({}),p=ps(t,h),b=Array.from(d.layers),[y]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),S=y?b.indexOf(y):-1,g=f?b.indexOf(f):-1,w=d.layersWithOutsidePointerEventsDisabled.size>0,C=g>=S,R=l.useRef(!1),A=wv(N=>{o?.(N),c?.(N),N.defaultPrevented||u?.()},{ownerDocument:v,deferPointerDownOutside:n,isDeferredPointerDownOutsideRef:R,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:l.useCallback(N=>{if(!(N instanceof Node))return!1;const L=[...d.branches].some(D=>D.contains(N));return C&&!L},[d.branches,C])}),j=Sv(N=>{if(n&&R.current)return;const L=N.target;[...d.branches].some(k=>k.contains(L))||(i?.(N),c?.(N),N.defaultPrevented||u?.())},v),T=f?g===b.length-1:!1,P=fn(N=>{N.key==="Escape"&&(a?.(N),!N.defaultPrevented&&u&&(N.preventDefault(),u()))});return l.useEffect(()=>{if(T)return v.addEventListener("keydown",P,{capture:!0}),()=>v.removeEventListener("keydown",P,{capture:!0})},[v,T,P]),l.useEffect(()=>{if(f)return s&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(nl=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(f)),d.layers.add(f),rl(),()=>{s&&(d.layersWithOutsidePointerEventsDisabled.delete(f),d.layersWithOutsidePointerEventsDisabled.size===0&&(v.body.style.pointerEvents=nl))}},[f,v,s,d]),l.useEffect(()=>()=>{f&&(d.layers.delete(f),d.layersWithOutsidePointerEventsDisabled.delete(f),rl())},[f,d]),l.useEffect(()=>{const N=()=>x({});return document.addEventListener(Na,N),()=>document.removeEventListener(Na,N)},[]),r.jsx(zt.div,{...m,ref:p,style:{pointerEvents:w?C?"auto":"none":void 0,...e.style},onFocusCapture:Qt(e.onFocusCapture,j.onFocusCapture),onBlurCapture:Qt(e.onBlurCapture,j.onBlurCapture),onPointerDownCapture:Qt(e.onPointerDownCapture,A.onPointerDownCapture)})});Au.displayName=hv;var xv="DismissableLayerBranch",bv=l.forwardRef((e,t)=>{const s=l.useContext(Io),n=l.useRef(null),a=ps(t,n);return l.useEffect(()=>{const o=n.current;if(o)return s.branches.add(o),()=>{s.branches.delete(o)}},[s.branches]),r.jsx(zt.div,{...e,ref:a})});bv.displayName=xv;function vv(){const e=l.useContext(Io),[t,s]=l.useState(null);return l.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),s}var yv=()=>!0;function wv(e,t){const{ownerDocument:s=globalThis?.document,deferPointerDownOutside:n=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:o,shouldHandlePointerDownOutside:i=yv}=t,c=fn(e),u=l.useRef(!1),m=l.useRef(!1),d=l.useRef(new Map),f=l.useRef(()=>{});return l.useEffect(()=>{function h(){m.current=!1,a.current=!1,d.current.clear()}function v(){return Array.from(d.current.values()).some(Boolean)}function x(g){if(!m.current)return;const w=g.target;w instanceof Node&&[...o].some(R=>R.contains(w))||d.current.set(g.type,!0),g.type==="click"&&window.setTimeout(()=>{m.current&&f.current()},0)}function p(g){m.current&&d.current.set(g.type,!1)}const b=g=>{if(g.target&&!u.current){let w=function(){s.removeEventListener("click",f.current);const R=v();h(),R||Ou(pv,c,C,{discrete:!0})};if(!i(g.target)){s.removeEventListener("click",f.current),h(),u.current=!1;return}const C={originalEvent:g};m.current=!0,a.current=n&&g.button===0,d.current.clear(),!n||g.button!==0?w():(s.removeEventListener("click",f.current),f.current=w,s.addEventListener("click",f.current,{once:!0}))}else s.removeEventListener("click",f.current),h();u.current=!1},y=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const g of y)s.addEventListener(g,x,!0),s.addEventListener(g,p);const S=window.setTimeout(()=>{s.addEventListener("pointerdown",b)},0);return()=>{window.clearTimeout(S),s.removeEventListener("pointerdown",b),s.removeEventListener("click",f.current);for(const g of y)s.removeEventListener(g,x,!0),s.removeEventListener(g,p)}},[s,c,n,a,o,i]),{onPointerDownCapture:()=>u.current=!0}}function Sv(e,t=globalThis?.document){const s=fn(e),n=l.useRef(!1);return l.useEffect(()=>{const a=o=>{o.target&&!n.current&&Ou(gv,s,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,s]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function rl(){const e=new CustomEvent(Na);document.dispatchEvent(e)}function Ou(e,t,s,{discrete:n}){const a=s.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:s});t&&a.addEventListener(e,t,{once:!0}),n?mv(a,o):a.dispatchEvent(o)}var An=0,ws=null;function Cv(){l.useEffect(()=>{ws||(ws={start:al(),end:al()});const{start:e,end:t}=ws;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),An++,()=>{An===1&&(ws?.start.remove(),ws?.end.remove(),ws=null),An=Math.max(0,An-1)}},[])}function al(){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 Zr="focusScope.autoFocusOnMount",ea="focusScope.autoFocusOnUnmount",ol={bubbles:!1,cancelable:!0},kv="FocusScope",Du=l.forwardRef((e,t)=>{const{loop:s=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[c,u]=l.useState(null),m=fn(a),d=fn(o),f=l.useRef(null),h=ps(t,u),v=l.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;l.useEffect(()=>{if(n){let p=function(g){if(v.paused||!c)return;const w=g.target;c.contains(w)?f.current=w:Kt(f.current,{select:!0})},b=function(g){if(v.paused||!c)return;const w=g.relatedTarget;w!==null&&(c.contains(w)||Kt(f.current,{select:!0}))},y=function(g){if(document.activeElement===document.body)for(const C of g)C.removedNodes.length>0&&Kt(c)};document.addEventListener("focusin",p),document.addEventListener("focusout",b);const S=new MutationObserver(y);return c&&S.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",b),S.disconnect()}}},[n,c,v.paused]),l.useEffect(()=>{if(c){ll.add(v);const p=document.activeElement;if(!c.contains(p)){const y=new CustomEvent(Zr,ol);c.addEventListener(Zr,m),c.dispatchEvent(y),y.defaultPrevented||(jv(Tv(Pu(c)),{select:!0}),document.activeElement===p&&Kt(c))}return()=>{c.removeEventListener(Zr,m),setTimeout(()=>{const y=new CustomEvent(ea,ol);c.addEventListener(ea,d),c.dispatchEvent(y),y.defaultPrevented||Kt(p??document.body,{select:!0}),c.removeEventListener(ea,d),ll.remove(v)},0)}}},[c,m,d,v]);const x=l.useCallback(p=>{if(!s&&!n||v.paused)return;const b=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,y=document.activeElement;if(b&&y){const S=p.currentTarget,[g,w]=Nv(S);g&&w?!p.shiftKey&&y===w?(p.preventDefault(),s&&Kt(g,{select:!0})):p.shiftKey&&y===g&&(p.preventDefault(),s&&Kt(w,{select:!0})):y===S&&p.preventDefault()}},[s,n,v.paused]);return r.jsx(zt.div,{tabIndex:-1,...i,ref:h,onKeyDown:x})});Du.displayName=kv;function jv(e,{select:t=!1}={}){const s=document.activeElement;for(const n of e)if(Kt(n,{select:t}),document.activeElement!==s)return}function Nv(e){const t=Pu(e),s=il(t,e),n=il(t.reverse(),e);return[s,n]}function Pu(e){const t=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const a=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||a?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)t.push(s.currentNode);return t}function il(e,t){const s=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const n of e)if(!(s?!n.checkVisibility({checkVisibilityCSS:!0}):Ev(n,{upTo:t})))return n}function Ev(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 Iv(e){return e instanceof HTMLInputElement&&"select"in e}function Kt(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&Iv(e)&&t&&e.select()}}var ll=Rv();function Rv(){let e=[];return{add(t){const s=e[0];t!==s&&s?.pause(),e=cl(e,t),e.unshift(t)},remove(t){e=cl(e,t),e[0]?.resume()}}}function cl(e,t){const s=[...e],n=s.indexOf(t);return n!==-1&&s.splice(n,1),s}function Tv(e){return e.filter(t=>t.tagName!=="A")}var Mv=Ka[" useId ".trim().toString()]||(()=>{}),Av=0;function ta(e){const[t,s]=l.useState(Mv());return dn(()=>{s(n=>n??String(Av++))},[e]),e||(t?`radix-${t}`:"")}var Ov="Portal",Lu=l.forwardRef((e,t)=>{const{container:s,...n}=e,[a,o]=l.useState(!1);dn(()=>o(!0),[]);const i=s||a&&globalThis?.document?.body;return i?qa.createPortal(r.jsx(zt.div,{...n,ref:t}),i):null});Lu.displayName=Ov;function Dv(e,t){return l.useReducer((s,n)=>t[s][n]??s,e)}var Nr=e=>{const{present:t,children:s}=e,n=Pv(t),a=typeof s=="function"?s({present:n.isPresent}):l.Children.only(s),o=Lv(n.ref,Fv(a));return typeof s=="function"||n.isPresent?l.cloneElement(a,{ref:o}):null};Nr.displayName="Presence";function Pv(e){const[t,s]=l.useState(),n=l.useRef(null),a=l.useRef(e),o=l.useRef("none"),i=l.useRef(void 0),c=e?"mounted":"unmounted",[u,m]=Dv(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return l.useEffect(()=>{u==="mounted"?(o.current=i.current??Ys(n.current),i.current=void 0):o.current="none"},[u]),dn(()=>{const d=n.current,f=a.current;if(f!==e){const v=o.current,x=Ys(d);e?(i.current=x,m("MOUNT")):x==="none"||d?.display==="none"?m("UNMOUNT"):m(f&&v!==x?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,m]),dn(()=>{if(t){let d;const f=t.ownerDocument.defaultView??window,h=x=>{const b=Ys(n.current).includes(CSS.escape(x.animationName));if(x.target===t&&b&&(m("ANIMATION_END"),!a.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",d=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},v=x=>{x.target===t&&(o.current=Ys(n.current))};return t.addEventListener("animationstart",v),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{f.clearTimeout(d),t.removeEventListener("animationstart",v),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:l.useCallback(d=>{if(d){const f=getComputedStyle(d);n.current=f,i.current=Ys(f)}else n.current=null;s(d)},[])}}function ul(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Lv(...e){const t=l.useRef(e);return t.current=e,l.useCallback(s=>{const n=t.current;let a=!1;const o=n.map(i=>{const c=ul(i,s);return!a&&typeof c=="function"&&(a=!0),c});if(a)return()=>{for(let i=0;i<o.length;i++){const c=o[i];typeof c=="function"?c():ul(n[i],null)}}},[])}function Ys(e){return e?.animationName||"none"}function Fv(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 $v=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ss=new WeakMap,On=new WeakMap,Dn={},sa=0,Fu=function(e){return e&&(e.host||Fu(e.parentNode))},_v=function(e,t){return t.map(function(s){if(e.contains(s))return s;var n=Fu(s);return n&&e.contains(n)?n:(console.error("aria-hidden",s,"in not contained inside",e,". Doing nothing"),null)}).filter(function(s){return!!s})},zv=function(e,t,s,n){var a=_v(t,Array.isArray(e)?e:[e]);Dn[s]||(Dn[s]=new WeakMap);var o=Dn[s],i=[],c=new Set,u=new Set(a),m=function(f){!f||c.has(f)||(c.add(f),m(f.parentNode))};a.forEach(m);var d=function(f){!f||u.has(f)||Array.prototype.forEach.call(f.children,function(h){if(c.has(h))d(h);else try{var v=h.getAttribute(n),x=v!==null&&v!=="false",p=(Ss.get(h)||0)+1,b=(o.get(h)||0)+1;Ss.set(h,p),o.set(h,b),i.push(h),p===1&&x&&On.set(h,!0),b===1&&h.setAttribute(s,"true"),x||h.setAttribute(n,"true")}catch(y){console.error("aria-hidden: cannot operate on ",h,y)}})};return d(t),c.clear(),sa++,function(){i.forEach(function(f){var h=Ss.get(f)-1,v=o.get(f)-1;Ss.set(f,h),o.set(f,v),h||(On.has(f)||f.removeAttribute(n),On.delete(f)),v||f.removeAttribute(s)}),sa--,sa||(Ss=new WeakMap,Ss=new WeakMap,On=new WeakMap,Dn={})}},Bv=function(e,t,s){s===void 0&&(s="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),a=$v(e);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live], script"))),zv(n,a,s,"aria-hidden")):function(){return null}},Kn="right-scroll-bar-position",qn="width-before-scroll-bar",Uv="with-scroll-bars-hidden",Kv="--removed-body-scroll-bar-size";function na(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function qv(e,t){var s=l.useState(function(){return{value:e,callback:t,facade:{get current(){return s.value},set current(n){var a=s.value;a!==n&&(s.value=n,s.callback(n,a))}}}})[0];return s.callback=t,s.facade}var Hv=typeof window<"u"?l.useLayoutEffect:l.useEffect,dl=new WeakMap;function Wv(e,t){var s=qv(null,function(n){return e.forEach(function(a){return na(a,n)})});return Hv(function(){var n=dl.get(s);if(n){var a=new Set(n),o=new Set(e),i=s.current;a.forEach(function(c){o.has(c)||na(c,null)}),o.forEach(function(c){a.has(c)||na(c,i)})}dl.set(s,e)},[e]),s}function Vv(e){return e}function Qv(e,t){t===void 0&&(t=Vv);var s=[],n=!1,a={read:function(){if(n)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,n);return s.push(i),function(){s=s.filter(function(c){return c!==i})}},assignSyncMedium:function(o){for(n=!0;s.length;){var i=s;s=[],i.forEach(o)}s={push:function(c){return o(c)},filter:function(){return s}}},assignMedium:function(o){n=!0;var i=[];if(s.length){var c=s;s=[],c.forEach(o),i=s}var u=function(){var d=i;i=[],d.forEach(o)},m=function(){return Promise.resolve().then(u)};m(),s={push:function(d){i.push(d),m()},filter:function(d){return i=i.filter(d),s}}}};return a}function Gv(e){e===void 0&&(e={});var t=Qv(null);return t.options=qt({async:!0,ssr:!1},e),t}var $u=function(e){var t=e.sideCar,s=fc(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return l.createElement(n,qt({},s))};$u.isSideCarExport=!0;function Yv(e,t){return e.useMedium(t),$u}var _u=Gv(),ra=function(){},Er=l.forwardRef(function(e,t){var s=l.useRef(null),n=l.useState({onScrollCapture:ra,onWheelCapture:ra,onTouchMoveCapture:ra}),a=n[0],o=n[1],i=e.forwardProps,c=e.children,u=e.className,m=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,v=e.noRelative,x=e.noIsolation,p=e.inert,b=e.allowPinchZoom,y=e.as,S=y===void 0?"div":y,g=e.gapMode,w=fc(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=h,R=Wv([s,t]),A=qt(qt({},w),a);return l.createElement(l.Fragment,null,d&&l.createElement(C,{sideCar:_u,removeScrollBar:m,shards:f,noRelative:v,noIsolation:x,inert:p,setCallbacks:o,allowPinchZoom:!!b,lockRef:s,gapMode:g}),i?l.cloneElement(l.Children.only(c),qt(qt({},A),{ref:R})):l.createElement(S,qt({},A,{className:u,ref:R}),c))});Er.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Er.classNames={fullWidth:qn,zeroRight:Kn};var Xv=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Jv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Xv();return t&&e.setAttribute("nonce",t),e}function Zv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function ey(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var ty=function(){var e=0,t=null;return{add:function(s){e==0&&(t=Jv())&&(Zv(t,s),ey(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},sy=function(){var e=ty();return function(t,s){l.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},zu=function(){var e=sy(),t=function(s){var n=s.styles,a=s.dynamic;return e(n,a),null};return t},ny={left:0,top:0,right:0,gap:0},aa=function(e){return parseInt(e||"",10)||0},ry=function(e){var t=window.getComputedStyle(document.body),s=t[e==="padding"?"paddingLeft":"marginLeft"],n=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return[aa(s),aa(n),aa(a)]},ay=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return ny;var t=ry(e),s=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-s+t[2]-t[0])}},oy=zu(),Rs="data-scroll-locked",iy=function(e,t,s,n){var a=e.left,o=e.top,i=e.right,c=e.gap;return s===void 0&&(s="margin"),`
76
+ .`.concat(Uv,` {
77
+ overflow: hidden `).concat(n,`;
78
+ padding-right: `).concat(c,"px ").concat(n,`;
79
+ }
80
+ body[`).concat(Rs,`] {
81
+ overflow: hidden `).concat(n,`;
82
+ overscroll-behavior: contain;
83
+ `).concat([t&&"position: relative ".concat(n,";"),s==="margin"&&`
84
+ padding-left: `.concat(a,`px;
85
+ padding-top: `).concat(o,`px;
86
+ padding-right: `).concat(i,`px;
87
+ margin-left:0;
88
+ margin-top:0;
89
+ margin-right: `).concat(c,"px ").concat(n,`;
90
+ `),s==="padding"&&"padding-right: ".concat(c,"px ").concat(n,";")].filter(Boolean).join(""),`
91
+ }
92
+
93
+ .`).concat(Kn,` {
94
+ right: `).concat(c,"px ").concat(n,`;
95
+ }
96
+
97
+ .`).concat(qn,` {
98
+ margin-right: `).concat(c,"px ").concat(n,`;
99
+ }
100
+
101
+ .`).concat(Kn," .").concat(Kn,` {
102
+ right: 0 `).concat(n,`;
103
+ }
104
+
105
+ .`).concat(qn," .").concat(qn,` {
106
+ margin-right: 0 `).concat(n,`;
107
+ }
108
+
109
+ body[`).concat(Rs,`] {
110
+ `).concat(Kv,": ").concat(c,`px;
111
+ }
112
+ `)},fl=function(){var e=parseInt(document.body.getAttribute(Rs)||"0",10);return isFinite(e)?e:0},ly=function(){l.useEffect(function(){return document.body.setAttribute(Rs,(fl()+1).toString()),function(){var e=fl()-1;e<=0?document.body.removeAttribute(Rs):document.body.setAttribute(Rs,e.toString())}},[])},cy=function(e){var t=e.noRelative,s=e.noImportant,n=e.gapMode,a=n===void 0?"margin":n;ly();var o=l.useMemo(function(){return ay(a)},[a]);return l.createElement(oy,{styles:iy(o,!t,a,s?"":"!important")})},Ea=!1;if(typeof window<"u")try{var Pn=Object.defineProperty({},"passive",{get:function(){return Ea=!0,!0}});window.addEventListener("test",Pn,Pn),window.removeEventListener("test",Pn,Pn)}catch{Ea=!1}var Cs=Ea?{passive:!1}:!1,uy=function(e){return e.tagName==="TEXTAREA"},Bu=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!uy(e)&&s[t]==="visible")},dy=function(e){return Bu(e,"overflowY")},fy=function(e){return Bu(e,"overflowX")},ml=function(e,t){var s=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=Uu(e,n);if(a){var o=Ku(e,n),i=o[1],c=o[2];if(i>c)return!0}n=n.parentNode}while(n&&n!==s.body);return!1},my=function(e){var t=e.scrollTop,s=e.scrollHeight,n=e.clientHeight;return[t,s,n]},hy=function(e){var t=e.scrollLeft,s=e.scrollWidth,n=e.clientWidth;return[t,s,n]},Uu=function(e,t){return e==="v"?dy(t):fy(t)},Ku=function(e,t){return e==="v"?my(t):hy(t)},py=function(e,t){return e==="h"&&t==="rtl"?-1:1},gy=function(e,t,s,n,a){var o=py(e,window.getComputedStyle(t).direction),i=o*n,c=s.target,u=t.contains(c),m=!1,d=i>0,f=0,h=0;do{if(!c)break;var v=Ku(e,c),x=v[0],p=v[1],b=v[2],y=p-b-o*x;(x||y)&&Uu(e,c)&&(f+=y,h+=x);var S=c.parentNode;c=S&&S.nodeType===Node.DOCUMENT_FRAGMENT_NODE?S.host:S}while(!u&&c!==document.body||u&&(t.contains(c)||t===c));return(d&&Math.abs(f)<1||!d&&Math.abs(h)<1)&&(m=!0),m},Ln=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},hl=function(e){return[e.deltaX,e.deltaY]},pl=function(e){return e&&"current"in e?e.current:e},xy=function(e,t){return e[0]===t[0]&&e[1]===t[1]},by=function(e){return`
113
+ .block-interactivity-`.concat(e,` {pointer-events: none;}
114
+ .allow-interactivity-`).concat(e,` {pointer-events: all;}
115
+ `)},vy=0,ks=[];function yy(e){var t=l.useRef([]),s=l.useRef([0,0]),n=l.useRef(),a=l.useState(vy++)[0],o=l.useState(zu)[0],i=l.useRef(e);l.useEffect(function(){i.current=e},[e]),l.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=gm([e.lockRef.current],(e.shards||[]).map(pl),!0).filter(Boolean);return p.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var c=l.useCallback(function(p,b){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var y=Ln(p),S=s.current,g="deltaX"in p?p.deltaX:S[0]-y[0],w="deltaY"in p?p.deltaY:S[1]-y[1],C,R=p.target,A=Math.abs(g)>Math.abs(w)?"h":"v";if("touches"in p&&A==="h"&&R.type==="range")return!1;var j=window.getSelection(),T=j&&j.anchorNode,P=T?T===R||T.contains(R):!1;if(P)return!1;var N=ml(A,R);if(!N)return!0;if(N?C=A:(C=A==="v"?"h":"v",N=ml(A,R)),!N)return!1;if(!n.current&&"changedTouches"in p&&(g||w)&&(n.current=C),!C)return!0;var L=n.current||C;return gy(L,b,p,L==="h"?g:w)},[]),u=l.useCallback(function(p){var b=p;if(!(!ks.length||ks[ks.length-1]!==o)){var y="deltaY"in b?hl(b):Ln(b),S=t.current.filter(function(C){return C.name===b.type&&(C.target===b.target||b.target===C.shadowParent)&&xy(C.delta,y)})[0];if(S&&S.should){b.cancelable&&b.preventDefault();return}if(!S){var g=(i.current.shards||[]).map(pl).filter(Boolean).filter(function(C){return C.contains(b.target)}),w=g.length>0?c(b,g[0]):!i.current.noIsolation;w&&b.cancelable&&b.preventDefault()}}},[]),m=l.useCallback(function(p,b,y,S){var g={name:p,delta:b,target:y,should:S,shadowParent:wy(y)};t.current.push(g),setTimeout(function(){t.current=t.current.filter(function(w){return w!==g})},1)},[]),d=l.useCallback(function(p){s.current=Ln(p),n.current=void 0},[]),f=l.useCallback(function(p){m(p.type,hl(p),p.target,c(p,e.lockRef.current))},[]),h=l.useCallback(function(p){m(p.type,Ln(p),p.target,c(p,e.lockRef.current))},[]);l.useEffect(function(){return ks.push(o),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",u,Cs),document.addEventListener("touchmove",u,Cs),document.addEventListener("touchstart",d,Cs),function(){ks=ks.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,Cs),document.removeEventListener("touchmove",u,Cs),document.removeEventListener("touchstart",d,Cs)}},[]);var v=e.removeScrollBar,x=e.inert;return l.createElement(l.Fragment,null,x?l.createElement(o,{styles:by(a)}):null,v?l.createElement(cy,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function wy(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Sy=Yv(_u,yy);var qu=l.forwardRef(function(e,t){return l.createElement(Er,qt({},e,{ref:t,sideCar:Sy}))});qu.classNames=Er.classNames;var Cy=class extends xm{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,n=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:c}=n,u=s.fetchMeta?.fetchMore?.direction,m=i&&u==="forward",d=a&&u==="forward",f=i&&u==="backward",h=a&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:vm(t,s.data),hasPreviousPage:bm(t,s.data),isFetchNextPageError:m,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:c&&!m&&!f,isRefetching:o&&!d&&!h}}};function Hu(e,t){return ym(e,Cy)}function ky(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const s=!!(e.condition??!0),n=e.blockerFn;return{shouldBlockFn:async()=>s&&n!==void 0?await n():s,enableBeforeUnload:s,withResolver:n===void 0}}function Wu(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:a=!1,withResolver:o=!1}=ky(e),i=mc(),{history:c}=i,[u,m]=l.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return l.useEffect(()=>{const d=async f=>{function h(y){const S=i.parseLocation(y),g=i.getMatchedRoutes(S.pathname);return g.foundRoute===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:g.routeParams,search:i.options.parseSearch(y.search)}:{routeId:g.foundRoute.id,fullPath:g.foundRoute.fullPath,pathname:S.pathname,params:g.routeParams,search:i.options.parseSearch(y.search)}}const v=h(f.currentLocation),x=h(f.nextLocation);if(v.routeId==="__notFound__"&&x.routeId!=="__notFound__")return!1;const p=await s({action:f.action,current:v,next:x});if(!o)return p;if(!p)return!1;const b=await new Promise(y=>{m({status:"blocked",current:v,next:x,action:f.action,proceed:()=>y(!1),reset:()=>y(!0)})});return m({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),b};return a?void 0:c.block({blockerFn:d,enableBeforeUnload:n})},[s,n,a,o,c,i]),u}function kt(e){const t=mc({warn:e?.router===void 0}),s=e?.router||t;return wm(s.stores.__store,Sm(e,s))}const jy=()=>{const{state:e,openCompose:t}=Ft(),s=Ha(),n=l.useCallback(()=>{t({mode:"new"})},[t]),o=!!s.search?.selectedMessageId;return!s.pathname.startsWith("/mail")||e.isOpen||o?null:r.jsx("button",{type:"button",onClick:n,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:r.jsx(xh,{className:"size-6"})})},Vu=({trigger:e,children:t,align:s="right"})=>{const[n,a]=l.useState(!1),o=l.useRef(null),i=l.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),c=l.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return l.useEffect(()=>(n&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",c)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",c)}),[n,i,c]),r.jsxs("div",{ref:o,className:"relative",children:[r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!n)},className:Ve("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),n&&r.jsx("div",{className:Ve("absolute z-50 mt-1 min-w-[180px] py-1","bg-surface border border-line rounded-md shadow-lg",s==="right"?"right-0":"left-0"),children:t})]})},nn=({onClick:e,disabled:t,destructive:s,children:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:Ve("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:n}),Qu=()=>r.jsx("div",{className:"my-1 h-px bg-line"}),Gu=({children:e})=>{const{Account:t}=lr();return r.jsx(t,{children:e})},Ny=({email:e,onSignOut:t})=>{const s=e??"Account";return r.jsxs(Vu,{trigger:r.jsx(Nt,{name:s,email:e??void 0,size:"sm"}),align:"right",children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),r.jsx(Qu,{})]}),r.jsxs(nn,{onClick:t,children:[r.jsx(Wc,{className:"size-4"}),"Sign out"]})]})},Ey=()=>r.jsx(Gu,{children:({email:e,signOut:t})=>r.jsx(Ny,{email:e,onSignOut:t})}),Iy=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function Ro(e){return!!e&&Iy.has(e)}const Yu=3e3,Ry=Yu*2,gl={syncing:!1,resolved:!1,synced:0,total:0};function Ty(e,t){const s=e.join(","),[n,a]=l.useState(!1),[o,i]=l.useState(!1);l.useEffect(()=>{a(!1),i(!1)},[s,t]),l.useEffect(()=>{if(!t)return;const x=setTimeout(()=>i(!0),Ry);return()=>clearTimeout(x)},[s,t]);const c=gt({queries:e.map(x=>({...Gn({path:{accountId:x}}),enabled:t&&!n,refetchInterval:Yu,meta:{softError:!0}}))}),u=c.every(x=>x.isSuccess||x.isError),m=c.length===0||u||o;let d=!1,f=0,h=0;for(const x of c)if(Ro(x.data?.syncPhase)){d=!0;for(const p of x.data?.mailboxes??[])f+=p.messagesSynced,h+=p.messagesTotal}const v=t&&m&&!d;return l.useEffect(()=>{v&&a(!0)},[v]),!t||!m?gl:{syncing:d,resolved:!0,synced:f,total:h}}const xl=6e4,My=new Set(["sent","drafts","trash","archive"]),bl=(e,t)=>{const s=new Map;for(const n of e){const a=t.get(n.mailboxId)?.role;a&&My.has(a)||s.set(n.mailboxId,n.messagesTotal)}return s},Ay=(e,t)=>{for(const[s,n]of t)if(n>(e.get(s)??0))return!0;return!1},Xu=l.createContext(null),Ir=()=>{const e=l.useContext(Xu);if(!e)throw new Error("useMailFreshness must be used inside <MailFreshnessProvider>");return e};function Oy({accountIds:e,children:t}){const s=Pe(),{resultFolderIndex:n}=Fe(),a=l.useRef(new Map),o=l.useRef(new Set),[i,c]=l.useState(new Set),u=gt({queries:e.map(x=>({...Gn({path:{accountId:x}}),refetchInterval:xl,staleTime:xl,meta:{softError:!0}}))}),m=u.map(x=>x.dataUpdatedAt).join(","),d=e.join(",");l.useEffect(()=>{let x=!1;const p=new Set(i);e.forEach((b,y)=>{const S=u[y]?.data;if(!S)return;const g=bl(S.mailboxes??[],n);if(!o.current.has(b)){o.current.add(b),a.current.set(b,g);return}if(p.has(b))return;const w=a.current.get(b)??new Map;Ay(w,g)&&(p.add(b),x=!0)}),x&&c(p)},[d,m]);const f=l.useCallback(x=>x.some(p=>i.has(p)),[i]),h=l.useCallback(x=>{c(p=>{if(x.every(y=>!p.has(y)))return p;const b=new Set(p);for(const y of x)b.delete(y);return b});for(const p of x){const b=s.getQueryData(Gn({path:{accountId:p}}).queryKey);a.current.set(p,bl(b?.mailboxes??[],n)),o.current.add(p)}},[s,n]),v=l.useMemo(()=>({hasNewMail:f,acknowledge:h}),[f,h]);return r.jsx(Xu.Provider,{value:v,children:t})}const Dy=2e3,Py=45e3,Ly=e=>new Promise(t=>setTimeout(t,e)),Ia=e=>e instanceof Error&&e.message?e.message:"Something went wrong",Fy=e=>{pc(e,{softError:!0})&&Wa(e)},Ju=e=>e.reduce((t,s)=>Math.max(t,s.lastSyncedAt??0),0),Zu=(e,t)=>e.fetchQuery({...Gn({path:{accountId:t}}),staleTime:0}),$y=async(e,t,s,n)=>{let a=!1;for(;;){const o=await Zu(e,t).then(u=>({ok:!0,data:u})).catch(u=>({ok:!1,error:u}));if(!o.ok)return{accountId:t,message:Ia(o.error)};const{syncPhase:i,mailboxes:c}=o.data;if(Ro(i))a=!0;else if(a||Ju(c??[])>s)return i==="error"?{accountId:t,message:"Sync failed for this account"}:void 0;if(Date.now()>=n)return{accountId:t,message:"Refresh is taking longer than usual"};await Ly(Dy)}},_y=async(e,t,s,n)=>{const a=await Zu(e,s).then(c=>({ok:!0,maxLastSynced:Ju(c.mailboxes??[])})).catch(c=>({ok:!1,error:c}));if(!a.ok)return{accountId:s,enqueued:!1,ok:!1,message:Ia(a.error)};const o=await hc({path:{accountId:s},throwOnError:!0}).then(()=>({ok:!0})).catch(c=>({ok:!1,error:c}));if(!o.ok)return Fy(o.error),{accountId:s,enqueued:!1,ok:!1,message:Ia(o.error)};t.recordEvent("sync.triggered");const i=await $y(e,s,a.maxLastSynced,n);return i?{accountId:s,enqueued:!0,ok:!1,message:i.message}:{accountId:s,enqueued:!0,ok:!0}},To=(e,t={})=>{const s=Pe(),n=Ps(),{acknowledge:a}=Ir(),[o,i]=l.useState("idle"),[c,u]=l.useState(),m=l.useRef(0),d=l.useRef(e);d.current=e;const f=l.useRef(t);f.current=t,l.useEffect(()=>{if(o!=="success")return;const v=setTimeout(()=>i("idle"),2e3);return()=>clearTimeout(v)},[o]);const h=l.useCallback(()=>{const v=d.current;if(v.length===0){i("error"),u("Nothing to refresh yet");return}const x=++m.current;i("refreshing"),u(void 0),(async()=>{const p=Date.now()+Py,b=await Promise.all(v.map(g=>_y(s,n,g,p)));if(m.current!==x)return;const y=b.filter(g=>g.enqueued).map(g=>g.accountId);for(const g of y)s.invalidateQueries({queryKey:$t({path:{accountId:g}})});y.length>0&&(f.current.onSettled?.(),a(y));const S=b.filter(g=>!g.ok);S.length===0?i("success"):(i("error"),u(S[0]?.message))})()},[a,s,n]);return{state:o,errorMessage:c,refresh:h}},ed="/mail/",Mo="/mail/$mailboxId",td="/mail/outbox",sd="/mail/flagged";function Ao(e){return e.some(t=>t.routeId===ed)}function vn(e){return e.some(t=>t.routeId===sd)}function Rr(e){return e.some(t=>t.routeId===td)}function nd(e){return e.some(t=>t.routeId===Mo)}function zy(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Mo}:${t}`:vn(e)?sd:Rr(e)?td:Ao(e)?ed:""}const Hn="search-scope";function By(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function rd(e){return vn(e)||Rr(e)||nd(e)}function ad(e){return e.find(t=>t.routeId===Mo)?.params?.mailboxId}function Uy(e){const t=ad(e.matches);return t||(rd(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function Ky(e,t){return Ao(e)?{kind:"global"}:vn(e)?{kind:"scoped",chip:{id:Hn,label:"is:starred"}}:Rr(e)?{kind:"scoped",chip:{id:Hn,label:"in:outbox"}}:nd(e)?t?{kind:"scoped",chip:{id:Hn,label:By(t)}}:{kind:"pending"}:{kind:"global"}}function qy(e,t,s){return t.kind==="global"?{kind:"global"}:vn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const od=({accounts:e})=>{const t=Va({strict:!1}),s=Ha(),n=t.mailboxId,{t:a}=Qa("mail",{useSuspense:!1}),o=l.useCallback((c,u)=>a(c,{defaultValue:u}),[a]),i=gt({queries:e.map(c=>({...ft({path:{accountId:c.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!n)return null;for(let c=0;c<e.length;c++){const u=i[c]?.data?.items;if(!u)continue;const m=u.find(f=>f.mailboxId===n);if(!m)continue;const d=gc(e[c].folderAppointments);return Yn(m,d.get(n),o)}return null},Hy=({accounts:e})=>{const s=Va({strict:!1}).mailboxId,n=gt({queries:e.map(a=>({...ft({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of n){const o=a.data?.items;if(!o)continue;const i=o.find(c=>c.mailboxId===s);if(i)return i.unseenCount}return null};function id(e){const t=Je(),{searchInput:s}=Fe(),n=od({accounts:e}),a=kt({select:c=>c.matches}),o=Ky(a,n),i=l.useCallback(c=>{c===Hn&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}function Wy({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:n,onSearchClearQuery:a}=Fe(),o=Je(),{openCompose:i}=Ft(),c=l.useCallback(()=>{i({mode:"new"})},[i]),{scope:u,clearScope:m}=id(e),d=u.kind==="scoped"?[{id:u.chip.id,label:u.chip.label,tone:"scope"}]:void 0,f=l.useMemo(()=>e.map(b=>b.accountId),[e]),{hasNewMail:h}=Ir(),{state:v,errorMessage:x,refresh:p}=To(f);return r.jsx(Jx,{search:{value:t,scope:u.kind,chips:d,onChange:s,onClear:n,onClearQuery:a,onRemoveChip:m},onCompose:c,onReportBug:xc,onOpenSettings:()=>o({to:"/settings/accounts"}),composeShortcut:Jc("compose"),refreshControl:r.jsx(So,{state:v,onRefresh:p,label:"Refresh all accounts",errorMessage:x,hasUpdate:h(f)}),account:r.jsx(Ey,{})})}const Oo=({isOpen:e,onClose:t,children:s,ariaLabel:n="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=l.useRef(null),c=l.useRef(null);if(l.useEffect(()=>{if(!e)return;c.current=document.activeElement;const m=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",m),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=f,c.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return r.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":n,children:[r.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),r.jsxs("div",{ref:i,className:Ve("safe-area-frame absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[r.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:r.jsx(Et,{className:"size-5"})})}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},Vy=e=>{const t=e.filter(a=>!a.isMultipart&&a.disposition!=="attachment"&&a.mediaType==="TEXT"&&a.contentUrl.length>0),s=t.find(a=>a.mediaSubtype.toUpperCase()==="HTML");if(s)return{kind:"html",contentUrl:s.contentUrl};const n=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return n?{kind:"text",contentUrl:n.contentUrl}:null},Ra={all:["messages"],detail:e=>[...Ra.all,"detail",e],body:e=>[...Ra.detail(e),"body"]};class ls extends Error{reason;status;retryAfterSeconds;constructor(t,s,n,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=n,this.retryAfterSeconds=a}}const Qy=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},Gy=8,Yy="x-remit-403-reason",ld=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},Xy=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,Jy=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},Zy=async(e,t,s=async()=>null)=>{const n={},a=await s();a&&(n.Authorization=`Bearer ${a}`);const o=await bc(e,{headers:n});if(o.status===202)throw new ls("not-ready","Message body is still syncing",202,Qy(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(Yy),m=ld(o.status,u);throw new ls(m,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(Jy(t,i))throw new ls("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const c=await o.text();if(Xy(c,i))throw new ls("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return c},e0=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),cd=({messageId:e,bodyParts:t,enabled:s=!0})=>{const n=t?Vy(t):null,a=Ps(),{getToken:o}=lr(),i=l.useRef(null),c=Pe(),u=l.useRef(!1),m=l.useRef(null),d=e&&n?`${e}:${n.contentUrl}`:null;m.current!==d&&(m.current=d,u.current=!1);const f=Ce({queryKey:e?[...Ra.body(e),n?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!n)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const x=u.current;return u.current=!1,e0({fetchContent:(p,b)=>Zy(p,b,o),refetchDescribeMessage:()=>c.refetchQueries({queryKey:Ga({path:{messageId:e}})})},{contentUrl:n.contentUrl,kind:n.kind,isRetryAfterNotReady:x})},enabled:s&&!!e&&!!n,staleTime:300*1e3,gcTime:1800*1e3,retry:(x,p)=>p instanceof ls&&p.reason==="not-ready"?x<Gy:x<1,retryDelay:(x,p)=>p instanceof ls&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=f.isLoading&&!!n;l.useEffect(()=>{h&&(i.current=performance.now())},[h]),l.useEffect(()=>{f.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[f.isSuccess,a]);const v=f.data&&n?{kind:n.kind,body:f.data}:void 0;return{picked:n,data:v,isLoading:h,isError:f.isError,error:f.error,refetch:f.refetch}},t0=e=>e.then(()=>{},()=>{}),s0=({outboxMessageId:e,onDraftCreated:t})=>{const[s,n]=l.useState("idle"),[a,o]=l.useState(null),i=l.useRef(void 0),c=l.useRef(new Set),u=Pe(),m=l.useRef(e),d=l.useRef(e);m.current!==e&&(m.current=e,d.current=e);const f=Ue(Cm()),h=Ue(km()),v=l.useCallback(async g=>{n("saving"),o(null);const w=d.current;if(w){const R=await h.mutateAsync({path:{outboxMessageId:w},body:{toAddresses:g.toAddresses,ccAddresses:g.ccAddresses,bccAddresses:g.bccAddresses,subject:g.subject,textBody:g.textBody,htmlBody:g.htmlBody,inReplyTo:g.inReplyTo,references:g.references}});return n("saved"),R}const C=await f.mutateAsync({body:{...g,sendImmediately:!1}});return d.current=C.outboxMessageId,t(C.outboxMessageId),n("saved"),u.invalidateQueries({queryKey:cr().queryKey}),C},[f,h,t,u]),x=l.useRef(Promise.resolve()),p=l.useCallback(g=>{const w=x.current.then(()=>v(g));return x.current=t0(w),w},[v]),b=l.useCallback(g=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{const w=d.current;w&&c.current.has(w)||p(g).catch(C=>{o(C),n("error")})},2e3)},[p]),y=l.useCallback(g=>(i.current&&clearTimeout(i.current),p(g).then(w=>({outcome:"saved",outboxMessageId:w.outboxMessageId})).catch(w=>(n("error"),{outcome:"failed",error:w}))),[p]),S=l.useCallback(g=>{i.current&&clearTimeout(i.current),g&&c.current.add(g)},[]);return{saveStatus:s,saveError:a,saveDraft:b,saveImmediately:y,stopAutoSave:S}},oa=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=l.useState(""),i=gr(a,200),{data:c}=Ce({...ur({query:{q:i,limit:8}}),enabled:i.length>=2}),u=l.useMemo(()=>(c?.items??[]).map(m=>({email:m.normalizedEmail,displayName:m.displayName})),[c]);return r.jsx(dx,{label:e,addresses:t,onChange:s,placeholder:n,suggestions:u,onQueryChange:o})},n0=({accountId:e})=>{const t=Je();return r.jsx(px,{onConfigure:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})}})},vl=150,r0=()=>{const[e,t]=l.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>vl}});return l.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>vl})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},a0=({selectedAccountId:e,onSelect:t})=>{const{data:s}=Ce({..._t(),staleTime:1/0}),n=s?.accounts??[];if(l.useEffect(()=>{!e&&n.length===1&&n[0]&&t(n[0])},[e,n,t]),n.length<=1){const a=n[0];return a?r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=n.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:n.map(a=>r.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},o0=l.lazy(()=>Rm(()=>import("./rich-text-CK9ku6ou.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}))),i0=()=>r.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[r.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),r.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),l0=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),c0=e=>e.split(`
116
+ `).map(t=>`<p>${l0(t)}</p>`).join(""),yl=e=>e?`<p></p><p>-- </p>${c0(e)}`:"",u0=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",d0=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",f0=(e,t,s)=>{const{envelope:n}=e,o=(n.replyTo.length>0?n.replyTo:n.from).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),c=new Set(o.map(m=>m.email.toLowerCase())),u=[...n.to,...n.cc].filter(m=>m.normalizedEmail.toLowerCase()!==i&&!c.has(m.normalizedEmail.toLowerCase())).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));return{to:o,cc:u}},m0=e=>{const t=e.envelope.messageIdValue,n=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!n.includes(t)&&n.push(t),{inReplyTo:t,references:n}},wl=(e,t,s)=>({textBody:t.text||void 0,htmlBody:e==="plain"?"":t.html?Im(t.html,s):void 0}),h0=(e,t,s,n,a)=>e.length===0&&t.length===0&&s.length===0&&n.trim()===""&&a.text.trim()==="",p0=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:n,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:c,showCc:u,setShowCc:m,showBcc:d,setShowBcc:f,subject:h,setSubject:v})=>{const x=es(),{isKeyboardOpen:p}=r0();return r.jsx(hx,{collapsed:!x&&p,summary:mx({to:s,cc:a,bcc:i,subject:h}),from:r.jsx(a0,{selectedAccountId:e,onSelect:t}),to:r.jsx(oa,{label:"To",addresses:s,onChange:n,placeholder:"Recipients"}),cc:u?r.jsx(oa,{label:"Cc",addresses:a,onChange:o}):void 0,bcc:d?r.jsx(oa,{label:"Bcc",addresses:i,onChange:c}):void 0,subject:r.jsx(gx,{value:h,onChange:v}),onShowCc:()=>m(!0),onShowBcc:()=>f(!0)})},Do=({mode:e,account:t,sourceMessage:s,onClose:n,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:c}=Ft(),{pushError:u}=st(),{outboxMessageId:m}=o,[d,f]=l.useState([]),[h,v]=l.useState([]),[x,p]=l.useState([]),[b,y]=l.useState(""),[S,g]=l.useState(!1),[w,C]=l.useState(!1),[R,A]=l.useState(t?.accountId),[j,T]=l.useState(!1),P=l.useRef(m);l.useEffect(()=>{const xe=P.current;xe!==m&&(P.current=m,!(!m||xe===void 0)&&(f([]),v([]),p([]),y(""),g(!1),C(!1),I(""),M(""),E("rich"),ae(void 0),oe(Yx),D(ke=>ke+1),T(!1)))},[m]);const{signature:N}=Sh(R),[L,D]=l.useState(0),[k,I]=l.useState(()=>yl(N.plainText)),[O,M]=l.useState(N.plainText),[F,E]=l.useState("rich"),[V,X]=l.useState("en"),[Z,ae]=l.useState(),[ie,oe]=l.useState(()=>({html:yl(N.plainText),text:N.plainText,formatting:[]})),{data:ue}=Ce({...jm({path:{outboxMessageId:m??""}}),enabled:!!m&&!j});l.useEffect(()=>{if(!ue||j)return;f(ue.toAddresses.map($=>({email:$,displayName:void 0}))),ue.ccAddresses&&ue.ccAddresses.length>0&&(v(ue.ccAddresses.map($=>({email:$,displayName:void 0}))),g(!0)),ue.bccAddresses&&ue.bccAddresses.length>0&&(p(ue.bccAddresses.map($=>({email:$,displayName:void 0}))),C(!0)),ue.subject&&y(ue.subject);const xe=Nm(ue.htmlBody??""),ke=xe.html,Te=ue.textBody??"";E(wb(ue.htmlBody)),ae(xe.language??void 0),I(ke),M(Te),oe({html:ke,text:Te,formatting:[]}),D($=>$+1),A(ue.accountId),T(!0)},[ue,j]),l.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:xe,cc:ke}=f0(s,e,t?.email);f(xe),v(ke),ke.length>0&&g(!0),y(u0(s.envelope.subject))}e==="forward"&&y(d0(s.envelope.subject))}},[e,s,t?.email]);const ge=e==="reply"||e==="reply_all"||e==="forward",{data:B}=cd({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:ge&&!!s}),U=B?.kind==="text"?B.body:"",he=B?.kind==="html"?cb(B.body):void 0,me=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,se=l.useCallback(xe=>{T(!0),i(xe)},[i]),{saveStatus:we,saveError:K,saveDraft:Ee,saveImmediately:be,stopAutoSave:je}=s0({outboxMessageId:m,onDraftCreated:se});l.useEffect(()=>{K&&u({title:"Couldn't save draft",detail:dt(K)??"Saving the draft failed.",error:K})},[K,u]);const fe=Ue(vc()),ne=Ue({...dr(),onError:xe=>{u(us("Couldn't discard draft","The draft wasn't discarded.",xe))}}),{data:Se}=Ce({..._t(),staleTime:1/0}),Le=Se?.accounts.find(xe=>xe.accountId===R),ze=Le?yh(Le):!1,J=Le?.composeLanguages,Ze=l.useMemo(()=>J&&J.length>0?J:Em(navigator.languages),[J]),Ie=l.useRef(!1),[qe,q]=l.useState(!1),Qe=d.length>0&&!!R&&!ze;l.useEffect(()=>{if(!R||m&&!j||h0(d,h,x,b,ie))return;const{htmlBody:xe,textBody:ke}=wl(F,ie,V);Ee({accountId:R,toAddresses:d.map(Te=>Te.email),ccAddresses:h.length>0?h.map(Te=>Te.email):void 0,bccAddresses:x.length>0?x.map(Te=>Te.email):void 0,subject:b||void 0,textBody:ke,htmlBody:xe})},[R,m,j,d,h,x,b,ie,F,V,Ee]);const Re=l.useCallback(async()=>{if(!Ie.current&&!(!R||d.length===0)){Ie.current=!0,q(!0);try{je();const xe=s&&(e==="reply"||e==="reply_all")?m0(s):{},{htmlBody:ke,textBody:Te}=wl(F,ie,V),$=!m,le=await be({accountId:R,toAddresses:d.map(H=>H.email),ccAddresses:h.length>0?h.map(H=>H.email):void 0,bccAddresses:x.length>0?x.map(H=>H.email):void 0,subject:b||void 0,textBody:Te,htmlBody:ke,...xe});if(le.outcome==="failed"){u({title:"Couldn't send message",detail:dt(le.error)??"Saving the message failed, so nothing was sent. Try again.",error:le.error});return}const de=le.outboxMessageId;if(await fe.mutateAsync({path:{outboxMessageId:de}}).catch(H=>(u({title:"Couldn't send message",detail:dt(H)??($?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:H}),null))===null)return;je(de),c(de),n()}finally{Ie.current=!1,q(!1)}}},[R,d,h,x,b,ie,F,V,e,s,m,be,fe,je,c,u,n]),ve=l.useCallback(()=>{je(m),m&&ne.mutate({path:{outboxMessageId:m}}),n()},[je,m,ne,n]),Oe=l.useCallback(xe=>{A(xe.accountId),a?.(xe)},[a]);return r.jsx(fx,{banner:Le&&ze?r.jsx(n0,{accountId:Le.accountId}):void 0,header:r.jsx(p0,{selectedAccountId:R,onAccountChange:Oe,toAddresses:d,setToAddresses:f,ccAddresses:h,setCcAddresses:v,bccAddresses:x,setBccAddresses:p,showCc:S,setShowCc:g,showBcc:w,setShowBcc:C,subject:b,setSubject:y}),quoted:U||he?r.jsx(Lx,{text:U,html:he,senderName:me}):void 0,actionBar:r.jsx(lx,{onSend:Re,onDiscard:ve,sending:qe,canSend:Qe,saveStatus:we,unavailableReason:ze?"SMTP not configured":void 0,onUnavailable:xe=>u({title:"Can't send yet",detail:xe})}),children:r.jsx(l.Suspense,{fallback:r.jsx(i0,{}),children:r.jsx(o0,{mode:F,onModeChange:E,initialHtml:k,initialText:O,onChange:oe,onSubmit:Re,autoFocus:e==="new",onConversionError:u,languages:Ze,initialLanguage:Z,onLanguageChange:X},L)})})},Sl=({mode:e,account:t,sourceMessage:s,onClose:n})=>r.jsx("div",{className:"border-t border-line bg-canvas max-h-[min(400px,60dvh)] flex flex-col",children:r.jsx(Do,{mode:e,account:t,sourceMessage:s,onClose:n})}),ud=({message:e,icon:t})=>r.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&r.jsx("div",{className:"mb-4 text-fg-muted",children:t}),r.jsx("p",{className:"text-fg-muted",children:e})]}),Po=({enabled:e=!0,bindings:t,capture:s=!1})=>{const n=l.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const m=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(m&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);l.useEffect(()=>{if(e)return window.addEventListener("keydown",n,s),()=>window.removeEventListener("keydown",n,s)},[e,n,s])},Lo=e=>{const{data:t,isLoading:s}=Ce({..._t(),staleTime:1/0}),n=l.useMemo(()=>(t?.accounts??[]).map(c=>c.accountId),[t?.accounts]),a=gt({queries:n.map(c=>({...ft({path:{accountId:c}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(c=>c.isLoading);return{accountId:l.useMemo(()=>{if(e){for(let c=0;c<n.length;c++)if((a[c].data?.items??[]).some(d=>d.mailboxId===e))return n[c]}},[e,n,a]),isLoading:o}},g0=100,Ta=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),x0=(e,t=g0)=>{if(e.length===0)return[];const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s},dd=async(e,t,s,n)=>{const a=x0(e),o=e.length;let i=0;const c=[];for(let u=0;u<a.length;u++){if(n())return c.push(...a.slice(u).flat()),{done:i,failedIds:c,cancelled:!0};const m=a[u],d=await Ta(t(m));if(!d.ok)return c.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:c,cancelled:!1,error:d.error};i+=m.length,s({done:i,total:o})}return{done:i,failedIds:c,cancelled:!1}},As=async(e,t)=>{await dd(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},b0=async(e,t,s,n,a)=>{let o=0;const i=[];let c;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await Ta(e(c));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const m=u.value;if(m.ids.length>0){const d=await Ta(s(m.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=m.ids.length,n({done:o,total:t})}c=m.continuationToken}while(c);return{done:o,failedIds:i,cancelled:!1}},v0=e=>({done:e.done,total:Math.max(e.total,e.done)}),fd=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),md=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),hd=(e,t)=>e===void 0?e:fd(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:md(e)?{...e,items:t(e.items)}:e,It=e=>{const t=[];for(const s of new Set(e))t.push(fr({path:{mailboxId:s}})),t.push(Ya({path:{mailboxId:s}}));return t.push(Xa()),t},yn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),wn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,n])=>({queryKey:s,data:n})),Sn=(e,t,s)=>{const n=a=>hd(a,s);for(const a of t)e.setQueriesData({queryKey:a},n)},Cn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},Rt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},y0=3e3,w0=(e,t,s)=>{if(e.length===0)return()=>{};const n=setTimeout(()=>s(e),t);return()=>clearTimeout(n)},Tr=(e,t,s)=>{const n=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(n.get(o)??s);return[...a]},tr=(e,t,s)=>e.map(n=>t.has(n.messageId)?{...n,isRead:s}:n),S0=(e,t,s,n)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!n.has(a.messageId)).map(a=>a.messageId),C0=({messages:e,expandedIds:t,threadId:s,mailboxId:n,accountId:a})=>{const o=Pe(),{pushError:i}=st(),c=l.useRef(new Set),u=l.useRef(new Set),{mutate:m}=Ue({...mr(),onMutate:async h=>{const v=new Set(h.body.messageIds??[]),x=h.body.isRead??!0,p=Zt({path:{threadId:s}}),b=It(Tr(v,e,n));await Promise.all([o.cancelQueries({queryKey:p}),yn(o,b)]);const y=o.getQueriesData({queryKey:p}).filter(g=>g[1]!==void 0).map(([g,w])=>({queryKey:g,data:w})),S=wn(o,b);return o.setQueriesData({queryKey:p},g=>g&&{...g,items:tr(g.items,v,x)}),Sn(o,b,g=>tr(g,v,x)),{threadMessagesPrefix:p,listPrefixes:b,previousThreadMessages:y,previousThreadsList:S}},onSuccess:(h,v)=>{const x=v.body.messageIds??[];for(const p of x)c.current.add(p),u.current.delete(p)},onError:(h,v,x)=>{const p=v.body.messageIds??[];for(const y of p)u.current.delete(y);if(x){for(const y of x.previousThreadMessages)o.setQueryData(y.queryKey,y.data);Cn(o,x.previousThreadsList)}const b=v.body.isRead??!0;i({title:b?"Couldn't mark as read":"Couldn't mark as unread",detail:dt(h),error:h})},onSettled:(h,v,x,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),Rt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:$t({path:{accountId:a}})}))}}),d=l.useCallback(h=>{const v=h.filter(x=>!c.current.has(x)&&!u.current.has(x));if(v.length!==0){for(const x of v)u.current.add(x);m({body:{messageIds:v,isRead:!0}})}},[m]),f=l.useMemo(()=>S0(e,t,c.current,u.current),[e,t]);l.useEffect(()=>w0(f,y0,d),[f,d]),l.useEffect(()=>{c.current.clear(),u.current.clear()},[s])},Mr=e=>{const{mailboxId:t,accountId:s,messages:n}=e,a=Pe(),{pushError:o}=st(),{mutateAsync:i,isPending:c}=Ue({...mr(),onError:(m,d)=>{const f=d.body.isRead??!0;o({title:f?"Couldn't mark as read":"Couldn't mark as unread",detail:dt(m),error:m})},onSettled:(m,d,f)=>{Rt(a,It(Tr(f.body.messageIds??[],n??[],t))),s&&a.invalidateQueries({queryKey:$t({path:{accountId:s}})})}});return{toggleReadFor:l.useCallback((m,d)=>{m.length!==0&&As(m,f=>i({body:{messageIds:f,isRead:d}}))},[i]),isPending:c}},k0=60,j0=1.5,N0=(e,t,s)=>{const n=Math.abs(e),a=Math.abs(t);return n<s?{direction:null}:n<a*j0?{direction:null}:{direction:e<0?"left":"right"}},E0=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=k0})=>{const n=l.useRef(null),a=l.useCallback(u=>{if(u.pointerType==="mouse"){n.current=null;return}n.current={x:u.clientX,y:u.clientY}},[]),o=l.useCallback(()=>{},[]),i=l.useCallback(u=>{const m=n.current;if(n.current=null,!m)return;const{direction:d}=N0(u.clientX-m.x,u.clientY-m.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),c=l.useCallback(()=>{n.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:c}}},I0=(e,t,s)=>t?.find(n=>n.messageId===e)?.mailboxId??s,Cl=(e,t,s)=>e.map(n=>n.messageId===t?{...n,hasStars:s}:n),Fo=({threadId:e,mailboxId:t,messages:s})=>{const n=Pe(),{pushError:a}=st(),{mutate:o,isPending:i,variables:c}=Ue({...Tm(),onMutate:async m=>{const d=m.path.messageId,f=m.body.isStarred??!1,h=Zt({path:{threadId:e}}),v=It([I0(d,s,t)]);await Promise.all([n.cancelQueries({queryKey:h}),yn(n,v)]);const x=n.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})),p=wn(n,v);return n.setQueriesData({queryKey:h},b=>hd(b,y=>Cl(y,d,f))),Sn(n,v,b=>Cl(b,d,f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:x,previousThreadsList:p}},onError:(m,d,f)=>{if(f){for(const v of f.previousThreadMessages)n.setQueryData(v.queryKey,v.data);Cn(n,f.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:dt(m),error:m})},onSettled:(m,d,f,h)=>{h&&(n.invalidateQueries({queryKey:h.threadMessagesPrefix}),Rt(n,h.listPrefixes))}});return{toggleStar:(m,d)=>{o({path:{messageId:m},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?c?.path.messageId:void 0}};function Ar(e){return e===void 0?"uncategorized":e}const R0={inbox:"Inbox",junk:"Junk"},$o=e=>e.destinationMailboxId!==void 0,T0=(e,t)=>{if($o(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${R0[s]??"another folder"} by Remit`},M0=(e,t)=>{if(e===ui.MoveToInbox)return t.inboxMailboxId;if(e===ui.MoveToJunk)return t.junkMailboxId},A0=(e,t,s)=>{if(!e||!t)return!1;const n=$o(e)?e.destinationMailboxId:M0(e.action,s);return n!==void 0&&n===t},O0="Reported as spam",D0=(e,t)=>{if(e){if($o(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},Or=(e,t)=>{const{data:s,isLoading:n}=Ce({..._t(),staleTime:1/0,enabled:!!e});return{mailboxId:l.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:n}},P0=e=>{const{mailboxId:t,isLoading:s}=Or(e,"Archive");return{archiveMailboxId:t,isLoading:s}},L0=e=>{const{mailboxId:t,isLoading:s}=Or(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},pd=e=>{const{mailboxId:t,isLoading:s}=Or(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},kn=e=>{const{mailboxId:t,isLoading:s}=Or(e,"Junk");return{junkMailboxId:t,isLoading:s}},_o=e=>{const{data:t}=Ce({..._t(),staleTime:1/0,enabled:!!e});return l.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},kl=(e,t)=>e.filter(s=>!t.has(s.messageId)),Os=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=Pe(),{pushError:o}=st(),{mutateAsync:i,isPending:c,isError:u}=Ue({...Mm(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],v=It([e,d.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:h})]:[],yn(a,v)]);const x=t?a.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})):[],p=wn(a,v);return t&&a.setQueriesData({queryKey:h},b=>b&&{...b,items:kl(b.items,f)}),Sn(a,v,b=>kl(b,f)),n?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:x,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const x of h.previousThreadMessages)a.setQueryData(x.queryKey,x.data);Cn(a,h.previousThreadsList)}const v=f.body.messageIds?.length??0;o({title:v>1?`Couldn't move ${v} messages`:"Couldn't move this message",detail:dt(d),error:d})},onSettled:(d,f,h,v)=>{v&&(t&&a.invalidateQueries({queryKey:v.threadMessagesPrefix}),Rt(a,v.listPrefixes),s&&a.invalidateQueries({queryKey:$t({path:{accountId:s}})}))}});return{moveMessages:l.useCallback((d,f)=>{d.length!==0&&As(d,h=>i({body:{messageIds:h,destinationMailboxId:f}}))},[i]),isPending:c,isError:u}},F0="This message could not be processed. Please try again.",$0=(e,t)=>e.replace(`Message ${t}'s`,"This message's"),jl=e=>{if(e.failureCount===0)return;const t=e.failures?.[0],s=t?.reason??F0,n=t?$0(s,t.messageId):s;throw new Dm(n,422)};function gd({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n}){const a=Pe(),{pushError:o}=st(),i=It([e]),c=t?Zt({path:{threadId:t}}):[],u=()=>{t&&a.invalidateQueries({queryKey:c}),Rt(a,i),s&&a.invalidateQueries({queryKey:$t({path:{accountId:s}})})},m=()=>(p,b)=>{u(),n?.(b.body.messageIds)},d=p=>(b,y)=>{o({title:p(y.body.messageIds.length),detail:dt(b),error:b})},f=Ue({mutationFn:async p=>{const{data:b}=await Am({...p,throwOnError:!0});return jl(b),b},meta:{softError:!0},onSuccess:m(),onError:d(p=>p>1?`Couldn't report ${p} messages as spam`:"Couldn't report this message as spam")}),h=Ue({mutationFn:async p=>{const{data:b}=await Om({...p,throwOnError:!0});return jl(b),b},meta:{softError:!0},onSuccess:m(),onError:d(p=>p>1?`Couldn't undo the spam report for ${p} messages`:"Couldn't undo the spam report")}),v=l.useCallback(p=>{p.length!==0&&As(p,b=>f.mutateAsync({body:{messageIds:b}}))},[f.mutateAsync]),x=l.useCallback(p=>{p.length!==0&&As(p,b=>h.mutateAsync({body:{messageIds:b}}))},[h.mutateAsync]);return{reportSpam:v,notSpam:x,isReporting:f.isPending,isRestoring:h.isPending}}const _0=({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o})=>{const{inboxMailboxId:i}=pd(e),{junkMailboxId:c}=kn(e),{moveMessages:u,isPending:m}=Os({mailboxId:n,threadId:s,accountId:e}),{notSpam:d,isRestoring:f}=gd({mailboxId:n,threadId:s,accountId:e}),{data:h}=Ce({...ft({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),v={inboxMailboxId:i,junkMailboxId:c},x=D0(a,v),p=l.useCallback(()=>{x&&u([t],x)},[u,t,x]),b=l.useCallback(()=>{d([t])},[d,t]);if(o)return{show:!0,label:O0,onUndo:b,isUndoing:f};if(!A0(a,n,v)||!a)return{show:!1,label:"",isUndoing:!1};const S=a.fromMailboxId?h?.items.filter(g=>g.mailboxId===a.fromMailboxId).map(g=>xa(g.fullPath))[0]:void 0;return{show:!0,label:T0(a,S),onUndo:x?p:void 0,isUndoing:m,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function z0({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o}){const i=_0({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o});return i.show?r.jsx(nx,{label:i.label,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:i.filtersHref}):null}const Nl=(e,t)=>e.filter(s=>!t.has(s.messageId)),B0=e=>e.filter(t=>t.isDeleted!==!0),fs=({mailboxId:e,threadId:t,accountId:s,messages:n,onAfterOptimisticRemove:a})=>{const o=Pe(),{pushError:i}=st(),{mutateAsync:c,isPending:u}=Ue({...Pm(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],v=It(Tr(f,n??[],e));await Promise.all([o.cancelQueries({queryKey:h}),yn(o,v)]);const x=t?o.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})):[],p=wn(o,v);return t&&o.setQueriesData({queryKey:h},b=>b&&{...b,items:Nl(b.items,f)}),Sn(o,v,b=>Nl(b,f)),a?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:x,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const x of h.previousThreadMessages)o.setQueryData(x.queryKey,x.data);Cn(o,h.previousThreadsList)}const v=f.body.messageIds?.length??0;i({title:v>1?`Couldn't delete ${v} messages`:"Couldn't delete this message",detail:dt(d),error:d})},onSettled:(d,f,h,v)=>{v&&(t&&o.invalidateQueries({queryKey:v.threadMessagesPrefix}),Rt(o,v.listPrefixes),s&&o.invalidateQueries({queryKey:$t({path:{accountId:s}})}))}});return{deleteMessages:l.useCallback(d=>{d.length!==0&&As(d,f=>c({body:{messageIds:f}}))},[c]),isPending:u}},xd=(e,t=Date.now())=>({value:e,setAt:t}),U0=(e,t,s,n)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=xd(!0,n):delete a.trusted,{...e,flags:a}},K0=(e,t,s,n)=>{const a=o=>o.map(i=>U0(i,t,s,n));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},zo=({messageId:e})=>{const t=Pe(),{pushError:s}=st(),{mutate:n,isPending:a,error:o,reset:i}=Ue({...yc(),onMutate:async u=>{const m=u.path.addressId,f=u.body.flags?.trusted?.value===!0,h=Ga({path:{messageId:e}});await t.cancelQueries({queryKey:h});const v=t.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,p])=>({queryKey:x,data:p}));return t.setQueriesData({queryKey:h},x=>x&&K0(x,m,f)),{describePrefix:h,previous:v}},onError:(u,m,d)=>{if(d)for(const f of d.previous)t.setQueryData(f.queryKey,f.data);s(us("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,m,d,f)=>{f&&t.invalidateQueries({queryKey:f.describePrefix})}});return{toggleTrusted:(u,m)=>{n({path:{addressId:u},body:{flags:{trusted:xd(!m)}}})},isPending:a,error:o,reset:i}};var Dr="Dialog",[bd]=Xb(Dr),[q0,bt]=bd(Dr),vd=e=>{const{__scopeDialog:t,children:s,open:n,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,c=l.useRef(null),u=l.useRef(null),[m,d]=ev({prop:n,defaultProp:a??!1,onChange:o,caller:Dr});return r.jsx(q0,{scope:t,triggerRef:c,contentRef:u,contentId:ta(),titleId:ta(),descriptionId:ta(),open:m,onOpenChange:d,onOpenToggle:l.useCallback(()=>d(f=>!f),[d]),modal:i,children:s})};vd.displayName=Dr;var yd="DialogTrigger",H0=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=bt(yd,s),o=ps(t,a.triggerRef);return r.jsx(zt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Uo(a.open),...n,ref:o,onClick:Qt(e.onClick,a.onOpenToggle)})});H0.displayName=yd;var Bo="DialogPortal",[W0,wd]=bd(Bo,{forceMount:void 0}),Sd=e=>{const{__scopeDialog:t,forceMount:s,children:n,container:a}=e,o=bt(Bo,t);return r.jsx(W0,{scope:t,forceMount:s,children:l.Children.map(n,i=>r.jsx(Nr,{present:s||o.open,children:r.jsx(Lu,{asChild:!0,container:a,children:i})}))})};Sd.displayName=Bo;var sr="DialogOverlay",Cd=l.forwardRef((e,t)=>{const s=wd(sr,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=bt(sr,e.__scopeDialog);return o.modal?r.jsx(Nr,{present:n||o.open,children:r.jsx(Q0,{...a,ref:t})}):null});Cd.displayName=sr;var V0=Mu("DialogOverlay.RemoveScroll"),Q0=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=bt(sr,s),o=vv(),i=ps(t,o);return r.jsx(qu,{as:V0,allowPinchZoom:!0,shards:[a.contentRef],children:r.jsx(zt.div,{"data-state":Uo(a.open),...n,ref:i,style:{pointerEvents:"auto",...n.style}})})}),Ds="DialogContent",kd=l.forwardRef((e,t)=>{const s=wd(Ds,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=bt(Ds,e.__scopeDialog);return r.jsx(Nr,{present:n||o.open,children:o.modal?r.jsx(G0,{...a,ref:t}):r.jsx(Y0,{...a,ref:t})})});kd.displayName=Ds;var G0=l.forwardRef((e,t)=>{const s=bt(Ds,e.__scopeDialog),n=l.useRef(null),a=ps(t,s.contentRef,n);return l.useEffect(()=>{const o=n.current;if(o)return Bv(o)},[]),r.jsx(jd,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Qt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Qt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&o.preventDefault()}),onFocusOutside:Qt(e.onFocusOutside,o=>o.preventDefault())})}),Y0=l.forwardRef((e,t)=>{const s=bt(Ds,e.__scopeDialog),n=l.useRef(!1),a=l.useRef(!1);return r.jsx(jd,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(n.current||s.triggerRef.current?.focus(),o.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),jd=l.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,c=bt(Ds,s);return Cv(),r.jsx(r.Fragment,{children:r.jsx(Du,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:r.jsx(Au,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":Uo(c.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})}),Nd="DialogTitle",Ed=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=bt(Nd,s);return r.jsx(zt.h2,{id:a.titleId,...n,ref:t})});Ed.displayName=Nd;var Id="DialogDescription",X0=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=bt(Id,s);return r.jsx(zt.p,{id:a.descriptionId,...n,ref:t})});X0.displayName=Id;var Rd="DialogClose",J0=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=bt(Rd,s);return r.jsx(zt.button,{type:"button",...n,ref:t,onClick:Qt(e.onClick,()=>a.onOpenChange(!1))})});J0.displayName=Rd;function Uo(e){return e?"open":"closed"}function Z0(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 Td=W.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),jn=()=>{const e=W.useContext(Td);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};Z0(`[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
+ [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 ew(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function tw(){return Ko(/^Mac/)}function sw(){return Ko(/^iPhone/)}function El(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function nw(){return Ko(/^iPad/)||tw()&&navigator.maxTouchPoints>1}function Md(){return sw()||nw()}function Ko(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const rw=24,aw=typeof window<"u"?l.useLayoutEffect:l.useEffect;function Il(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const ia=typeof document<"u"&&window.visualViewport;function Rl(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Ad(e){for(Rl(e)&&(e=e.parentElement);e&&!Rl(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const ow=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Fn=0,la;function iw(e={}){let{isDisabled:t}=e;aw(()=>{if(!t)return Fn++,Fn===1&&Md()&&(la=lw()),()=>{Fn--,Fn===0&&la?.()}},[t])}function lw(){let e,t=0,s=f=>{e=Ad(f.target),!(e===document.documentElement&&e===document.body)&&(t=f.changedTouches[0].pageY)},n=f=>{if(!e||e===document.documentElement||e===document.body){f.preventDefault();return}let h=f.changedTouches[0].pageY,v=e.scrollTop,x=e.scrollHeight-e.clientHeight;x!==0&&((v<=0&&h>t||v>=x&&h<t)&&f.preventDefault(),t=h)},a=f=>{let h=f.target;Ma(h)&&h!==document.activeElement&&(f.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=f=>{let h=f.target;Ma(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",ia&&(ia.height<window.innerHeight?requestAnimationFrame(()=>{Tl(h)}):ia.addEventListener("resize",()=>Tl(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},c=window.pageXOffset,u=window.pageYOffset,m=Il(cw(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=Il(Xs(document,"touchstart",s,{passive:!1,capture:!0}),Xs(document,"touchmove",n,{passive:!1,capture:!0}),Xs(document,"touchend",a,{passive:!1,capture:!0}),Xs(document,"focus",o,!0),Xs(window,"scroll",i));return()=>{m(),d(),window.scrollTo(c,u)}}function cw(e,t,s){let n=e.style[t];return e.style[t]=s,()=>{e.style[t]=n}}function Xs(e,t,s,n){return e.addEventListener(t,s,n),()=>{e.removeEventListener(t,s,n)}}function Tl(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=Ad(e);if(s!==document.documentElement&&s!==document.body&&s!==e){let n=s.getBoundingClientRect().top,a=e.getBoundingClientRect().top,o=e.getBoundingClientRect().bottom;const i=s.getBoundingClientRect().bottom+rw;o>i&&(s.scrollTop+=a-n)}e=s.parentElement}}function Ma(e){return e instanceof HTMLInputElement&&!ow.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function uw(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function dw(...e){return t=>e.forEach(s=>uw(s,t))}function Od(...e){return l.useCallback(dw(...e),e)}const Dd=new WeakMap;function Ge(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let n={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}n[a]=e.style[a],e.style[a]=o}),!s&&Dd.set(e,n)}function fw(e,t){if(!e||!(e instanceof HTMLElement))return;let s=Dd.get(e);s&&(e.style[t]=s[t])}const We=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function $n(e,t){if(!e)return null;const s=window.getComputedStyle(e),n=s.transform||s.webkitTransform||s.mozTransform;let a=n.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[We(t)?13:12]):(a=n.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[We(t)?5:4]):null)}function mw(e){return 8*(Math.log(e+1)-2)}function ca(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function hw(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const $e={DURATION:.5,EASE:[.32,.72,0,1]},Pd=.4,pw=.25,gw=100,Ld=8,os=16,Aa=26,ua="vaul-dragging";function Fd(e){const t=W.useRef(e);return W.useEffect(()=>{t.current=e}),W.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function xw({defaultProp:e,onChange:t}){const s=W.useState(e),[n]=s,a=W.useRef(n),o=Fd(t);return W.useEffect(()=>{a.current!==n&&(o(n),a.current=n)},[n,a,o]),s}function $d({prop:e,defaultProp:t,onChange:s=()=>{}}){const[n,a]=xw({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:n,c=Fd(s),u=W.useCallback(m=>{if(o){const f=typeof m=="function"?m(e):m;f!==e&&c(f)}else a(m)},[o,e,a,c]);return[i,u]}function bw({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:n,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:c="bottom",container:u,snapToSequentialPoint:m}){const[d,f]=$d({prop:e,defaultProp:s?.[0],onChange:t}),[h,v]=W.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);W.useEffect(()=>{function A(){v({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)},[]);const x=W.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=W.useMemo(()=>{var A;return(A=s?.findIndex(j=>j===d))!=null?A:null},[s,d]),b=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,y=W.useMemo(()=>{const A=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var j;return(j=s?.map(T=>{const P=typeof T=="string";let N=0;if(P&&(N=parseInt(T,10)),We(c)){const D=P?N:h?T*A.height:0;return h?c==="bottom"?A.height-D:-A.height+D:D}const L=P?N:h?T*A.width:0;return h?c==="right"?A.width-L:-A.width+L:L}))!=null?j:[]},[s,h,u]),S=W.useMemo(()=>p!==null?y?.[p]:null,[y,p]),g=W.useCallback(A=>{var j;const T=(j=y?.findIndex(P=>P===A))!=null?j:null;i(T),Ge(n.current,{transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,transform:We(c)?`translate3d(0, ${A}px, 0)`:`translate3d(${A}px, 0, 0)`}),y&&T!==y.length-1&&o!==void 0&&T!==o&&T<o?Ge(a.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,opacity:"0"}):Ge(a.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,opacity:"1"}),f(s?.[Math.max(T,0)])},[n.current,s,y,o,a,f]);W.useEffect(()=>{if(d||e){var A;const j=(A=s?.findIndex(T=>T===e||T===d))!=null?A:-1;y&&j!==-1&&typeof y[j]=="number"&&g(y[j])}},[d,e,s,y,g]);function w({draggedDistance:A,closeDrawer:j,velocity:T,dismissible:P}){if(o===void 0)return;const N=c==="bottom"||c==="right"?(S??0)-A:(S??0)+A,L=p===o-1,D=p===0,k=A>0;if(L&&Ge(a.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`}),!m&&T>2&&!k){P?j():g(y[0]);return}if(!m&&T>2&&k&&y&&s){g(y[s.length-1]);return}const I=y?.reduce((M,F)=>typeof M!="number"||typeof F!="number"?M:Math.abs(F-N)<Math.abs(M-N)?F:M),O=We(c)?window.innerHeight:window.innerWidth;if(T>Pd&&Math.abs(A)<O*.4){const M=k?1:-1;if(M>0&&x&&s){g(y[s.length-1]);return}if(D&&M<0&&P&&j(),p===null)return;g(y[p+M]);return}g(I)}function C({draggedDistance:A}){if(S===null)return;const j=c==="bottom"||c==="right"?S-A:S+A;(c==="bottom"||c==="right")&&j<y[y.length-1]||(c==="top"||c==="left")&&j>y[y.length-1]||Ge(n.current,{transform:We(c)?`translate3d(0, ${j}px, 0)`:`translate3d(${j}px, 0, 0)`})}function R(A,j){if(!s||typeof p!="number"||!y||o===void 0)return null;const T=p===o-1;if(p>=o&&j)return 0;if(T&&!j)return 1;if(!b&&!T)return null;const N=T?p+1:p-1,L=T?y[N]-y[N-1]:y[N+1]-y[N],D=A/Math.abs(L);return T?1-D:D}return{isLastSnapPoint:x,activeSnapPoint:d,shouldFade:b,getPercentageDragged:R,setActiveSnapPoint:f,activeSnapPointIndex:p,onRelease:w,onDrag:C,snapPointsOffset:y}}const vw=()=>()=>{};function yw(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:n,noBodyStyles:a}=jn(),o=W.useRef(null),i=l.useMemo(()=>document.body.style.backgroundColor,[]);function c(){return(window.innerWidth-Aa)/window.innerWidth}W.useEffect(()=>{if(t&&s){o.current&&clearTimeout(o.current);const u=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!u)return;hw(n&&!a?ca(document.body,{background:"black"}):vw,ca(u,{transformOrigin:We(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${$e.DURATION}s`,transitionTimingFunction:`cubic-bezier(${$e.EASE.join(",")})`}));const m=ca(u,{borderRadius:`${Ld}px`,overflow:"hidden",...We(e)?{transform:`scale(${c()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${c()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{m(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},$e.DURATION*1e3)}}},[t,s,i])}let Js=null;function ww({isOpen:e,modal:t,nested:s,hasBeenOpened:n,preventScrollRestoration:a,noBodyStyles:o}){const[i,c]=W.useState(()=>typeof window<"u"?window.location.href:""),u=W.useRef(0),m=W.useCallback(()=>{if(El()&&Js===null&&e&&!o){Js={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:f,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-f}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const v=h-window.innerHeight;v&&u.current>=h&&(document.body.style.top=`${-(u.current+v)}px`)}),300)}},[e]),d=W.useCallback(()=>{if(El()&&Js!==null&&!o){const f=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Js),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){c(window.location.href);return}window.scrollTo(h,f)}),Js=null}},[i]);return W.useEffect(()=>{function f(){u.current=window.scrollY}return f(),window.addEventListener("scroll",f),()=>{window.removeEventListener("scroll",f)}},[]),W.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),W.useEffect(()=>{s||!n||(e?(!window.matchMedia("(display-mode: standalone)").matches&&m(),t||window.setTimeout(()=>{d()},500)):d())},[e,n,i,t,s,m,d]),{restorePositionSetting:d}}function Sw({open:e,onOpenChange:t,children:s,onDrag:n,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:c=!0,closeThreshold:u=pw,scrollLockTimeout:m=gw,dismissible:d=!0,handleOnly:f=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:v,setActiveSnapPoint:x,fixed:p,modal:b=!0,onClose:y,nested:S,noBodyStyles:g=!1,direction:w="bottom",defaultOpen:C=!1,disablePreventScroll:R=!0,snapToSequentialPoint:A=!1,preventScrollRestoration:j=!1,repositionInputs:T=!0,onAnimationEnd:P,container:N,autoFocus:L=!1}){var D,k;const[I=!1,O]=$d({defaultProp:C,prop:e,onChange:H=>{t?.(H),!H&&!S&&q(),setTimeout(()=>{P?.(H)},$e.DURATION*1e3),H&&!b&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),H||(document.body.style.pointerEvents="auto")}}),[M,F]=W.useState(!1),[E,V]=W.useState(!1),[X,Z]=W.useState(!1),ae=W.useRef(null),ie=W.useRef(null),oe=W.useRef(null),ue=W.useRef(null),ge=W.useRef(null),B=W.useRef(!1),U=W.useRef(null),he=W.useRef(0),me=W.useRef(!1),se=W.useRef(!C),we=W.useRef(0),K=W.useRef(null),Ee=W.useRef(((D=K.current)==null?void 0:D.getBoundingClientRect().height)||0),be=W.useRef(((k=K.current)==null?void 0:k.getBoundingClientRect().width)||0),je=W.useRef(0),fe=W.useCallback(H=>{o&&H===J.length-1&&(ie.current=new Date)},[]),{activeSnapPoint:ne,activeSnapPointIndex:Se,setActiveSnapPoint:Le,onRelease:ze,snapPointsOffset:J,onDrag:Ze,shouldFade:Ie,getPercentageDragged:qe}=bw({snapPoints:o,activeSnapPointProp:v,setActiveSnapPointProp:x,drawerRef:K,fadeFromIndex:h,overlayRef:ae,onSnapPointChange:fe,direction:w,container:N,snapToSequentialPoint:A});iw({isDisabled:!I||E||!b||X||!M||!T||!R});const{restorePositionSetting:q}=ww({isOpen:I,modal:b,nested:S??!1,hasBeenOpened:M,preventScrollRestoration:j,noBodyStyles:g});function Qe(){return(window.innerWidth-Aa)/window.innerWidth}function Re(H){var pe,re;!d&&!o||K.current&&!K.current.contains(H.target)||(Ee.current=((pe=K.current)==null?void 0:pe.getBoundingClientRect().height)||0,be.current=((re=K.current)==null?void 0:re.getBoundingClientRect().width)||0,V(!0),oe.current=new Date,Md()&&window.addEventListener("touchend",()=>B.current=!1,{once:!0}),H.target.setPointerCapture(H.pointerId),he.current=We(w)?H.pageY:H.pageX)}function ve(H,pe){var re;let ee=H;const Ne=(re=window.getSelection())==null?void 0:re.toString(),De=K.current?$n(K.current,w):null,Be=new Date;if(ee.tagName==="SELECT"||ee.hasAttribute("data-vaul-no-drag")||ee.closest("[data-vaul-no-drag]"))return!1;if(w==="right"||w==="left")return!0;if(ie.current&&Be.getTime()-ie.current.getTime()<500)return!1;if(De!==null&&(w==="bottom"?De>0:De<0))return!0;if(Ne&&Ne.length>0)return!1;if(ge.current&&Be.getTime()-ge.current.getTime()<m&&De===0||pe)return ge.current=Be,!1;for(;ee;){if(ee.scrollHeight>ee.clientHeight){if(ee.scrollTop!==0)return ge.current=new Date,!1;if(ee.getAttribute("role")==="dialog")return!0}ee=ee.parentNode}return!0}function Oe(H){if(K.current&&E){const pe=w==="bottom"||w==="right"?1:-1,re=(he.current-(We(w)?H.pageY:H.pageX))*pe,ee=re>0,Ne=o&&!d&&!ee;if(Ne&&Se===0)return;const De=Math.abs(re),Be=document.querySelector("[data-vaul-drawer-wrapper]"),Ye=w==="bottom"||w==="top"?Ee.current:be.current;let Ke=De/Ye;const Me=qe(De,ee);if(Me!==null&&(Ke=Me),Ne&&Ke>=1||!B.current&&!ve(H.target,ee))return;if(K.current.classList.add(ua),B.current=!0,Ge(K.current,{transition:"none"}),Ge(ae.current,{transition:"none"}),o&&Ze({draggedDistance:re}),ee&&!o){const He=mw(re),nt=Math.min(He*-1,0)*pe;Ge(K.current,{transform:We(w)?`translate3d(0, ${nt}px, 0)`:`translate3d(${nt}px, 0, 0)`});return}const et=1-Ke;if((Ie||h&&Se===h-1)&&(n?.(H,Ke),Ge(ae.current,{opacity:`${et}`,transition:"none"},!0)),Be&&ae.current&&i){const He=Math.min(Qe()+Ke*(1-Qe()),1),nt=8-Ke*8,rt=Math.max(0,14-Ke*14);Ge(Be,{borderRadius:`${nt}px`,transform:We(w)?`scale(${He}) translate3d(0, ${rt}px, 0)`:`scale(${He}) translate3d(${rt}px, 0, 0)`,transition:"none"},!0)}if(!o){const He=De*pe;Ge(K.current,{transform:We(w)?`translate3d(0, ${He}px, 0)`:`translate3d(${He}px, 0, 0)`})}}}W.useEffect(()=>{window.requestAnimationFrame(()=>{se.current=!0})},[]),W.useEffect(()=>{var H;function pe(){if(!K.current||!T)return;const re=document.activeElement;if(Ma(re)||me.current){var ee;const Ne=((ee=window.visualViewport)==null?void 0:ee.height)||0,De=window.innerHeight;let Be=De-Ne;const Ye=K.current.getBoundingClientRect().height||0,Ke=Ye>De*.8;je.current||(je.current=Ye);const Me=K.current.getBoundingClientRect().top;if(Math.abs(we.current-Be)>60&&(me.current=!me.current),o&&o.length>0&&J&&Se){const et=J[Se]||0;Be+=et}if(we.current=Be,Ye>Ne||me.current){const et=K.current.getBoundingClientRect().height;let He=et;et>Ne&&(He=Ne-(Ke?Me:Aa)),p?K.current.style.height=`${et-Math.max(Be,0)}px`:K.current.style.height=`${Math.max(He,Ne-Me)}px`}else ew()||(K.current.style.height=`${je.current}px`);o&&o.length>0&&!me.current?K.current.style.bottom="0px":K.current.style.bottom=`${Math.max(Be,0)}px`}}return(H=window.visualViewport)==null||H.addEventListener("resize",pe),()=>{var re;return(re=window.visualViewport)==null?void 0:re.removeEventListener("resize",pe)}},[Se,o,J]);function xe(H){Te(),y?.(),H||O(!1),setTimeout(()=>{o&&Le(o[0])},$e.DURATION*1e3)}function ke(){if(!K.current)return;const H=document.querySelector("[data-vaul-drawer-wrapper]"),pe=$n(K.current,w);Ge(K.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`}),Ge(ae.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,opacity:"1"}),i&&pe&&pe>0&&I&&Ge(H,{borderRadius:`${Ld}px`,overflow:"hidden",...We(w)?{transform:`scale(${Qe()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${Qe()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${$e.DURATION}s`,transitionTimingFunction:`cubic-bezier(${$e.EASE.join(",")})`},!0)}function Te(){!E||!K.current||(K.current.classList.remove(ua),B.current=!1,V(!1),ue.current=new Date)}function $(H){if(!E||!K.current)return;K.current.classList.remove(ua),B.current=!1,V(!1),ue.current=new Date;const pe=$n(K.current,w);if(!H||!ve(H.target,!1)||!pe||Number.isNaN(pe)||oe.current===null)return;const re=ue.current.getTime()-oe.current.getTime(),ee=he.current-(We(w)?H.pageY:H.pageX),Ne=Math.abs(ee)/re;if(Ne>.05&&(Z(!0),setTimeout(()=>{Z(!1)},200)),o){ze({draggedDistance:ee*(w==="bottom"||w==="right"?1:-1),closeDrawer:xe,velocity:Ne,dismissible:d}),a?.(H,!0);return}if(w==="bottom"||w==="right"?ee>0:ee<0){ke(),a?.(H,!0);return}if(Ne>Pd){xe(),a?.(H,!1);return}var De;const Be=Math.min((De=K.current.getBoundingClientRect().height)!=null?De:0,window.innerHeight);var Ye;const Ke=Math.min((Ye=K.current.getBoundingClientRect().width)!=null?Ye:0,window.innerWidth),Me=w==="left"||w==="right";if(Math.abs(pe)>=(Me?Ke:Be)*u){xe(),a?.(H,!1);return}a?.(H,!0),ke()}W.useEffect(()=>(I&&(Ge(document.documentElement,{scrollBehavior:"auto"}),ie.current=new Date),()=>{fw(document.documentElement,"scrollBehavior")}),[I]);function le(H){const pe=H?(window.innerWidth-os)/window.innerWidth:1,re=H?-os:0;U.current&&window.clearTimeout(U.current),Ge(K.current,{transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,transform:We(w)?`scale(${pe}) translate3d(0, ${re}px, 0)`:`scale(${pe}) translate3d(${re}px, 0, 0)`}),!H&&K.current&&(U.current=setTimeout(()=>{const ee=$n(K.current,w);Ge(K.current,{transition:"none",transform:We(w)?`translate3d(0, ${ee}px, 0)`:`translate3d(${ee}px, 0, 0)`})},500))}function de(H,pe){if(pe<0)return;const re=(window.innerWidth-os)/window.innerWidth,ee=re+pe*(1-re),Ne=-os+pe*os;Ge(K.current,{transform:We(w)?`scale(${ee}) translate3d(0, ${Ne}px, 0)`:`scale(${ee}) translate3d(${Ne}px, 0, 0)`,transition:"none"})}function ye(H,pe){const re=We(w)?window.innerHeight:window.innerWidth,ee=pe?(re-os)/re:1,Ne=pe?-os:0;pe&&Ge(K.current,{transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,transform:We(w)?`scale(${ee}) translate3d(0, ${Ne}px, 0)`:`scale(${ee}) translate3d(${Ne}px, 0, 0)`})}return W.useEffect(()=>{b||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[b]),W.createElement(vd,{defaultOpen:C,onOpenChange:H=>{!d&&!H||(H?F(!0):xe(!0),O(H))},open:I},W.createElement(Td.Provider,{value:{activeSnapPoint:ne,snapPoints:o,setActiveSnapPoint:Le,drawerRef:K,overlayRef:ae,onOpenChange:t,onPress:Re,onRelease:$,onDrag:Oe,dismissible:d,shouldAnimate:se,handleOnly:f,isOpen:I,isDragging:E,shouldFade:Ie,closeDrawer:xe,onNestedDrag:de,onNestedOpenChange:le,onNestedRelease:ye,keyboardIsOpen:me,modal:b,snapPointsOffset:J,activeSnapPointIndex:Se,direction:w,shouldScaleBackground:i,setBackgroundColorOnScale:c,noBodyStyles:g,container:N,autoFocus:L}},s))}const _d=W.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:n,onRelease:a,shouldFade:o,isOpen:i,modal:c,shouldAnimate:u}=jn(),m=Od(t,s),d=n&&n.length>0;if(!c)return null;const f=W.useCallback(h=>a(h),[a]);return W.createElement(Cd,{onMouseUp:f,ref:m,"data-vaul-overlay":"","data-vaul-snap-points":i&&d?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});_d.displayName="Drawer.Overlay";const zd=W.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...n},a){const{drawerRef:o,onPress:i,onRelease:c,onDrag:u,keyboardIsOpen:m,snapPointsOffset:d,activeSnapPointIndex:f,modal:h,isOpen:v,direction:x,snapPoints:p,container:b,handleOnly:y,shouldAnimate:S,autoFocus:g}=jn(),[w,C]=W.useState(!1),R=Od(a,o),A=W.useRef(null),j=W.useRef(null),T=W.useRef(!1),P=p&&p.length>0;yw();const N=(D,k,I=0)=>{if(T.current)return!0;const O=Math.abs(D.y),M=Math.abs(D.x),F=M>O,E=["bottom","right"].includes(k)?1:-1;if(k==="left"||k==="right"){if(!(D.x*E<0)&&M>=0&&M<=I)return F}else if(!(D.y*E<0)&&O>=0&&O<=I)return!F;return T.current=!0,!0};W.useEffect(()=>{P&&window.requestAnimationFrame(()=>{C(!0)})},[]);function L(D){A.current=null,T.current=!1,c(D)}return W.createElement(kd,{"data-vaul-drawer-direction":x,"data-vaul-drawer":"","data-vaul-delayed-snap-points":w?"true":"false","data-vaul-snap-points":v&&P?"true":"false","data-vaul-custom-container":b?"true":"false","data-vaul-animate":S?.current?"true":"false",...n,ref:R,style:d&&d.length>0?{"--snap-point-height":`${d[f??0]}px`,...t}:t,onPointerDown:D=>{y||(n.onPointerDown==null||n.onPointerDown.call(n,D),A.current={x:D.pageX,y:D.pageY},i(D))},onOpenAutoFocus:D=>{s?.(D),g||D.preventDefault()},onPointerDownOutside:D=>{if(e?.(D),!h||D.defaultPrevented){D.preventDefault();return}m.current&&(m.current=!1)},onFocusOutside:D=>{if(!h){D.preventDefault();return}},onPointerMove:D=>{if(j.current=D,y||(n.onPointerMove==null||n.onPointerMove.call(n,D),!A.current))return;const k=D.pageY-A.current.y,I=D.pageX-A.current.x,O=D.pointerType==="touch"?10:2;N({x:I,y:k},x,O)?u(D):(Math.abs(I)>O||Math.abs(k)>O)&&(A.current=null)},onPointerUp:D=>{n.onPointerUp==null||n.onPointerUp.call(n,D),A.current=null,T.current=!1,c(D)},onPointerOut:D=>{n.onPointerOut==null||n.onPointerOut.call(n,D),L(j.current)},onContextMenu:D=>{n.onContextMenu==null||n.onContextMenu.call(n,D),j.current&&L(j.current)}})});zd.displayName="Drawer.Content";const Cw=250,kw=120,Bd=W.forwardRef(function({preventCycle:e=!1,children:t,...s},n){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:c,setActiveSnapPoint:u,dismissible:m,handleOnly:d,isOpen:f,onPress:h,onDrag:v}=jn(),x=W.useRef(null),p=W.useRef(!1);function b(){if(p.current){g();return}window.setTimeout(()=>{y()},kw)}function y(){if(o||e||p.current){g();return}if(g(),!i||i.length===0){m||a();return}if(c===i[i.length-1]&&m){a();return}const C=i.findIndex(A=>A===c);if(C===-1)return;const R=i[C+1];u(R)}function S(){x.current=window.setTimeout(()=>{p.current=!0},Cw)}function g(){x.current&&window.clearTimeout(x.current),p.current=!1}return W.createElement("div",{onClick:b,onPointerCancel:g,onPointerDown:w=>{d&&h(w),S()},onPointerMove:w=>{d&&v(w)},ref:n,"data-vaul-drawer-visible":f?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},W.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});Bd.displayName="Drawer.Handle";function jw(e){const t=jn(),{container:s=t.container,...n}=e;return W.createElement(Sd,{container:s,...n})}const ut={Root:Sw,Content:zd,Overlay:_d,Portal:jw,Handle:Bd,Title:Ed},Ud="inline-flex items-center justify-center transition-colors",Nw=Ve(Ud,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Ew=Ve(Ud,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),qo=({accountId:e,currentMailboxId:t,onMove:s,disabled:n=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[c,u]=l.useState(!1),[m,d]=l.useState(),f=es(),h=l.useRef(null),v=i??"Move to folder",x=l.useId(),{t:p}=Qa("mail",{useSuspense:!1}),b=ro(),{data:y,isLoading:S,isError:g,error:w,refetch:C}=Ce({...ft({path:{accountId:e}}),staleTime:1/0,enabled:c}),R=_o(e),{createFolderIn:A}=Tc(e),j=l.useMemo(()=>ao({mailboxes:y?.items??[],folderAppointments:R,currentMailboxId:t,translator:b}),[y?.items,R,t,b]),T=oo(y?.items??[]),P=j.find(M=>M.id===m),N=l.useCallback(()=>{u(!1),d(void 0)},[]),L=l.useCallback(()=>{P&&(N(),s(P.id))},[P,N,s]);l.useEffect(()=>{if(!c||!f)return;const M=E=>{h.current&&!h.current.contains(E.target)&&N()},F=E=>{E.key==="Escape"&&N()};return document.addEventListener("mousedown",M),document.addEventListener("keydown",F),()=>{document.removeEventListener("mousedown",M),document.removeEventListener("keydown",F)}},[c,f,N]);const D=n||!!a,k=r.jsxs("button",{type:"button",onClick:M=>{M.stopPropagation(),!D&&u(F=>!F)},"aria-label":v,"aria-haspopup":f?"tree":"dialog","aria-expanded":c,"aria-controls":c?x:void 0,title:a,className:o==="icon-only"?Nw:Ew,children:[r.jsx(_a,{className:o==="icon-only"?"size-5":"size-4"}),o==="compact"&&r.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),I=S?r.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):g?r.jsx("div",{className:"p-3",children:r.jsx(ts,{variant:"inline",title:"Couldn't load folders",error:w,onRetry:()=>C()})}):r.jsx(dc,{folders:j,selectedId:m,delimiter:T,onSelect:d,onCreateFolder:A,onCancel:N,labels:{filterPlaceholder:p("move_picker_filter_placeholder",{defaultValue:"Filter folders…"}),filterAriaLabel:p("move_picker_filter_label",{defaultValue:"Filter folders"})}}),O=P&&r.jsx("div",{className:"shrink-0 border-t border-line p-2",children:r.jsx(ce,{variant:"primary",onClick:L,className:"h-11 w-full font-semibold",children:`Move to ${P.label}`})});return f?r.jsxs("div",{ref:h,className:"relative inline-block",children:[k,c&&r.jsxs("div",{id:x,className:Ve("absolute right-0 mt-1 z-50 w-72 max-h-96 flex flex-col","bg-surface border border-line rounded-md shadow-lg"),children:[I,O]})]}):r.jsxs(r.Fragment,{children:[k,r.jsx(ut.Root,{open:c,onOpenChange:M=>M?u(!0):N(),children:r.jsxs(ut.Portal,{children:[r.jsx(ut.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(ut.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-lg bg-canvas pb-[env(safe-area-inset-bottom,0px)]",style:{maxHeight:"85dvh"},id:x,children:[r.jsx(ut.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),r.jsx(ut.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),r.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:I}),O]})]})})]})},Iw=({messageId:e,threadId:t,mailboxId:s,isRead:n,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:c=!1,onToggleRaw:u})=>{const m=Pe(),d=Je(),{pushError:f}=st(),{selectedMessageId:h}=Ms({strict:!1}),{mutate:v,isPending:x}=Ue({...mr(),onMutate:async I=>{const O=I.body.isRead??!0,M=new Set(I.body.messageIds??[]),F=Zt({path:{threadId:t}}),E=It([s]);await Promise.all([m.cancelQueries({queryKey:F}),yn(m,E)]);const V=m.getQueriesData({queryKey:F}).filter(Z=>Z[1]!==void 0).map(([Z,ae])=>({queryKey:Z,data:ae})),X=wn(m,E);return m.setQueriesData({queryKey:F},Z=>Z&&{...Z,items:tr(Z.items,M,O)}),Sn(m,E,Z=>tr(Z,M,O)),{threadMessagesPrefix:F,listPrefixes:E,previousThreadMessages:V,previousThreadsList:X}},onError:(I,O,M)=>{if(M){for(const E of M.previousThreadMessages)m.setQueryData(E.queryKey,E.data);Cn(m,M.previousThreadsList)}const F=O.body.isRead??!0;f({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:dt(I),error:I})},onSettled:(I,O,M,F)=>{F&&(m.invalidateQueries({queryKey:F.threadMessagesPrefix}),Rt(m,F.listPrefixes))}}),p=l.useCallback(I=>{h&&I.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:O=>({...O,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:b,isPending:y}=fs({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:S,isPending:g}=Os({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:w,isPending:C,error:R,reset:A}=zo({messageId:e}),j=()=>{v({body:{messageIds:[e],isRead:!1}})},T=()=>{b([e])},P=()=>{o&&w(o,i)},N=x||y||g||C,L=N||!o,D=l.useCallback(I=>{S([e],I)},[S,e]),k=o?void 0:"Sender has no parseable address";return r.jsxs("div",{className:"flex flex-col items-end gap-1",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[a&&r.jsx(qo,{accountId:a,currentMailboxId:s,onMove:D,disabled:N,label:"Move this message"}),r.jsxs(Vu,{trigger:r.jsx(qc,{className:"size-4"}),children:[r.jsxs(nn,{onClick:P,disabled:L,children:[i?r.jsx(br,{className:"size-4 text-positive"}):r.jsx(hn,{className:"size-4 opacity-0"}),r.jsx("span",{title:k,children:"Trusted sender"})]}),n&&r.jsxs(nn,{onClick:j,disabled:N,children:[r.jsx(vr,{className:"size-4"}),"Mark as unread"]}),u&&r.jsxs(nn,{onClick:u,children:[r.jsx(Kc,{className:"size-4"}),c?"Show formatted":"Show raw email"]}),r.jsx(Qu,{}),r.jsxs(nn,{onClick:T,disabled:N,destructive:!0,children:[r.jsx(Lt,{className:"size-4"}),"Delete"]})]})]}),R&&r.jsx("div",{className:"w-64",children:r.jsx(ts,{variant:"inline",title:"Couldn't update trust",error:R,onRetry:()=>{A(),P()}})})]})},Rw=e=>e==="link-expired"||e==="not-ready";class Oa extends Error{reason;status;constructor(t,s,n){super(s),this.name="AttachmentFetchError",this.reason=t,this.status=n}}const Tw="x-remit-403-reason",Mw="expired",Aw=(e,t)=>{if(t?.trim()===Mw)return"link-expired";const s=ld(e,t);return s==="auth"?"auth":s==="body-missing"?"missing":"generic"},Ow=300*1e3,Ml=async(e,t)=>{const s={},n=await t();n&&(s.Authorization=`Bearer ${n}`);const a=await bc(e,{headers:s,signal:AbortSignal.timeout(Ow)});if(a.status===202)throw new Oa("not-ready","Attachment is still being fetched from the mail server",202);if(!a.ok)throw new Oa(Aw(a.status,a.headers.get(Tw)),`Failed to download attachment (${a.status} ${a.statusText})`,a.status);return a.blob()},Dw=(e,t,s)=>{switch(e){case"auth":return{title:"Your session expired",detail:`Sign in again, then download ${t} once more. Other parts of the app may also stop responding until you do.`};case"link-expired":return{title:"This download link expired and could not be renewed",detail:`Reload the page, then download ${t} again. If that keeps failing, this is worth reporting.`};case"missing":return{title:"This attachment is missing from storage",detail:"Remit has the message but not the file. Re-sync the account from Settings, then try again."};case"not-ready":return{title:"Still fetching this attachment",detail:"Remit is downloading it from the mail server now. Try again in a few seconds."};default:return{title:"Couldn't download this attachment",detail:s}}},Al=e=>e instanceof Oa?e.reason:"generic",Pw=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while downloading this attachment.",Lw=(e,t,s)=>{if(e!=="auth")return Ja(Za({title:`Bug: attachment download failed (${e})`,errorMessage:`Downloading "${t}" failed: ${s}`}))},Fw=(e,t)=>{const s=URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,n.rel="noopener",document.body.append(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(s),0)},$w=e=>{const t=e.toUpperCase();return t==="OCTET-STREAM"?"FILE":t},_w=e=>{const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return t.length>0?`attachment.${t}`:"attachment"},Ol=e=>e.filter(t=>!t.isMultipart&&t.disposition===Oh.Attachment&&t.contentUrl.length>0).map(t=>({bodyPartId:t.bodyPartId,filename:Zg(t.dispositionFilename??"",_w(t.mediaSubtype)),typeLabel:$w(t.mediaSubtype),sizeOctets:t.sizeOctets,contentUrl:t.contentUrl})),Dl={status:"idle"},zw=({messageId:e,bodyParts:t,hasAttachment:s=!1,className:n})=>{const{getToken:a}=lr(),o=Pe(),[i,c]=l.useState({}),u=l.useMemo(()=>Ol(t??[]),[t]),m=Ga({path:{messageId:e}}),d=x=>Ml(x.contentUrl,a).catch(p=>{if(!Rw(Al(p)))throw p;return o.refetchQueries({queryKey:m}).then(()=>{const b=o.getQueryData(m),y=b?Ol(b.bodyParts).find(S=>S.bodyPartId===x.bodyPartId):void 0;return Ml(y?.contentUrl??x.contentUrl,a)})}),f=(x,p)=>c(b=>({...b,[x]:p})),h=x=>{const p=u.find(b=>b.bodyPartId===x);if(!p)throw new Error(`No attachment part ${x} on message ${e}`);f(x,{status:"downloading"}),d(p).then(b=>{Fw(b,p.filename),f(x,Dl)}).catch(b=>{const y=Al(b),S=Pw(b),{title:g,detail:w}=Dw(y,p.filename,S);f(x,{status:"failed",title:g,detail:w,reportUrl:Lw(y,p.filename,S)})})},v=s&&t!==void 0&&u.length===0;return r.jsx(sx,{className:n,attachments:u.map(x=>({attachmentId:x.bodyPartId,filename:x.filename,typeLabel:x.typeLabel,sizeOctets:x.sizeOctets,download:i[x.bodyPartId]??Dl})),onDownload:h,hasUnlistedAttachment:v})},Bw=()=>{const[e,t]=l.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return l.useEffect(()=>{const s=document.documentElement,n=new MutationObserver(()=>{t(s.classList.contains("dark"))});return n.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e},Uw=({blockedImageCount:e,canAlwaysTrust:t,isTrustPending:s,onLoadOnce:n,onAlwaysTrust:a})=>r.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-md bg-surface-sunken/50 px-3 py-2 text-sm",children:[r.jsxs("span",{className:"text-fg-muted",children:[e," image",e>1?"s":""," blocked for privacy"]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("button",{type:"button",onClick:n,className:"text-accent hover:underline",children:"Load once"}),t&&r.jsx("button",{type:"button",onClick:a,"aria-busy":s,className:"text-accent hover:underline aria-busy:opacity-50",children:s?"Trusting…":"Always trust"})]})]}),Kw=(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}}},qw=e=>e instanceof ls?e.reason:"generic",Hw=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",Ww=({error:e,onRetry:t})=>{const s=qw(e),n=Hw(e),{title:a,detail:o}=Kw(s,n),[i,c]=l.useState(!1),{Account:u}=lr();return i?null:r.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[r.jsx(Pt,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"font-medium text-danger",children:a}),r.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&r.jsx(u,{children:({signOut:m})=>r.jsx("button",{type:"button",onClick:()=>m(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&r.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),r.jsx("button",{type:"button",onClick:()=>c(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:r.jsx(Et,{className:"size-4","aria-hidden":"true"})})]})]})},Vw=()=>r.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),Pl=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Kd=({bodyParts:e,html:t,text:s,isTrusted:n=!1,messageId:a,fromAddressId:o,category:i,className:c})=>{const[u,m]=l.useState(!1),d=n||u,f=Bw(),{toggleTrusted:h,isPending:v}=zo({messageId:a??""}),x=!!e&&e.length>0,{picked:p,data:b,isLoading:y,isError:S,error:g,refetch:w}=cd({messageId:a,bodyParts:e,enabled:x}),C=l.useMemo(()=>mg(e??[]),[e]),R=x&&b?.kind==="html"?b.body:t,A=x&&b?.kind==="text"?b.body:s;if(x){if(y)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(Vw,{})});if(S)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(Ww,{error:g,onRetry:()=>w()})});if(!p)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(Pl,{})})}else if(!t&&!s)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(Pl,{})});const j=!!(o&&a),T=()=>{!o||v||(m(!0),h(o,!1))};return r.jsx(fu,{className:c,html:R,text:A,isDark:f,category:i,allowImages:d,resolveCid:C,renderBlockedNotice:P=>r.jsx(Uw,{blockedImageCount:P,canAlwaysTrust:j,isTrustPending:v,onLoadOnce:()=>m(!0),onAlwaysTrust:T})})},Qw=({messageId:e,threadId:t,mailboxId:s,accountId:n,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:c,isTrusted:u,showRaw:m,onToggleRaw:d,onReply:f,onReplyAll:h,onForward:v})=>{const x=Pe(),{deleteMessages:p}=fs({mailboxId:s,threadId:t}),{moveMessages:b}=Os({mailboxId:s,threadId:t,accountId:n}),{toggleTrusted:y}=zo({messageId:e}),{mutate:S}=Ue({...mr(),onSettled:()=>{x.invalidateQueries({queryKey:Zt({path:{threadId:t}})}),Rt(x,It([s]))}}),g=l.useCallback(A=>{b([e],A)},[b,e]),w=l.useCallback(()=>{p([e])},[p,e]),C=l.useCallback(()=>{S({body:{messageIds:[e],isRead:!a}})},[S,e,a]),R=[];return c&&R.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?r.jsx(br,{className:"size-4 text-positive"}):r.jsx(hn,{className:"size-4"}),onSelect:()=>y(c,u)}),d&&R.push({key:"raw",label:m?"Show formatted":"Show raw email",icon:r.jsx(Kc,{className:"size-4"}),onSelect:d}),r.jsx(du,{hasThread:!0,onReply:f,onReplyAll:h,onForward:v,isStarred:o,onToggleStar:i,onDelete:w,isRead:a,onToggleRead:C,overflowItems:R,moveSlot:n?r.jsx(qo,{accountId:n,currentMailboxId:s,onMove:g,label:"Move this message"}):void 0})},Gw=()=>r.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading raw email",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"})]}),Yw=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:n,isError:a,error:o,refetch:i}=Ce({...Lm({path:{messageId:e}}),enabled:t});if(n)return r.jsx("div",{className:"message-body",children:r.jsx(Gw,{})});if(a)return r.jsx("div",{className:"message-body",children:r.jsx(ts,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const c=s?.raw??"";return c===""?r.jsx("div",{className:"message-body",children:r.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):r.jsx("div",{className:"message-body",children:r.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:c})})},Xw=()=>r.jsx(br,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),qd=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),Hd=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:Ve("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":Ve("text-fg-subtle hover:text-warning",n&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:r.jsx(Jt,{className:Ve("size-3.5",e&&"fill-current")})}),Jw=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:n,isStarPending:a})=>{const o=Ic(e.sentDate,"datetime"),i=qd(e,o);return r.jsx(mu,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:r.jsxs(r.Fragment,{children:[e.hasAttachment&&r.jsx(yr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"}),r.jsx(Hd,{isStarred:e.hasStars,onToggleStar:n,isStarPending:a,hoverReveal:!0}),r.jsx("span",{"data-testid":"message-date",className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:o})]})})},Zw=({threadMessage:e,messageData:t,isLoading:s,isError:n,error:a,onRetry:o,isFocused:i,onToggle:c,onToggleStar:u,isStarPending:m,accountId:d,showRaw:f,onToggleRaw:h,mobile:v,onReply:x,onReplyAll:p,onForward:b})=>{const y=Ic(e.sentDate,"long"),S=!e.isRead,g=t?.envelope.from[0]?.flags?.trusted?.value===!0,w=t?.envelope.from[0]?.addressId,C=qd(e,y),R=e.autoMoved||e.spamReport?r.jsx(z0,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,spamReport:e.spamReport}):null;return r.jsx(hu,{message:C,isFocused:v?!1:i,onHeaderClick:c,senderBadge:g?r.jsx(Xw,{}):void 0,trailing:r.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:y}),to:t?r.jsx(Ip,{label:"To",addresses:t.envelope.to}):null,indicators:R||!v?r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[R,!v&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"flex items-center justify-end gap-1",children:r.jsx(Hd,{isStarred:e.hasStars,onToggleStar:u,isStarPending:m})}),S&&r.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:v?void 0:r.jsx(Iw,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:w,isTrusted:g,showRaw:f,onToggleRaw:h}),actionBar:v?r.jsx(Qw,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:w,isTrusted:g,showRaw:f,onToggleRaw:h,onReply:x,onReplyAll:p,onForward:b}):void 0,body:s?r.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):n&&Fm(a)?r.jsx("div",{className:"mt-3",children:r.jsx(ud,{message:"This message has been deleted"})}):n?r.jsx("div",{className:"mt-3",children:r.jsx(ts,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):f?r.jsx("div",{className:"mt-3",children:r.jsx(Yw,{messageId:e.messageId})}):r.jsxs("div",{className:"mt-3",children:[r.jsx(Kd,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:g,category:Ar(e.category)}),r.jsx(zw,{messageId:e.messageId,bodyParts:t?.bodyParts,hasAttachment:e.hasAttachment,className:"mt-4 px-2 lg:px-0"})]})})},eS=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,mobile:c,onReply:u,onReplyAll:m,onForward:d})=>{const[f,h]=l.useState(!1),{data:v,isLoading:x,isError:p,error:b,refetch:y}=Ce({...hr({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?r.jsx(Zw,{threadMessage:e,messageData:v,isLoading:x,isError:p,error:b,onRetry:()=>y(),isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,showRaw:f,onToggleRaw:()=>h(S=>!S),mobile:c,onReply:u,onReplyAll:m,onForward:d}):r.jsx(Jw,{threadMessage:e,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o})},tS=()=>r.jsxs("div",{className:"animate-pulse p-4",children:[r.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),r.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>r.jsxs("div",{className:"flex gap-3 py-3",children:[r.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function Ll({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?r.jsxs("div",{className:"flex items-start gap-2 rounded-none border-b border-danger/20 bg-danger-soft px-5 py-2.5 text-sm",children:[r.jsx(Fs,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",r.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&r.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const zs=({threadId:e,mailboxId:t,subject:s,selectedMessageId:n,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:c,onComposeClose:u,onSwipeNext:m,onSwipePrevious:d,mobileIntelligenceOpen:f})=>{const h=es(),{handlers:v}=E0({onSwipeLeft:m,onSwipeRight:d}),{accountId:x}=Lo(t),{data:p,isLoading:b,isError:y,error:S,refetch:g}=Ce({...$m({path:{threadId:e}})}),w=l.useMemo(()=>p?.items??[],[p?.items]),C=w[w.length-1],R=l.useRef(new Map),[A,j]=l.useState(new Set),[T,P]=l.useState(null),[N,L]=l.useState(0);l.useEffect(()=>{if(w.length>0&&e!==T){P(e);const fe=new Set([w[w.length-1].threadMessageId]);if(n){const ne=w.find(Se=>Se.messageId===n);ne&&fe.add(ne.threadMessageId)}j(fe),L(w.length-1)}},[e,w,T,n]);const D=l.useCallback(fe=>{j(ne=>{const Se=new Set(ne);return Se.has(fe)?Se.delete(fe):Se.add(fe),Se})},[]),k=l.useCallback(fe=>{const ne=w[fe];if(!ne)return;R.current.get(ne.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[w]),I=l.useCallback(()=>{if(w.length===0)return;const fe=Math.min(N+1,w.length-1);L(fe),k(fe)},[w.length,N,k]),O=l.useCallback(()=>{if(w.length===0)return;const fe=Math.max(N-1,0);L(fe),k(fe)},[w.length,N,k]),M=l.useCallback(()=>{const fe=w[N];fe&&D(fe.threadMessageId)},[w,N,D]),{data:F}=Ce({..._t(),staleTime:1/0}),E=F?.accounts?.[0];C0({messages:w,expandedIds:A,threadId:e,mailboxId:t,accountId:E?.accountId});const{toggleStar:V,isPending:X,pendingMessageId:Z}=Fo({threadId:e,mailboxId:t,messages:w}),[ae,ie]=l.useState(null),[oe,ue]=l.useState(0),ge=l.useCallback(fe=>{ie(fe),ue(ne=>ne+1)},[]);l.useEffect(()=>{c&&c!=="new"&&(ge(c),u?.())},[c,u,ge]);const{data:B}=Ce({...hr({path:{messageId:C?.messageId??""}}),enabled:!!C&&ae!==null}),U=l.useCallback(()=>ge("reply"),[ge]),he=l.useCallback(()=>ge("reply_all"),[ge]),me=l.useCallback(()=>ge("forward"),[ge]),se=l.useCallback(()=>{ie(null),u?.()},[u]),we=l.useRef(null);if(l.useEffect(()=>{if(ae===null||oe===0)return;const fe=we.current;if(!fe)return;const ne=()=>fe.scrollIntoView({behavior:"smooth",block:"end"});if(ne(),typeof ResizeObserver>"u")return;const Se=new ResizeObserver(ne);return Se.observe(fe),()=>Se.disconnect()},[oe,ae]),Po({enabled:!b&&w.length>0&&ae===null,bindings:[{key:"j",handler:I,preventDefault:!0},{key:"ArrowDown",handler:I,preventDefault:!0},{key:"k",handler:O,preventDefault:!0},{key:"ArrowUp",handler:O,preventDefault:!0},{key:"Enter",handler:M,preventDefault:!0},{key:"o",handler:M,preventDefault:!0},{key:"r",handler:U,preventDefault:!0},{key:"R",handler:he,noModifiers:!1,preventDefault:!0},{key:"f",handler:me,preventDefault:!0}]}),b)return r.jsx(tS,{});if(y)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(ts,{title:"Couldn't load this conversation",error:S,onRetry:()=>g()})});if(w.length===0)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(ud,{message:"No messages in this thread"})});const K=s||w[0]?.subject||"(No subject)",Ee=w.length,be=fe=>r.jsx("div",{children:w.map((ne,Se)=>r.jsx("div",{ref:Le=>{Le&&R.current.set(ne.threadMessageId,Le)},children:r.jsx(eS,{threadMessage:ne,isExpanded:A.has(ne.threadMessageId),isFocused:Se===N,onToggle:()=>D(ne.threadMessageId),onToggleStar:()=>V(ne.messageId,ne.hasStars),isStarPending:X&&Z===ne.messageId,accountId:x,mobile:fe,onReply:fe?U:void 0,onReplyAll:fe?he:void 0,onForward:fe?me:void 0})},ne.threadMessageId))}),je=r.jsxs("header",{className:"border-b border-line px-5 pt-5 pb-3",children:[r.jsx("h1",{className:"max-w-2xl text-lg font-semibold leading-snug text-fg",children:K}),r.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Ee," ",Ee===1?"message":"messages"]})]});return h?r.jsxs("article",{className:"h-full flex flex-col",children:[je,a?.dkimMismatch&&r.jsx(Ll,{authenticity:a,onOpenIntelligence:o}),r.jsx("div",{className:"flex-1 overflow-auto",children:be(!1)}),ae!==null&&r.jsx(Sl,{mode:ae,account:E,sourceMessage:B,onClose:se})]}):r.jsxs($g,{thread:{subject:K,messages:[]},onBack:i??(()=>{}),intelligenceOpen:f,onToggleIntelligence:o,touchHandlers:v,children:[a?.dkimMismatch&&r.jsx(Ll,{authenticity:a,onOpenIntelligence:o}),be(!0),ae!==null&&r.jsx("div",{ref:we,children:r.jsx(Sl,{mode:ae,account:E,sourceMessage:B,onClose:se})})]})},sS=768,Wd=e=>e!=="desktop",Nn=()=>{const e=li(`(min-width: ${sS}px)`);return li(Nc)?"desktop":e?"tablet":"phone"};function gs(){const{mailboxNameIndex:e,accountNameIndex:t}=Fe();return{...kt({select:n=>rd(n.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Ho=e=>e.trim().toLocaleLowerCase(),Vd={personal:"Personal",uncategorized:"Unclassified",transactional:"Transactional",newsletter:"Newsletter",marketing:"Marketing",social:"Social",automated:"Automated"},nS=Object.values(lt).map(e=>({value:e,label:Vd[e]})),rS={unclassified:"uncategorized"},Da=[{name:"from",label:"Sender",values:"contact"},{name:"subject",label:"Subject",values:"text"},{name:"category",label:"Category",values:"fixed",options:nS},{name:"is",label:"State",values:"fixed",options:[{value:"unread",label:"Unread"},{value:"read",label:"Read"},{value:"starred",label:"Starred"}]},{name:"has",label:"Contents",values:"fixed",options:[{value:"attachment",label:"Has attachment"}]},{name:"in",label:"Folder",values:"mailbox"},{name:"account",label:"Account",values:"account"},{name:"after",label:"Sent on or after",values:"date"},{name:"before",label:"Sent before",values:"date"}],aS=new Map(Da.map(e=>[e.name,e])),Qd=e=>aS.get(e.toLowerCase()),oS=/^\d{4}-\d{2}-\d{2}$/;function iS(e,t,s){if(!oS.test(s))return;const n=Date.parse(`${s}T00:00:00Z`);if(!Number.isNaN(n))return{type:e,raw:t,value:s,epochSeconds:Math.floor(n/1e3)}}function lS(e){const t=e.toLowerCase(),s=rS[t];return s||Object.values(lt).find(a=>a===t)}function cS(e,t){switch(t.toLowerCase()){case"unread":return{type:"isUnread",raw:e};case"read":return{type:"isRead",raw:e};case"starred":case"flagged":return{type:"isStarred",raw:e};default:return}}function uS(e,t){const s=Sr(e);if(!s||s.value.length===0)return;const{name:n,value:a}=s;switch(n){case"from":return{type:"from",raw:e,value:a};case"subject":return{type:"subject",raw:e,value:a};case"category":{const o=lS(a);return o?{type:"category",raw:e,value:a,category:o}:void 0}case"is":return cS(e,a);case"has":return a.toLowerCase()==="attachment"?{type:"hasAttachment",raw:e}:void 0;case"before":case"after":return iS(n,e,a);case"in":{const o=t.mailboxesByName?.get(a.toLowerCase());return o?{type:"in",raw:e,value:a,mailboxId:o}:void 0}case"account":{const o=t.accountsByName?.get(a.toLowerCase());return o?{type:"account",raw:e,value:a,accountId:o}:void 0}default:return}}function Bs(e,t={}){const s=[],n=[];for(const a of wr(e)){const o=uS(a.raw,t);o?s.push(o):n.push(a.raw)}return{freeText:n.join(" "),tokens:s}}function dS(e,t){return wr(e).filter(s=>s.raw!==t.raw).map(s=>s.raw).join(" ")}function Gd(e){switch(e.type){case"from":return`From: ${e.value}`;case"subject":return`Subject: ${e.value}`;case"category":return`Category: ${Vd[e.category]}`;case"hasAttachment":return"Has attachment";case"isUnread":return"Unread";case"isRead":return"Read";case"isStarred":return"Starred";case"before":return`Before ${e.value}`;case"after":return`After ${e.value}`;case"in":return`In: ${e.value}`;case"account":return`Account: ${e.value}`}}const fS=20,mS=new Set(Object.values(lt)),hS=e=>e!==void 0&&mS.has(e)?e:void 0,pS=e=>{if(e.some(t=>t.type==="isUnread"))return!1;if(e.some(t=>t.type==="isRead"))return!0};function Yd({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Fe(),n=gs(),a=kt({select:w=>w.matches}),o=Ho(s),{freeText:i,tokens:c}=Bs(o,n),u=i.length>0,m=c.find(w=>w.type==="category"),d=hS(t)??m?.category,f=c.some(w=>w.type==="hasAttachment")?!0:void 0,h=c.some(w=>w.type==="isStarred")?!0:void 0,v=pS(c),x=c.find(w=>w.type==="after"),p=c.find(w=>w.type==="before"),b=c.find(w=>w.type==="in"),y=Uy({matches:a,callerMailboxId:e,inTokenMailboxId:b?.mailboxId}),{data:S,isLoading:g}=Ce({...wc({query:{query:i,mailboxId:y,limit:fS,...d!==void 0?{category:d}:{},...f!==void 0?{hasAttachment:f}:{},...h!==void 0?{hasStars:h}:{},...v!==void 0?{isRead:v}:{},...x?{sentDateFrom:x.epochSeconds}:{},...p?{sentDateTo:p.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:S?.items??[],isLoading:u&&g}}const gS=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),xS=e=>[...e].sort(gS);function nr(e){const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId,mailboxId:e.mailboxId,threadId:e.threadId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:xt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Ar(e.category),suspicious:t}}function Fl(e){return e.filter(t=>t.muted!==!0)}function bS(e,t){const s=new Set,n=[];for(const a of[...e,...t])s.has(a.id)||(s.add(a.id),n.push(a));return n.sort((a,o)=>(o.sentDate??0)-(a.sentDate??0))}const $l=[{id:"personal",label:"Personal",category:lt.personal},{id:"transactional",label:"Transactional",category:lt.transactional},{id:"newsletter",label:"Newsletter",category:lt.newsletter},{id:"marketing",label:"Marketing",category:lt.marketing},{id:"social",label:"Social",category:lt.social},{id:"automated",label:"Automated",category:lt.automated},{id:"uncategorized",label:"Unclassified",category:lt.uncategorized}];function vS(e){const t=new Map($l.map(n=>[n.category,[]]));for(const n of e){const a=n.category??lt.uncategorized;(t.get(a)??t.get(lt.uncategorized))?.push(n)}const s=[];for(const n of $l){const a=t.get(n.category);a&&a.length>0&&s.push({id:n.id,label:n.label,threads:a})}return s}function Xd(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Wo(e,t){return t.every(s=>{switch(s.type){case"from":{const n=s.value.toLowerCase();return e.fromEmail.toLowerCase().includes(n)||e.fromName.toLowerCase().includes(n)}case"subject":return e.subject.toLowerCase().includes(s.value.toLowerCase());case"category":return(e.category??"uncategorized")===s.category;case"hasAttachment":return e.hasAttachment===!0;case"isUnread":return!e.isRead;case"isRead":return e.isRead===!0;case"isStarred":return e.starred===!0;case"after":return e.sentDate!=null&&e.sentDate>=s.epochSeconds*1e3;case"before":return e.sentDate!=null&&e.sentDate<s.epochSeconds*1e3;case"in":return e.mailboxId===s.mailboxId;case"account":return e.accountId===s.accountId;default:return!1}})}const Jd="This account has no Junk folder appointed, so there is nowhere to file these. Appoint one under Settings › Folders.",yS="These are already in Junk, so there is nowhere to file them.",Pr=(e,t)=>e!==void 0&&e!==t?e:void 0,wS=(e,t)=>{if(Pr(e,t)===void 0)return e===void 0?Jd:yS},SS={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function CS(e){return SS[e]??e}function kS(e,t){const{folder:s}=eo(t,[e.mailboxId]);return{id:e.messageId,sender:e.fromName??e.fromEmail??"Unknown",...e.fromEmail?{senderEmail:e.fromEmail}:{},subject:e.subject??"(No subject)",snippet:e.snippet??"",date:xt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Wn(e,t){const{folder:s}=eo(t,e.mailboxId?[e.mailboxId]:[]);return{id:e.id,sender:e.fromName,...e.fromEmail?{senderEmail:e.fromEmail}:{},subject:e.subject,snippet:e.snippet,date:e.timeLabel,unread:!e.isRead,flagged:e.starred===!0,...e.threadId?{threadId:e.threadId}:{},...e.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function jS(e,t){const{mailboxId:s,folder:n}=eo(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?xt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:CS(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...n?{folder:n}:{}}}function Zd(e,t,s){const n=new Set(t),a=[];for(const o of[...e].sort((i,c)=>c.score-i.score))n.has(o.threadId)||(n.add(o.threadId),a.push(jS(o,s)));return a}const ef=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function tf(e){const{spam:t}=wo([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let n;for(const[a,o]of s)(!n||o>n.count)&&(n={mailboxId:a,count:o});return n}const NS=e=>{const{mailboxId:t,messages:s}=e,n=Pe(),{pushError:a}=st(),{mutateAsync:o,isPending:i}=Ue({..._m(),onError:(u,m)=>{a({title:m.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:dt(u),error:u})},onSettled:(u,m,d)=>{Rt(n,It(Tr(d.body.messageIds??[],s??[],t)))}});return{applyLabel:l.useCallback((u,m,d)=>{u.length!==0&&As(u,f=>o({body:{messageIds:f,labelId:m,action:d}}))},[o]),isPending:i}};function sf({accountId:e,mailboxId:t,messageIds:s}){const{labels:n}=io(e),{applyLabel:a}=NS({mailboxId:t}),o=l.useMemo(()=>n.map(i=>({key:i.labelId,label:i.name,icon:r.jsx("span",{className:`size-2.5 rounded-full ${zm(i.color)?ai[i.color]:ai.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[n,s,a]);return o.length===0?null:r.jsx(bo,{triggerLabel:"Apply label to selected messages",triggerIcon:r.jsx(Bm,{className:"size-4 text-fg-subtle"}),triggerText:"Apply label",items:o,align:"start",nested:!0,touch:!1,triggerClassName:"min-h-11 w-full justify-start gap-3 px-4 py-2.5 text-sm font-normal text-fg"})}const nf=8;function Vo(e,t){const s=Math.max(0,Math.min(t,e.length)),n=wr(e).find(o=>s>=o.start&&s<=o.end);if(!n)return{start:s,end:s,raw:""};const a=Sr(n.raw);return a?{start:n.start,end:n.end,raw:n.raw,name:a.name,value:a.value}:{start:n.start,end:n.end,raw:n.raw}}function ES(e,t){const s=Vo(e,t);if(s.name===void 0)return{kind:"token",query:s.raw};const n=Qd(s.name);if(n)return{kind:"value",token:n.name,source:n.values,query:s.value??""}}const IS={mailbox:"mailboxes",account:"accounts",contact:"contacts"},RS=(e,t)=>{if(e.values==="fixed")return e.options??[];const s=IS[e.values];return s?t[s]??[]:[]},TS=(e,t)=>{if(t==="")return 1;const s=e.toLowerCase();return s.startsWith(t)?0:s.includes(t)?1:-1},Pa=(e,...t)=>{let s=-1;for(const n of t){if(n===void 0)continue;const a=TS(n,e);a<0||(s<0||a<s)&&(s=a)}return s},rf=e=>{const t=new Set;return e.filter(s=>s.rank>=0).sort((s,n)=>s.rank-n.rank).filter(s=>{const n=s.suggestion.value.toLowerCase();return t.has(n)?!1:(t.add(n),!0)}).slice(0,nf).map(s=>s.suggestion)},_l=e=>({value:`${e.name}:`,label:`${e.name}:`,hint:e.label});function MS(e){const t=e.trim().toLowerCase();if(t==="")return Da.map(_l);const s=[];for(const n of Da)if(s.push({rank:Pa(t,`${n.name}:`,n.label),suggestion:_l(n)}),n.values==="fixed")for(const a of n.options??[]){const o=Cr(n.name,a.value);s.push({rank:Pa(t,o,a.label),suggestion:{value:o,label:a.label??o,hint:o}})}return rf(s)}function AS(e,t,s){const n=t.trim().toLowerCase(),a=RS(e,s).map(o=>({rank:Pa(n,o.value,o.label),suggestion:{value:Cr(e.name,o.value),label:o.label??o.value,...o.hint?{hint:o.hint}:{}}}));return rf(a)}function OS(e,t,s={}){const n=Vo(e,t);if(n.name===void 0)return MS(n.raw);const a=Qd(n.name);return a?AS(a,n.value??"",s):[]}function DS(e,t,s){const n=Vo(e,t),a=!s.value.endsWith(":"),o=/\s/.test(e.slice(n.end,n.end+1)),i=a&&!o?`${s.value} `:s.value;return{query:e.slice(0,n.start)+i+e.slice(n.end),cursor:n.start+i.length+(a&&o?1:0)}}const PS=e=>({value:e.normalizedEmail,...e.displayName?{label:e.displayName,hint:e.normalizedEmail}:{}});function LS(e){const t=new Map;for(const s of e){const n=s.email.toLowerCase(),a=n.split("@")[0];a&&!t.has(a)&&t.set(a,s.accountId),t.has(n)||t.set(n,s.accountId)}return t}function FS(e){const t=new Map;for(const s of e)for(const n of s){const a=n.fullPath?.toLowerCase();if(!a)continue;const o=a.split("/").pop();t.has(a)||t.set(a,n.mailboxId),o&&!t.has(o)&&t.set(o,n.mailboxId)}return t}function $S(e,t=[]){const s=e.flat().filter(o=>o.fullPath),n=new Map;for(const o of s){const i=xa(o.fullPath).toLowerCase();n.set(i,(n.get(i)??0)+1)}const a=new Map(t.map(o=>[o.accountId,o.email]));return s.map(o=>{const i=xa(o.fullPath),c=n.get(i.toLowerCase())===1,u=t.length>1?a.get(o.accountId):void 0;return{value:c?i:o.fullPath,label:o.displayNameOverride?.trim()||i,...u?{hint:u}:{}}})}function _S(e){const t=new Map;for(const s of e){const n=s.email.toLowerCase().split("@")[0]??"";t.set(n,(t.get(n)??0)+1)}return e.map(s=>{const n=s.email.split("@")[0]??s.email,a=t.get(n.toLowerCase())===1,o=s.displayName?.trim();return{value:a?n:s.email,label:o||s.email,...o?{hint:s.email}:{}}})}const zS=250,BS=2;function US({query:e,cursor:t,enabled:s}){const{accounts:n}=Fe(),{mailboxesByName:a}=gs(),o=a!==void 0,i=s?ES(e,t):void 0,c=i?.source==="contact"?i.query.trim():"",u=gr(c,zS),{data:m}=Ce({...ur({query:{q:u,limit:nf}}),enabled:u.length>=BS}),d=gt({queries:n.map(x=>({...ft({path:{accountId:x.accountId}}),staleTime:1/0}))}),f=l.useMemo(()=>o?$S(d.map(x=>x.data?.items??[]),n):[],[o,d,n]),h=l.useMemo(()=>_S(n),[n]),v=l.useMemo(()=>(m?.items??[]).map(PS),[m]);return l.useMemo(()=>{if(!s)return[];const x=OS(e,t,{mailboxes:f,accounts:h,contacts:v});return o?x:x.filter(p=>p.value!=="in:")},[s,e,t,f,h,v,o])}const KS={title:"",navSlot:null,titleMeta:null,searchSlot:null,searchField:null,searchResults:null,makeFilterSlot:null},La=l.createContext(KS),Lr=()=>l.useContext(La),qS=new Set(["hasAttachment","isUnread","isRead","isStarred","category","before","after"]),HS=e=>qS.has(e),WS=(e,{searchHadSemanticReach:t})=>{const s=[],n=[];let a,o;for(const u of e.tokens){if(u.type==="from"){s.push({field:"From",value:u.value});continue}if(u.type==="subject"){s.push({field:"Subject",value:u.value});continue}if(u.type==="in"){a={mailboxId:u.mailboxId,label:u.value};continue}if(u.type==="account"){o=u.accountId;continue}HS(u.type)&&n.push({type:u.type,label:Gd(u)})}const i=e.freeText.trim(),c=i.length>0;return c&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:n,targetAccountId:o,keptTerms:c,droppedSemantic:c&&t}},VS=(e,t,s)=>e.targetAccountId??t??s[0]?.accountId,af="remit.recentSearches",QS=5;function Fa(){try{const e=localStorage.getItem(af);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function zl(e){const t=e.trim();if(!t)return Fa();const s=[t,...Fa().filter(n=>n!==t)].slice(0,QS);try{localStorage.setItem(af,JSON.stringify(s))}catch{return s}return s}function of({title:e,unreadCount:t,children:s,selectionBar:n,paneOverlay:a,footer:o,searchFilter:i,searchResults:c,searchLoading:u,relatedResults:m,relatedLoading:d,onSelectSearchResult:f,searchResultsLabel:h="Top matches",relatedResultsLabel:v="Related",searchResultsInBody:x=!1,refreshControl:p}){const{accounts:b,resultFolderIndex:y,searchQuery:S,searchInput:g,onSearchChange:w,onSearchClear:C,searchViewKey:R}=Fe(),A=gs(),j=Je(),T=hs(),P=Nn(),[N,L]=l.useState(!1),[D,k]=l.useState(Fa),I=Um(),O=l.useRef(R);l.useEffect(()=>{O.current!==R&&(O.current=R,L(!1))},[R]);const[M,F]=l.useState(0),[E,V]=l.useState(!1),[X,Z]=l.useState(void 0),ae=US({query:g,cursor:M,enabled:E&&g.trim().length>0}),ie=l.useCallback(re=>{const ee=DS(g,M,re);w(ee.query),Z({cursor:ee.cursor})},[g,M,w]),oe=lc({count:ae.length,onAccept:re=>{const ee=ae[re];ee&&ie(ee)}}),{comboboxProps:ue,handleKeyDown:ge}=oe,B=l.useMemo(()=>({comboboxProps:ue,onKeyDown:ge,onCaretChange:F,onFocusChange:V,...X?{caret:X}:{}}),[ue,ge,X]),U=oe.open?r.jsx(cc,{id:oe.listId,suggestions:ae,activeIndex:oe.activeIndex,optionId:oe.optionId,onPick:ie,onHighlight:oe.setActiveIndex,label:"Search suggestions",className:"mx-row-inset mt-1 shrink-0"}):null,he=g.trim().length>0,{mailboxesByName:me,accountsByName:se}=A,we=l.useMemo(()=>Bs(g,{mailboxesByName:me,accountsByName:se}),[g,me,se]),K=we.tokens.map(re=>({label:Gd(re),onRemove:()=>w(dS(g,re))})),Ee=c??[],be=m??[],je=he?[{id:"top",label:h,results:Ee},{id:"related",label:v,results:be}]:[],ne=!(Ee.length+be.length>0)&&(u===!0||d===!0),{scope:Se}=id(b),Le=kt({select:re=>re.matches}),ze=ad(Le),J=qy(Le,Se,ze?y.get(ze)?.role:void 0),Ze=J.kind==="global"?tf([...Ee,...be]):void 0,Ie=Ze?{kind:"global",onScopeToSpam:()=>j({to:"/mail/$mailboxId",params:{mailboxId:Ze.mailboxId},search:{q:S||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:J,qe=be.length>0,q=l.useMemo(()=>WS(we,{searchHadSemanticReach:qe}),[we,qe]),Qe=he?q:void 0,Re=he?{onClick:()=>{L(!1),I("properties","search")},blockedReason:Vb(q)?void 0:Km(q.droppedFacets.map(re=>re.label))}:void 0,ve=Re?r.jsx(gu,{...Re}):null,Oe=ef({tier:P,hasLiveInput:he,hasCommittedQuery:S.trim().length>0,bodyRendersCommittedResults:x}),xe=re=>{k(zl(g)),f?.(re)},ke=r.jsx(xu,{value:g,sections:je,loading:ne,onSelectResult:xe,tokens:K,scope:Ie}),Te=n===void 0,$=Oe?r.jsx("div",{className:"h-full overflow-y-auto",children:ke}):null,le=$&&!Te?$:s,de=$&&Te?$:null,ye=Wd(P),H=ye&&(N||he),pe=l.useMemo(()=>({title:e,searchResults:de,makeFilterSlot:ve,searchConversion:Qe,navSlot:T&&!T.showNavPane&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(pr,{className:"size-5"}),onClick:()=>T.openNav(),"aria-label":"Menu",className:"-ml-2 shrink-0"}),titleMeta:r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[t.toLocaleString()," unread"]}),r.jsx(oi,{}),p]}),searchSlot:ye&&!H&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(ir,{className:"size-5"}),onClick:()=>L(!0),"aria-label":"Search",className:"shrink-0"}),searchField:H&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(yo,{value:g,onChange:w,onClear:C,globalFocusKey:!1,showClearButton:!1,suggest:B})}),r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(Et,{className:"size-5"}),onClick:()=>{C(),L(!1)},"aria-label":"Close search",className:"shrink-0"}),r.jsx(oi,{})]})}),[e,t,T,ye,H,g,w,C,B,de,ve,Qe,p]);if(P==="phone"&&N){const re=ee=>{k(zl(g)),L(!1),f?.(ee)};return r.jsxs(La.Provider,{value:pe,children:[r.jsx(Rx,{value:g,onChange:w,onClear:C,onCancel:()=>{L(!1),C()},filter:i,recentSearches:D,onPickRecent:w,makeFilter:Re,sections:je,loading:ne,onSelectResult:re,tokens:K,scope:Ie,suggest:B,suggestList:U}),a]})}return r.jsx(La.Provider,{value:pe,children:r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[n?.(pe),U,r.jsx("div",{className:"min-h-0 flex-1",children:le}),o,a]})})}const GS=["intelligence","nav","shortcuts","filters"];qm(GS);const YS=Hm(Wm);function Wt({fragment:e,...t}){return r.jsx(YS,{...t,hash:e})}const XS=120,lf=({keyboardFocusedMessageId:e,openMessageId:t,enabled:s,open:n,delayMs:a=XS})=>{const o=l.useRef(n);o.current=n;const i=l.useRef(void 0);l.useEffect(()=>{const c=e;if(!s){i.current=c;return}if(c===void 0||c===t)return;if(c===i.current){i.current=void 0;return}const u=setTimeout(()=>o.current(c),a);return()=>clearTimeout(u)},[s,e,t,a])};function cf(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Qo=l.createContext(null),JS=e=>{const t=l.useContext(Qo);return t?t.rowInteraction(e):null},Go=()=>{const e=l.useContext(Qo);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},ZS="[data-message-id]",eC=e=>Array.from(e.querySelectorAll(ZS)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),tC=(e,t)=>e.length===t.length&&e.every((s,n)=>s===t[n]),sC=e=>{const[t,s]=l.useState([]);return l.useEffect(()=>{const n=e.current;if(!n)return;const a=()=>{const i=eC(n);s(c=>tC(c,i)?c:i)};a();const o=new MutationObserver(a);return o.observe(n,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function uf({selectedMessageId:e,onOpen:t,onDeleteMessages:s,onSelectionVerb:n,wizardOpen:a=!1,isDeleting:o=!1,commandsRef:i,onTriageContextChange:c,children:u}){const m=es(),d=l.useRef(null),f=sC(d),h=Gb({orderedIds:f,isDesktop:m,initialFocusedId:e}),{focusedMessageId:v,setFocusedMessageId:x,pendingDomFocusRef:p,cursorMovedByPointerRef:b,selection:y,isMultiSelectMode:S,exitSelection:g,handleRowSelect:w}=h,{selectedIds:C,selectedCount:R,isSelected:A,toggle:j,select:T,toggleAll:P}=y,N=f.length>0&&f.every(U=>C.has(U)),L=l.useCallback(()=>{f.length>0&&P(f)},[f,P]),{intersectWith:D}=y;l.useEffect(()=>{D(f)},[D,f]),l.useEffect(()=>{const U=p.current;U!==null&&(p.current=null,d.current?.querySelector(`[data-message-id="${U}"]`)?.focus())});const k=l.useCallback(U=>{b.current=!0,x(U)},[b,x]),I=l.useCallback(U=>{m||T(U)},[m,T]),O=l.useCallback(()=>{v&&t(v)},[v,t]),M=l.useCallback(U=>t(U,{replace:!0}),[t]);lf({keyboardFocusedMessageId:h.keyboardFocusedMessageId,openMessageId:e,enabled:m&&R===0,open:M});const[F,E]=l.useState(null),V=l.useCallback(U=>F!==null?!0:R>0?(n(U),!0):U!=="delete"||!v?!1:(E([v]),!0),[F,R,n,v]),X=l.useCallback(()=>{F!==null&&(s(F),E(null),g())},[F,s,g]),Z=l.useCallback(()=>E(null),[]),ae=l.useCallback(()=>R===0?!1:(g(),!0),[R,g]),ie=f.length>0;l.useEffect(()=>{if(i){if(!ie){i.current=null;return}return i.current={focusNext:h.focusNext,focusPrevious:h.focusPrevious,focusFirst:h.focusFirst,focusLast:h.focusLast,openFocused:O,toggleSelect:h.toggleFocusedSelection,extendSelectDown:h.extendRangeDown,extendSelectUp:h.extendRangeUp,selectAll:h.selectAllLoaded,clearSelection:ae,requestVerb:V,toggleDensity:()=>{}},()=>{i.current=null}}},[i,ie,h.focusNext,h.focusPrevious,h.focusFirst,h.focusLast,h.toggleFocusedSelection,h.extendRangeDown,h.extendRangeUp,h.selectAllLoaded,O,ae,V]);const oe=l.useMemo(()=>Array.from(C),[C]),ue=F!==null;l.useEffect(()=>{c?.({focusedMessageId:v,selectedIds:oe,orderedIds:f,hasList:ie,blocksKeyboard:ue||a})},[c,v,oe,f,ie,ue,a]);const ge=cf(f,v),B=l.useMemo(()=>({selectedIds:C,selectedCount:R,exitSelection:g,startSelectionVerb:n,orderedIds:f,allSelected:N,toggleAllLoaded:L,rowInteraction:U=>({focused:U===v,isTabStop:U===ge,isDesktop:m,onFocusRow:k,selection:{isChecked:A(U),onToggleCheck:j,onRowSelect:w,isMultiSelectMode:S,onLongPress:I}})}),[C,R,g,n,f,N,L,v,ge,m,k,A,j,w,S,I]);return r.jsxs(Qo.Provider,{value:B,children:[r.jsx("div",{ref:d,className:"contents",children:u}),r.jsx(lo,{isOpen:ue,title:Rc(F?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:o,onConfirm:X,onCancel:Z})]})}function nC({title:e,isDeleting:t}){const s=Lr(),{selectedCount:n,exitSelection:a,startSelectionVerb:o,orderedIds:i,allSelected:c,toggleAllLoaded:u}=Go();return r.jsx(ko,{title:s.title||e,navSlot:s.navSlot,titleMeta:s.titleMeta,searchSlot:s.searchSlot,searchField:s.searchField,idleSlot:s.makeFilterSlot,count:n,onCancel:a,onDelete:()=>o("delete"),onMarkRead:()=>o("markRead"),isBusy:t,selectAll:i.length>0?{checked:c,indeterminate:n>0&&!c,onChange:u}:void 0})}const da=e=>{e.preventDefault(),e.stopPropagation()},df=(e,t)=>{const s=l.useRef(!1),n=l.useCallback(i=>{if(s.current=!1,i.button!==0)return;const c=Zn(i);yi(c)&&t?.(e,c)&&(da(i),s.current=!0,i.currentTarget.focus(),c.shiftKey&&window.getSelection()?.removeAllRanges())},[t,e]),a=l.useCallback(i=>{!i.ctrlKey||!t||i.preventDefault()},[t]),o=l.useCallback(i=>{if(s.current)return s.current=!1,da(i),!0;const c=Zn(i);return!yi(c)||!t?.(e,c)?!1:(da(i),c.shiftKey&&window.getSelection()?.removeAllRanges(),!0)},[t,e]);return{onMouseDown:n,onContextMenu:a,claimClick:o}},rC=({thread:e,active:t=!1,focused:s,isTabStop:n,density:a="comfortable",isDesktop:o,badge:i,selection:c,inListbox:u=!1,linkMailboxId:m,onClick:d,onFocusRow:f})=>{const h=Pe(),v=e.id,x=JS(v),p=s??x?.focused??!1,b=n??x?.isTabStop??!1,y=c??x?.selection,S=f??x?.onFocusRow,g=o??x?.isDesktop??!0,w=y?.isChecked??!1,C=y?.isMultiSelectMode??!1,R=y?.onToggleCheck,A=y?.onRowSelect,j=y?.onLongPress,T=l.useCallback(E=>{E.preventDefault(),E.stopPropagation(),R?.(v)},[R,v]),P=df(v,A),N=l.useCallback(E=>{if(!P.claimClick(E)){if(!g){if(C){E.preventDefault(),E.stopPropagation(),R?.(v);return}d?.();return}A?.(v,Zn(E)),d?.()}},[P,g,C,R,A,d,v]),L=l.useCallback(()=>{j?.(v)},[j,v]),{longPressProps:D}=lu({onLongPress:L,accessibilityDescription:w?"Deselect message":"Select message"}),k=l.useCallback(()=>{h.prefetchQuery(hr({path:{messageId:v}}))},[h,v]),I=l.useCallback(()=>{k(),S?.(v)},[k,S,v]),O=Ls({"data-list-row":"","data-message-row":!0,"data-message-id":v,...u?{role:"option","aria-selected":w}:{},tabIndex:b?0:-1,onClick:N,onMouseDown:P.onMouseDown,onContextMenu:P.onContextMenu,onMouseEnter:k,onFocus:I},g||!y?{}:D),M=Ve(a==="compact"?ru({active:t,focused:p}):Ve("group",$s({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",w&&"bg-accent-soft",!g&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?r.jsx(au,{thread:e}):r.jsx(xo,{thread:e,badge:i,selection:y?{checked:w,alwaysVisible:C,onToggle:T}:void 0});return m===void 0?r.jsx("button",{type:"button",...O,className:M,children:F}):r.jsx(Wt,{to:"/mail/$mailboxId",params:{mailboxId:m},search:E=>({...E,selectedMessageId:v}),variant:"row",...O,className:M,children:F})},Yo=l.memo(rC),ff=8,mf=e=>e==="From"||e==="FromDomain",aC=e=>({value:e.email,label:e.displayName??e.email,...e.displayName?{hint:e.email}:{},...e.fromSelection?{source:"selected"}:{}}),oC=e=>{const t=Iu(e.email);if(t!==null)return{value:t,...e.fromSelection?{source:"selected"}:{}}},iC=(e,t)=>e.value.toLowerCase().includes(t)||(e.label??"").toLowerCase().includes(t),lC=(e,t,s)=>{if(!mf(e))return[];const n=t.trim().toLowerCase(),a=new Set,o=[];for(const i of s){if(i.email.trim()==="")continue;const c=e==="From"?aC(i):oC(i);if(!c)continue;const u=c.value.toLowerCase();if(!(u===""||a.has(u))&&(a.add(u),u!==n&&!(n!==""&&!iC(c,n))&&(o.push(c),o.length===ff)))break}return o},cC=250,uC=2,dC=(e,t,s)=>{const n=t.trim(),a=gr(n,cC),o=e!==void 0&&mf(e),{data:i}=Ce({...ur({query:{q:a,limit:ff}}),enabled:o&&a.length>=uC});if(!o||e===void 0)return[];const c=[...s.map(u=>({email:u,fromSelection:!0})),...(i?.items??[]).map(u=>({email:u.normalizedEmail,...u.displayName?{displayName:u.displayName}:{}}))];return lC(e,n,c)},fC={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},hf={delete:"moved to Trash",move:"moved",markRead:"marked as read"},mC={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},hC={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},pC={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},gC=(e,t,s)=>fC[e](Yt(t),Yt(s)),Bl=(e,t)=>`${Yt(t)} ${hf[e]}. Your mail server is still catching up.`,xC=e=>`Stopped after ${Yt(e)}`,bC=(e,t,s)=>`${Yt(t)} of ${Yt(s)} ${hf[e]}. Nothing was sent for the rest, so they are untouched.`,vC=(e,t)=>t>0?`Stopped after ${Yt(t)} — some messages ${mC[e]}`:hC[e],yC=e=>pC[e],wC=e=>e==="delete"?"danger":"info",SC=100,CC=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],pf=({mailboxId:e,accountId:t,enabled:s,predicateKey:n,searchQuery:a})=>{const[o,i]=l.useState({kind:"idle"}),[c,u]=l.useState(void 0),[m,d]=l.useState(void 0),f=l.useRef(!1),h=l.useRef(!1),v=Pe(),{pushError:x}=st();l.useEffect(()=>{h.current||(f.current=!0),i({kind:"idle"})},[s,n]);const p=l.useRef(a);p.current=a;const b=l.useCallback(j=>async T=>{const{data:P}=await ba({path:{mailboxId:e},query:{...j,continuationToken:T,limit:SC},throwOnError:!0});return{ids:(P.items??[]).map(N=>N.messageId),continuationToken:P.continuationToken}},[e]),y=l.useCallback(async()=>{const{data:j}=await ba({path:{mailboxId:e},query:{...p.current,count:!0,results:!1},throwOnError:!0});if(j.count===void 0)throw new Error("the search returned no count for the selection");return j.count},[e]),S=l.useCallback(j=>async T=>{if(j.kind==="move"){const{data:N}=await Vm({body:{messageIds:T,destinationMailboxId:j.destinationMailboxId},throwOnError:!0});return N}if(j.kind==="markRead"){const{data:N}=await Qm({body:{messageIds:T,isRead:!0},throwOnError:!0});return N}const{data:P}=await Gm({body:{messageIds:T},throwOnError:!0});return P},[]),g=l.useCallback(j=>{Rt(v,It(CC(j,e))),t&&v.invalidateQueries({queryKey:$t({path:{accountId:t}})})},[v,e,t]),w=l.useCallback(()=>{f.current=!1,i({kind:"counting"}),y().then(j=>{if(f.current){i({kind:"idle"});return}i({kind:"escalated",total:j})},j=>{x(us("Couldn't count matching messages","The count didn't finish.",j)),i({kind:"idle"})})},[y,x]),C=l.useCallback(()=>{f.current=!0},[]),R=l.useCallback(()=>{h.current||(f.current=!0,i({kind:"idle"}))},[]),A=l.useCallback(async(j,T)=>{f.current=!1,h.current=!0,u(j);const P=k=>d(v0(k)),N=S(j),L=b(p.current);let D;try{D=T!==void 0?await dd(T,N,P,()=>f.current):await b0(L,o.kind==="escalated"?o.total:0,N,P,()=>f.current)}finally{h.current=!1}return u(void 0),d(void 0),i({kind:"idle"}),D.error&&x(us(vC(j.kind,D.done),yC(j.kind),D.error)),D.done>0&&g(j),D},[S,b,o,x,g]);return{phase:o,escalate:w,stop:C,clear:R,isRunning:c!==void 0,runningAction:c,progress:m,runAction:A}},gf=12,kC=e=>{const{envelope:t}=e,s=t.from[0];return{id:t.messageId,sender:s?Ru({normalizedEmail:s.normalizedEmail,displayName:s.displayName}):"Unknown",subject:t.subject??"(No subject)",date:xt(t.date)}},jC=(e,t)=>{const s=e!==void 0&&t!==void 0,{data:n,isLoading:a}=Ce({...Sc({path:{mailboxId:e??""},query:{...t,limit:gf}}),enabled:s,staleTime:3e4});return{messages:(n?.items??[]).map(NC),isPending:s&&a}},NC=e=>({id:e.messageId,sender:e.fromName||e.fromEmail||"Unknown",subject:e.subject??"(No subject)",date:xt(e.sentDate)}),EC=e=>gt({queries:e.slice(0,gf).map(t=>({...hr({path:{messageId:t}}),staleTime:Number.POSITIVE_INFINITY})),combine:t=>({messages:t.map(s=>s.data).filter(s=>s!==void 0).map(kC),isPending:t.some(s=>s.isPending)})}),IC=e=>({matchOperator:"Or",literalClauses:jr(e)}),RC=(e,t,s)=>{const n=Ue(Ym()),{mutate:a,reset:o}=n,[i,c]=l.useState(!1),u=l.useMemo(()=>kr(s),[s]),m=l.useCallback(()=>{!e||!t||(c(!1),a({path:{accountId:e},body:ci({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=l.useCallback(()=>{c(!1),o()},[o]),f=n.data,h=f?.semanticUnavailable===!0&&!i&&u.length>0;l.useEffect(()=>{!h||!e||(c(!0),a({path:{accountId:e},body:ci(IC(u))}))},[h,e,u,a]);const v=i||(f?.semanticUnavailable??!1),x=n.isPending||h,p=i?{matchOperator:"Or",literalClauses:jr(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:m,reset:d,matchedCount:x?void 0:f?.matchedCount,messageIds:x?void 0:f?.messageIds,semanticUnavailable:v,senderFallback:i,senders:u,matchPredicate:p,isPending:x,isError:n.isError,error:n.error}},TC=()=>[fr({path:{mailboxId:""}}),Ya({path:{mailboxId:""}}),Xa()].map(e=>[{_id:e[0]._id}]),MC=e=>fd(e)?e.pages:md(e)?[e]:[],AC=e=>typeof e=="object"&&e!==null&&typeof e.messageId=="string",OC=(e,t)=>{const s=new Set(t),n=new Map;for(const a of e)for(const o of MC(a))for(const i of o.items){if(!AC(i)||!s.has(i.messageId))continue;const c=i.subject?.trim();c&&n.set(i.messageId,c)}return t.map(a=>n.get(a)).filter(a=>a!==void 0)},DC=e=>{const t=Pe(),s=e.join("\0");return l.useMemo(()=>{const n=TC().flatMap(a=>t.getQueriesData({queryKey:a}).map(([,o])=>o));return OC(n,e)},[t,s])},PC=({failure:e,isStarting:t,isRunning:s,isDone:n,failedCount:a,ruleSaved:o})=>e?.kind==="restartFailed"?"backApplyRestartFailed":e?.kind==="startFailed"?o?"backApplyStartFailed":"commitFailed":n?a>0?"backApplyFailed":"backApplyComplete":e?.kind==="statusUnreadable"?"statusUnknown":t||s?"backApplyRunning":"saving",LC={clauses:[],matchOperator:"any"},FC={clauses:[],matchOperator:"all",droppedFacets:[],keptTerms:!1,droppedSemantic:!1},$C=[],is={state:"saving",matched:0,applied:0,failed:0,failures:[]},fa=(e,t)=>e.map((s,n)=>({...s,id:`${t}-${n}`})),Ul=(e,t,s)=>{if(e==="delete")return{kind:"delete"};if(e==="markRead")return{kind:"markRead"};const n=e==="junk"?s:t;return n?{kind:"move",destinationMailboxId:n}:void 0},ma=e=>e==="move"||e==="junk"||e==="organize",Kl=e=>e==="junk"?Jd:"No destination was chosen, so there is nowhere to file these. Go back and pick a folder.";function _C({verb:e,accountId:t,mailboxId:s,selection:n,crossAccount:a=!1,escalated:o,escalatedProgress:i,searchConversion:c,onFinished:u,onRunEnded:m,step:d,goToStep:f,goBack:h,closeWizard:v}){const[x]=l.useState(()=>c),[p]=l.useState(()=>o),b=x!==void 0,[y,S]=l.useState(b?"properties":"selected"),g=p?"escalated":y,[w,C]=l.useState(()=>x?{clauses:fa(x.clauses,"search"),matchOperator:x.matchOperator}:LC),[R,A]=l.useState(void 0),[j,T]=l.useState(void 0),[P,N]=l.useState(!1),[L,D]=l.useState(void 0),[k,I]=l.useState(void 0),[O,M]=l.useState(),F=l.useRef(!1),E=l.useRef(!1),V=l.useMemo(()=>n.map(z=>z.id),[n]),X=l.useMemo(()=>n.map(z=>z.email).filter(Boolean),[n]),Z=V[0],ae=DC(V),{junkMailboxId:ie}=kn(t),oe=RC(p?void 0:t,Z,X),{preview:ue}=oe;l.useEffect(()=>{ue()},[ue]);const ge=g==="similar"||g==="properties",B=l.useMemo(()=>({matchOperator:w.matchOperator==="all"?"And":"Or",literalClauses:w.clauses.map(z=>({field:z.field,value:z.value}))}),[w.clauses,w.matchOperator]),U=g==="similar"?oe.matchPredicate:B,{count:he,matchedIds:me}=kh(ge?t:void 0,U),se=EC(ge?me:[]),we=jC(p?s:void 0,p?.searchQuery),K=p?{status:"ready",count:p.total}:ge?he:{status:"ready",count:n.length},{data:Ee}=Ce({...ft({path:{accountId:t??""}}),enabled:!!t,staleTime:Number.POSITIVE_INFINITY}),be=_o(t),je=ro(),fe=l.useMemo(()=>ao({mailboxes:Ee?.items??[],folderAppointments:be,currentMailboxId:s,translator:je}),[Ee?.items,be,s,je]),{createFolderIn:ne}=Tc(t),Se=fe.find(z=>z.id===w.moveMailboxId)?.label,Le=$b(n.map(z=>({normalizedEmail:z.email,displayName:z.sender}))),ze=Wb({match:g==="properties"&&w.clauses[0]?.value.trim()||void 0,sender:Le?Ru(Le):void 0,folder:Se}),J=l.useMemo(()=>({...w,name:w.name??ze}),[w,ze]),Ze=dC(R?.draft.field,R?.draft.value??"",X),Ie=jh(t),qe=Nh(t),q=pf({mailboxId:s??"",accountId:t,enabled:!1,predicateKey:"selection-wizard",searchQuery:{}}),{runAction:Qe}=q,Re=Zm({verb:e,mode:g,scope:w.scope,fromSearch:b}),ve=Re[ii(Re,d)],Oe=!a&&!!t,xe=Oe?void 0:sh,ke=Oe?void 0:nh,$=(z=>{if(z==="folder")return ke;if(z==="rule")return J.scope==="standing"||J.scope==="until"?xe:void 0})(ve)??eh(ve,J,K),le=l.useCallback(()=>fa(Hb(X,ae),"seed"),[X,ae]),de=l.useCallback(z=>{S(z),C(Y=>({...Y,widen:z==="similar"&&Z?{anchorCount:Math.max(n.length,1)}:void 0,...z==="properties"&&Y.clauses.length===0?{clauses:le()}:{}}))},[Z,n.length,le]),ye=l.useCallback(()=>{N(!0),S("properties"),C(z=>({...z,widen:void 0,clauses:fa(jr(X),"sender"),matchOperator:"any"})),f("properties")},[X,f]),H=oe.semanticUnavailable||oe.isError;l.useEffect(()=>{ve==="match"&&(g!=="similar"||!H||P||ye())},[ve,g,H,P,ye]);const pe=l.useCallback(()=>{A({mode:"add",draft:{field:"From",value:""}})},[]),re=l.useCallback(z=>{const Y=w.clauses.find(Ae=>Ae.id===z);Y&&A({mode:"edit",clauseId:z,draft:{field:Y.field,value:Y.value}})},[w.clauses]),ee=l.useCallback(z=>{C(Y=>({...Y,clauses:Y.clauses.filter(Ae=>Ae.id!==z)}))},[]),Ne=l.useCallback(z=>{A(Y=>Y&&{...Y,draft:z})},[]),De=l.useCallback(()=>{A(z=>{if(!z)return;const Y=Eh(z.draft.field,z.draft.value),Ae={...z.draft,value:Y};C(pt=>({...pt,clauses:z.clauseId?pt.clauses.map(yt=>yt.id===z.clauseId?{...yt,...Ae}:yt):[...pt.clauses,{id:crypto.randomUUID(),...Ae}]}))})},[]),Be=l.useCallback(()=>{if($){T(ve);return}T(void 0);const z=Re[ii(Re,ve)+1];z&&f(z)},[$,ve,Re,f]),Ye=l.useCallback(async z=>{const Y=Ul(e,J.moveMailboxId,ie);if(!Y){I({matched:z.length,failureReason:Kl(e)});return}I({matched:z.length});const Ae=await Qe(Y,[...z]);I({matched:z.length,outcome:Ae}),E.current&&m?.(Y.kind,z.length,Ae)},[e,J.moveMailboxId,ie,Qe,m]),Ke=l.useCallback(async()=>{if(!p)return;const z=Ul(e,J.moveMailboxId,ie);if(!z){I({matched:p.total,failureReason:Kl(e)});return}I({matched:p.total});const Y=await p.run(z);I({matched:p.total,outcome:Y}),E.current&&m?.(z.kind,p.total,Y)},[p,e,J.moveMailboxId,ie,m]),{start:Me}=Ie,{createFilterAsync:et}=qe,He=l.useCallback(()=>{if(p){Ke();return}const z=Ih({mode:y,ruleScope:J.scope}),Y=Rh({mode:y,ruleScope:J.scope,anchorMessageId:Z,clauses:J.clauses,matchOperator:J.matchOperator,moveMailboxId:J.moveMailboxId,until:J.until});if(D(z),z==="standing"||z==="temporary"){const Ae=Th(Y)?Y:void 0;M(Ae),et(Y,z,(J.name??"").trim()).then(pt=>{pt&&Ae&&Me(Ae)});return}if(z==="all-like-these"&&ma(e)){Me(Y);return}Ye(z==="just-these"?V:me)},[p,Ke,y,J,Z,e,V,me,et,Me,Ye]),nt=l.useCallback(()=>{if($){T(ve);return}F.current||(F.current=!0,f("run"),He())},[$,ve,f,He]),rt=l.useCallback(z=>{const Y=Ie.progress,Ae=PC({failure:Ie.failure,isStarting:Ie.isStarting,isRunning:Ie.isRunning,isDone:Ie.isDone,failedCount:Y.failedCount,ruleSaved:z});return Ae==="saving"||Ae==="commitFailed"||Ae==="backApplyStartFailed"?{...is,state:Ae}:{state:Ae,matched:Y.matchedCount,applied:Y.appliedCount,failed:Ae==="backApplyFailed"||Ae==="backApplyRestartFailed"?Y.failedCount:0,failures:[]}},[Ie]),mt=l.useMemo(()=>{const z=new Map;for(const Y of[...n,...se.messages,...we.messages])z.set(Y.id,Y);return z},[n,se.messages,we.messages]),Bt=p?i:q.progress,Tt=l.useCallback(()=>{if(!k)return is;const{matched:z,outcome:Y,failureReason:Ae}=k;if(Ae!==void 0)return{...is,state:"commitFailed",failureReason:Ae};if(!Y){const wt=Bt?.done??0;return{state:"backApplyRunning",matched:Math.max(z,wt),applied:wt,failed:0,failures:[]}}if(!(Y.cancelled||Y.error!==void 0))return{state:"backApplyComplete",matched:Math.max(z,Y.done),applied:Y.done,failed:0,failures:[]};if(Y.done===0)return{...is,state:"commitFailed"};const yt=Y.failedIds.map(wt=>mt.get(wt)).filter(wt=>wt!==void 0),bs=Y.failedIds.length>0?Y.failedIds.length:Math.max(z-Y.done,1);return{state:"runStopped",matched:Math.max(z,Y.done),applied:Y.done,failed:bs,failures:yt}},[k,Bt,mt]),at=p?Tt():L==="standing"||L==="temporary"?qe.isError?{...is,state:"commitFailed"}:qe.isSuccess?O?rt(!0):{...is,state:"filterSaved"}:is:L==="all-like-these"&&ma(e)?rt(!1):Tt(),xs=()=>{if(at.state==="statusUnknown"){Ie.refreshStatus();return}if(p){Ke();return}if(L==="standing"||L==="temporary"){if(qe.isError){qe.reset(),He();return}O&&Me(O);return}if(L==="all-like-these"&&ma(e)){He();return}const z=k?.outcome?.failedIds??[];Ye(z.length>0?z:V)},ht=l.useCallback(()=>{v(Re,ve)},[v,Re,ve]),vt=l.useCallback(()=>{E.current=!0,v(Re,ve),u()},[v,Re,ve,u]),{stop:Mt}=q,ct=k!==void 0&&k.outcome===void 0&&k.failureReason===void 0,qs=l.useCallback(()=>{if(p){p.stop();return}Mt()},[p,Mt]);Wu({shouldBlockFn:({action:z})=>z!=="BACK"?!1:(vt(),!0),enableBeforeUnload:!1,disabled:ve!=="run"});const ns={messages:p?we.messages:ge?se.messages:n,count:K,label:g==="selected"?"Your selection":"A sample of what matches",emptyReason:g==="similar"&&H?"notIndexed":"noMatch",loading:p?we.isPending:ge&&(K.status==="loading"||se.isPending)};return r.jsx(th,{verb:e,steps:Re,step:ve,blockedReason:$,nudged:j===ve,onBack:h,onExit:ve==="run"?vt:ht,onContinue:Be,onCommit:nt,match:{selectedCount:n.length,mode:g,onModeChange:de,semanticUnavailable:H,semanticErrorDetail:oe.error instanceof Error?oe.error.message:void 0,semanticFallbackTaken:P,onSemanticFallback:ye,escalatedScope:p?.scope,sample:ns},properties:{clauses:J.clauses,matchOperator:J.matchOperator,onMatchOperatorChange:z=>C(Y=>({...Y,matchOperator:z})),clauseEdit:R,onStartAddClause:pe,onStartEditClause:re,onRemoveClause:ee,onChangeDraft:Ne,onSubmitClause:De,onCancelClause:()=>A(void 0),clauseFields:Mh,clauseSuggestions:Ze,conversionNotice:x?Qb(x):void 0,semanticFallbackTaken:P,sample:{...ns,label:"What this matches"}},folder:{folders:fe,mailboxId:J.moveMailboxId,delimiter:oo(Ee?.items??[]),onSelect:z=>C(Y=>({...Y,moveMailboxId:z})),onCreateFolder:t?ne:void 0,restriction:ke},rule:{draft:J,onScopeChange:z=>C(Y=>({...Y,scope:z})),onUntilChange:z=>C(Y=>({...Y,until:z})),restriction:xe},name:{name:J.name??"",onNameChange:z=>C(Y=>({...Y,name:z})),nudged:j===ve},review:{verb:e,mode:g,selectedCount:n.length,clauses:J.clauses,matchOperator:J.matchOperator,folder:Se,scope:J.scope,until:J.until,ruleName:Re.includes("name")?J.name:void 0,escalatedScope:p?.scope,sample:ns},run:{state:at.state,verb:e,scope:J.scope,matched:at.matched,applied:at.applied,failedCount:at.failed,failures:at.failures,failureReason:at.failureReason,onRetry:xs,onDismiss:vt,onCancelRun:ct?qs:void 0}})}function Xo(e){const t=Xm()==="search",{searchConversion:s}=Lr(),{accounts:n}=Fe(),{step:a,goToStep:o,goBack:i,closeWizard:c}=Jm(t?"properties":"match");if(!a)return null;const u=t?s??FC:void 0;return r.jsx(_C,{...e,...u?{verb:"organize",accountId:VS(u,e.accountId,n),selection:$C,crossAccount:!1,escalated:void 0,searchConversion:u}:{},step:a,goToStep:o,goBack:i,closeWizard:c})}const zC=200,ql=()=>r.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>r.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[r.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsxs("div",{className:"flex justify-between gap-2",children:[r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),BC=({accountEmail:e})=>{const t=Je();return r.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[r.jsx(Pt,{className:"size-3.5 shrink-0"}),r.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),r.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})},UC=(e,t)=>{if(t.size===0)return{};const s=new Set,n=new Set;for(const o of e)t.has(o.id)&&(o.accountId&&s.add(o.accountId),o.mailboxId&&n.add(o.mailboxId));if(s.size>1)return{moveDisabledHint:"Move only works within one account — clear selection or pick messages from a single account"};const a=s.size===1?[...s][0]:void 0;return n.size>1?{accountId:a,moveDisabledHint:`Move only works within one folder — this selection spans ${n.size} folders`}:{accountId:a,mailboxId:n.size===1?[...n][0]:void 0}};function KC({header:e,rows:t,wizard:s,children:n}){const{selectedIds:a,selectedCount:o,exitSelection:i,orderedIds:c,allSelected:u,toggleAllLoaded:m}=Go(),d=l.useMemo(()=>UC(t,a),[t,a]),{junkMailboxId:f}=kn(d.accountId),{labels:h}=io(d.accountId),v=l.useMemo(()=>Array.from(a),[a]),x=l.useMemo(()=>t.filter(g=>a.has(g.id)).map(g=>({id:g.id,sender:g.fromName,email:g.fromEmail,subject:g.subject,date:g.timeLabel})),[t,a]),p=Pr(f,d.mailboxId),b=l.useMemo(()=>c.length>0?{checked:u,indeterminate:o>0&&!u,onChange:m}:void 0,[c.length,u,o,m]),y=d.moveDisabledHint?{tone:"warning",text:d.moveDisabledHint}:void 0,S=g=>r.jsx(ko,{title:g.title,navSlot:g.navSlot,titleMeta:g.titleMeta,searchSlot:g.searchSlot,searchField:g.searchField,idleSlot:g.makeFilterSlot,count:o,onCancel:i,onDelete:()=>s.start("delete"),onMove:()=>s.start("move"),onOrganize:()=>s.start("organize"),onJunk:p?()=>s.start("junk"):void 0,onMarkRead:()=>s.start("markRead"),overflowSlot:d.accountId&&d.mailboxId&&o>0&&h.length>0?r.jsx(sf,{accountId:d.accountId,mailboxId:d.mailboxId,messageIds:v}):void 0,selectAll:b,notice:y});return r.jsx(of,{...e,selectionBar:S,paneOverlay:r.jsx(Xo,{verb:s.verb,accountId:d.accountId,mailboxId:d.mailboxId,selection:x,crossAccount:d.moveDisabledHint!==void 0,onFinished:i}),children:n})}function qC({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:n,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i}){const{searchQuery:c,searchInput:u,resultFolderIndex:m,onSearchChange:d}=Fe(),f=gs(),h=es(),v=Nn(),x=to(),p=Je(),b=l.useMemo(()=>xS(e.filter($=>!$.muted?.value)),[e]),[y,S]=l.useState("all"),[g,w]=l.useState("all"),[C,R]=l.useState(new Set),[A,j]=l.useState(!1),T=l.useCallback($=>{R(le=>{const de=new Set(le);return de.has($)?de.delete($):de.add($),de})},[]),P=l.useCallback(()=>R(new Set),[]),N=u.trim().length>0,L=l.useMemo(()=>vb({query:u,ownFilters:C}),[u,C]),D=l.useMemo(()=>yb({query:u,ownCategory:g}),[u,g]),k=l.useCallback($=>{if(!N||!Nu($)){T($);return}const le=gb(u,$);le!==void 0&&d(le)},[N,u,d,T]),I=l.useCallback($=>{if(!N){w($);return}d(xb(u,$))},[N,u,d]),O=l.useCallback(()=>{w("all"),S("all"),P(),N&&d(bb(u))},[N,u,d,P]),{data:M,isLoading:F,isError:E,refetch:V}=Ce({...va(),staleTime:6e4}),X=gt({queries:b.map($=>({...ft({path:{accountId:$.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),Z=l.useMemo(()=>{const $=new Map;for(let le=0;le<b.length;le++){const de=b[le].accountId,H=(X[le]?.data?.items??[]).reduce((pe,re)=>pe+(re.unseenCount??0),0);$.set(de,H)}return $},[b,X]),ae=l.useMemo(()=>b.filter(($,le)=>{const de=X[le];return de?.isError?!ya(de.error):!1}),[b,X]),{freeText:ie,tokens:oe}=Bs(c.trim().toLowerCase(),f),{data:ue,isFetching:ge}=Ce({...va({query:{query:ie,limit:zC}}),enabled:ie.length>0,staleTime:3e4}),B=l.useMemo(()=>{const $=Fl(M?.items??[]).map(nr);return(ie?bS($.filter(de=>Xd(de,ie)),Fl(ue?.items??[]).map(nr)):$).filter(de=>(y==="all"||de.accountId===y)&&Wo(de,oe))},[M,ue,y,ie,oe]),{bodyRows:U,briefSpamOffer:he}=l.useMemo(()=>{if(!ie)return{bodyRows:B,briefSpamOffer:void 0};const $=B.map(ye=>Wn(ye,m)),{spam:le}=wo($);if(le.length===0)return{bodyRows:B,briefSpamOffer:void 0};const de=new Set(le.map(ye=>ye.id));return{bodyRows:B.filter(ye=>!de.has(ye.id)),briefSpamOffer:tf($)}},[B,ie,m]),me=l.useMemo(()=>vS(U),[U]),se=l.useCallback(($,le)=>{const de=ie?U.find(ye=>ye.id===$):void 0;if(de?.threadId&&de.mailboxId&&n){n(Wn(de,m),le);return}s?.($,le)},[ie,U,m,n,s]),we=l.useMemo(()=>b.length<=1?[]:[{id:"all",label:"All",active:y==="all"},...b.map($=>({id:$.accountId,label:$.email.split("@")[0]??$.email,count:Z.get($.accountId),active:y===$.accountId}))],[b,Z,y]),K=l.useMemo(()=>e.filter($=>$.muted?.value).length,[e]),Ee=l.useMemo(()=>Array.from(Z.values()).reduce(($,le)=>$+le,0),[Z]),be=l.useMemo(()=>b.map($=>$.accountId),[b]),{hasNewMail:je}=Ir(),{state:fe,errorMessage:ne,refresh:Se}=To(be,{onSettled:()=>V()}),Le=l.useMemo(()=>r.jsx(So,{state:fe,onRefresh:Se,label:"Refresh daily brief",errorMessage:ne,hasUpdate:je(be)}),[fe,Se,ne,je,be]),ze=l.useMemo(()=>B.filter($=>(D==="all"||$.category===D)&&rh($,L)).map($=>Wn($,m)),[B,D,L,m]),{hits:J,isLoading:Ze}=Yd(),Ie=l.useMemo(()=>{const $=new Map;for(const de of M?.items??[])$.set(de.messageId,de.threadId);const le=ze.map(de=>$.get(de.id)).filter(de=>de!=null);return Zd(J,le,m)},[J,ze,M,m]),qe=l.useMemo(()=>{const $=tb(we.map(le=>({id:le.id,label:le.label,count:le.count,active:le.active})));return{categories:$.categories,filters:$.filters,sources:$.sources,sourcesNote:K>0?`+${K} muted`:void 0,selectedCategory:D,activeFilters:L,expanded:A,onExpandedChange:j,onSelectCategory:le=>I(le),onSelectSource:S,onToggleFilter:le=>k(le),onClear:O}},[we,K,D,L,A,k,I,O]),q=me.length===0&&y==="all"&&ie.length===0&&oe.length===0,Qe=l.useMemo(()=>b.map($=>$.accountId),[b]),Re=l.useMemo(()=>b.some($=>Ro($.syncPhase)),[b]),ve=Ty(Qe,q||Re),Oe=r.jsxs("div",{className:"h-full overflow-y-auto",children:[r.jsx(ql,{}),r.jsx(ql,{})]}),xe=!F&&!E&&!q,ke=ef({tier:v,hasLiveInput:N,hasCommittedQuery:c.trim().length>0,bodyRendersCommittedResults:!0}),Te=xe?r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[he&&r.jsx(pu,{count:he.count,onScopeToSpam:()=>p({to:"/mail/$mailboxId",params:{mailboxId:he.mailboxId},search:{q:c||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}),r.jsx("div",{className:"min-h-0 flex-1",children:r.jsx(rc,{sections:me,briefCategory:D,Row:Yo,selectedThreadId:t,onSelectThread:se,onSelectBriefCategory:I,sources:we,sourcesNote:K>0?`+${K} muted`:void 0,onSelectSource:S,activeFilters:L,onToggleFilter:k,onClearFilters:O})})]}):F?Oe:E?r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[r.jsx(Pt,{className:"size-8 text-danger"}),r.jsx("p",{children:"Couldn't load your messages"}),r.jsxs("button",{type:"button",onClick:()=>V(),className:"flex items-center gap-1 text-accent underline text-xs",children:[r.jsx(ho,{className:"size-3.5"}),"Try again"]})]}):ve.resolved?r.jsx(rx,{sync:ve.syncing?{synced:ve.synced,total:ve.total}:void 0}):Oe;return r.jsx(Cc,{hasSheet:xe&&!ke,children:r.jsx(uf,{selectedMessageId:t,onOpen:se,onDeleteMessages:i,onSelectionVerb:x.start,wizardOpen:x.isOpen,commandsRef:a,onTriageContextChange:o,children:r.jsx(KC,{wizard:x,header:{title:"Daily brief",unreadCount:Ee,footer:h?r.jsx(tu,{}):void 0,searchFilter:qe,searchResults:ze,searchLoading:F||ge,relatedResults:Ie,relatedLoading:Ze,onSelectSearchResult:n,searchResultsInBody:!0,refreshControl:Le},rows:B,children:r.jsxs("div",{className:"flex h-full flex-col",children:[ae.map($=>r.jsx(BC,{accountEmail:$.email,accountId:$.accountId},$.accountId)),r.jsx("div",{className:"min-h-0 flex-1",children:Te})]})})})})}const HC=10,xf=e=>({q:e?.toLowerCase()??"",limit:HC}),WC=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(n=>n.normalizedEmail===s)};function VC(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Xn(t,{month:"short",year:"numeric"})}function bf(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const QC="We can't verify the sender of this email, which could mean it's from an insecure source.",GC="We couldn't read this sender's address, so we can't confirm who really sent this message.";function YC(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?VC(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:bf(e.fromEmail)}}function XC(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 Hl(e){if(e.fromName&&e.fromName!==e.fromEmail)return e.fromName}function JC(e){return e.length===1?e[0]:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function ZC(e,t){const s=[],n=e.displayNameCorrespondence;t&&(n===di.Unrelated?s.push(`The name it shows, "${t}", has nothing to do with ${e.fromDomain}.`):n===di.Lookalike&&s.push(`The name it shows, "${t}", only looks like ${e.fromDomain}.`));const a=ek(e.offDomainLinkDomains);return a.length>0&&s.push(`Its links go to ${JC(a.slice(0,3))}.`),s}function ek(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function tk(e,t){const s=t>0?t:void 0;if(bf(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:GC,similarCount:s};const n=e.authenticity;if(!n)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:QC};if(!n.dkimMismatch){const m=Hl(e),d=ZC(n,m);return d.length>0?{verdict:"caution",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,claimedBrand:m,summary:d.join(" ")}:{verdict:"aligned",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,summary:n.dkimDomain?`This message was signed by ${n.dkimDomain}.`:"Nothing looks unusual about this sender."}}const a=n.fromDomain,o=n.dkimDomain,i=Hl(e),c=o?`it was actually sent from ${o}`:"its signature failed to verify",u=i?`The display name claims "${i}", but ${c}${o?` — not ${a}`:""}. Real senders use their own address.`:`This message claims to be from ${a}, but ${c}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:u,similarCount:s}}function vf(e,t){const s=e?.fromEmail??null,n=e?.subject??"",{data:a,error:o}=Ce({...ur({query:xf(s??void 0)}),enabled:!!s,staleTime:3e4}),i=WC(a?.items,s??void 0),c=[n,s].filter(Boolean).join(" "),{data:u,isLoading:m,error:d}=Ce({...wc({query:{query:c,limit:5}}),enabled:!!(e&&c.length>3),staleTime:6e4,retry:1});return{data:l.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(y=>y.messageId!==e.messageId).map(y=>({id:y.messageId,mailboxId:t!=null&&y.mailboxIds.includes(t)?t:y.mailboxIds[0]??"",fromName:y.fromName??"",subject:y.subject??"(No subject)",timeLabel:y.sentDate!=null?xt(y.sentDate*1e3):"",matched:y.matchedChunkType})),v=YC(e,i),x=tk(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},b=XC(i);return{sender:v,authenticity:x,category:p,flags:b,similar:h}},[e,i,u,t]),isSimilarLoading:m,similarError:d,similarErrorIsFatal:ya(d),addressErrorIsFatal:ya(o),addressId:i?.addressId,address:i}}function sk(e,t){const s={...e??{}};for(const[n,a]of Object.entries(t))a==null?delete s[n]:s[n]={...a,setAt:a.setAt??Date.now()};return s}function yf({addressId:e,senderEmail:t}){const s=Pe(),{pushError:n}=st(),a=ah({query:xf(t)}),{mutate:o,isPending:i}=Ue({...yc(),onMutate:async u=>{const m=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,f=>f&&{...f,items:f.items.map(h=>h.addressId===u.path.addressId?{...h,flags:sk(h.flags,m)}:h)}),{previous:d}},onError:(u,m,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),n({title:"Couldn't update sender preference",detail:dt(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:l.useCallback(u=>{if(!e){Wa(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 nk=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",wf=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function rk(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function ak(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function ok(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Sf(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const ik=["personal","newsletter","marketing","automated","transactional","social"],lk=e=>e.spamReport?"notSpam":"reportSpam",ck=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:n}=e;return t&&!s?"error":n?"loading":"ready"};function uk(){return r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Dt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"h-8 rounded bg-surface"})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>r.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function dk({isOpen:e,current:t,onSelect:s,onCancel:n}){return e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx(kc,{label:"Dismiss reclassify sender",onDismiss:n,className:"backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),r.jsx("div",{className:"mt-4 flex flex-col gap-1",children:ik.map(a=>r.jsxs("button",{type:"button",onClick:()=>s(a),className:`flex min-h-11 items-center justify-between rounded px-3 text-left text-sm capitalize transition-colors hover:bg-surface-raised ${a===t?"font-semibold text-accent":"text-fg"}`,children:[a,a===t&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"current"})]},a))}),r.jsx("div",{className:"mt-6 flex justify-end",children:r.jsx("button",{type:"button",onClick:n,className:"inline-flex min-h-11 items-center justify-center rounded border border-line px-4 text-sm font-medium transition-colors hover:bg-surface-raised",children:"Cancel"})})]})]}):null}function fk({thread:e,onClose:t,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o}){const{data:i,addressId:c,isSimilarLoading:u,similarError:m,similarErrorIsFatal:d}=vf(e,s),[f,h]=l.useState(!1),v=e.fromEmail??void 0,{updateFlags:x}=yf({addressId:c,senderEmail:v}),{reportSpam:p,notSpam:b,isReporting:y,isRestoring:S}=gd({mailboxId:e.mailboxId,threadId:e.threadId,accountId:n,onAfterOptimisticRemove:o}),g=Ps(),w=lk(e),C=l.useCallback(()=>{b([e.messageId])},[b,e.messageId]),R=l.useCallback(()=>{Sf(g,{count:1,senderTrust:e.senderTrust,wasRescuable:wf(e)}),p([e.messageId])},[p,e,g]),A=l.useCallback(()=>{},[]),j=l.useCallback(()=>{const O=i?.flags?.vip!==!0;x({vip:{value:O}})},[i?.flags?.vip,x]),T=l.useCallback(()=>{const O=i?.flags?.muted!==!0;x({muted:{value:O}})},[i?.flags?.muted,x]),P=l.useCallback(()=>{const O=i?.flags?.unsubscribed!==!0;x({unsubscribed:{value:O}})},[i?.flags?.unsubscribed,x]),N=l.useCallback(O=>{h(!1),x({category:{value:O}})},[x]),L=c!==void 0,D={onToggleVip:L?j:void 0,onToggleMute:L?T:void 0,onToggleUnsubscribe:L?P:void 0,onReclassify:L?()=>h(!0):void 0,onNotSpam:w==="notSpam"?C:void 0,onReportSpam:w==="reportSpam"?R:void 0},k=({mailboxId:O,messageId:M,className:F,ariaLabel:E,children:V})=>r.jsx(Wt,{to:"/mail/$mailboxId",params:{mailboxId:O},search:X=>({...X,selectedMessageId:M}),variant:"row",className:F,"aria-label":E,children:V});if(!i)return r.jsx(uk,{});const I=ck({similarError:m,similarErrorIsFatal:d,isSimilarLoading:u});return r.jsxs(r.Fragment,{children:[r.jsx(Yc,{data:i,onClose:t,hideCloseButton:a,onShowSimilar:A,actions:D,similarState:I,similarLinkComponent:k,reportSpamPending:y,notSpamPending:S,className:"border-l-0 h-full w-full"}),r.jsx(dk,{isOpen:f,current:i.category.value,onSelect:N,onCancel:()=>h(!1)})]})}const Us=({onClose:e,thread:t,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o})=>t?r.jsx(fk,{thread:t,onClose:e,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o}):r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Dt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[r.jsx(Dt,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),ha="Open a message first",Jo=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:n,onReply:a,onReplyAll:o,onForward:i,onDelete:c,canDelete:u,onToggleStar:m,isStarred:d,moveContext:f})=>{const[h,v]=l.useState(null),x=u??e,p=b=>()=>v(b);return r.jsx(ug,{hasThread:e,isStarred:d,onUnavailable:b=>v(ha),unavailableHint:h,replyTitle:`Reply ${Vs("reply")}`,replyAllTitle:`Reply all ${Vs("replyAll")}`,forwardTitle:`Forward ${Vs("forward")}`,deleteTitle:`Move to Trash ${Vs("delete")}`,flagTitle:`Star ${Vs("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:x?c:p(ha),onToggleStar:m,onMove:p(ha),moveSlot:f?r.jsx(qo,{accountId:f.accountId,currentMailboxId:f.currentMailboxId,onMove:f.onMove,label:"Move to mailbox"}):void 0,children:r.jsx(cg,{open:t,enabled:s,onToggle:n})})},Cf=()=>{const e=Pe();return l.useCallback(t=>{const s=Zt({path:{threadId:t.threadId}}),a=e.getQueriesData({queryKey:s}).flatMap(([,o])=>o?.items.map(i=>i.messageId)??[]);return a.length>0?a:[t.messageId]},[e])},mn=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=t??e?.mailboxId,o=s??e?.accountId,{accountId:i}=Lo(o?void 0:a),c=o??i,u=Cf(),{deleteMessages:m}=fs({mailboxId:a??"",threadId:e?.threadId,accountId:c,onAfterOptimisticRemove:n}),{moveMessages:d}=Os({mailboxId:a??"",threadId:e?.threadId,accountId:c,onAfterOptimisticRemove:n}),{toggleStar:f}=Fo({threadId:e?.threadId??"",mailboxId:a??""}),h=l.useCallback(()=>{e&&m(u(e))},[e,u,m]),v=l.useCallback(S=>{e&&d(u(e),S)},[e,u,d]),x=l.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[p,b]=l.useState(null),y=l.useCallback(()=>b(null),[]);return{mailboxId:a,accountId:c,isStarred:e?.hasStars,deleteThread:h,moveThread:v,toggleStar:x,composeRequest:p,requestCompose:b,clearComposeRequest:y}},Wl=(e,t,s)=>{if(!t)return null;const n=e.indexOf(t);if(n===-1)return null;const a=s==="next"?n+1:n-1;return a<0||a>=e.length?null:e[a]},Zo=()=>{const[e,t]=l.useState(void 0),[s,n]=l.useState([]),[a,o]=l.useState([]),i=l.useRef(null),[c,u]=l.useState(!1),[m,d]=l.useState(!1),f=l.useCallback(h=>{t(h.focusedMessageId),n(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:f,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:c,blocksKeyboard:m}},ei=({context:e,orderedIds:t,selectedMessageId:s,enabled:n=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:c,blocksKeyboard:u}=e,m=l.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return Tu({enabled:n&&!u,handlers:{...c?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:m,...o}}),{goBack:m,nextMessageId:Wl(t,s,"next")??void 0,previousMessageId:Wl(t,s,"previous")??void 0}};function mk(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function kf(e,t){if(e)return mk(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const jf=l.createContext(null);function Fr(){const e=l.useContext(jf);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function hk({selectedMessageId:e,children:t}){const s=Je(),{searchInput:n}=Fe(),{selectedThreadId:a,selectedMailboxId:o}=Ms({strict:!1}),{data:i}=Ce({...va(),staleTime:6e4}),c=l.useMemo(()=>{if(e)return i?.items.find(T=>T.messageId===e)},[i,e]),u=l.useMemo(()=>kf(c,{messageId:e,threadId:a,mailboxId:o}),[c,e,a,o]),m=l.useCallback((T,P)=>{s({to:"/mail",search:N=>({...N,selectedMessageId:T,selectedThreadId:void 0,selectedMailboxId:void 0}),replace:P?.replace})},[s]),d=l.useCallback((T,P)=>{s({to:"/mail",replace:P?.replace,search:N=>({...N,q:n||void 0,selectedMessageId:T.id,selectedThreadId:T.threadId,selectedMailboxId:T.mailboxId})})},[s,n]),f=l.useCallback(T=>{e&&T.includes(e)&&s({to:"/mail",search:P=>({...P,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=mn({thread:c,onAfterOptimisticRemove:f}),v=l.useCallback(()=>{s({to:"/mail",search:T=>({...T,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),x=Zo(),p=l.useMemo(()=>i?.items??[],[i]),{deleteMessages:b}=fs({mailboxId:c?.mailboxId??"",messages:p,onAfterOptimisticRemove:f}),{toggleReadFor:y}=Mr({mailboxId:c?.mailboxId??"",messages:p}),S=x.focusedMessageId,w=l.useMemo(()=>i?.items.find(T=>T.messageId===S),[i,S])??c,C=mn({thread:w}),{nextMessageId:R,previousMessageId:A}=ei({context:x,orderedIds:x.orderedIds,selectedMessageId:e,onClose:v,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{x.listCommandsRef.current?.requestVerb("delete")||C.deleteThread()},toggleStar:C.toggleStar,toggleRead:()=>{x.listCommandsRef.current?.requestVerb("markRead")||w&&y([w.messageId],!w.isRead)},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),j={selectedMessageId:e,selectedThread:c,conversation:u,onSelectMessage:m,onSelectSearchResult:d,onCloseThread:v,actions:h,triage:x,onDeleteMessages:b,nextMessageId:R,previousMessageId:A,handleDeselectIfRemoved:f};return r.jsx(jf.Provider,{value:j,children:t})}function Nf(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:n,onDeleteMessages:a}=Fr(),{accounts:o}=Fe();return r.jsx(qC,{accounts:o,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:n.listCommandsRef,onTriageContextChange:n.onTriageContextChange,onDeleteMessages:a})}function pk(){const{conversation:e,actions:t}=Fr(),{intelligenceOpen:s,onToggleIntelligence:n}=Fe(),a=hs()?.showIntelligencePane??!1,o=!!e,i=a&&o;return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Jo,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(zs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(_s,{})})]})}function gk(){const{selectedThread:e,handleDeselectIfRemoved:t}=Fr(),{onToggleIntelligence:s}=Fe();return r.jsx(Us,{onClose:s,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,onAfterOptimisticRemove:t})}function xk(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:n,nextMessageId:a,previousMessageId:o,handleDeselectIfRemoved:i}=Fr(),{intelligenceOpen:c,onToggleIntelligence:u}=Fe();return t?r.jsxs(r.Fragment,{children:[r.jsx(zs,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:n,onOpenIntelligence:u,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:c}),r.jsx(Oo,{isOpen:c,onClose:u,ariaLabel:"Message details",side:"right",children:r.jsx(Us,{onClose:u,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,hideCloseButton:!0,onAfterOptimisticRemove:i})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Nf,{})})}const Zs=Object.assign(hk,{List:Nf,Reading:pk,Intelligence:gk,Phone:xk}),bk=()=>Xa({query:{starred:!0,order:"desc"}});function Ef(){const{data:e,isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:c}=Hu({queryKey:bk(),queryFn:async({pageParam:m})=>{const{data:d}=await oh({query:{starred:!0,order:"desc",continuationToken:m},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:m=>m.continuationToken,staleTime:6e4});return{threads:l.useMemo(()=>(e?.pages??[]).flatMap(m=>m.items??[]),[e]),isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:c}}const vk=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function If({title:e,unreadCount:t,preset:s,selectedCategory:n,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:c,onClearFilters:u,children:m,footer:d,searchResults:f,searchLoading:h,relatedResults:v,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:y,searchResultsInBody:S,refreshControl:g}){const{searchInput:w}=Fe(),C=w.trim().length>0,R={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:n,activeFilters:a,onSelectCategory:o,onSelectSource:c,onToggleFilter:i,onClear:u};return r.jsx(Cc,{hasSheet:!C,children:r.jsx(of,{title:e,unreadCount:t,footer:d,searchFilter:R,searchResults:f,searchLoading:h,relatedResults:v,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:y,searchResultsInBody:S,refreshControl:g,children:r.jsx(uc,{...R,hideChrome:C,children:m})})})}const yk={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function wk({rows:e,verb:t}){const{selectedIds:s,exitSelection:n}=Go(),a=l.useMemo(()=>e.filter(o=>s.has(o.id)).map(o=>({id:o.id,sender:o.fromName,email:o.fromEmail,subject:o.subject,date:o.timeLabel})),[e,s]);return r.jsx(Xo,{verb:t,selection:a,crossAccount:!0,onFinished:n})}function Sk({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:n,onDeleteMessages:a}){const{searchQuery:o,resultFolderIndex:i}=Fe(),c=gs(),u=es(),m=to(),[d,f]=l.useState("all"),[h,v]=l.useState(new Set),x=l.useCallback(F=>{v(E=>{const V=new Set(E);return V.has(F)?V.delete(F):V.add(F),V})},[]),p=l.useCallback(()=>{f("all"),v(new Set)},[]),{threads:b,isLoading:y,isError:S,error:g,refetch:w,fetchNextPage:C,hasNextPage:R,isFetchingNextPage:A}=Ef(),{freeText:j,tokens:T}=Bs(o.trim().toLowerCase(),c),P=l.useMemo(()=>{const F=Array.from(h).map(E=>yk[E]).filter(E=>E!=null);return vk(b).map(nr).filter(E=>(d==="all"||E.category===d)&&F.every(V=>V(E))&&(!j||Xd(E,j))&&Wo(E,T))},[b,d,h,j,T]),N=l.useMemo(()=>sb(),[]),L=l.useMemo(()=>P.map(F=>Wn(F,i)),[P,i]),D=l.useMemo(()=>P.filter(F=>!F.isRead).length,[P]),k=y?"loading":S?"error":P.length===0?"empty":"ready",I=l.useCallback(()=>{const F=Ja(Za());window.open(F,"_blank","noopener,noreferrer")},[]),O=Lr(),M=r.jsx("div",{className:"flex h-full min-h-0 flex-col",children:r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r.jsx("div",{className:"divide-y divide-line",children:P.map(F=>r.jsx(Yo,{thread:F,active:F.id===e,onClick:()=>t?.(F.id)},F.id))}),R?r.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>C(),disabled:A,children:A?"Loading…":"Load more"}):null]})});return r.jsx(If,{title:"Starred",unreadCount:D,preset:N,selectedCategory:d,activeFilters:h,onSelectCategory:f,onToggleFilter:x,onClearFilters:p,searchResults:L,searchLoading:y,onSelectSearchResult:F=>t?.(F.id),searchResultsInBody:!0,children:r.jsxs(uf,{selectedMessageId:e,onOpen:(F,E)=>t?.(F,E),onDeleteMessages:a,onSelectionVerb:m.start,wizardOpen:m.isOpen,commandsRef:s,onTriageContextChange:n,children:[r.jsx(uu,{listTitle:"Starred",sections:[{id:"flagged",threads:P}],flatList:!0,hideHeader:!0,listState:O.searchResults?"ready":k,searchQuery:j?o:void 0,errorMessage:S?Ec(g):void 0,onRetry:()=>w(),onReportError:I,selectedThreadId:e,onSelectThread:t,isDesktop:u,selectionBar:r.jsx(nC,{title:"Starred"}),listBody:O.searchResults??(k==="ready"?M:void 0)}),r.jsx(wk,{rows:P,verb:m.verb})]})})}const Rf=l.createContext(null);function $r(){const e=l.useContext(Rf);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function Ck({selectedMessageId:e,children:t}){const s=Je(),{threads:n}=Ef(),a=l.useMemo(()=>{if(e)return n.find(g=>g.messageId===e)},[n,e]),o=l.useCallback((g,w)=>{s({to:"/mail/flagged",search:C=>({...C,selectedMessageId:g}),replace:w?.replace})},[s]),i=l.useCallback(()=>{s({to:"/mail/flagged",search:g=>({...g,selectedMessageId:void 0})})},[s]),c=l.useCallback(g=>{e&&g.includes(e)&&i()},[e,i]),u=mn({thread:a,onAfterOptimisticRemove:c}),m=Zo(),{deleteMessages:d}=fs({mailboxId:a?.mailboxId??"",messages:n,onAfterOptimisticRemove:c}),{toggleReadFor:f}=Mr({mailboxId:a?.mailboxId??"",messages:n}),h=m.focusedMessageId,x=l.useMemo(()=>n.find(g=>g.messageId===h),[n,h])??a,p=mn({thread:x}),{nextMessageId:b,previousMessageId:y}=ei({context:m,orderedIds:m.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{m.listCommandsRef.current?.requestVerb("delete")||p.deleteThread()},toggleStar:p.toggleStar,toggleRead:()=>{m.listCommandsRef.current?.requestVerb("markRead")||x&&f([x.messageId],!x.isRead)},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),S={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:m,onDeleteMessages:d,nextMessageId:b,previousMessageId:y,handleDeselectIfRemoved:c};return r.jsx(Rf.Provider,{value:S,children:t})}function Tf(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:n}=$r();return r.jsx(Sk,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:n})}function kk(){const{selectedThread:e,actions:t}=$r(),{intelligenceOpen:s,onToggleIntelligence:n}=Fe(),a=hs()?.showIntelligencePane??!1,o=!!e,i=a&&o;return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Jo,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(zs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(_s,{})})]})}function jk(){const{selectedThread:e,handleDeselectIfRemoved:t}=$r(),{onToggleIntelligence:s}=Fe();return r.jsx(Us,{onClose:s,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,onAfterOptimisticRemove:t})}function Nk(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:n,previousMessageId:a,handleDeselectIfRemoved:o}=$r(),{intelligenceOpen:i,onToggleIntelligence:c}=Fe();return e?r.jsxs(r.Fragment,{children:[r.jsx(zs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:c,onSwipeNext:n?()=>s(n):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:i}),r.jsx(Oo,{isOpen:i,onClose:c,ariaLabel:"Message details",side:"right",children:r.jsx(Us,{onClose:c,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,hideCloseButton:!0,onAfterOptimisticRemove:o})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Tf,{})})}const en=Object.assign(Ck,{List:Tf,Reading:kk,Intelligence:jk,Phone:Nk}),Ek={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Ik=()=>{const e=l.useRef(!1);return l.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector('[data-testid="compose-body"]')?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},Rk=()=>{const{state:e,closeCompose:t}=Ft(),s=Ik(),[n,a]=l.useState(!1),{isError:o,error:i,refetch:c}=Ce({..._t(),staleTime:1/0}),u=l.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),m=l.useCallback(()=>{a(!1),t()},[t]),d=l.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const f=Ek[e.mode]??"New Message";return r.jsxs(ut.Root,{open:e.isOpen,onOpenChange:u,children:[r.jsxs(ut.Portal,{children:[r.jsx(ut.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(ut.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-lg bg-canvas pb-[env(safe-area-inset-bottom,0px)]",style:{height:"95dvh"},children:[r.jsx(ut.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),r.jsx(ut.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:f}),o?r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(ts,{title:"Couldn't load compose",error:i,onRetry:()=>{c()}})}):r.jsx("div",{className:"flex-1 overflow-hidden",children:r.jsx(Do,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),r.jsx(lo,{isOpen:n,title:"Discard draft?",description:"Your message has unsaved content. Are you sure you want to discard it?",confirmLabel:"Discard",cancelLabel:"Keep editing",destructive:!0,onConfirm:m,onCancel:d})]})},Tk={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Mf=()=>{const{state:e,closeCompose:t}=Ft(),s=es(),{isError:n,error:a,refetch:o}=Ce({..._t(),staleTime:1/0});if(!s)return r.jsx(Rk,{});if(!e.isOpen)return null;const i=Tk[e.mode]??"New Message",c=r.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[r.jsx("div",{className:"flex items-center gap-2 min-w-0",children:r.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:r.jsx(Et,{className:"size-5"})})]});return n?r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[c,r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(ts,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):r.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[c,r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:r.jsx(Do,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function Mk(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:xt(e.updatedAt),isRead:!0}}function Ak(e){return{id:e.messageId,accountId:e.accountId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:xt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function Ok({outboxMessages:e,accountId:t,imapThreads:s}){const n=e.filter(i=>i.status==="draft"&&i.accountId===t).map(Mk),a=s.map(Ak),o=[];return n.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:n}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function ti(){const e=hs();return!e||e.showNavPane?null:r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(pr,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const Dk=({label:e,count:t})=>r.jsxs("div",{className:"sticky top-0 z-10 flex items-baseline justify-between border-b border-line bg-surface-sunken px-row-inset py-1",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:t})]}),Pk=({row:e,isSelected:t,onOpen:s,onDelete:n,isDeleting:a})=>r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:Q("group",$s({active:t})),children:[r.jsx(ic,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),r.jsx(cn,{thread:e}),r.jsx("div",{className:"flex items-center gap-1 shrink-0",children:r.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),n(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:r.jsx(Lt,{className:"size-3.5"})})})]}),Lk=({row:e,isSelected:t,onOpen:s})=>{const n=!e.isRead;return r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:Q("group",$s({active:t})),children:[n&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx(Nt,{name:e.fromName,email:e.fromEmail,size:"sm"}),r.jsx(cn,{thread:e})]})};function Fk({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:n,title:a,unreadCount:o}){const{openCompose:i,state:c}=Ft(),u=Je(),m=Pe(),{data:d}=Ce(cr()),f=l.useMemo(()=>Ok({outboxMessages:d?.items??[],accountId:t,imapThreads:n}),[d?.items,t,n]),h=Ue({...dr(),onSuccess:()=>{m.invalidateQueries({queryKey:so()})}}),v=y=>{h.mutate({path:{outboxMessageId:y}})},x=y=>{i({mode:"new",outboxMessageId:y})},p=y=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:y}})},b=f.length===0;return r.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(ti,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:a}),(o??0)>0&&r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:[o," unread"]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:b?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[r.jsx(za,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):f.map(y=>r.jsxs("div",{children:[y.label&&r.jsx(Dk,{label:y.label,count:y.threads.length}),r.jsx("div",{className:"divide-y divide-line",children:y.threads.map(S=>y.id==="remit-drafts"?r.jsx(Pk,{row:S,isSelected:c.isOpen&&S.id===c.outboxMessageId,onOpen:x,onDelete:v,isDeleting:h.isPending},S.id):r.jsx(Lk,{row:S,isSelected:S.id===s,onOpen:p},S.id))})]},y.id))})]})}function $k(e,t,s){const n=new Array(e);return new Proxy(n,{get(a,o,i){if(typeof o=="string"){const c=o.charCodeAt(0);if(c>=48&&c<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let m=a[u];if(!m){const d=t[u*2];m=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return m}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function js(e,t,s){let n=s.initialDeps??[],a,o=!0;function i(){const c=e();return(c.length!==n.length||c.some((m,d)=>n[d]!==m))&&(n=c,a=t(...c),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=c=>{n=c},i}function Vl(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _k=(e,t)=>Math.abs(e-t)<1.01,zk=(e,t,s)=>{let n;return function(...a){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,a),s)}};let tn;const pa=()=>{if(tn!==void 0)return tn;if(typeof navigator>"u")return tn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return tn=!0;const e=navigator.maxTouchPoints;return tn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Ql=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},Bk=e=>e,Uk=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,a=new Array(n);for(let o=0;o<n;o++)a[o]=t+o;return a},Kk=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const a=i=>{const{width:c,height:u}=i;t({width:Math.round(c),height:Math.round(u)})};if(a(Ql(s)),!n.ResizeObserver)return()=>{};const o=new n.ResizeObserver(i=>{const c=()=>{const u=i[0];if(u?.borderBoxSize){const m=u.borderBoxSize[0];if(m){a({width:m.inlineSize,height:m.blockSize});return}}a(Ql(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},rr={passive:!0},qk=typeof window>"u"?!0:"onscrollend"in window,Hk=(e,t,s)=>{const n=e.scrollElement;if(!n)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&qk;let i=0;const c=o?null:zk(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=f=>()=>{i=s(n),c?.(),t(i,f)},m=u(!0),d=u(!1);return n.addEventListener("scroll",m,rr),o&&n.addEventListener("scrollend",d,rr),()=>{n.removeEventListener("scroll",m),o&&n.removeEventListener("scrollend",d)}},Wk=(e,t)=>Hk(e,t,s=>{const{horizontal:n,isRtl:a}=e.options;return n?s.scrollLeft*(a&&-1||1):s.scrollTop}),Vk=(e,t,s)=>{if(s.options.useCachedMeasurements){const n=s.indexFromElement(e),a=s.options.getItemKey(n);return s.itemSizeCache.get(a)??s.options.estimateSize(n)}if(t?.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}if(!t){const n=s.indexFromElement(e),a=s.options.getItemKey(n),o=s.itemSizeCache.get(a);if(o!==void 0)return o}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},Qk=(e,{adjustments:t=0,behavior:s},n)=>{var a,o;(o=(a=n.scrollElement)==null?void 0:a.scrollTo)==null||o.call(a,{[n.options.horizontal?"left":"top"]:e+t,behavior:s})},Gk=Qk;class Yk{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,n,a;return((a=(n=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:n.now)==null?void 0:a.call(n))??Date.now()},this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const c=o.target,u=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);for(const[m,d]of this.elementsCache)if(d===c){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(c,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=n())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=n())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=n())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var n,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Bk,rangeExtractor:Uk,onChange:()=>{},measureElement:Vk,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in s){const v=s[h];v!==void 0&&(o[h]=v)}const i=this.options;let c=null,u=null,m=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,v=o.count,x=this.getMeasurements(),p=h>0?((n=x[0])==null?void 0:n.key)??i.getItemKey(0):null,b=h>0?((a=x[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(v!==h||h>0&&v>0&&(o.getItemKey(0)!==p||o.getItemKey(v-1)!==b)){m=!0;const g=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??x[0]:null;g&&(c=[g.key,this.getScrollOffset()-g.start]);const w=o.followOnAppend===!0?"auto":o.followOnAppend||null;w&&v>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(v-1)!==b)&&(u=w)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(c&&this.scrollOffset!==null){const[h,v]=c,x=this.getMeasurements(),{count:p,getItemKey:b}=this.options;let y=0;for(;y<p&&b(y)!==h;)y++;if(y<p){const S=x[y];if(S){const g=S.start+v;g!==this.scrollOffset&&(f=g-this.scrollOffset,this.scrollOffset=g,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?c[0]:null,d?c[1]:0,u,f])},this.notify=s=>{var n,a;(a=(n=this.options).onChange)==null||a.call(n,this,s)},this.maybeNotify=js(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}if(this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const c=this.getScrollOffset();this.scrollDirection=i?c===o?this.scrollDirection:c<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},c=()=>{this._iosTouching=!1,!(!pa()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,rr),o.addEventListener("touchend",c,rr),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",c),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,c,u]=a;o!==null&&!c&&(pa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),c&&this.scrollToEnd({behavior:c})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),n=this.getMaxScrollOffset();if(s<0||s>n)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=js(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,n,a,o,i,c,u,m)=>(this.prevLanes!==void 0&&this.prevLanes!==c&&(this.lanesChangedFlag=!0),this.prevLanes=c,this.pendingMin=null,{count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:c,laneAssignmentMode:u,gap:m}),{key:!1}),this.getMeasurements=js(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:c,laneAssignmentMode:u,gap:m},d)=>{const f=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const y of this.laneAssignments.keys())y>=s&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),c===1){const y=s*2;let S=this._flatMeasurements;if(!S||S.length<y){const C=new Float64Array(y);S&&h>0&&C.set(S.subarray(0,h*2)),S=C,this._flatMeasurements=S}let g;if(h===0)g=n+a;else{const C=h-1;g=S[C*2]+S[C*2+1]+m}for(let C=h;C<s;C++){const R=o(C),A=f.get(R),j=typeof A=="number"?A:this.options.estimateSize(C);S[C*2]=g,S[C*2+1]=j,g+=j+m}const w=$k(s,S,o);return this.measurementsCache=w,w}const v=this.measurementsCache.slice(0,h),x=new Array(c).fill(void 0),p=new Float64Array(c);let b=0;for(let y=0;y<h;y++){const S=v[y];S&&(x[S.lane]===void 0&&b++,x[S.lane]=y,p[S.lane]=S.end)}for(let y=h;y<s;y++){const S=o(y),g=this.laneAssignments.get(y);let w,C;const R=u==="estimate"||f.has(S);if(g!==void 0&&this.options.lanes>1){w=g;const P=x[w],N=P!==void 0?v[P]:void 0;C=N?N.end+m:n+a}else if(b===c){let P=0,N=p[0],L=x[0];for(let D=1;D<c;D++){const k=p[D];(k<N||k===N&&x[D]<L)&&(P=D,N=k,L=x[D])}w=P,C=N+m,R&&this.laneAssignments.set(y,w)}else w=y%this.options.lanes,C=n+a,R&&this.laneAssignments.set(y,w);const A=f.get(S),j=typeof A=="number"?A:this.options.estimateSize(y),T=C+j;v[y]={index:y,start:C,size:j,end:T,key:S,lane:w},x[w]===void 0&&b++,x[w]=y,p[w]=T}return this.measurementsCache=v,v},{key:!1,debug:()=>this.options.debug}),this.calculateRange=js(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,a,o)=>s.length===0||n===0?(this.range=null,null):(this.range=Jk(s,n,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=js(()=>{let s=null,n=null;const a=this.calculateRange();return a&&(s=a.startIndex,n=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:n,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,a=s.getAttribute(n);return a?parseInt(a,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),c=Math.min(this.options.count-1,a+o);return s>=i&&s<=c}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,c)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(c))});return}const n=this.indexFromElement(s),a=this.options.getItemKey(n),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,n)=>{var a,o;if(s<0||s>=this.options.count)return;let i,c,u;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)u=this.options.getItemKey(s),c=m[s*2],i=m[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,c=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,f=n-d;if(f!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,v=h?this.getTotalSize():0,x=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:c,size:i,end:c+i,lane:0},f,this):c<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,n),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-v):x&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=js(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const c=s[o],u=n[c];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=Af(0,n.length-1,o?c=>a[c*2]:c=>Vl(n[c]).start,s);return Vl(n[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,n,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+o?"end":"start"),n==="center"?s+=(a-o)/2:n==="end"&&(s-=o);const c=this.getMaxScrollOffset();return Math.max(Math.min(c,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(n==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)n="end";else if(i.start<=o+this.options.scrollPaddingStart)n="start";else return[o,n];if(n==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),n];const c=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(c,n,i.size),n]},this.scrollToOffset=(s,{align:n="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,n),i=this.now();this.scrollState={index:null,align:n,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:n="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,n);if(!o)return;const[i,c]=o,u=this.now();this.scrollState={index:s,align:c,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:n="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let a;if(n.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=n.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=n[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&o.some(c=>c===null);){const c=n[i];o[c.lane]===null&&(o[c.lane]=c.end),i--}a=Math.max(...o.filter(c=>c!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const n=this.getMeasurements();for(const a of n)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:n,behavior:a})=>{this._intendedScrollOffset=s+(n??0),this.options.scrollToFn(s,{behavior:a,adjustments:n},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&(pa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const n=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=n?n[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&_k(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const c=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&u>c;this.scrollState.lastTargetOffset=a,m||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Af=(e,t,s,n)=>{for(;e<=t;){const a=(e+t)/2|0,o=s(a);if(o<n)e=a+1;else if(o>n)t=a-1;else return a}return e>0?e-1:0};function Xk(e,t,s){let n=0;for(;n<=t;){const a=(n+t)/2|0,o=e[a*2];if(o<s)n=a+1;else if(o>s)t=a-1;else return a}return n>0?n-1:0}function Jk(e,t,s,n,a){const o=e.length-1;if(e.length<=n)return{startIndex:0,endIndex:o};if(n===1&&a!==null){const m=Xk(a,o,s);let d=m;const f=s+t;for(;d<o&&a[d*2]+a[d*2+1]<f;)d++;return{startIndex:m,endIndex:d}}let c=Af(0,o,m=>e[m].start,s),u=c;if(n===1)for(;u<o&&e[u].end<s+t;)u++;else if(n>1){const m=Array(n).fill(0);for(;u<o&&m.some(f=>f<s+t);){const f=e[u];m[f.lane]=f.end,u++}const d=Array(n).fill(s+t);for(;c>=0&&d.some(f=>f>=s);){const f=e[c];d[f.lane]=f.start,c--}c=Math.max(0,c-c%n),u=Math.min(o,u+(n-1-u%n))}return{startIndex:c,endIndex:u}}const ga=typeof document<"u"?l.useLayoutEffect:l.useEffect;function Zk({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...n}){const a=l.useReducer(m=>m+1,0)[1],o=l.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=m=>{const d=o.current;if(!d.enabled||!d.container)return;const f=m.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const y=m.options.horizontal?"width":"height";d.container.style[y]=`${f}px`}const h=!!m.options.horizontal,v=d.mode==="transform",x=h?"left":"top",p=m.options.scrollMargin,b=m.getVirtualItems();for(const y of b){const S=y.start-p,g=m.elementsCache.get(y.key);g&&d.lastPositions.get(g)!==S&&(d.lastPositions.set(g,S),v?g.style.transform=h?`translate3d(${S}px, 0, 0)`:`translate3d(0, ${S}px, 0)`:g.style[x]=`${S}px`)}},c={...n,onChange:(m,d)=>{var f;const h=o.current;let v=!0;if(h.enabled){i(m);const x=m.range,p=h.prevRange;v=!p||p.isScrolling!==m.isScrolling||p.startIndex!==x?.startIndex||p.endIndex!==x?.endIndex,v&&(h.prevRange=x?{startIndex:x.startIndex,endIndex:x.endIndex,isScrolling:m.isScrolling}:null)}v&&(e&&d?qa.flushSync(a):a()),(f=n.onChange)==null||f.call(n,m,d)}},[u]=l.useState(()=>{const m=new Yk(c);return Object.assign(m,{containerRef:d=>{const f=o.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const h=m.getTotalSize();f.lastSize=h;const v=m.options.horizontal?"width":"height";d.style[v]=`${h}px`}}})});return u.setOptions(c),ga(()=>u._didMount(),[]),ga(()=>u._willUpdate()),ga(()=>{i(u)}),u}function ej(e){return Zk({observeElementRect:Kk,observeElementOffset:Wk,scrollToFn:Gk,...e})}const si=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",tj=e=>`Select all ${si(e)}`,sj=(e,t)=>`All ${Yt(t)} ${si(e)} selected`,nj=({verb:e,confirmingDelete:t,hasSelection:s,junkMailboxId:n,currentMailboxId:a,deletableMessageId:o})=>{if(t)return{kind:"withheld"};if(e==="junk"){const i=wS(n,a);if(i!==void 0)return{kind:"unavailable",reason:i}}return s?{kind:"openWizard"}:e!=="delete"||o===void 0?{kind:"declined"}:{kind:"confirmDelete",messageId:o}},rj=(e,t,s)=>e==="BACK"&&t&&s===void 0,aj=(e,t)=>({id:e.messageId,accountId:e.accountId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:xt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Ar(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),oj=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,messageCount:m,isMultiSelectMode:d,onLongPress:f,isDesktop:h,density:v})=>r.jsx(Yo,{thread:aj(e,m),linkMailboxId:t,inListbox:!0,active:s,focused:n,isTabStop:a,density:v,isDesktop:h,onFocusRow:o,selection:{isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:d,onLongPress:f}}),ij=l.memo(oj),lj=e=>{const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:xt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Ar(e.category),suspicious:t}},cj=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,onDelete:h,onToggleRead:v,density:x})=>{const[p,b]=l.useState("none"),y=Je(),S=l.useCallback(A=>{navigator.vibrate?.(10),A==="trailing"?h(e.messageId):v(e.messageId,e.isRead),b("none")},[h,v,e.messageId,e.isRead]),g=l.useCallback(()=>{d(e.messageId)},[d,e.messageId]),w=l.useCallback(()=>{c(e.messageId)},[c,e.messageId]),C=l.useCallback(()=>{y({to:"/mail/$mailboxId",params:{mailboxId:t},search:A=>({...A,selectedMessageId:e.messageId})})},[y,t,e.messageId]),R=df(e.messageId,u);return f||m?r.jsx(ij,{thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,density:x}):r.jsx("div",{role:"presentation",onPointerDownCapture:R.onMouseDown,onClickCapture:R.claimClick,onContextMenu:R.onContextMenu,children:r.jsx(cu,{thread:lj(e),selectionMode:!1,checked:!1,active:s,peek:p,onPeek:b,onToggleCheck:w,onLongPress:g,onOpen:C,onAct:S})})},uj=72,dj=32,fj=5,Of="remit:list-density",mj=()=>{try{const e=localStorage.getItem(Of);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},hj=({query:e})=>r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[r.jsx(ir,{className:"size-4 text-fg-muted"}),r.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),pj=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:n,isError:a=!1,error:o,onRetry:i,searchQuery:c,searchPredicate:u,onDeleteMessages:m,isDeleting:d=!1,isMoving:f=!1,onLoadMore:h,hasMore:v=!1,isLoadingMore:x=!1,accountId:p,listTitle:b,listMeta:y,listFilter:S,listScopeLabel:g,onTriageContextChange:w,commandsRef:C,hideHeader:R=!1})=>{const A=l.useRef(null),j=Je(),T=es(),P=to(),{verb:N,start:L,startFromSearch:D}=P,k=ih(),I=!!c?.trim(),O=Lr(),{labels:M}=io(p),{pushError:F}=st(),[E,V]=l.useState(s),[X,Z]=l.useState(),ae=l.useCallback(_=>{Z(G=>G===_?G:void 0),V(_)},[]),[ie,oe]=l.useState(mj),ue=l.useCallback(()=>{oe(_=>{const G=_==="comfortable"?"compact":"comfortable";try{localStorage.setItem(Of,G)}catch{}return G})},[]),{toggleReadFor:ge}=Mr({mailboxId:e}),{junkMailboxId:B}=kn(p),U=Pr(B,e),{selectedIds:he,selectedCount:me,hasSelection:se,isSelected:we,toggle:K,select:Ee,clearSelection:be,selectRange:je,setAnchor:fe,selectAll:ne,toggleAll:Se,intersectWith:Le}=eu(),ze=go(me,T),[J,Ze]=l.useState(null),Ie=I&&!!u,qe=`${e}|${JSON.stringify(u??{})}`,q=pf({mailboxId:e,accountId:p,enabled:Ie,predicateKey:qe,searchQuery:u??{}}),Qe=l.useCallback((_,G,St)=>{if(St.error===void 0){if(St.cancelled){F({severity:"warning",title:xC(St.done),detail:bC(_,St.done,G)});return}F({severity:"info",title:Bl(_,St.done)})}},[F]),Re=q.phase.kind,ve=q.clear,Oe=l.useCallback(()=>{Re==="escalated"&&ve(),be()},[be,ve,Re]),[xe,ke]=l.useState(null),Te=l.useRef(null),$=l.useRef(!1),le=l.useRef(null),de=!n&&t.length>0,ye=J!==null,H=ej({count:t.length,getScrollElement:()=>A.current,estimateSize:()=>ie==="compact"?dj:uj,overscan:fj}),pe=s?t.findIndex(_=>_.messageId===s):-1,re=E?t.findIndex(_=>_.messageId===E):-1,ee=l.useCallback(_=>{if(_<0||_>=t.length)return;const G=t[_];if(ze){K(G.messageId);return}Te.current=G.messageId,$.current=!1,Z(G.messageId),V(G.messageId)},[t,ze,K]),Ne=l.useCallback(()=>{if(t.length===0)return;const _=re<0?0:Math.min(re+1,t.length-1);ee(_)},[t.length,re,ee]),De=l.useCallback(()=>{if(t.length===0)return;const _=re<=0?0:re-1;ee(_)},[t.length,re,ee]),Be=l.useCallback(()=>ee(0),[ee]),Ye=l.useCallback(()=>ee(t.length-1),[ee,t.length]),Ke=l.useCallback(()=>{E&&K(E)},[E,K]),Me=l.useMemo(()=>t.map(_=>_.messageId),[t]),et=l.useMemo(()=>{const _=[];for(const G of t)he.has(G.messageId)&&_.push({id:G.messageId,sender:G.fromName??G.fromEmail??"Unknown",email:G.fromEmail??"",subject:G.subject??"(No subject)",date:xt(G.sentDate)});return _},[t,he]),He=l.useCallback((_,G)=>G.shiftKey?(je(Me,_,E),!0):G.metaKey||G.ctrlKey?(K(_),!0):(Oe(),fe(_),!1),[Me,E,je,K,Oe,fe]),nt=l.useCallback(_=>{!m||_.length===0||(le.current=E??null,Ze(_))},[m,E]),rt=l.useCallback(_=>{const G=Zc(Me,E,_);G!==void 0&&(je(Me,G),Te.current=G,$.current=!1,Z(void 0),V(G))},[Me,E,je]),mt=l.useCallback(()=>rt(-1),[rt]),Bt=l.useCallback(()=>rt(1),[rt]),Tt=l.useCallback(()=>{Me.length>0&&ne(Me)},[Me,ne]),Ks=l.useCallback(_=>{const G=nj({verb:_,confirmingDelete:J!==null,hasSelection:se,junkMailboxId:B,currentMailboxId:e,deletableMessageId:m?E:void 0});return G.kind==="openWizard"?(L(_),!0):G.kind==="confirmDelete"?(nt([G.messageId]),!0):G.kind==="unavailable"?(F({severity:"warning",title:G.reason}),!0):G.kind==="withheld"},[J,m,se,B,e,L,E,nt,F]),at=l.useCallback(()=>{E&&j({to:"/mail/$mailboxId",params:{mailboxId:e},search:_=>({..._,selectedMessageId:E})})},[E,j,e]),xs=l.useCallback(_=>{j({to:"/mail/$mailboxId",params:{mailboxId:e},search:G=>({...G,selectedMessageId:_}),replace:!0})},[j,e]);lf({keyboardFocusedMessageId:X,openMessageId:s,enabled:T&&me===0,open:xs});const ht=q.phase.kind==="escalated"?{scope:si(u??{}),total:q.phase.total,searchQuery:u??{},run:_=>q.runAction(_),stop:q.stop}:void 0,vt=l.useCallback(()=>{if(!J)return;const _=J;if(_.length===0){Ze(null);return}const G=new Set(_),St=t.findIndex(tt=>G.has(tt.messageId));let At;for(let tt=St+1;tt<t.length;tt++)if(!G.has(t[tt].messageId)){At=t[tt].messageId;break}if(At===void 0){for(let tt=St-1;tt>=0;tt--)if(!G.has(t[tt].messageId)){At=t[tt].messageId;break}}m?.(_),Oe(),le.current=null,Ze(null),At!==void 0&&(Te.current=At,$.current=!1,ae(At),T&&j({to:"/mail/$mailboxId",params:{mailboxId:e},search:tt=>({...tt,selectedMessageId:At}),replace:!0})),T||ke(Bl("delete",_.length))},[J,t,m,Oe,j,e,T,ae]),Mt=l.useCallback(()=>{const _=le.current;le.current=null,Ze(null),_!==null&&(Te.current=_,$.current=!1,ae(_))},[ae]),ct=l.useMemo(()=>{if(me===0)return;const _=new Set;for(const G of t)he.has(G.messageId)&&_.add(G.accountConfigId);if(_.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[me,he,t]),qs=l.useCallback(()=>{if(ht){D();return}L("organize")},[ht,D,L]),En=l.useCallback(_=>{m?.([_])},[m]),ns=l.useCallback((_,G)=>{ge([_],!G)},[ge]),z=l.useCallback(_=>{T||Ee(_)},[T,Ee]),Y=l.useCallback(()=>{if(q.isRunning||q.phase.kind==="counting"){q.stop();return}Oe()},[q,Oe]),Ae=l.useCallback(()=>{q.clear()},[q]);l.useEffect(()=>{if($.current||!T&&s)return;const _=re>=0?re:pe;_>=0&&H.scrollToIndex(_,{align:"auto"})},[re,pe,H,T,s]),l.useEffect(()=>{s&&($.current=!1,ae(s))},[s,ae]),l.useEffect(()=>{E&&(t.some(_=>_.messageId===E)||ae(t[0]?.messageId))},[t,E,ae]),l.useEffect(()=>{w?.({focusedMessageId:E,selectedIds:Array.from(he),hasList:de,blocksKeyboard:ye||P.isOpen})},[E,he,de,ye,P.isOpen,w]);const pt=l.useRef(w);pt.current=w,l.useEffect(()=>()=>pt.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),l.useEffect(()=>{q.phase.kind!=="idle"||q.isRunning||Le(t.map(_=>_.messageId))},[t,Le,q.phase,q.isRunning]);const yt=l.useRef(e);l.useEffect(()=>{yt.current!==e&&(yt.current=e,Oe())},[e,Oe]),Wu({shouldBlockFn:({action:_})=>rj(_,se,k)?(Oe(),!0):!1,enableBeforeUnload:!1,disabled:!se||k!==void 0}),l.useEffect(()=>{const _=A.current;if(!_||!v||!h)return;const G=()=>{if(x)return;const{scrollTop:St,scrollHeight:At,clientHeight:tt}=_;St+tt>=At-200&&h()};return _.addEventListener("scroll",G,{passive:!0}),G(),()=>_.removeEventListener("scroll",G)},[v,x,h]),l.useEffect(()=>{const _=Te.current;if(!_)return;const G=A.current?.querySelector(`[data-message-id="${_}"]`);G&&(Te.current=null,G.focus({preventScroll:!0}))}),l.useEffect(()=>{if(C){if(!de){C.current=null;return}return C.current={focusNext:Ne,focusPrevious:De,focusFirst:Be,focusLast:Ye,openFocused:at,toggleSelect:Ke,extendSelectDown:Bt,extendSelectUp:mt,selectAll:Tt,clearSelection:()=>se?(Oe(),!0):!1,requestVerb:Ks,toggleDensity:ue},()=>{C.current=null}}},[C,de,Ne,De,Be,Ye,at,Ke,Bt,mt,Tt,se,Oe,Ks,ue]);const bs=n?"loading":a?"error":t.length===0?"empty":"ready",wt=a?Ec(o):void 0,zr=l.useCallback(()=>{const _=Ja(Za());window.open(_,"_blank","noopener,noreferrer")},[]),rs=[{id:"inbox",threads:[]}],vs=Me.length>0&&Me.every(_=>he.has(_)),In=Ie&&v&&vs&&!d&&!f&&q.phase.kind==="idle"&&!q.isRunning,Br=d||f||q.isRunning,Hs=q.phase.kind==="escalated"?q.phase.total:me,Ur=q.runningAction?gC(q.runningAction.kind,q.progress?.done??0,q.progress?.total??Hs):q.phase.kind==="counting"?"Counting matches…":q.phase.kind==="escalated"?sj(u??{},q.phase.total):void 0,Kr=q.phase.kind!=="escalated"&&Me.length>0?{checked:vs,indeterminate:me>0&&!vs,onChange:()=>Se(Me)}:void 0,qr=q.runningAction?{value:q.progress?.done??0,max:q.progress?.total??Hs,tone:wC(q.runningAction.kind)}:void 0,ot=(q.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:q.stop}}:q.phase.kind==="escalated"&&!q.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:Ae}}:In?{tone:"info",text:"",action:{label:tj(u??{}),onClick:q.escalate}}:void 0)??(ct?{tone:"warning",text:ct}:void 0),it=r.jsx(ko,{title:O.title||b,navSlot:O.navSlot,titleMeta:O.titleMeta,searchSlot:O.searchSlot,searchField:O.searchField,idleSlot:O.makeFilterSlot,count:Hs,onCancel:Y,onDelete:()=>L("delete"),onMove:()=>L("move"),onOrganize:qs,onJunk:U?()=>L("junk"):void 0,onMarkRead:()=>L("markRead"),overflowSlot:p&&e&&me>0&&M.length>0?r.jsx(sf,{accountId:p,mailboxId:e,messageIds:Array.from(he)}):void 0,isBusy:Br,isCounting:q.phase.kind==="counting",selectAll:Kr,statusLabel:Ur,progress:qr,notice:ot}),Hf=cf(Me,E),Wf=l.useCallback(_=>{$.current=!0,ae(_)},[ae]),Vf=r.jsxs(r.Fragment,{children:[I&&c&&r.jsx(hj,{query:c}),r.jsxs("div",{ref:A,role:"listbox","aria-multiselectable":!0,"aria-label":b,className:"flex-1 overflow-y-auto",children:[r.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${H.getTotalSize()}px`},children:H.getVirtualItems().map(_=>{const G=t[_.index];return r.jsx("div",{role:"presentation","data-index":_.index,ref:H.measureElement,className:Ve("absolute left-0 top-0 w-full border-b border-line",q.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${_.start}px)`},children:r.jsx(cj,{thread:G,mailboxId:e,isSelected:s===G.messageId,isFocused:E===G.messageId,isTabStop:Hf===G.messageId,onFocusRow:Wf,isChecked:we(G.messageId),onToggleCheck:K,onRowSelect:He,isMultiSelectMode:ze,onLongPress:z,isDesktop:T,onDelete:En,onToggleRead:ns,density:ie})},_.key)})}),x&&r.jsx(Wp,{})]})]});return r.jsxs(r.Fragment,{children:[xe&&!T&&r.jsx(gn,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>ke(null),children:xe}),r.jsx(uu,{listTitle:b,listMeta:y,sections:rs,flatList:!0,listState:O.searchResults?"ready":bs,searchQuery:I?c:void 0,listFilter:S,listScopeLabel:g,errorMessage:wt,onRetry:i,onReportError:zr,density:ie,selectedThreadId:s,onSelectThread:_=>j({to:"/mail/$mailboxId",params:{mailboxId:e},search:G=>({...G,selectedMessageId:_})}),isDesktop:T,hideHeader:R,selectionBar:it,listBody:O.searchResults??(bs==="ready"?Vf:void 0)}),r.jsx(lo,{isOpen:J!==null,title:Rc(J?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:d,onConfirm:vt,onCancel:Mt}),r.jsx(Xo,{verb:N,accountId:p,mailboxId:e,selection:et,crossAccount:ct!==void 0,escalated:ht,escalatedProgress:q.progress,onFinished:Oe,onRunEnded:Qe})]})},gj=e=>$t({path:{accountId:e}}),xj=e=>{const t=Pe(),s=Ps(),n=Ue({...lh(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:gj(e)})}});return{trigger:()=>{n.mutate({path:{accountId:e}})},triggerAsync:()=>n.mutateAsync({path:{accountId:e}}),isPending:n.isPending,error:n.error,reset:n.reset}},bj=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:n}=xj(e);return r.jsx(Px,{onRefresh:s,isRefreshing:n,children:t})};function vj({accountId:e,currentMailboxId:t,candidates:s,onMove:n,children:a}){const[o,i]=l.useState(!1),c=Ps(),u=ro(),{inboxMailboxId:m}=pd(e),d=_o(e),{data:f}=Ce({...ft({path:{accountId:e}}),staleTime:1/0}),h=l.useMemo(()=>ao({mailboxes:f?.items??[],folderAppointments:d,currentMailboxId:t,translator:u}),[f?.items,d,t,u]),v=l.useMemo(()=>m||(h.find(S=>S.label.toLowerCase()==="inbox")?.id??h.find(S=>!S.isCurrent)?.id??""),[m,h]),x=l.useRef(!1);l.useEffect(()=>{x.current||(x.current=!0,rk(c,s.length))},[c,s.length]);const p=l.useCallback(()=>{ak(c,s.length),i(!0)},[c,s.length]),b=l.useCallback((y,S)=>{ok(c,{selected:y.length,total:s.length,toInbox:S===m}),n(y,S)},[c,s.length,m,n]);return r.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[r.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:r.jsx($x,{count:s.length,onReview:p})}),r.jsx("div",{className:"min-h-0 flex-1",children:a}),r.jsx(Gx,{open:o,candidates:s,defaultDestinationId:v,availableFolders:h,delimiter:oo(f?.items??[]),onConfirmMove:b,onCancel:()=>i(!1)})]})}const yj="We can verify this sender";function wj(e){const{data:t}=Ce({...Sc({path:{mailboxId:e??""},query:{senderTrust:["vip","wellknown"],dkimMismatch:!1,results:!0,limit:500}}),enabled:!!e,staleTime:6e4});return{candidates:(t?.items??[]).map(n=>({id:n.messageId,senderName:n.fromName||n.fromEmail||"Unknown sender",senderAddress:n.fromEmail??"",subject:n.subject||"(no subject)",snippet:n.snippet??"",trustReason:yj,trustSubReason:nk(n.senderTrust),senderTrust:n.senderTrust}))}}const Sj=e=>{const t=new Set,s=[];for(const n of e)t.has(n.threadMessageId)||(t.add(n.threadMessageId),s.push(n));return s},Cj={unread:"unread",flagged:"starred",attachment:"attachments"},kj=new Set(Object.values(lt)),Df=e=>kj.has(e),jj=e=>Df(e.category)||e.attributes.size>0,Nj=e=>{const t={};Df(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const n=Cj[s];n&&(t[n]=!0)}return t},Ej=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",Ij=["category","unread","starred","attachments"],Gl=e=>JSON.stringify(Ij.map(t=>e?.[t]??null)),Rj=e=>{if(!Array.isArray(e))return;const[t]=e;if(typeof t!="object"||t===null)return;const s=t.query;if(!(typeof s!="object"||s===null))return s},Tj=(e,t)=>{const s=Rj(e);return s?Gl(s)===Gl(t):!1},Pf="remit:intelligence-open";function Mj(){try{return localStorage.getItem(Pf)!=="closed"}catch{return!0}}function Yl(e){try{localStorage.setItem(Pf,e?"open":"closed")}catch{}}const Aj=(e,t)=>e!==t,Oj=(e,t,s)=>{if(!(s||!t))return e.find(n=>n.messageId===t)},Dj=(e,t,s,n)=>{if(e)return e;if(!(n||!s))return t?.messageId===s?t:void 0},_n=e=>e[0],Pj=e=>{const t=_n(e.filter(c=>c.type==="from").map(c=>c.value)),s=_n(e.filter(c=>c.type==="subject").map(c=>c.value)),n=_n(e.filter(c=>c.type==="category").map(c=>c.category)),a=_n(e.filter(c=>c.type==="isUnread"||c.type==="isRead").map(c=>c.type==="isUnread")),o=e.some(c=>c.type==="isStarred")?!0:void 0,i=e.some(c=>c.type==="hasAttachment")?!0:void 0;return{...t!==void 0?{from:t}:{},...s!==void 0?{subject:s}:{},...n!==void 0?{category:[n]}:{},...a!==void 0?{unread:a}:{},...o!==void 0?{starred:o}:{},...i!==void 0?{attachments:i}:{}}},Lj=(e,t)=>{switch(t.type){case"from":return e.from?.toLowerCase()===t.value.toLowerCase();case"subject":return e.subject?.toLowerCase()===t.value.toLowerCase();case"category":return e.category?.length===1&&e.category[0]===t.category;case"isUnread":return e.unread===!0;case"isRead":return e.unread===!1;case"isStarred":return e.starred===!0;case"hasAttachment":return e.attachments===!0;case"before":case"after":case"in":case"account":return!1}};function Fj(e,t={}){const s=Pj(e),n={...s,...t};return{params:s,residual:e.filter(a=>!Lj(n,a))}}function $j(e,t,s){if(t.length===0)return e;const n=[...t];return e.filter(a=>{const o=nr(a);return Wo({...o,accountId:o.accountId??s},n)})}const _j=50,zj=new Map(wu().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),Lf=l.createContext(null);function _r(){const e=l.useContext(Lf);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function Bj({mailboxId:e,selectedMessageId:t,children:s}){const n=Je(),o=Nn()==="desktop",i=Ps(),{accounts:c,searchQuery:u,searchInput:m,intelligenceOpen:d,onToggleIntelligence:f,onSetIntelligenceOpen:h}=Fe(),v=gs(),x=Ho(u),p=x.length>0,{freeText:b,tokens:y}=Bs(x,v),[S,g]=l.useState("all"),[w,C]=l.useState(new Set),R=l.useMemo(()=>({category:S,attributes:w}),[S,w]),A=l.useMemo(()=>Nj(R),[R]),j=p||jj(R),{params:T,residual:P}=Fj(y,A),N={order:"desc",limit:_j,...b?{query:b}:{},...T,...A},L={category:N.category,unread:N.unread,starred:N.starred,attachments:N.attachments},D=j?Ya({path:{mailboxId:e},query:N}):fr({path:{mailboxId:e},query:{order:"desc"}}),{data:k,isLoading:I,isError:O,error:M,refetch:F,fetchNextPage:E,hasNextPage:V,isFetchingNextPage:X}=Hu({queryKey:D,queryFn:async({pageParam:te})=>{if(j){const{data:it}=await ba({path:{mailboxId:e},query:{...N,continuationToken:te},throwOnError:!0});return it}const{data:ot}=await ch({path:{mailboxId:e},query:{order:"desc",continuationToken:te},throwOnError:!0});return ot},initialPageParam:void 0,getNextPageParam:te=>te.continuationToken,placeholderData:(te,ot)=>Tj(ot?.queryKey,L)?te:void 0}),Z=l.useCallback(te=>{t&&te.includes(t)&&n({to:"/mail/$mailboxId",params:{mailboxId:e},search:ot=>({...ot,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,n]),{deleteMessages:ae,isPending:ie}=fs({mailboxId:e,onAfterOptimisticRemove:Z}),{accountId:oe}=Lo(e),ue=od({accounts:c}),{moveMessages:ge,isPending:B}=Os({mailboxId:e,accountId:oe,onAfterOptimisticRemove:Z}),U=$j(B0(Sj(k?.pages.flatMap(te=>te.items??[])??[])),P,oe),he=l.useCallback(te=>{g(te)},[]),me=l.useCallback(te=>{C(ot=>{const it=new Set(ot);return it.has(te)?it.delete(te):it.add(te),it})},[]),se=l.useCallback(()=>{g("all"),C(new Set)},[]),we=zj.get(S),K=we?{label:we,reach:P.length>0?"loaded-pages":Ej(N),onClear:se}:void 0,Ee=Aj(m,u),be=Oj(U,t,Ee),[je,fe]=l.useState(void 0);l.useEffect(()=>{be&&fe(be)},[be]);const ne=Dj(be,je,t,Ee),{selectedThreadId:Se}=Ms({strict:!1}),Le=l.useMemo(()=>kf(ne,{messageId:t,threadId:Ee?void 0:Se,mailboxId:e}),[ne,t,Se,Ee,e]),ze=Zo(),{listCommandsRef:J,onTriageContextChange:Ze,focusedMessageId:Ie,selectedIds:qe}=ze,q=U.find(te=>te.messageId===Ie)??ne,Qe=l.useRef(null);l.useEffect(()=>{const te=ne?.messageId??null;te&&Qe.current!==te&&ne?.authenticity?.dkimMismatch&&(Qe.current=te,d||f())},[ne?.messageId,ne?.authenticity?.dkimMismatch,d,f]);const Re=l.useRef(!1);l.useEffect(()=>{Re.current||o&&ne?.messageId&&(Re.current=!0,Mj()&&!d&&h(!0))},[o,ne?.messageId,d,h]);const ve=Hy({accounts:c})??0,Oe=Pe(),{pushError:xe}=st(),ke=mn({thread:ne,mailboxId:e,accountId:oe,onAfterOptimisticRemove:Z}),{draftsMailboxId:Te}=L0(oe),$=Te!==void 0&&Te===e,{archiveMailboxId:le}=P0(oe),de=Cf(),{requestCompose:ye}=ke,H=l.useCallback(()=>{ye("reply")},[ye]),pe=l.useCallback(()=>{ye("reply_all")},[ye]),re=l.useCallback(()=>{ye("forward")},[ye]),{state:ee,openCompose:Ne,closeCompose:De}=Ft(),Be=l.useCallback(()=>{Ne({mode:"new"})},[Ne]),Ye=l.useRef(t);l.useEffect(()=>{const te=Ye.current;Ye.current=t,!(!t||t===te)&&De()},[t,De]);const Ke=Ue({...dr(),onError:te=>{xe(us("Couldn't discard draft","The draft wasn't deleted.",te))}}),Me=l.useCallback(()=>{const te=ee.outboxMessageId;te&&(Ke.mutate({path:{outboxMessageId:te}}),Oe.invalidateQueries({queryKey:so()}),De())},[ee.outboxMessageId,Ke,Oe,De]),et=l.useCallback(()=>{n({to:"/mail/$mailboxId",params:{mailboxId:e},search:te=>({...te,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,n]),He=l.useCallback(te=>te?de(te):[],[de]),{toggleStar:nt}=Fo({threadId:q?.threadId??"",mailboxId:e}),{toggleReadFor:rt}=Mr({mailboxId:e,accountId:oe}),{junkMailboxId:mt}=kn(oe),Bt=mt!=null&&mt===e,Tt=Pr(mt,e),{candidates:Ks}=wj(Bt?mt:void 0),{moveMessages:at}=Os({mailboxId:e,threadId:q?.threadId,accountId:oe,onAfterOptimisticRemove:Z}),{deleteMessages:xs}=fs({mailboxId:e,threadId:q?.threadId,onAfterOptimisticRemove:Z}),{addressId:ht,address:vt}=vf(q),{updateFlags:Mt}=yf({addressId:ht,senderEmail:q?.fromEmail??void 0}),ct=l.useCallback(()=>t||!Ie?!1:(n({to:"/mail/$mailboxId",params:{mailboxId:e},search:te=>({...te,selectedMessageId:Ie})}),!0),[t,Ie,e,n]),qs=l.useCallback(()=>{ct()||ne&&ye("reply")},[ct,ne,ye]),En=l.useCallback(()=>{ct()||ne&&ye("reply_all")},[ct,ne,ye]),ns=l.useCallback(()=>{ct()||ne&&ye("forward")},[ct,ne,ye]),z=l.useCallback(()=>He(q),[He,q]),Y=l.useCallback(()=>{if(J.current?.requestVerb("delete"))return;const te=z();te.length>0&&xs(te)},[J,z,xs]),Ae=l.useCallback(()=>{if(J.current?.requestVerb("junk")||!Tt)return;const te=z();te.length!==0&&(Sf(i,{count:te.length,senderTrust:q?.senderTrust??"unknown",wasRescuable:q?wf(q):!1}),at(te,Tt))},[J,Tt,z,at,i,q]),pt=l.useCallback(()=>{if(qe.length>0){const te=!(q?.hasStars??!1),ot=new Set(qe);for(const it of U)ot.has(it.messageId)&&it.hasStars!==te&&nt(it.messageId,it.hasStars);return}q&&nt(q.messageId,q.hasStars)},[qe,U,q,nt]),yt=l.useCallback(()=>{if(J.current?.requestVerb("markRead"))return;const te=z();if(te.length===0)return;const ot=!(q?.isRead??!1);rt(te,ot)},[J,z,q,rt]),bs=l.useCallback(()=>{if(!ht)return;const te=vt?.flags?.muted?.value!==!0;Mt({muted:{value:te}})},[ht,vt,Mt]),wt=l.useCallback(()=>{if(!ht)return;const te=vt?.flags?.vip?.value!==!0;Mt({vip:{value:te}})},[ht,vt,Mt]),zr=l.useCallback(()=>{d||f()},[d,f]),rs=l.useCallback(te=>{n({to:te})},[n]),vs=$?"drafts":le===e?"archive":mt===e?"junk":"inbox",In=l.useRef("");l.useEffect(()=>{const te=In.current;In.current=x,x.length>0&&te.length===0&&i.recordEvent("search.submitted",{mailboxType:vs})},[x,vs,i]);const Br=$&&ee.isOpen&&!!ee.outboxMessageId&&!ne,{goBack:Hs,nextMessageId:Ur,previousMessageId:Kr}=ei({context:ze,orderedIds:U.map(te=>te.messageId),selectedMessageId:t,enabled:!ee.isOpen,onClose:et,handlers:{reply:qs,replyAll:En,forward:ns,delete:Y,toggleStar:pt,toggleRead:yt,muteSender:bs,blockSender:zr,vipSender:wt,markJunk:Ae,toggleIntelligence:ne?f:void 0,compose:Be,goBrief:()=>rs("/mail"),goInbox:()=>rs("/mail"),goSent:()=>rs("/mail"),goFlagged:()=>rs("/mail/flagged"),goSettings:()=>rs("/settings")}});Po({enabled:ee.isOpen,bindings:[{key:"Escape",handler:De,preventDefault:!0}]});const qr={mailboxId:e,selectedMessageId:t,selectedThread:ne,conversation:Le,threads:U,isLoading:I,isError:O,error:M,mailboxAccountId:oe,mailboxName:ue,unreadCount:ve,isDraftsMailbox:$,isSpamFolder:Bt,rescueCandidates:Ks,filterCategory:S,filterAttributes:w,onSelectFilterCategory:he,onToggleFilterAttribute:me,onClearFilters:se,listFilter:K,intelligenceOpen:d,onToggleIntelligence:f,handleDeselectIfRemoved:Z,searchPredicate:p&&P.length===0?N:void 0,onDeleteMessages:ae,onMoveMessages:ge,isDeleting:ie,isMoving:B,onLoadMore:E,hasMore:V,isLoadingMore:X,onTriageContextChange:Ze,listCommandsRef:J,onRetry:()=>F(),toolbarComposeRequest:ke.composeRequest,onToolbarReply:H,onToolbarReplyAll:pe,onToolbarForward:re,onClearComposeRequest:ke.clearComposeRequest,onToolbarDelete:ke.deleteThread,onToolbarStar:ke.toggleStar,onToolbarDiscardDraft:Me,onToolbarMove:ke.moveThread,composeState:ee,closeCompose:De,hasRemitDraftOpen:Br,onBack:Hs,nextMessageId:Ur,previousMessageId:Kr};return r.jsx(Lf.Provider,{value:qr,children:s})}function Ff(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:n,isError:a,error:o,onDeleteMessages:i,onMoveMessages:c,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,mailboxAccountId:v,mailboxName:x,unreadCount:p,isDraftsMailbox:b,isSpamFolder:y,rescueCandidates:S,onTriageContextChange:g,listCommandsRef:w,onRetry:C,filterCategory:R,filterAttributes:A,onSelectFilterCategory:j,onToggleFilterAttribute:T,onClearFilters:P,listFilter:N,searchPredicate:L}=_r(),{searchQuery:D,searchInput:k,accounts:I,resultFolderIndex:O}=Fe(),M=Nn(),F=Je(),E=x??"Inbox",V=l.useMemo(()=>wu(),[]),X=l.useMemo(()=>v?[v]:[],[v]),{hasNewMail:Z}=Ir(),{state:ae,errorMessage:ie,refresh:oe}=To(X,{onSettled:C}),ue=l.useMemo(()=>r.jsx(So,{state:ae,onRefresh:oe,label:`Refresh ${E}`,errorMessage:ie,hasUpdate:Z(X)}),[ae,oe,E,ie,Z,X]),ge=l.useMemo(()=>s.map(be=>kS(be,O)),[s,O]),{hits:B,isLoading:U}=Yd({mailboxId:e,filterCategory:R}),he=l.useMemo(()=>Zd(B,s.map(be=>be.threadId),O),[B,s,O]),me=l.useCallback(be=>F({to:"/mail/$mailboxId",params:{mailboxId:be.mailboxId??e},search:je=>({...je,q:k||void 0,selectedMessageId:be.id,selectedThreadId:be.threadId})}),[e,F,k]);if(b&&v)return r.jsx(Fk,{mailboxId:e,accountId:v,selectedMessageId:t,imapThreads:s,title:x??"Drafts",unreadCount:p??void 0});const se=r.jsx(pj,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:n,isError:a,error:o,onRetry:C,searchQuery:D,searchPredicate:L,onDeleteMessages:i,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,accountId:v,listTitle:E,listFilter:N,listScopeLabel:E,hideHeader:!0,onTriageContextChange:g,commandsRef:w}),we=I[0]?.accountId,K=M==="phone"&&we?r.jsx(bj,{accountId:we,children:se}):se,Ee=y&&S.length>0&&v?r.jsx(vj,{accountId:v,currentMailboxId:e,candidates:S,onMove:c,children:K}):K;return r.jsx(If,{title:E,unreadCount:p,preset:V,selectedCategory:R,activeFilters:A,onSelectCategory:j,onToggleFilter:T,onClearFilters:P,searchResults:ge,searchLoading:n,relatedResults:he,relatedLoading:U,onSelectSearchResult:me,searchResultsInBody:!0,refreshControl:ue,children:Ee})}function Uj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:c,onToolbarReply:u,onToolbarReplyAll:m,onToolbarForward:d,onClearComposeRequest:f,onToolbarDelete:h,onToolbarStar:v,onToolbarDiscardDraft:x,onToolbarMove:p,composeState:b}=_r(),y=hs()?.showIntelligencePane??!1,S=!!n,g=y&&S,w=b.isOpen&&!n?r.jsx(Mf,{}):n?r.jsx(zs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onOpenIntelligence:n.authenticity?.dkimMismatch?i:void 0,composeRequest:c,onComposeClose:f}):r.jsx(_s,{});return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Jo,{hasThread:S,intelligenceOpen:g&&o,canToggleIntelligence:g,onToggleIntelligence:i,onReply:S?u:void 0,onReplyAll:S?m:void 0,onForward:S?d:void 0,canDelete:S||a,onDelete:S?h:a?x:void 0,onToggleStar:S?v:void 0,isStarred:s?.hasStars,moveContext:S&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:w})]})}function Kj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:n,handleDeselectIfRemoved:a}=_r();return r.jsx(Us,{onClose:n,thread:s,mailboxId:e,accountId:t,onAfterOptimisticRemove:a})}function qj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,intelligenceOpen:a,onToggleIntelligence:o,onBack:i,nextMessageId:c,previousMessageId:u,composeState:m,handleDeselectIfRemoved:d}=_r(),f=Je();if(n){const h=v=>f({to:"/mail/$mailboxId",params:{mailboxId:e},search:x=>({...x,selectedMessageId:v,selectedThreadId:void 0})});return r.jsxs(r.Fragment,{children:[r.jsx(zs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onBack:i,onOpenIntelligence:o,onSwipeNext:c?()=>h(c):void 0,onSwipePrevious:u?()=>h(u):void 0,mobileIntelligenceOpen:a}),r.jsx(Oo,{isOpen:a,onClose:o,ariaLabel:"Message details",side:"right",children:r.jsx(Us,{onClose:o,thread:s,mailboxId:e,accountId:t,hideCloseButton:!0,onAfterOptimisticRemove:d})})]})}return m.isOpen?r.jsx("div",{className:"h-full",children:r.jsx(Mf,{})}):r.jsx(Ff,{})}const sn=Object.assign(Bj,{List:Ff,Reading:Uj,Intelligence:Kj,Phone:qj}),$f=e=>e==="failed"||e==="blocked",_f=e=>e!=="draft"&&e!=="sent",ni="remit.savedSearches",Hj=25;function ar(){try{const e=localStorage.getItem(ni);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Wj(e){const t=e.trim();if(!t)return ar();const s=[t,...ar().filter(n=>n!==t)].slice(0,Hj);try{localStorage.setItem(ni,JSON.stringify(s))}catch{return s}return s}function Vj(e){const t=ar().filter(s=>s!==e);try{localStorage.setItem(ni,JSON.stringify(t))}catch{return t}return t}const Xl=e=>/^\d/.test(e),Qj=(e,t)=>{const s=Xl(e),n=Xl(t);return s&&!n?-1:!s&&n?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function Gj(e,t,s){const n=[],a=[];for(const o of e)t.has(o.mailboxId)?n.push(o):a.push(o);return a.sort((o,i)=>Qj(Yn(o,void 0,s),Yn(i,void 0,s))),{system:n,labels:a}}function Yj(e,t,s){const n=uh(t)&&e.unseenCount>0;return{id:e.mailboxId,name:Yn(e,t,s),unseen:n?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function Xj(){const e=Ha(),t=Va({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 Jl({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const n=Pe(),a=Je(),o=Xj(),{searchInput:i,onSearchChange:c}=Fe(),[u,m]=l.useState(ar),{t:d}=Qa("mail",{useSuspense:!1}),f=l.useCallback((j,T)=>d(j,{defaultValue:T}),[d]),h=gt({queries:e.map(j=>({...ft({path:{accountId:j.accountId}}),staleTime:1/0}))}),{data:v}=Ce(cr()),x=l.useMemo(()=>(v?.items??[]).filter(j=>_f(j.status)).length,[v?.items]),p=l.useMemo(()=>e.map((j,T)=>{const P=h[T],N=P?.data?.items??[],L=gc(j.folderAppointments),{system:D,labels:k}=Gj(N,L,f),I=P?.isError?"error":P?.isLoading?"loading":"ready";return{id:j.accountId,label:j.email,email:j.email,muted:!!j.muted,outboxPending:x,status:I,onRetry:()=>P?.refetch(),mailboxes:[...D,...k].map(O=>Yj(O,L.get(O.mailboxId),f))}}),[e,h,x,f]),b=j=>{n.invalidateQueries({queryKey:fr({path:{mailboxId:j},query:{order:"desc"}})})},y=({navId:j,className:T,ariaLabel:P,title:N,children:L,onClick:D})=>j==="brief"?r.jsx(Wt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},activeOptions:{exact:!0,includeSearch:!1},onClick:()=>D?.(),className:T,"aria-label":P,title:N,children:L}):j==="outbox"?r.jsx(Wt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>D?.(),className:T,"aria-label":P,title:N,children:L}):j==="flagged"?r.jsx(Wt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>D?.(),className:T,"aria-label":P,title:N,children:L}):j==="settings"?r.jsx(Wt,{to:"/settings/accounts",onClick:()=>D?.(),className:T,"aria-label":P,title:N,children:L}):r.jsx(Wt,{to:"/mail/$mailboxId",params:{mailboxId:j},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{b(j),D?.()},className:T,"aria-label":P,title:N,children:L}),S=()=>{c(""),t?.()},g=i.trim(),w=g.length>0&&!u.includes(g)?g:void 0,C=l.useCallback(()=>{w&&m(Wj(w))},[w]),R=l.useCallback(j=>{m(Vj(j))},[]),A=l.useCallback(j=>{c(j),a({to:"/mail",search:{q:j,selectedMessageId:void 0}}),t?.()},[c,a,t]);return r.jsx(Wg,{accounts:p,selectedNavId:o,onSelectNav:S,linkComponent:y,variant:s,savedSearches:u,saveableQuery:w,onSaveCurrentSearch:C,onSelectSavedSearch:A,onRemoveSavedSearch:R})}function Jj(){return r.jsxs("button",{type:"button",onClick:xc,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[r.jsx(Uc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]})}function Zj({accounts:e,onMailboxSelect:t}){return hs()?.showNavPane??!0?r.jsx(Jl,{accounts:e}):r.jsxs("div",{className:"flex h-full flex-col",children:[r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(Jl,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),r.jsxs("div",{className:"border-t border-line px-2 py-2",children:[r.jsxs(Wt,{to:"/settings/accounts",onClick:t,children:[r.jsx(Gc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),r.jsx(Jj,{}),r.jsx(Gu,{children:({signOut:a})=>r.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[r.jsx(Wc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function eN(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const n=[e.subject,e.fromAddress,e.fromName,...e.toAddresses??[],...e.ccAddresses??[]].filter(a=>typeof a=="string").join(" ").toLowerCase();return s.split(/\s+/).every(a=>a.length===0||n.includes(a))}function tN(e){return e.tokens.length>0&&e.freeText.trim().length===0}const zf={queued:{icon:no,label:"Queued",className:"text-warning"},sending:{icon:ms,label:"Sending…",className:"text-accent-2"},sent:{icon:mo,label:"Sent",className:"text-positive"},failed:{icon:Pt,label:"Failed",className:"text-danger"},blocked:{icon:Ua,label:"Blocked",className:"text-warning"}},sN=e=>Ah(e).toDateString()===new Date().toDateString()?Xn(e,{hour:"numeric",minute:"2-digit"}):Xn(e,{month:"short",day:"numeric"}),Zl=e=>Xn(e,{dateStyle:"medium",timeStyle:"short"}),nN=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},Bf=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",Uf=l.createContext(null);function ri(){const e=l.useContext(Uf);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function rN({children:e}){const t=Je(),{selectedOutboxMessageId:s}=Ms({strict:!1}),{data:n,isLoading:a}=Ce(cr()),{searchQuery:o}=Fe(),i=gs(),c=Ho(o),u=Bs(c,i),m=c.length>0,d=tN(u),f=l.useMemo(()=>d?[]:(n?.items??[]).filter(p=>_f(p.status)).filter(p=>eN(p,u.freeText)),[n,u.freeText,d]),h=l.useMemo(()=>f.find(p=>p.outboxMessageId===s),[f,s]),v=l.useCallback(p=>{t({to:"/mail/outbox",search:b=>({...b,selectedOutboxMessageId:p})})},[t]),x={messages:f,hasQuery:m,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:v};return r.jsx(Uf.Provider,{value:x,children:e})}function Kf({message:e,isSelected:t,onSelect:s}){const n=Pe(),{openCompose:a}=Ft(),{pushError:o}=st(),i=l.useCallback(()=>{n.invalidateQueries({queryKey:so()})},[n]),c=Ue({...vc(),onSuccess:i,onError:f=>{o(us("Couldn't resend message","The message wasn't sent.",f))}}),u=Ue({...dr(),onSuccess:i,onError:f=>{o(us("Couldn't delete message","The message wasn't deleted.",f))}}),m=e.status;if(!zf[m])return null;const d=$f(e.status);return r.jsx(Ox,{recipients:nN(e),subject:e.subject||"",time:sN(e.sentAt??e.updatedAt),status:m,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:m==="failed"?()=>c.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:c.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function qf({message:e,onBack:t}){const s=e.status,n=zf[s],a=n?.icon??pn,o=e.sentAt?Zl(e.sentAt):Zl(e.updatedAt);return r.jsxs("div",{className:"h-full overflow-y-auto bg-canvas",children:[r.jsxs("div",{className:"border-b border-line p-4",children:[t&&r.jsxs("button",{type:"button",onClick:t,className:"mb-3 inline-flex items-center gap-1 text-sm text-fg-muted hover:text-fg",children:[r.jsx(Ba,{className:"size-4"}),r.jsx("span",{children:"Back"})]}),r.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),r.jsxs("div",{className:"space-y-1 text-sm",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),r.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),r.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),r.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),r.jsx("span",{className:"text-fg",children:o})]}),n&&r.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[r.jsx(a,{className:Ve("size-4",n.className,s==="sending"&&"animate-spin")}),r.jsx("span",{className:Ve("text-xs font-medium",n.className),children:n.label}),$f(e.status)&&e.lastError&&r.jsxs("span",{className:"text-xs text-fg-muted",children:["— ",e.lastError]})]})]})]}),r.jsx("div",{className:"p-4",children:r.jsx(Kd,{html:e.htmlBody,text:e.textBody})})]})}function aN(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,onSelectMessage:o}=ri(),i=l.useRef(null);return or({containerRef:i,itemSelector:Qn}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(_s,{message:Bf(t,s),showHints:!1})}):r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(ti,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(c=>r.jsx(Kf,{message:c,isSelected:a===c.outboxMessageId,onSelect:()=>o(c.outboxMessageId)},c.outboxMessageId))})]})}function oN(){const{selectedMessage:e}=ri();return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx("header",{className:"flex h-pane-header shrink-0 items-center border-b border-line px-3"}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(qf,{message:e}):r.jsx(_s,{message:"Select a message to read",showHints:!1})})]})}function iN(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=ri(),c=l.useRef(null);return or({containerRef:c,itemSelector:Qn}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?r.jsx(qf,{message:o,onBack:()=>i(void 0)}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(_s,{message:Bf(t,s),showHints:!1})}):r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(ti,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:c,className:"flex-1 overflow-y-auto",children:e.map(u=>r.jsx(Kf,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const zn=Object.assign(rN,{List:aN,Reading:oN,Phone:iN}),lN=({isOpen:e,onClose:t})=>{const s=l.useCallback(n=>{n.key==="Escape"&&(n.preventDefault(),t())},[t]);return l.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx(kc,{label:"Dismiss keyboard shortcuts",onDismiss:t,className:"backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",className:Ve("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"),children:[r.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),r.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:r.jsx(Et,{className:"size-5"})})]}),r.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:Xc.map(n=>r.jsxs("div",{children:[r.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:n.title}),r.jsx("div",{className:"space-y-2",children:n.hints.map(a=>r.jsxs("div",{className:"flex items-center justify-between gap-4",children:[r.jsx("span",{className:"text-sm",children:a.description}),r.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>r.jsxs(l.Fragment,{children:[i>0&&a.keys[0]==="g"&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),r.jsx(Es,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},n.title))}),r.jsx("div",{className:"mt-6 border-t border-line pt-4",children:r.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",r.jsx(Es,{children:"Esc"})," to close"]})})]})]}):null};function cN(e){const t=gt({queries:e.map(s=>({...ft({path:{accountId:s.accountId}}),staleTime:1/0}))});return l.useMemo(()=>FS(t.map(s=>s.data?.items??[])),[t])}const uN=e=>e.map(t=>t.data?.items??[]);function dN(e){const t=gt({queries:e.map(s=>({...ft({path:{accountId:s.accountId}}),staleTime:1/0})),combine:uN});return l.useMemo(()=>dh(e.map((s,n)=>({folderAppointments:s.folderAppointments,mailboxes:t[n]??[]}))),[e,t])}var Bn={exports:{}},ec;function fN(){if(ec)return Bn.exports;ec=1;const e=(t,s,n)=>new Promise((a,o)=>{if(n=Object.assign({concurrency:1/0},n),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=n;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const c=[],u=t[Symbol.iterator]();let m=!1,d=!1,f=0,h=0;const v=()=>{if(m)return;const x=u.next(),p=h;if(h++,x.done){d=!0,f===0&&a(c);return}f++,Promise.resolve(x.value).then(b=>s(b,p)).then(b=>{c[p]=b,f--,v()},b=>{m=!0,o(b)})};for(let x=0;x<i&&(v(),!d);x++);});return Bn.exports=e,Bn.exports.default=e,Bn.exports}var mN=fN();const hN=fh(mN),pN=900*1e3,gN=300,xN=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},bN=60*1e3,vN=e=>Math.max(xN(e,gN)*1e3,bN),Vn=vN(mh().mailboxPollIntervalSeconds),yN=5,$a=new Set,wN=(e,t,s=pN)=>e.filter(n=>{const a=n.lastSyncAt;return a==null?!0:t-a>s}).map(n=>n.accountId),SN=(e,t,s=Vn)=>e-t>=s,CN=(e,t)=>e.filter(s=>!t.has(s)),tc=(e,t)=>{if($a.delete(e),pc(t,{softError:!0})){Wa(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},sc=(e,t)=>hc({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:$t({path:{accountId:e}})})}),kN=e=>{const t=Pe(),s=l.useRef(e);s.current=e;const n=e.map(a=>a.accountId).join(",");l.useEffect(()=>{const a=Date.now(),i=wN(s.current,a).filter(c=>!$a.has(c));if(i.length!==0)for(const c of i)$a.add(c),sc(c,t).catch(u=>{tc(c,u)})},[n,t]),l.useEffect(()=>{let a=Date.now(),o;const i=new Set,c=()=>{a=Date.now();const d=CN(s.current.map(f=>f.accountId),i);for(const f of d)i.add(f);hN(d,f=>sc(f,t).catch(h=>{tc(f,h)}).finally(()=>{i.delete(f)}),{concurrency:yN})},u=()=>{if(document.visibilityState==="visible"){c(),o=setTimeout(u,Vn);return}},m=()=>{document.visibilityState==="visible"&&SN(Date.now(),a)&&(o!==void 0&&clearTimeout(o),c(),o=setTimeout(u,Vn))};return o=setTimeout(u,Vn),document.addEventListener("visibilitychange",m),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",m)}},[n,t])};function jN(e,t,s){if(e!==t)return s}function NN(e,t){return e===""?"":t}function EN(e,t,s){return t!==e?!1:t!==s}function IN(){const{q:e=""}=Ms({from:"/mail"}),t=Je(),s=Nn(),n=Wd(s),[a,o]=l.useState(!1),[i,c]=l.useState(!1),[u,m]=l.useState(!1),d=l.useCallback(se=>{m(se),Yl(se)},[]),[f,h]=l.useState(e),v=gr(f,200),x=NN(f,v),p=l.useRef(e);p.current=e;const b=kt({select:se=>se.location.pathname}),y=kt({select:se=>zy(se.matches)}),[S,g]=l.useState(y);if(S!==y){const se=jN(S,y,e);g(y),se!==void 0&&h(se)}l.useEffect(()=>{EN(f,x,p.current)&&t({to:".",search:se=>{const we=se.q===x;return{...se,q:x||void 0,...x&&!we?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[f,x,t]);const{data:w,isLoading:C,isError:R,error:A,refetch:j}=Ce({..._t(),staleTime:1/0}),T=!!(w&&(w.accounts?.length??0)===0);l.useEffect(()=>{T&&t({to:"/onboarding",replace:!0})},[T,t]),Po({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const{openCompose:P}=Ft(),N=l.useMemo(()=>({compose:()=>P({mode:"new"})}),[P]);Tu({enabled:!hh(b),handlers:N});const L=l.useCallback(se=>{h(se)},[]),D=l.useCallback(()=>{h("")},[]),k=l.useCallback(()=>{h("")},[]),I=l.useCallback(()=>{m(se=>{const we=!se;return Yl(we),we})},[]),O=w?.accounts??[],M=l.useMemo(()=>O.map(se=>se.accountId),[O]),F=cN(O),E=dN(O),V=l.useMemo(()=>LS(O),[O]),X=kt({select:se=>se.matches.find(K=>"mailboxId"in K.params)?.params.mailboxId}),{selectedMessageId:Z}=Ms({strict:!1}),ae=kt({select:se=>Ao(se.matches)}),ie=kt({select:se=>vn(se.matches)}),oe=kt({select:se=>Rr(se.matches)});kN(O);const ue=l.useCallback(()=>{c(!1)},[]),ge={accounts:O,mailboxNameIndex:F,accountNameIndex:V,resultFolderIndex:E,searchQuery:x,searchInput:f,searchViewKey:y,onSearchChange:L,onSearchClear:D,onSearchClearQuery:k,intelligenceOpen:u,onToggleIntelligence:I,onSetIntelligenceOpen:d},B=r.jsx(Zj,{accounts:O,onMailboxSelect:ue}),U=n?r.jsx(jy,{}):void 0,he=n?void 0:r.jsx(Wy,{accounts:O}),me={navOpen:i,onOpenNav:()=>c(!0),onCloseNav:()=>c(!1)};return r.jsx(ph.Provider,{value:ge,children:r.jsxs(Oy,{accountIds:M,children:[R?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:r.jsx(ts,{title:"Couldn't load your account",error:A,onRetry:()=>{j()}})}):ae?r.jsx(Zs,{selectedMessageId:Z,children:n?r.jsx(Ut,{nav:B,list:r.jsx(Zs.Phone,{}),intelligenceOpen:u,overlay:U,skeleton:r.jsx(Ot,{}),isLoading:C||T,...me}):r.jsx(Ut,{nav:B,topBar:he,list:r.jsx(Zs.List,{}),reading:r.jsx(Zs.Reading,{}),intelligence:r.jsx(Zs.Intelligence,{}),intelligenceOpen:u,hasThread:!!Z,overlay:U,skeleton:r.jsx(Ot,{}),isLoading:C||T,...me})}):ie?r.jsx(en,{selectedMessageId:Z,children:n?r.jsx(Ut,{nav:B,list:r.jsx(en.Phone,{}),intelligenceOpen:u,overlay:U,skeleton:r.jsx(Ot,{}),isLoading:C||T,...me}):r.jsx(Ut,{nav:B,topBar:he,list:r.jsx(en.List,{}),reading:r.jsx(en.Reading,{}),intelligence:r.jsx(en.Intelligence,{}),intelligenceOpen:u,hasThread:!!Z,overlay:U,skeleton:r.jsx(Ot,{}),isLoading:C||T,...me})}):X?r.jsx(sn,{mailboxId:X,selectedMessageId:Z,children:n?r.jsx(Ut,{nav:B,list:r.jsx(sn.Phone,{}),intelligenceOpen:u,overlay:U,skeleton:r.jsx(Ot,{}),isLoading:C||T,...me}):r.jsx(Ut,{nav:B,topBar:he,list:r.jsx(sn.List,{}),reading:r.jsx(sn.Reading,{}),intelligence:r.jsx(sn.Intelligence,{}),intelligenceOpen:u,hasThread:!!Z,overlay:U,skeleton:r.jsx(Ot,{}),isLoading:C||T,...me})}):oe?r.jsx(zn,{children:n?r.jsx(Ut,{nav:B,list:r.jsx(zn.Phone,{}),intelligenceOpen:!1,overlay:U,skeleton:r.jsx(Ot,{}),isLoading:C||T,...me}):r.jsx(Ut,{nav:B,topBar:he,list:r.jsx(zn.List,{}),reading:r.jsx(zn.Reading,{}),intelligenceOpen:!1,overlay:U,skeleton:r.jsx(Ot,{}),isLoading:C||T,...me})}):r.jsx(Ot,{}),r.jsx(lN,{isOpen:a,onClose:()=>o(!1)}),r.jsx(gh,{})]})})}const GN=Object.freeze(Object.defineProperty({__proto__:null,component:IN,useMailContext:Fe},Symbol.toStringTag,{value:"Module"}));export{Yx as E,Np as U,VN as a,QN as c,GN as m,WN as s};